lang
stringclasses
2 values
license
stringclasses
13 values
stderr
stringlengths
0
343
commit
stringlengths
40
40
returncode
int64
0
128
repos
stringlengths
6
87.7k
new_contents
stringlengths
0
6.23M
new_file
stringlengths
3
311
old_contents
stringlengths
0
6.23M
message
stringlengths
6
9.1k
old_file
stringlengths
3
311
subject
stringlengths
0
4k
git_diff
stringlengths
0
6.31M
Java
apache-2.0
cbe88b46ca3814f51034116f0b990656cce8a6c3
0
izumin5210/Bletia
bletia/src/main/java/info/izumin/android/bletia/BleActionStore.java
package info.izumin.android.bletia; import java.util.ArrayList; import java.util.EnumMap; import java.util.List; import info.izumin.android.bletia.action.Action; import info.izumin.android.bletia.wrapper.BluetoothGattWrapper; /** * Created by izumin on 9/14/15. */ public class BleActionStore { private EnumMap<Action.Type, List<Action>> mWaitingActionQueue; private EnumMap<Action.Type, List<Action>> mRunningActionQueue; public BleActionStore() { mWaitingActionQueue = new EnumMap<>(Action.Type.class); mRunningActionQueue = new EnumMap<>(Action.Type.class); } public void enqueue(Action action) { Action.Type type = action.getType(); if (!mWaitingActionQueue.containsKey(type)) { mWaitingActionQueue.put(type, new ArrayList<Action>()); } mWaitingActionQueue.get(type).add(action); } public void execute(Action.Type type, BluetoothGattWrapper gattWrapper) { Action action = mWaitingActionQueue.get(type).remove(0); if (!mRunningActionQueue.containsKey(type)) { mRunningActionQueue.put(type, new ArrayList<Action>()); } mRunningActionQueue.get(type).add(action); action.execute(gattWrapper); } public Action dequeue(Action.Type type) { return mRunningActionQueue.get(type).remove(0); } public boolean isRunning(Action.Type type) { return mRunningActionQueue.containsKey(type) && (mRunningActionQueue.get(type).size() > 0); } }
Remove BleActionStore
bletia/src/main/java/info/izumin/android/bletia/BleActionStore.java
Remove BleActionStore
<ide><path>letia/src/main/java/info/izumin/android/bletia/BleActionStore.java <del>package info.izumin.android.bletia; <del> <del>import java.util.ArrayList; <del>import java.util.EnumMap; <del>import java.util.List; <del> <del>import info.izumin.android.bletia.action.Action; <del>import info.izumin.android.bletia.wrapper.BluetoothGattWrapper; <del> <del>/** <del> * Created by izumin on 9/14/15. <del> */ <del>public class BleActionStore { <del> private EnumMap<Action.Type, List<Action>> mWaitingActionQueue; <del> private EnumMap<Action.Type, List<Action>> mRunningActionQueue; <del> <del> public BleActionStore() { <del> mWaitingActionQueue = new EnumMap<>(Action.Type.class); <del> mRunningActionQueue = new EnumMap<>(Action.Type.class); <del> } <del> <del> public void enqueue(Action action) { <del> Action.Type type = action.getType(); <del> if (!mWaitingActionQueue.containsKey(type)) { <del> mWaitingActionQueue.put(type, new ArrayList<Action>()); <del> } <del> mWaitingActionQueue.get(type).add(action); <del> } <del> <del> public void execute(Action.Type type, BluetoothGattWrapper gattWrapper) { <del> Action action = mWaitingActionQueue.get(type).remove(0); <del> if (!mRunningActionQueue.containsKey(type)) { <del> mRunningActionQueue.put(type, new ArrayList<Action>()); <del> } <del> mRunningActionQueue.get(type).add(action); <del> action.execute(gattWrapper); <del> } <del> <del> public Action dequeue(Action.Type type) { <del> return mRunningActionQueue.get(type).remove(0); <del> } <del> <del> public boolean isRunning(Action.Type type) { <del> return mRunningActionQueue.containsKey(type) && (mRunningActionQueue.get(type).size() > 0); <del> } <del>}
Java
apache-2.0
6bebc5f839734777375ddf641bbae6b0c801c304
0
NativeScript/android-runtime,NativeScript/android-runtime,NativeScript/android-runtime,NativeScript/android-runtime,NativeScript/android-runtime,NativeScript/android-runtime,NativeScript/android-runtime
package com.tns; import java.io.BufferedReader; import java.io.File; import java.io.FileOutputStream; import java.io.FileReader; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import java.io.OutputStream; import java.io.OutputStreamWriter; import java.io.UnsupportedEncodingException; import java.net.ServerSocket; import java.net.Socket; import java.util.ArrayList; import java.util.NoSuchElementException; import java.util.Scanner; import java.util.concurrent.LinkedBlockingQueue; import android.content.BroadcastReceiver; import android.content.Context; import android.content.Intent; import android.content.IntentFilter; import android.os.Bundle; public class JsDebugger { private static native void processDebugMessages(); private static native void enable(); private static native void disable(); private static native void debugBreak(); private static native void sendCommand(byte[] command, int length); private static ThreadScheduler threadScheduler; private static final int INVALID_PORT = -1; private static final String portEnvInputFile = "envDebug.in"; private static final String portEnvOutputFile = "envDebug.out"; private static final String DEBUG_BREAK_FILENAME = "debugbreak"; private static int currentPort = INVALID_PORT; private static LinkedBlockingQueue<String> dbgMessages = new LinkedBlockingQueue<String>(); private final File debuggerSetupDirectory; private Boolean shouldDebugBreakFlag = null; private final Logger logger; public JsDebugger(Logger logger, ThreadScheduler threadScheduler, File debuggerSetupDirectory) { this.logger = logger; JsDebugger.threadScheduler = threadScheduler; this.debuggerSetupDirectory = debuggerSetupDirectory; } private static ServerSocket serverSocket; private static ServerThread serverThread = null; private static Thread javaServerThread = null; private static class ServerThread implements Runnable { private volatile boolean running; private final int port; private ResponseWorker responseWorker; private ListenerWorker commThread; public ServerThread(int port) { this.port = port; this.running = false; } public void stop() { this.running = false; this.responseWorker.stop(); try { serverSocket.close(); } catch (IOException e) { e.printStackTrace(); } } //when someone runs our server we do: public void run() { try { //open server port to run on serverSocket = new ServerSocket(this.port); running = true; } catch (IOException e) { running = false; e.printStackTrace(); } //start listening and responding through that socket while (running) { try { //wait for someone to connect to port and if he does ... open a socket Socket socket = serverSocket.accept(); //out (send messages to node inspector) this.responseWorker = new ResponseWorker(socket); new Thread(this.responseWorker).start(); //in (recieve messages from node inspector) commThread = new ListenerWorker(socket.getInputStream()); new Thread(commThread).start(); } catch (IOException e) { e.printStackTrace(); } } } } private static class ListenerWorker implements Runnable { private enum State { Header, Message } private BufferedReader input; public ListenerWorker(InputStream inputStream) { this.input = new BufferedReader(new InputStreamReader(inputStream)); } private volatile boolean running = true; public void run() { Scanner scanner = new Scanner(this.input); scanner.useDelimiter("\r\n"); ArrayList<String> headers = new ArrayList<String>(); String line; State state = State.Header; int messageLength = -1; String leftOver = null; Runnable dispatchProcessDebugMessages = new Runnable() { @Override public void run() { processDebugMessages(); } }; try { while (running && ((line = (leftOver != null) ? leftOver : scanner.nextLine()) != null)) { switch (state) { case Header: if (line.length() == 0) { state = State.Message; } else { headers.add(line); if (line.startsWith("Content-Length:")) { String strLen = line.substring(15).trim(); messageLength = Integer.parseInt(strLen); } if (leftOver != null) leftOver = null; } break; case Message: if ((-1 < messageLength) && (messageLength <= line.length())) { String msg = line.substring(0, messageLength); if (messageLength < line.length()) leftOver = line.substring(messageLength); state = State.Header; headers.clear(); try { byte[] cmdBytes = msg.getBytes("UTF-16LE"); int cmdLength = cmdBytes.length; sendCommand(cmdBytes, cmdLength); boolean success = JsDebugger.threadScheduler.post(dispatchProcessDebugMessages); assert success; } catch (UnsupportedEncodingException e) { // TODO Auto-generated catch block e.printStackTrace(); } } else { if (leftOver == null) { leftOver = line; } else { leftOver += line; } } break; } } } catch (NoSuchElementException e) { e.printStackTrace(); } finally { scanner.close(); } } } private static class ResponseWorker implements Runnable { private Socket socket; private final static String END_MSG = "#end#"; private OutputStream output; public ResponseWorker(Socket clientSocket) throws IOException { this.socket = clientSocket; this.output = this.socket.getOutputStream(); } public void stop() { dbgMessages.add(END_MSG); } @Override public void run() { byte[] LINE_END_BYTES = new byte[2]; LINE_END_BYTES[0] = (byte) '\r'; LINE_END_BYTES[1] = (byte) '\n'; while (true) { try { String msg = dbgMessages.take(); if (msg.equals(END_MSG)) break; byte[] utf8; try { utf8 = msg.getBytes("UTF8"); } catch (UnsupportedEncodingException e1) { utf8 = null; e1.printStackTrace(); } if (utf8 != null) { try { String s = "Content-Length: " + utf8.length; byte[] arr = s.getBytes("UTF8"); output.write(arr, 0, arr.length); output.write(LINE_END_BYTES, 0, LINE_END_BYTES.length); output.write(LINE_END_BYTES, 0, LINE_END_BYTES.length); output.write(utf8, 0, utf8.length); output.flush(); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } } } catch (InterruptedException e) { e.printStackTrace(); } } } } int getDebuggerPortFromEnvironment() { if (logger.isEnabled()) logger.write("getDebuggerPortFromEnvironment"); int port = INVALID_PORT; File envOutFile = new File(debuggerSetupDirectory, portEnvOutputFile); OutputStreamWriter w = null; try { w = new OutputStreamWriter(new FileOutputStream(envOutFile, false)); String currentPID = "PID=" + android.os.Process.myPid() + "\n"; w.write(currentPID); } catch (IOException e1) { e1.printStackTrace(); } finally { if (w != null) { try { w.close(); } catch (IOException e) { e.printStackTrace(); } } w = null; } boolean shouldDebugBreakFlag = shouldDebugBreak(); if (logger.isEnabled()) logger.write("shouldDebugBreakFlag=" + shouldDebugBreakFlag); if (shouldDebugBreakFlag) { try { Thread.sleep(3 * 1000); } catch (InterruptedException e1) { e1.printStackTrace(); } } } File envInFile = new File(debuggerSetupDirectory, portEnvInputFile); boolean envInFileFlag = envInFile.exists(); if (logger.isEnabled()) logger.write("envInFileFlag=" + envInFileFlag); if (envInFileFlag) { BufferedReader reader = null; try { reader = new BufferedReader(new FileReader(envInFile)); String line = reader.readLine(); int requestedPort; try { requestedPort = Integer.parseInt(line); } catch (NumberFormatException e) { requestedPort = INVALID_PORT; } w = new OutputStreamWriter(new FileOutputStream(envOutFile, true)); int localPort = (requestedPort != INVALID_PORT) ? requestedPort : getAvailablePort(); String strLocalPort = "PORT=" + localPort + "\n"; w.write(strLocalPort); port = currentPort = localPort; // enable(); debugBreak(); serverThread = new ServerThread(port); javaServerThread = new Thread(serverThread); javaServerThread.start(); } catch (IOException e1) { e1.printStackTrace(); } finally { if (reader != null) { try { reader.close(); } catch (IOException e) { e.printStackTrace(); } } if (w != null) { try { w.close(); } catch (IOException e) { e.printStackTrace(); } } envInFile.delete(); } } return port; } private static int getAvailablePort() { int port = 0; ServerSocket s = null; try { s = new ServerSocket(0); port = s.getLocalPort(); } catch (IOException e) { port = INVALID_PORT; } finally { if (s != null) { try { s.close(); } catch (IOException e) { } } } return port; } @RuntimeCallable private static void enqueueMessage(String message) { dbgMessages.add(message); } @RuntimeCallable private static void enableAgent(String packageName, int port, boolean waitForConnection) { enable(); if (serverThread == null) { serverThread = new ServerThread(port); } javaServerThread = new Thread(serverThread); javaServerThread.start(); } @RuntimeCallable private static void disableAgent() { disable(); if (serverThread != null) { serverThread.stop(); } } static void registerEnableDisableDebuggerReceiver(Context context) { String debugAction = context.getPackageName() + "-Debug"; context.registerReceiver(new BroadcastReceiver() { @Override public void onReceive(Context context, Intent intent) { Bundle bundle = intent.getExtras(); if (bundle != null) { boolean enable = bundle.getBoolean("enable", false); if (enable) { int port = bundle.getInt("debuggerPort", INVALID_PORT); if (port == INVALID_PORT) { if(currentPort == INVALID_PORT) { currentPort = getAvailablePort(); } port = currentPort; } String packageName = bundle.getString("packageName", context.getPackageName()); boolean waitForDebugger = bundle.getBoolean("waitForDebugger", false); JsDebugger.enableAgent(packageName, port, waitForDebugger); currentPort = port; this.setResultCode(currentPort); } else { // keep socket on the same port when we disable JsDebugger.disableAgent(); } } } }, new IntentFilter(debugAction)); } static void registerGetDebuggerPortReceiver(Context context) { String getDebuggerPortAction = context.getPackageName() + "-GetDbgPort"; context.registerReceiver(new BroadcastReceiver() { @Override public void onReceive(Context context, Intent intent) { this.setResultCode(currentPort); } }, new IntentFilter(getDebuggerPortAction)); } private boolean shouldDebugBreak() { if (shouldDebugBreakFlag != null) { return shouldDebugBreakFlag; } File debugBreakFile = new File(debuggerSetupDirectory, DEBUG_BREAK_FILENAME); shouldDebugBreakFlag = debugBreakFile.exists(); if (shouldDebugBreakFlag) { debugBreakFile.delete(); } } public static Boolean shouldDebugBreakFlag = null; public static boolean shouldDebugBreak(Context context) { if (shouldDebugBreakFlag != null) { return shouldDebugBreakFlag; } if (!shouldEnableDebugging(context)) { shouldDebugBreakFlag = false; return false; } File baseDir = context.getExternalFilesDir(null); File debugBreakFile = new File(baseDir, DEBUG_BREAK_FILENAME); if (debugBreakFile.exists()) { debugBreakFile.delete(); shouldDebugBreakFlag = true; return true; } shouldDebugBreakFlag = false; return false; } }
src/src/com/tns/JsDebugger.java
package com.tns; import java.io.BufferedReader; import java.io.File; import java.io.FileOutputStream; import java.io.FileReader; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import java.io.OutputStream; import java.io.OutputStreamWriter; import java.io.UnsupportedEncodingException; import java.net.ServerSocket; import java.net.Socket; import java.util.ArrayList; import java.util.NoSuchElementException; import java.util.Scanner; import java.util.concurrent.LinkedBlockingQueue; import android.content.BroadcastReceiver; import android.content.Context; import android.content.Intent; import android.content.IntentFilter; import android.os.Bundle; public class JsDebugger { private static native void processDebugMessages(); private static native void enable(); private static native void disable(); private static native void debugBreak(); private static native void sendCommand(byte[] command, int length); private static ThreadScheduler threadScheduler; private static final int INVALID_PORT = -1; private static final String portEnvInputFile = "envDebug.in"; private static final String portEnvOutputFile = "envDebug.out"; private static final String DEBUG_BREAK_FILENAME = "debugbreak"; private static int currentPort = INVALID_PORT; private static LinkedBlockingQueue<String> dbgMessages = new LinkedBlockingQueue<String>(); private final File debuggerSetupDirectory; private Boolean shouldDebugBreakFlag = null; private final Logger logger; public JsDebugger(Logger logger, ThreadScheduler threadScheduler, File debuggerSetupDirectory) { this.logger = logger; JsDebugger.threadScheduler = threadScheduler; this.debuggerSetupDirectory = debuggerSetupDirectory; } private static ServerSocket serverSocket; private static ServerThread serverThread = null; private static Thread javaServerThread = null; private static class ServerThread implements Runnable { private volatile boolean running; private final int port; private ResponseWorker responseWorker; private ListenerWorker commThread; public ServerThread(int port) { this.port = port; this.running = false; } public void stop() { this.running = false; this.responseWorker.stop(); try { serverSocket.close(); } catch (IOException e) { e.printStackTrace(); } } //when someone runs our server we do: public void run() { try { //open server port to run on serverSocket = new ServerSocket(this.port); running = true; } catch (IOException e) { running = false; e.printStackTrace(); } //start listening and responding through that socket while (running) { try { //wait for someone to connect to port and if he does ... open a socket Socket socket = serverSocket.accept(); //out (send messages to node inspector) this.responseWorker = new ResponseWorker(socket); new Thread(this.responseWorker).start(); //in (recieve messages from node inspector) commThread = new ListenerWorker(socket.getInputStream()); new Thread(commThread).start(); } catch (IOException e) { e.printStackTrace(); } } } } private static class ListenerWorker implements Runnable { private enum State { Header, Message } private BufferedReader input; public ListenerWorker(InputStream inputStream) { this.input = new BufferedReader(new InputStreamReader(inputStream)); } private volatile boolean running = true; public void run() { Scanner scanner = new Scanner(this.input); scanner.useDelimiter("\r\n"); ArrayList<String> headers = new ArrayList<String>(); String line; State state = State.Header; int messageLength = -1; String leftOver = null; Runnable dispatchProcessDebugMessages = new Runnable() { @Override public void run() { processDebugMessages(); } }; try { while (running && ((line = (leftOver != null) ? leftOver : scanner.nextLine()) != null)) { switch (state) { case Header: if (line.length() == 0) { state = State.Message; } else { headers.add(line); if (line.startsWith("Content-Length:")) { String strLen = line.substring(15).trim(); messageLength = Integer.parseInt(strLen); } if (leftOver != null) leftOver = null; } break; case Message: if ((-1 < messageLength) && (messageLength <= line.length())) { String msg = line.substring(0, messageLength); if (messageLength < line.length()) leftOver = line.substring(messageLength); state = State.Header; headers.clear(); try { byte[] cmdBytes = msg.getBytes("UTF-16LE"); int cmdLength = cmdBytes.length; sendCommand(cmdBytes, cmdLength); boolean success = JsDebugger.threadScheduler.post(dispatchProcessDebugMessages); assert success; } catch (UnsupportedEncodingException e) { // TODO Auto-generated catch block e.printStackTrace(); } } else { if (leftOver == null) { leftOver = line; } else { leftOver += line; } } break; } } } catch (NoSuchElementException e) { e.printStackTrace(); } finally { scanner.close(); } } } private static class ResponseWorker implements Runnable { private Socket socket; private final static String END_MSG = "#end#"; private OutputStream output; public ResponseWorker(Socket clientSocket) throws IOException { this.socket = clientSocket; this.output = this.socket.getOutputStream(); } public void stop() { dbgMessages.add(END_MSG); } @Override public void run() { byte[] LINE_END_BYTES = new byte[2]; LINE_END_BYTES[0] = (byte) '\r'; LINE_END_BYTES[1] = (byte) '\n'; while (true) { try { String msg = dbgMessages.take(); if (msg.equals(END_MSG)) break; byte[] utf8; try { utf8 = msg.getBytes("UTF8"); } catch (UnsupportedEncodingException e1) { utf8 = null; e1.printStackTrace(); } if (utf8 != null) { try { String s = "Content-Length: " + utf8.length; byte[] arr = s.getBytes("UTF8"); output.write(arr, 0, arr.length); output.write(LINE_END_BYTES, 0, LINE_END_BYTES.length); output.write(LINE_END_BYTES, 0, LINE_END_BYTES.length); output.write(utf8, 0, utf8.length); output.flush(); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } } } catch (InterruptedException e) { e.printStackTrace(); } } } } int getDebuggerPortFromEnvironment() { if (logger.isEnabled()) logger.write("getDebuggerPortFromEnvironment"); int port = INVALID_PORT; File envOutFile = new File(debuggerSetupDirectory, portEnvOutputFile); OutputStreamWriter w = null; try { w = new OutputStreamWriter(new FileOutputStream(envOutFile, false)); String currentPID = "PID=" + android.os.Process.myPid() + "\n"; w.write(currentPID); } catch (IOException e1) { e1.printStackTrace(); } finally { if (w != null) { try { w.close(); } catch (IOException e) { e.printStackTrace(); } } w = null; } boolean shouldDebugBreakFlag = shouldDebugBreak(); if (logger.isEnabled()) logger.write("shouldDebugBreakFlag=" + shouldDebugBreakFlag); if (shouldDebugBreakFlag) { { try { Thread.sleep(3 * 1000); } catch (InterruptedException e1) { e1.printStackTrace(); } } } File envInFile = new File(debuggerSetupDirectory, portEnvInputFile); boolean envInFileFlag = envInFile.exists(); if (logger.isEnabled()) logger.write("envInFileFlag=" + envInFileFlag); if (envInFileFlag) { BufferedReader reader = null; try { reader = new BufferedReader(new FileReader(envInFile)); String line = reader.readLine(); int requestedPort; try { requestedPort = Integer.parseInt(line); } catch (NumberFormatException e) { requestedPort = INVALID_PORT; } w = new OutputStreamWriter(new FileOutputStream(envOutFile, true)); int localPort = (requestedPort != INVALID_PORT) ? requestedPort : getAvailablePort(); String strLocalPort = "PORT=" + localPort + "\n"; w.write(strLocalPort); port = currentPort = localPort; // enable(); debugBreak(); serverThread = new ServerThread(port); javaServerThread = new Thread(serverThread); javaServerThread.start(); } catch (IOException e1) { e1.printStackTrace(); } finally { if (reader != null) { try { reader.close(); } catch (IOException e) { e.printStackTrace(); } } if (w != null) { try { w.close(); } catch (IOException e) { e.printStackTrace(); } } envInFile.delete(); } } return port; } private static int getAvailablePort() { int port = 0; ServerSocket s = null; try { s = new ServerSocket(0); port = s.getLocalPort(); } catch (IOException e) { port = INVALID_PORT; } finally { if (s != null) { try { s.close(); } catch (IOException e) { } } } return port; } @RuntimeCallable private static void enqueueMessage(String message) { dbgMessages.add(message); } @RuntimeCallable private static void enableAgent(String packageName, int port, boolean waitForConnection) { enable(); if (serverThread == null) { serverThread = new ServerThread(port); } javaServerThread = new Thread(serverThread); javaServerThread.start(); } @RuntimeCallable private static void disableAgent() { disable(); if (serverThread != null) { serverThread.stop(); } } static void registerEnableDisableDebuggerReceiver(Context context) { String debugAction = context.getPackageName() + "-Debug"; context.registerReceiver(new BroadcastReceiver() { @Override public void onReceive(Context context, Intent intent) { Bundle bundle = intent.getExtras(); if (bundle != null) { boolean enable = bundle.getBoolean("enable", false); if (enable) { int port = bundle.getInt("debuggerPort", INVALID_PORT); if (port == INVALID_PORT) { if(currentPort == INVALID_PORT) { currentPort = getAvailablePort(); } port = currentPort; } String packageName = bundle.getString("packageName", context.getPackageName()); boolean waitForDebugger = bundle.getBoolean("waitForDebugger", false); JsDebugger.enableAgent(packageName, port, waitForDebugger); currentPort = port; this.setResultCode(currentPort); } else { // keep socket on the same port when we disable JsDebugger.disableAgent(); } } } }, new IntentFilter(debugAction)); } static void registerGetDebuggerPortReceiver(Context context) { String getDebuggerPortAction = context.getPackageName() + "-GetDbgPort"; context.registerReceiver(new BroadcastReceiver() { @Override public void onReceive(Context context, Intent intent) { this.setResultCode(currentPort); } }, new IntentFilter(getDebuggerPortAction)); } private boolean shouldDebugBreak() { if (shouldDebugBreakFlag != null) { return shouldDebugBreakFlag; } File debugBreakFile = new File(debuggerSetupDirectory, DEBUG_BREAK_FILENAME); shouldDebugBreakFlag = debugBreakFile.exists(); if (shouldDebugBreakFlag) { debugBreakFile.delete(); } } public static Boolean shouldDebugBreakFlag = null; public static boolean shouldDebugBreak(Context context) { if (shouldDebugBreakFlag != null) { return shouldDebugBreakFlag; } if (!shouldEnableDebugging(context)) { shouldDebugBreakFlag = false; return false; } String appRoot = context.getFilesDir().getPath() + File.separator; File debugBreakFile = new File(appRoot, DEBUG_BREAK_FILENAME); if (debugBreakFile.exists()) { debugBreakFile.delete(); shouldDebugBreakFlag = true; return true; } shouldDebugBreakFlag = false; return false; } }
fix debugger
src/src/com/tns/JsDebugger.java
fix debugger
<ide><path>rc/src/com/tns/JsDebugger.java <ide> if (logger.isEnabled()) logger.write("shouldDebugBreakFlag=" + shouldDebugBreakFlag); <ide> <ide> if (shouldDebugBreakFlag) <del> { <del> { <add> { <add> <ide> try <ide> { <ide> Thread.sleep(3 * 1000); <ide> return false; <ide> } <ide> <del> String appRoot = context.getFilesDir().getPath() + File.separator; <del> File debugBreakFile = new File(appRoot, DEBUG_BREAK_FILENAME); <add> File baseDir = context.getExternalFilesDir(null); <add> File debugBreakFile = new File(baseDir, DEBUG_BREAK_FILENAME); <ide> if (debugBreakFile.exists()) <ide> { <ide> debugBreakFile.delete();
Java
mit
fdab972a79f2b53ff551c67c22fd3edca71ec4db
0
AndrewMiTe/realm-ruler
/* * MIT License * * Copyright (c) 2016 Andrew Michael Teller(https://github.com/AndrewMiTe) * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. */ package client; /** * Contains a phrase inputed by the client user that fulfills a requirement for * the client's continued operation. * @author Andrew M. Teller(https://github.com/AndrewMiTe) */ public class Phrase implements DataItem { /** * @see #setPhrase */ private String phrase = ""; /** * @see #setRequirement */ private RequiredInput requirement = null; public boolean isLegal() { assert phrase != null; return !phrase.isEmpty() && (requirement != null); } /** * @return prase property. * @see #setPhrase */ public String getPhrase() { assert phrase != null; return phrase; } /** * @param phrase text to meet the requirement. * @return this phrase. * @throws IllegalArgumentException if the given phrase is {@code null} or an * empty string. */ public Phrase setPhrase(String phrase) { if (phrase == null) throw new IllegalArgumentException("phrase: null"); if (phrase.isEmpty()) throw new IllegalArgumentException("phrase: empty"); this.phrase = phrase; return this; } @Override // from DataItem public RequiredInput getRequirement() { assert requirement != null; return requirement; } /** * @param requirement requirement that the text fulfills. * @return this phrase. * @throws IllegalArgumentException if the given requirement is {@code null}. */ public Phrase setRequirement(RequiredInput requirement) { if (requirement == null) throw new IllegalArgumentException("requirement: null"); this.requirement = requirement; return this; } }
src/client/Phrase.java
/* * MIT License * * Copyright (c) 2016 Andrew Michael Teller(https://github.com/AndrewMiTe) * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. */ package client; /** * Contains a phrase inputed by the client user that fulfills a requirement for * the client's continued operation. * @author Andrew M. Teller(https://github.com/AndrewMiTe) */ public class Phrase { /** * @see #setPhrase */ private String phrase = ""; /** * @see #setRequirement */ private RequiredInput requirement = null; public boolean isLegal() { assert phrase != null; return !phrase.isEmpty() && (requirement != null); } /** * @return prase property. * @see #setPhrase */ public String getPhrase() { assert phrase != null; return phrase; } /** * @param phrase text to meet the requirement. * @return this phrase. * @throws IllegalArgumentException if the given phrase is {@code null} or an * empty string. */ public Phrase setPhrase(String phrase) { if (phrase == null) throw new IllegalArgumentException("phrase: null"); if (phrase.isEmpty()) throw new IllegalArgumentException("phrase: empty"); this.phrase = phrase; return this; } /** * @return requirement property. * @see #setRequirement */ public RequiredInput getRequirement() { assert requirement != null; return requirement; } /** * @param requirement requirement that the text fulfills. * @return this phrase. * @throws IllegalArgumentException if the given requirement is {@code null}. */ public Phrase setRequirement(RequiredInput requirement) { if (requirement == null) throw new IllegalArgumentException("requirement: null"); this.requirement = requirement; return this; } }
Phrase implements DataItem
src/client/Phrase.java
Phrase implements DataItem
<ide><path>rc/client/Phrase.java <ide> * the client's continued operation. <ide> * @author Andrew M. Teller(https://github.com/AndrewMiTe) <ide> */ <del>public class Phrase { <add>public class Phrase implements DataItem { <ide> <ide> /** <ide> * @see #setPhrase <ide> return this; <ide> } <ide> <del> /** <del> * @return requirement property. <del> * @see #setRequirement <del> */ <add> @Override // from DataItem <ide> public RequiredInput getRequirement() { <ide> assert requirement != null; <ide> return requirement;
Java
apache-2.0
5b4ea8c5f03e9e2a840a4516b3ecb77c7651fe1a
0
rajapulau/qiscus-sdk-android,qiscus/qiscus-sdk-android
/* * Copyright (c) 2016 Qiscus. * * 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.qiscus.sdk.util; import android.app.Notification; import android.app.PendingIntent; import android.content.Context; import android.content.Intent; import android.graphics.Bitmap; import android.graphics.BitmapFactory; import android.graphics.drawable.Drawable; import android.media.RingtoneManager; import android.os.Build; import android.support.v4.app.NotificationCompat; import android.support.v4.app.NotificationManagerCompat; import android.support.v4.app.RemoteInput; import android.support.v4.content.ContextCompat; import android.support.v4.util.Pair; import android.text.TextUtils; import com.bumptech.glide.request.animation.GlideAnimation; import com.bumptech.glide.request.target.SimpleTarget; import com.qiscus.nirmana.Nirmana; import com.qiscus.sdk.Qiscus; import com.qiscus.sdk.R; import com.qiscus.sdk.data.local.QiscusCacheManager; import com.qiscus.sdk.data.model.QiscusChatRoom; import com.qiscus.sdk.data.model.QiscusComment; import com.qiscus.sdk.data.model.QiscusPushNotificationMessage; import com.qiscus.sdk.data.model.QiscusRoomMember; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; /** * Created on : June 15, 2017 * Author : zetbaitsu * Name : Zetra * GitHub : https://github.com/zetbaitsu */ public final class QiscusPushNotificationUtil { public static final String KEY_NOTIFICATION_REPLY = "KEY_NOTIFICATION_REPLY"; public static void handlePushNotification(Context context, QiscusComment qiscusComment) { QiscusAndroidUtil.runOnBackgroundThread(() -> handlePN(context, qiscusComment)); } private static void handlePN(Context context, QiscusComment qiscusComment) { if (Qiscus.getDataStore().isContains(qiscusComment)) { return; } if (Qiscus.getChatConfig().isEnablePushNotification() && !qiscusComment.getSenderEmail().equalsIgnoreCase(Qiscus.getQiscusAccount().getEmail())) { if (Qiscus.getChatConfig().isOnlyEnablePushNotificationOutsideChatRoom()) { Pair<Boolean, Integer> lastChatActivity = QiscusCacheManager.getInstance().getLastChatActivity(); if (!lastChatActivity.first || lastChatActivity.second != qiscusComment.getRoomId()) { showPushNotification(context, qiscusComment); } } else { showPushNotification(context, qiscusComment); } } } private static void showPushNotification(Context context, QiscusComment comment) { QiscusChatRoom room = Qiscus.getDataStore().getChatRoom(comment.getRoomId()); Map<String, QiscusRoomMember> members = new HashMap<>(); if (room != null) { for (QiscusRoomMember member : room.getMember()) { members.put(member.getEmail(), member); } } String messageText = comment.isGroupMessage() ? comment.getSender().split(" ")[0] + ": " : ""; if (comment.getType() == QiscusComment.Type.SYSTEM_EVENT) { messageText = ""; } switch (comment.getType()) { case IMAGE: messageText += "\uD83D\uDCF7 " + (TextUtils.isEmpty(comment.getCaption()) ? QiscusTextUtil.getString(R.string.qiscus_send_a_photo) : new QiscusSpannableBuilder(comment.getCaption(), members).build().toString()); break; case VIDEO: messageText += "\uD83C\uDFA5 " + (TextUtils.isEmpty(comment.getCaption()) ? QiscusTextUtil.getString(R.string.qiscus_send_a_video) : new QiscusSpannableBuilder(comment.getCaption(), members).build().toString()); break; case AUDIO: messageText += "\uD83D\uDD0A " + QiscusTextUtil.getString(R.string.qiscus_send_a_audio); break; case CONTACT: messageText += "\u260E " + QiscusTextUtil.getString(R.string.qiscus_contact) + ": " + comment.getContact().getName(); break; case LOCATION: messageText += "\uD83D\uDCCD " + comment.getMessage(); break; default: messageText += comment.isAttachment() ? "\uD83D\uDCC4 " + QiscusTextUtil.getString(R.string.qiscus_send_attachment) : new QiscusSpannableBuilder(comment.getMessage(), members).build().toString(); break; } if (!QiscusCacheManager.getInstance() .addMessageNotifItem(new QiscusPushNotificationMessage(comment.getId(), messageText), comment.getRoomId())) { return; } String finalMessageText = messageText; if (Qiscus.getChatConfig().isEnableAvatarAsNotificationIcon()) { QiscusAndroidUtil.runOnUIThread(() -> loadAvatar(context, comment, finalMessageText)); } else { pushNotification(context, comment, finalMessageText, BitmapFactory.decodeResource(context.getResources(), Qiscus.getChatConfig().getNotificationBigIcon())); } } private static void loadAvatar(Context context, QiscusComment comment, String finalMessageText) { Nirmana.getInstance().get() .load(comment.getRoomAvatar()) .asBitmap() .into(new SimpleTarget<Bitmap>() { @Override public void onResourceReady(Bitmap resource, GlideAnimation<? super Bitmap> glideAnimation) { QiscusAndroidUtil.runOnBackgroundThread(() -> { try { pushNotification(context, comment, finalMessageText, QiscusImageUtil.getCircularBitmap(resource)); } catch (Exception e) { pushNotification(context, comment, finalMessageText, BitmapFactory.decodeResource(context.getResources(), Qiscus.getChatConfig().getNotificationBigIcon())); } }); } @Override public void onLoadFailed(Exception e, Drawable errorDrawable) { super.onLoadFailed(e, errorDrawable); QiscusAndroidUtil.runOnBackgroundThread(() -> pushNotification(context, comment, finalMessageText, BitmapFactory.decodeResource(context.getResources(), Qiscus.getChatConfig().getNotificationBigIcon()))); } }); } private static void pushNotification(Context context, QiscusComment comment, String messageText, Bitmap largeIcon) { PendingIntent pendingIntent; Intent openIntent = new Intent("com.qiscus.OPEN_COMMENT_PN"); openIntent.putExtra("data", comment); pendingIntent = PendingIntent.getBroadcast(context, comment.getRoomId(), openIntent, PendingIntent.FLAG_CANCEL_CURRENT); NotificationCompat.Builder notificationBuilder = new NotificationCompat.Builder(context); notificationBuilder.setContentTitle(Qiscus.getChatConfig().getNotificationTitleHandler().getTitle(comment)) .setContentIntent(pendingIntent) .setContentText(messageText) .setTicker(messageText) .setSmallIcon(Qiscus.getChatConfig().getNotificationSmallIcon()) .setLargeIcon(largeIcon) .setColor(ContextCompat.getColor(context, Qiscus.getChatConfig().getInlineReplyColor())) .setGroupSummary(true) .setGroup("CHAT_NOTIF_" + comment.getRoomId()) .setAutoCancel(true) .setSound(RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION)); if (Qiscus.getChatConfig().isEnableReplyNotification() && Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) { String getRepliedTo = comment.getRoomName(); RemoteInput remoteInput = new RemoteInput.Builder(KEY_NOTIFICATION_REPLY) .setLabel(QiscusTextUtil.getString(R.string.qiscus_reply_to, getRepliedTo.toUpperCase())) .build(); NotificationCompat.Action replyAction = new NotificationCompat.Action.Builder(android.R.drawable.ic_menu_send, QiscusTextUtil.getString(R.string.qiscus_reply_to, getRepliedTo.toUpperCase()), pendingIntent) .addRemoteInput(remoteInput) .build(); notificationBuilder.addAction(replyAction); } boolean cancel = false; if (Qiscus.getChatConfig().getNotificationBuilderInterceptor() != null) { cancel = !Qiscus.getChatConfig().getNotificationBuilderInterceptor() .intercept(notificationBuilder, comment); } if (cancel) { return; } NotificationCompat.InboxStyle inboxStyle = new NotificationCompat.InboxStyle(); List<QiscusPushNotificationMessage> notifItems = QiscusCacheManager.getInstance() .getMessageNotifItems(comment.getRoomId()); if (notifItems == null) { notifItems = new ArrayList<>(); } int notifSize = 5; if (notifItems.size() < notifSize) { notifSize = notifItems.size(); } if (notifItems.size() > notifSize) { inboxStyle.addLine("......."); } int start = notifItems.size() - notifSize; for (int i = start; i < notifItems.size(); i++) { inboxStyle.addLine(notifItems.get(i).getMessage()); } inboxStyle.setSummaryText(QiscusTextUtil.getString(R.string.qiscus_notif_count, notifItems.size())); notificationBuilder.setStyle(inboxStyle); if (notifSize <= 3) { notificationBuilder.setPriority(Notification.PRIORITY_HIGH); } QiscusAndroidUtil.runOnUIThread(() -> NotificationManagerCompat.from(context) .notify(comment.getRoomId(), notificationBuilder.build())); } }
chat/src/main/java/com/qiscus/sdk/util/QiscusPushNotificationUtil.java
/* * Copyright (c) 2016 Qiscus. * * 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.qiscus.sdk.util; import android.app.Notification; import android.app.PendingIntent; import android.content.Context; import android.content.Intent; import android.graphics.Bitmap; import android.graphics.BitmapFactory; import android.graphics.drawable.Drawable; import android.media.RingtoneManager; import android.os.Build; import android.support.v4.app.NotificationCompat; import android.support.v4.app.NotificationManagerCompat; import android.support.v4.app.RemoteInput; import android.support.v4.content.ContextCompat; import android.support.v4.util.Pair; import android.text.TextUtils; import com.bumptech.glide.request.animation.GlideAnimation; import com.bumptech.glide.request.target.SimpleTarget; import com.qiscus.nirmana.Nirmana; import com.qiscus.sdk.Qiscus; import com.qiscus.sdk.R; import com.qiscus.sdk.data.local.QiscusCacheManager; import com.qiscus.sdk.data.model.QiscusChatRoom; import com.qiscus.sdk.data.model.QiscusComment; import com.qiscus.sdk.data.model.QiscusPushNotificationMessage; import com.qiscus.sdk.data.model.QiscusRoomMember; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; /** * Created on : June 15, 2017 * Author : zetbaitsu * Name : Zetra * GitHub : https://github.com/zetbaitsu */ public final class QiscusPushNotificationUtil { public static final String KEY_NOTIFICATION_REPLY = "KEY_NOTIFICATION_REPLY"; public static void handlePushNotification(Context context, QiscusComment qiscusComment) { QiscusAndroidUtil.runOnBackgroundThread(() -> handlePN(context, qiscusComment)); } private static void handlePN(Context context, QiscusComment qiscusComment) { if (Qiscus.getDataStore().isContains(qiscusComment)){ return; } if (Qiscus.getChatConfig().isEnablePushNotification() && !qiscusComment.getSenderEmail().equalsIgnoreCase(Qiscus.getQiscusAccount().getEmail())) { if (Qiscus.getChatConfig().isOnlyEnablePushNotificationOutsideChatRoom()) { Pair<Boolean, Integer> lastChatActivity = QiscusCacheManager.getInstance().getLastChatActivity(); if (!lastChatActivity.first || lastChatActivity.second != qiscusComment.getRoomId()) { showPushNotification(context, qiscusComment); } } else { showPushNotification(context, qiscusComment); } } } private static void showPushNotification(Context context, QiscusComment comment) { QiscusChatRoom room = Qiscus.getDataStore().getChatRoom(comment.getRoomId()); Map<String, QiscusRoomMember> members = new HashMap<>(); if (room != null) { for (QiscusRoomMember member : room.getMember()) { members.put(member.getEmail(), member); } } String messageText = comment.isGroupMessage() ? comment.getSender().split(" ")[0] + ": " : ""; if (comment.getType() == QiscusComment.Type.SYSTEM_EVENT) { messageText = ""; } switch (comment.getType()) { case IMAGE: messageText += "\uD83D\uDCF7 " + (TextUtils.isEmpty(comment.getCaption()) ? QiscusTextUtil.getString(R.string.qiscus_send_a_photo) : new QiscusSpannableBuilder(comment.getCaption(), members).build().toString()); break; case VIDEO: messageText += "\uD83C\uDFA5 " + (TextUtils.isEmpty(comment.getCaption()) ? QiscusTextUtil.getString(R.string.qiscus_send_a_video) : new QiscusSpannableBuilder(comment.getCaption(), members).build().toString()); break; case AUDIO: messageText += "\uD83D\uDD0A " + QiscusTextUtil.getString(R.string.qiscus_send_a_audio); break; case CONTACT: messageText += "\u260E " + QiscusTextUtil.getString(R.string.qiscus_contact) + ": " + comment.getContact().getName(); break; case LOCATION: messageText += "\uD83D\uDCCD " + comment.getMessage(); break; default: messageText += comment.isAttachment() ? "\uD83D\uDCC4 " + QiscusTextUtil.getString(R.string.qiscus_send_attachment) : new QiscusSpannableBuilder(comment.getMessage(), members).build().toString(); break; } if (!QiscusCacheManager.getInstance() .addMessageNotifItem(new QiscusPushNotificationMessage(comment.getId(), messageText), comment.getRoomId())) { return; } String finalMessageText = messageText; if (Qiscus.getChatConfig().isEnableAvatarAsNotificationIcon()) { QiscusAndroidUtil.runOnUIThread(() -> loadAvatar(context, comment, finalMessageText)); } else { pushNotification(context, comment, finalMessageText, BitmapFactory.decodeResource(context.getResources(), Qiscus.getChatConfig().getNotificationBigIcon())); } } private static void loadAvatar(Context context, QiscusComment comment, String finalMessageText) { Nirmana.getInstance().get() .load(comment.getRoomAvatar()) .asBitmap() .into(new SimpleTarget<Bitmap>() { @Override public void onResourceReady(Bitmap resource, GlideAnimation<? super Bitmap> glideAnimation) { QiscusAndroidUtil.runOnBackgroundThread(() -> { try { pushNotification(context, comment, finalMessageText, QiscusImageUtil.getCircularBitmap(resource)); } catch (Exception e) { pushNotification(context, comment, finalMessageText, BitmapFactory.decodeResource(context.getResources(), Qiscus.getChatConfig().getNotificationBigIcon())); } }); } @Override public void onLoadFailed(Exception e, Drawable errorDrawable) { super.onLoadFailed(e, errorDrawable); QiscusAndroidUtil.runOnBackgroundThread(() -> pushNotification(context, comment, finalMessageText, BitmapFactory.decodeResource(context.getResources(), Qiscus.getChatConfig().getNotificationBigIcon()))); } }); } private static void pushNotification(Context context, QiscusComment comment, String messageText, Bitmap largeIcon) { PendingIntent pendingIntent; Intent openIntent = new Intent("com.qiscus.OPEN_COMMENT_PN"); openIntent.putExtra("data", comment); pendingIntent = PendingIntent.getBroadcast(context, comment.getRoomId(), openIntent, PendingIntent.FLAG_CANCEL_CURRENT); NotificationCompat.Builder notificationBuilder = new NotificationCompat.Builder(context); notificationBuilder.setContentTitle(Qiscus.getChatConfig().getNotificationTitleHandler().getTitle(comment)) .setContentIntent(pendingIntent) .setContentText(messageText) .setTicker(messageText) .setSmallIcon(Qiscus.getChatConfig().getNotificationSmallIcon()) .setLargeIcon(largeIcon) .setColor(ContextCompat.getColor(context, Qiscus.getChatConfig().getInlineReplyColor())) .setGroupSummary(true) .setGroup("CHAT_NOTIF_" + comment.getRoomId()) .setAutoCancel(true) .setSound(RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION)); if (Qiscus.getChatConfig().isEnableReplyNotification() && Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) { String getRepliedTo = comment.getRoomName(); RemoteInput remoteInput = new RemoteInput.Builder(KEY_NOTIFICATION_REPLY) .setLabel(QiscusTextUtil.getString(R.string.qiscus_reply_to, getRepliedTo.toUpperCase())) .build(); NotificationCompat.Action replyAction = new NotificationCompat.Action.Builder(android.R.drawable.ic_menu_send, QiscusTextUtil.getString(R.string.qiscus_reply_to, getRepliedTo.toUpperCase()), pendingIntent) .addRemoteInput(remoteInput) .build(); notificationBuilder.addAction(replyAction); } boolean cancel = false; if (Qiscus.getChatConfig().getNotificationBuilderInterceptor() != null) { cancel = !Qiscus.getChatConfig().getNotificationBuilderInterceptor() .intercept(notificationBuilder, comment); } if (cancel) { return; } NotificationCompat.InboxStyle inboxStyle = new NotificationCompat.InboxStyle(); List<QiscusPushNotificationMessage> notifItems = QiscusCacheManager.getInstance() .getMessageNotifItems(comment.getRoomId()); if (notifItems == null) { notifItems = new ArrayList<>(); } int notifSize = 5; if (notifItems.size() < notifSize) { notifSize = notifItems.size(); } if (notifItems.size() > notifSize) { inboxStyle.addLine("......."); } int start = notifItems.size() - notifSize; for (int i = start; i < notifItems.size(); i++) { inboxStyle.addLine(notifItems.get(i).getMessage()); } inboxStyle.setSummaryText(QiscusTextUtil.getString(R.string.qiscus_notif_count, notifItems.size())); notificationBuilder.setStyle(inboxStyle); if (notifSize <= 3) { notificationBuilder.setPriority(Notification.PRIORITY_HIGH); } QiscusAndroidUtil.runOnUIThread(() -> NotificationManagerCompat.from(context) .notify(comment.getRoomId(), notificationBuilder.build())); } }
fixing checkstyle
chat/src/main/java/com/qiscus/sdk/util/QiscusPushNotificationUtil.java
fixing checkstyle
<ide><path>hat/src/main/java/com/qiscus/sdk/util/QiscusPushNotificationUtil.java <ide> } <ide> <ide> private static void handlePN(Context context, QiscusComment qiscusComment) { <del> if (Qiscus.getDataStore().isContains(qiscusComment)){ <add> if (Qiscus.getDataStore().isContains(qiscusComment)) { <ide> return; <ide> } <ide>
Java
mit
6b34536f9c1c67972d6ca4a91bba1e066ff2b80b
0
shallotsh/kylin,shallotsh/kylin,shallotsh/kylin
package org.kylin.util; import java.io.*; import java.text.Format; import java.util.ArrayList; import java.util.Collections; import java.util.List; import java.util.stream.Collectors; import freemarker.template.utility.StringUtil; import org.apache.commons.collections4.CollectionUtils; import org.apache.commons.lang3.StringUtils; import org.apache.poi.xwpf.usermodel.Borders; import org.apache.poi.xwpf.usermodel.BreakClear; import org.apache.poi.xwpf.usermodel.BreakType; import org.apache.poi.xwpf.usermodel.LineSpacingRule; import org.apache.poi.xwpf.usermodel.ParagraphAlignment; import org.apache.poi.xwpf.usermodel.TextAlignment; import org.apache.poi.xwpf.usermodel.UnderlinePatterns; import org.apache.poi.xwpf.usermodel.VerticalAlign; import org.apache.poi.xwpf.usermodel.XWPFDocument; import org.apache.poi.xwpf.usermodel.XWPFParagraph; import org.apache.poi.xwpf.usermodel.XWPFRun; import org.kylin.bean.W3DCode; import org.kylin.bean.WelfareCode; import org.kylin.bean.p5.WCode; import org.kylin.bean.p5.WCodeReq; import org.kylin.constant.ClassifyEnum; import org.kylin.constant.CodeTypeEnum; import org.slf4j.Logger; import org.slf4j.LoggerFactory; /** * @author huangyawu * @date 2017/7/16 下午3:57. * ref: http://svn.apache.org/repos/asf/poi/trunk/src/examples/src/org/apache/poi/xwpf/usermodel/examples/SimpleDocument.java * https://poi.apache.org/document/quick-guide-xwpf.html */ public class DocUtils { private static final Logger LOGGER = LoggerFactory.getLogger(DocUtils.class); private static final String BASE_PATH = "/var/attachment/"; public static void saveW3DCodes(WelfareCode welfareCode, OutputStream outputStream) throws IOException{ if(welfareCode == null || CollectionUtils.isEmpty(welfareCode.getW3DCodes())){ throw new IllegalArgumentException("参数错误"); } XWPFDocument doc = new XWPFDocument(); XWPFParagraph header = doc.createParagraph(); header.setVerticalAlignment(TextAlignment.TOP); header.setWordWrap(true); header.setAlignment(ParagraphAlignment.CENTER); XWPFRun hr1 = header.createRun(); hr1.setText(toUTF8("《我要发·518》福彩3D预测报表")); hr1.setBold(true); hr1.setUnderline(UnderlinePatterns.DOT_DOT_DASH); hr1.setTextPosition(20); hr1.setFontSize(28); hr1.addBreak(); XWPFRun hr2 = header.createRun(); hr2.setText(toUTF8("共计" + welfareCode.getW3DCodes().size() + "注3D码!!! 时间:" + CommonUtils.getCurrentDateString() + " 编码方式:" + welfareCode.getCodeTypeEnum().getDesc())); hr2.setTextPosition(10); hr2.setFontSize(18); List<W3DCode> pairCodes = TransferUtil.getPairCodes(welfareCode.getW3DCodes()); String title = String.format("对子共计 %d 注", pairCodes.size()); writeCodes(doc.createParagraph(), pairCodes, toUTF8(title)); List<W3DCode> nonPairCodes = TransferUtil.getNonPairCodes(welfareCode.getW3DCodes()); title = String.format("对子共计 %d 注", nonPairCodes.size()); writeCodes(doc.createParagraph(), nonPairCodes, toUTF8(title)); doc.write(outputStream); } public static String saveW3DCodes(WelfareCode welfareCode) throws IOException{ if(welfareCode == null || CollectionUtils.isEmpty(welfareCode.getW3DCodes())){ return ""; } String fileName = CommonUtils.getCurrentTimeString(); String subDirectory = fileName.substring(0,6); String targetDirName = BASE_PATH + subDirectory; if(!createDirIfNotExist(targetDirName)){ LOGGER.info("save-w3dCodes-create-directory-error targetDirName={}", targetDirName); throw new IOException("directory create error"); } XWPFDocument doc = new XWPFDocument(); XWPFParagraph header = doc.createParagraph(); header.setVerticalAlignment(TextAlignment.TOP); header.setWordWrap(true); header.setAlignment(ParagraphAlignment.CENTER); XWPFRun hr1 = header.createRun(); hr1.setText(toUTF8("《我要发·518》福彩3D预测报表")); hr1.setBold(true); hr1.setUnderline(UnderlinePatterns.DOT_DOT_DASH); hr1.setTextPosition(20); hr1.setFontSize(28); hr1.addBreak(); XWPFRun hr2 = header.createRun(); hr2.setText(toUTF8("共计" + welfareCode.getW3DCodes().size() + "注3D码!!! 时间:" + CommonUtils.getCurrentDateString() + " 编码方式:" + welfareCode.getCodeTypeEnum().getDesc())); hr2.setTextPosition(10); hr2.setFontSize(18); if(welfareCode.getW3DCodes().get(0).getClassify() != 0){ exportOneKeyStrategy(doc, welfareCode); }else{ exportNormal(doc, welfareCode); } // 保存 StringBuilder sb = new StringBuilder(); sb.append(targetDirName); sb.append(File.separator); sb.append(fileName); sb.append(".docx"); FileOutputStream out = new FileOutputStream(sb.toString()); doc.write(out); out.close(); return fileName + ".docx"; } private static void exportNormal(XWPFDocument doc, WelfareCode welfareCode){ List<W3DCode> w3DCodes = welfareCode.sort(WelfareCode::tailSort).generate().getW3DCodes(); List<W3DCode> repeatCodes = TransferUtil.findAllRepeatW3DCodes(w3DCodes); List<W3DCode> nonRepeatCodes = Encoders.minus(w3DCodes, repeatCodes, CodeTypeEnum.DIRECT); List<W3DCode> pairCodes = TransferUtil.getPairCodes(nonRepeatCodes); String title = String.format("对子不重叠部分 %d 注", pairCodes.size()); writeCodes(doc.createParagraph(), pairCodes, toUTF8(title)); List<W3DCode> repeatPairCodes = TransferUtil.getPairCodes(repeatCodes); title = String.format("对子重叠部分 %d 注", CollectionUtils.size(repeatPairCodes)); writeCodes(doc.createParagraph(), repeatPairCodes, toUTF8(title)); List<W3DCode> nonPairCodes = TransferUtil.getNonPairCodes(nonRepeatCodes); title = String.format("非对子不重叠共计 %d 注", nonPairCodes.size()); writeCodes(doc.createParagraph(), nonPairCodes, toUTF8(title)); List<W3DCode> repeatNonPairCodes = TransferUtil.getNonPairCodes(repeatCodes); title = String.format("非对子重叠部分 %d 注", CollectionUtils.size(repeatNonPairCodes)); writeCodes(doc.createParagraph(), repeatNonPairCodes, toUTF8(title)); // 输出组选 if(CodeTypeEnum.DIRECT.equals(welfareCode.getCodeTypeEnum())){ XWPFRun hr = doc.createParagraph().createRun(); hr.setFontSize(10); hr.setText("----------------------------------------------------------------------"); hr.addBreak(); List<W3DCode> groupRepeatPairCodes = TransferUtil.grouplize(repeatPairCodes); title = String.format("对子重叠部分(组选) %d 注", CollectionUtils.size(groupRepeatPairCodes)); writeCodes(doc.createParagraph(), groupRepeatPairCodes, toUTF8(title)); List<W3DCode> groupRepeatNonPairCodes = TransferUtil.grouplize(repeatNonPairCodes); title = String.format("非对子重叠部分 (组选) %d 注", CollectionUtils.size(groupRepeatNonPairCodes)); writeCodes(doc.createParagraph(), groupRepeatNonPairCodes, toUTF8(title)); } } private static void exportOneKeyStrategy(XWPFDocument doc, WelfareCode welfareCode){ List<W3DCode> w3DCodes = welfareCode.sort(WelfareCode::tailSort).generate().getW3DCodes(); // List<W3DCode> pairCodes = w3DCodes.stream().filter(w3DCode -> ClassifyEnum.PAIR_UNDERLAP.getIndex() == w3DCode.getClassify()).collect(Collectors.toList()); // String title = String.format("对子不重叠部分 %d 注", pairCodes.size()); // writeCodes(doc.createParagraph(), pairCodes, toUTF8(title)); List<W3DCode> repeatPairCodes = w3DCodes.stream().filter(w3DCode -> ClassifyEnum.PAIR_OVERLAP.getIndex() == w3DCode.getClassify()).collect(Collectors.toList()); String title = String.format("对子重叠部分 %d 注", CollectionUtils.size(repeatPairCodes)); writeCodes(doc.createParagraph(), repeatPairCodes, toUTF8(title)); // List<W3DCode> nonPairCodes = w3DCodes.stream().filter(w3DCode -> ClassifyEnum.NON_PAIR_UNDERLAP.getIndex() == w3DCode.getClassify()).collect(Collectors.toList()); // title = String.format("非对子不重叠共计 %d 注", nonPairCodes.size()); // writeCodes(doc.createParagraph(), nonPairCodes, toUTF8(title)); List<W3DCode> repeatNonPairCodes = w3DCodes.stream().filter(w3DCode -> ClassifyEnum.NON_PAIR_OVERLAP.getIndex() == w3DCode.getClassify()).collect(Collectors.toList()); title = String.format("非对子重叠部分 %d 注", CollectionUtils.size(repeatNonPairCodes)); writeCodes(doc.createParagraph(), repeatNonPairCodes, toUTF8(title)); // 输出组选 if(CodeTypeEnum.DIRECT.equals(welfareCode.getCodeTypeEnum())){ XWPFRun hr = doc.createParagraph().createRun(); hr.setFontSize(12); hr.setText("-------------------------------组选部分-----------------------------------"); hr.addBreak(); List<W3DCode> groupRepeatPairCodes = TransferUtil.grouplize(repeatPairCodes); title = String.format("对子重叠部分(组选) %d 注", CollectionUtils.size(groupRepeatPairCodes)); writeCodes(doc.createParagraph(), groupRepeatPairCodes, toUTF8(title)); List<W3DCode> groupRepeatNonPairCodes = TransferUtil.grouplize(repeatNonPairCodes); title = String.format("非对子重叠部分 (组选) %d 注", CollectionUtils.size(groupRepeatNonPairCodes)); writeCodes(doc.createParagraph(), groupRepeatNonPairCodes, toUTF8(title)); } } public static String saveWCodes(WCodeReq wCodeReq) throws IOException { if(wCodeReq == null || CollectionUtils.isEmpty(wCodeReq.getwCodes())){ return ""; } String fileName = CommonUtils.getCurrentTimeString(); String subDirectory = fileName.substring(0,6); String targetDirName = BASE_PATH + subDirectory; if(!createDirIfNotExist(targetDirName)){ LOGGER.info("save-wCodes-create-directory-error targetDirName={}", targetDirName); throw new IOException("directory create error"); } XWPFDocument doc = new XWPFDocument(); XWPFParagraph header = doc.createParagraph(); header.setVerticalAlignment(TextAlignment.TOP); header.setWordWrap(true); header.setAlignment(ParagraphAlignment.CENTER); XWPFRun hr1 = header.createRun(); hr1.setText(toUTF8("《我要发·排列5》福彩3D预测报表")); hr1.setBold(true); hr1.setUnderline(UnderlinePatterns.DOT_DOT_DASH); hr1.setTextPosition(20); hr1.setFontSize(28); hr1.addBreak(); XWPFRun hr2 = header.createRun(); hr2.setText(toUTF8("共计" + wCodeReq.getwCodes().size() + "注排列5码!!! 时间:" + CommonUtils.getCurrentDateString() )); hr2.setTextPosition(10); hr2.setFontSize(18); int randPairCount = 0; int nonRandPairCount = 0; List<WCode> pairCodes = WCodeUtils.filterPairCodes(wCodeReq.getwCodes()); if(!CollectionUtils.isEmpty(pairCodes)){ Collections.sort(pairCodes); String titleString = String.format("排列5码·对子( %d 注)", pairCodes.size()); exportWCodes(doc, pairCodes, titleString); randPairCount = pairCodes.size() > 10? 10: pairCodes.size(); } List<WCode> nonPairCodes = WCodeUtils.filterNonPairCodes(wCodeReq.getwCodes()); if(!CollectionUtils.isEmpty(nonPairCodes)){ Collections.sort(nonPairCodes); String titleString = String.format("排列5码·非对子( %d 注)", nonPairCodes.size()); exportWCodes(doc, nonPairCodes, titleString); nonRandPairCount = nonPairCodes.size() > 10? 10 : nonPairCodes.size(); } XWPFParagraph sep = doc.createParagraph(); XWPFRun hr3 = header.createRun(); hr3.setText(" "); hr3.addBreak(); List<WCode> nonRandPairCodes = WCodeUtils.getRandomList(nonPairCodes, nonRandPairCount); List<WCode> nCountRandPairCodes = WCodeUtils.getRandomList(nonPairCodes, 5); // List<WCode> randPairCodes = WCodeUtils.getRandomList(pairCodes, randPairCount); // if(!CollectionUtils.isEmpty(randPairCodes)){ // Collections.sort(randPairCodes); // String titleString = String.format("排列5码随机·对子( %d 注)", randPairCodes.size()); // exportWCodes(doc, randPairCodes, titleString); // } if(!CollectionUtils.isEmpty(nonRandPairCodes)){ Collections.sort(nonRandPairCodes); String titleString = String.format("排列5码随机·非对子( %d 注)", nonRandPairCodes.size()); exportWCodes(doc, nonRandPairCodes, titleString); } if(!CollectionUtils.isEmpty(nCountRandPairCodes)){ Collections.sort(nCountRandPairCodes); String titleString = String.format("排列5码随机·非对子( %d 注)", nCountRandPairCodes.size()); exportWCodes(doc, nCountRandPairCodes, titleString); } // List<WCode> firstAndlastNRowsInPairCodes = WCodeUtils.getFirstNRowsAndLastRowsInEveryPage(pairCodes,6, 22, 2); // List<WCode> firstAndlastNRowsInNonPairCodes = WCodeUtils.getFirstNRowsAndLastRowsInEveryPage(nonPairCodes,6, 22, 2); // // String firstAndLastRowsExport = String.format("排列5码首尾行( %d 注)", // (CollectionUtils.size(firstAndlastNRowsInNonPairCodes) + CollectionUtils.size(firstAndlastNRowsInPairCodes))); // exportWCodes(doc, firstAndlastNRowsInPairCodes, firstAndLastRowsExport); // exportWCodes(doc, firstAndlastNRowsInNonPairCodes, null); // 保存 StringBuilder sb = new StringBuilder(); sb.append(targetDirName); sb.append(File.separator); sb.append(fileName); sb.append(".docx"); FileOutputStream out = new FileOutputStream(sb.toString()); doc.write(out); out.close(); LOGGER.info("导出文件名: {}", sb.toString()); return fileName + ".docx"; } private static void exportWCodes(XWPFDocument doc, List<WCode> wCodes, String titleString){ if(CollectionUtils.isEmpty(wCodes)){ return; } XWPFParagraph paragraph = doc.createParagraph(); if(!StringUtils.isBlank(titleString)){ XWPFRun title = paragraph.createRun(); title.setFontSize(18); title.setBold(true); title.setText(toUTF8(titleString)); title.addBreak(); } XWPFRun hr = paragraph.createRun(); hr.setFontSize(10); hr.setText("----------------------------------------"); hr.addBreak(); XWPFRun content = paragraph.createRun(); content.setFontSize(14); for(WCode w3DCode : wCodes) { content.setText(w3DCode.getString() + " "); } content.addBreak(); content.setTextPosition(20); XWPFRun sep = paragraph.createRun(); sep.setTextPosition(50); } public static String saveWCodesHalf(WCodeReq wCodeReq) throws IOException { if(wCodeReq == null || CollectionUtils.isEmpty(wCodeReq.getwCodes())){ return ""; } String fileName = CommonUtils.getCurrentTimeString(); String subDirectory = fileName.substring(0,6); String targetDirName = BASE_PATH + subDirectory; if(!createDirIfNotExist(targetDirName)){ LOGGER.info("save-wCodes-create-directory-error targetDirName={}", targetDirName); throw new IOException("directory create error"); } XWPFDocument doc = new XWPFDocument(); XWPFParagraph header = doc.createParagraph(); header.setVerticalAlignment(TextAlignment.TOP); header.setWordWrap(true); header.setAlignment(ParagraphAlignment.CENTER); XWPFRun hr1 = header.createRun(); hr1.setText(toUTF8("《我要发·排列5》福彩3D预测报表(半页)")); hr1.setBold(true); hr1.setUnderline(UnderlinePatterns.DOT_DOT_DASH); hr1.setTextPosition(20); hr1.setFontSize(26); hr1.addBreak(); XWPFRun hr2 = header.createRun(); hr2.setText(toUTF8("共计" + wCodeReq.getwCodes().size() + "注排列5码!!! 时间:" + CommonUtils.getCurrentDateString() )); hr2.setTextPosition(10); hr2.setFontSize(16); List<WCode> nonPairCodes = WCodeUtils.filterNonPairCodes(wCodeReq.getwCodes()); List<WCode> halfPageCodes = WyfCollectionUtils.getSubList(nonPairCodes, 8, 4); if(!CollectionUtils.isEmpty(halfPageCodes)){ Collections.sort(halfPageCodes); String titleString = String.format("排列5码·半页码(非对子 %d 注)", halfPageCodes.size()); exportWCodes(doc, halfPageCodes, titleString); } // 保存 String prefix = "Half-"; StringBuilder sb = new StringBuilder(); sb.append(targetDirName); sb.append(File.separator); sb.append(prefix); sb.append(fileName); sb.append(".docx"); FileOutputStream out = new FileOutputStream(sb.toString()); doc.write(out); out.close(); LOGGER.info("导出文件名: {}", sb.toString()); return prefix + fileName + ".docx"; } public static void writeCodes(XWPFParagraph paragraph, List<W3DCode> w3DCodes, String titleString){ if(paragraph == null || CollectionUtils.isEmpty(w3DCodes)){ return; } XWPFRun title = paragraph.createRun(); title.setFontSize(18); title.setBold(true); title.setText(titleString); title.addBreak(); XWPFRun hr = paragraph.createRun(); hr.setFontSize(10); hr.setText("----------------------------------------"); hr.addBreak(); XWPFRun content = paragraph.createRun(); content.setFontSize(14); for(W3DCode w3DCode : w3DCodes) { content.setText(w3DCode.toString() + " "); } content.addBreak(); content.setTextPosition(20); XWPFRun sep = paragraph.createRun(); sep.setTextPosition(50); } public static void writeTitle(XWPFParagraph paragraph, String titleString){ paragraph.setPageBreak(true); XWPFRun title = paragraph.createRun(); title.setBold(true); title.setUnderline(UnderlinePatterns.DOT_DOT_DASH); title.setFontSize(24); title.setBold(true); title.setText(titleString); title.addBreak(); } public static boolean createDirIfNotExist(String destDirName) { File dir = new File(destDirName); if (dir.exists()) { return true; } if (!destDirName.endsWith(File.separator)) { destDirName = destDirName + File.separator; } //创建目录 if (dir.mkdirs()) { LOGGER.info("创建目录" + destDirName + "成功!"); return true; } else { LOGGER.info("创建目录" + destDirName + "失败!"); return false; } } public static String toUTF8(String str){ if(StringUtils.isBlank(str)){ return str; } LOGGER.info("target:{}", str); return str; // try { // return new String(str.getBytes(), "UTF-8"); // } catch (UnsupportedEncodingException e) { // return str; // } } public static void main(String[] args) throws Exception { WelfareCode welfareCode = new WelfareCode(); List<W3DCode> w3DCodes = new ArrayList<>(); W3DCode w3DCode = new W3DCode(2,3,5); w3DCodes.add(w3DCode); w3DCode = new W3DCode(2,3,5); w3DCodes.add(w3DCode); w3DCode = new W3DCode(2,2,5); w3DCodes.add(w3DCode); w3DCode = new W3DCode(2,1,5); w3DCodes.add(w3DCode); w3DCode = new W3DCode(1,3,5); w3DCodes.add(w3DCode); w3DCode = new W3DCode(1,2,5); w3DCodes.add(w3DCode); w3DCode = new W3DCode(1,1,5); w3DCodes.add(w3DCode); w3DCode = new W3DCode(2,3,4); w3DCodes.add(w3DCode); w3DCode = new W3DCode(2,2,4); w3DCodes.add(w3DCode); w3DCode = new W3DCode(2,1,4); w3DCodes.add(w3DCode); w3DCode = new W3DCode(2,3,6); w3DCodes.add(w3DCode); w3DCode = new W3DCode(2,2,6); w3DCodes.add(w3DCode); w3DCode = new W3DCode(2,1,6); w3DCodes.add(w3DCode); welfareCode.setW3DCodes(w3DCodes); String filePath = saveW3DCodes(welfareCode); LOGGER.info("file saved!!! path:{}", filePath); } }
src/main/java/org/kylin/util/DocUtils.java
package org.kylin.util; import java.io.*; import java.text.Format; import java.util.ArrayList; import java.util.Collections; import java.util.List; import java.util.stream.Collectors; import freemarker.template.utility.StringUtil; import org.apache.commons.collections4.CollectionUtils; import org.apache.commons.lang3.StringUtils; import org.apache.poi.xwpf.usermodel.Borders; import org.apache.poi.xwpf.usermodel.BreakClear; import org.apache.poi.xwpf.usermodel.BreakType; import org.apache.poi.xwpf.usermodel.LineSpacingRule; import org.apache.poi.xwpf.usermodel.ParagraphAlignment; import org.apache.poi.xwpf.usermodel.TextAlignment; import org.apache.poi.xwpf.usermodel.UnderlinePatterns; import org.apache.poi.xwpf.usermodel.VerticalAlign; import org.apache.poi.xwpf.usermodel.XWPFDocument; import org.apache.poi.xwpf.usermodel.XWPFParagraph; import org.apache.poi.xwpf.usermodel.XWPFRun; import org.kylin.bean.W3DCode; import org.kylin.bean.WelfareCode; import org.kylin.bean.p5.WCode; import org.kylin.bean.p5.WCodeReq; import org.kylin.constant.ClassifyEnum; import org.kylin.constant.CodeTypeEnum; import org.slf4j.Logger; import org.slf4j.LoggerFactory; /** * @author huangyawu * @date 2017/7/16 下午3:57. * ref: http://svn.apache.org/repos/asf/poi/trunk/src/examples/src/org/apache/poi/xwpf/usermodel/examples/SimpleDocument.java * https://poi.apache.org/document/quick-guide-xwpf.html */ public class DocUtils { private static final Logger LOGGER = LoggerFactory.getLogger(DocUtils.class); private static final String BASE_PATH = "/var/attachment/"; public static void saveW3DCodes(WelfareCode welfareCode, OutputStream outputStream) throws IOException{ if(welfareCode == null || CollectionUtils.isEmpty(welfareCode.getW3DCodes())){ throw new IllegalArgumentException("参数错误"); } XWPFDocument doc = new XWPFDocument(); XWPFParagraph header = doc.createParagraph(); header.setVerticalAlignment(TextAlignment.TOP); header.setWordWrap(true); header.setAlignment(ParagraphAlignment.CENTER); XWPFRun hr1 = header.createRun(); hr1.setText(toUTF8("《我要发·518》福彩3D预测报表")); hr1.setBold(true); hr1.setUnderline(UnderlinePatterns.DOT_DOT_DASH); hr1.setTextPosition(20); hr1.setFontSize(28); hr1.addBreak(); XWPFRun hr2 = header.createRun(); hr2.setText(toUTF8("共计" + welfareCode.getW3DCodes().size() + "注3D码!!! 时间:" + CommonUtils.getCurrentDateString() + " 编码方式:" + welfareCode.getCodeTypeEnum().getDesc())); hr2.setTextPosition(10); hr2.setFontSize(18); List<W3DCode> pairCodes = TransferUtil.getPairCodes(welfareCode.getW3DCodes()); String title = String.format("对子共计 %d 注", pairCodes.size()); writeCodes(doc.createParagraph(), pairCodes, toUTF8(title)); List<W3DCode> nonPairCodes = TransferUtil.getNonPairCodes(welfareCode.getW3DCodes()); title = String.format("对子共计 %d 注", nonPairCodes.size()); writeCodes(doc.createParagraph(), nonPairCodes, toUTF8(title)); doc.write(outputStream); } public static String saveW3DCodes(WelfareCode welfareCode) throws IOException{ if(welfareCode == null || CollectionUtils.isEmpty(welfareCode.getW3DCodes())){ return ""; } String fileName = CommonUtils.getCurrentTimeString(); String subDirectory = fileName.substring(0,6); String targetDirName = BASE_PATH + subDirectory; if(!createDirIfNotExist(targetDirName)){ LOGGER.info("save-w3dCodes-create-directory-error targetDirName={}", targetDirName); throw new IOException("directory create error"); } XWPFDocument doc = new XWPFDocument(); XWPFParagraph header = doc.createParagraph(); header.setVerticalAlignment(TextAlignment.TOP); header.setWordWrap(true); header.setAlignment(ParagraphAlignment.CENTER); XWPFRun hr1 = header.createRun(); hr1.setText(toUTF8("《我要发·518》福彩3D预测报表")); hr1.setBold(true); hr1.setUnderline(UnderlinePatterns.DOT_DOT_DASH); hr1.setTextPosition(20); hr1.setFontSize(28); hr1.addBreak(); XWPFRun hr2 = header.createRun(); hr2.setText(toUTF8("共计" + welfareCode.getW3DCodes().size() + "注3D码!!! 时间:" + CommonUtils.getCurrentDateString() + " 编码方式:" + welfareCode.getCodeTypeEnum().getDesc())); hr2.setTextPosition(10); hr2.setFontSize(18); if(welfareCode.getW3DCodes().get(0).getClassify() != 0){ exportOneKeyStrategy(doc, welfareCode); }else{ exportNormal(doc, welfareCode); } // 保存 StringBuilder sb = new StringBuilder(); sb.append(targetDirName); sb.append(File.separator); sb.append(fileName); sb.append(".docx"); FileOutputStream out = new FileOutputStream(sb.toString()); doc.write(out); out.close(); return fileName + ".docx"; } private static void exportNormal(XWPFDocument doc, WelfareCode welfareCode){ List<W3DCode> w3DCodes = welfareCode.sort(WelfareCode::tailSort).generate().getW3DCodes(); List<W3DCode> repeatCodes = TransferUtil.findAllRepeatW3DCodes(w3DCodes); List<W3DCode> nonRepeatCodes = Encoders.minus(w3DCodes, repeatCodes, CodeTypeEnum.DIRECT); List<W3DCode> pairCodes = TransferUtil.getPairCodes(nonRepeatCodes); String title = String.format("对子不重叠部分 %d 注", pairCodes.size()); writeCodes(doc.createParagraph(), pairCodes, toUTF8(title)); List<W3DCode> repeatPairCodes = TransferUtil.getPairCodes(repeatCodes); title = String.format("对子重叠部分 %d 注", CollectionUtils.size(repeatPairCodes)); writeCodes(doc.createParagraph(), repeatPairCodes, toUTF8(title)); List<W3DCode> nonPairCodes = TransferUtil.getNonPairCodes(nonRepeatCodes); title = String.format("非对子不重叠共计 %d 注", nonPairCodes.size()); writeCodes(doc.createParagraph(), nonPairCodes, toUTF8(title)); List<W3DCode> repeatNonPairCodes = TransferUtil.getNonPairCodes(repeatCodes); title = String.format("非对子重叠部分 %d 注", CollectionUtils.size(repeatNonPairCodes)); writeCodes(doc.createParagraph(), repeatNonPairCodes, toUTF8(title)); // 输出组选 if(CodeTypeEnum.DIRECT.equals(welfareCode.getCodeTypeEnum())){ XWPFRun hr = doc.createParagraph().createRun(); hr.setFontSize(10); hr.setText("----------------------------------------------------------------------"); hr.addBreak(); List<W3DCode> groupRepeatPairCodes = TransferUtil.grouplize(repeatPairCodes); title = String.format("对子重叠部分(组选) %d 注", CollectionUtils.size(groupRepeatPairCodes)); writeCodes(doc.createParagraph(), groupRepeatPairCodes, toUTF8(title)); List<W3DCode> groupRepeatNonPairCodes = TransferUtil.grouplize(repeatNonPairCodes); title = String.format("非对子重叠部分 (组选) %d 注", CollectionUtils.size(groupRepeatNonPairCodes)); writeCodes(doc.createParagraph(), groupRepeatNonPairCodes, toUTF8(title)); } } private static void exportOneKeyStrategy(XWPFDocument doc, WelfareCode welfareCode){ List<W3DCode> w3DCodes = welfareCode.sort(WelfareCode::tailSort).generate().getW3DCodes(); // List<W3DCode> pairCodes = w3DCodes.stream().filter(w3DCode -> ClassifyEnum.PAIR_UNDERLAP.getIndex() == w3DCode.getClassify()).collect(Collectors.toList()); // String title = String.format("对子不重叠部分 %d 注", pairCodes.size()); // writeCodes(doc.createParagraph(), pairCodes, toUTF8(title)); List<W3DCode> repeatPairCodes = w3DCodes.stream().filter(w3DCode -> ClassifyEnum.PAIR_OVERLAP.getIndex() == w3DCode.getClassify()).collect(Collectors.toList()); String title = String.format("对子重叠部分 %d 注", CollectionUtils.size(repeatPairCodes)); writeCodes(doc.createParagraph(), repeatPairCodes, toUTF8(title)); // List<W3DCode> nonPairCodes = w3DCodes.stream().filter(w3DCode -> ClassifyEnum.NON_PAIR_UNDERLAP.getIndex() == w3DCode.getClassify()).collect(Collectors.toList()); // title = String.format("非对子不重叠共计 %d 注", nonPairCodes.size()); // writeCodes(doc.createParagraph(), nonPairCodes, toUTF8(title)); List<W3DCode> repeatNonPairCodes = w3DCodes.stream().filter(w3DCode -> ClassifyEnum.NON_PAIR_OVERLAP.getIndex() == w3DCode.getClassify()).collect(Collectors.toList()); title = String.format("非对子重叠部分 %d 注", CollectionUtils.size(repeatNonPairCodes)); writeCodes(doc.createParagraph(), repeatNonPairCodes, toUTF8(title)); // 输出组选 if(CodeTypeEnum.DIRECT.equals(welfareCode.getCodeTypeEnum())){ XWPFRun hr = doc.createParagraph().createRun(); hr.setFontSize(12); hr.setText("-------------------------------组选部分-----------------------------------"); hr.addBreak(); List<W3DCode> groupRepeatPairCodes = TransferUtil.grouplize(repeatPairCodes); title = String.format("对子重叠部分(组选) %d 注", CollectionUtils.size(groupRepeatPairCodes)); writeCodes(doc.createParagraph(), groupRepeatPairCodes, toUTF8(title)); List<W3DCode> groupRepeatNonPairCodes = TransferUtil.grouplize(repeatNonPairCodes); title = String.format("非对子重叠部分 (组选) %d 注", CollectionUtils.size(groupRepeatNonPairCodes)); writeCodes(doc.createParagraph(), groupRepeatNonPairCodes, toUTF8(title)); } } public static String saveWCodes(WCodeReq wCodeReq) throws IOException { if(wCodeReq == null || CollectionUtils.isEmpty(wCodeReq.getwCodes())){ return ""; } String fileName = CommonUtils.getCurrentTimeString(); String subDirectory = fileName.substring(0,6); String targetDirName = BASE_PATH + subDirectory; if(!createDirIfNotExist(targetDirName)){ LOGGER.info("save-wCodes-create-directory-error targetDirName={}", targetDirName); throw new IOException("directory create error"); } XWPFDocument doc = new XWPFDocument(); XWPFParagraph header = doc.createParagraph(); header.setVerticalAlignment(TextAlignment.TOP); header.setWordWrap(true); header.setAlignment(ParagraphAlignment.CENTER); XWPFRun hr1 = header.createRun(); hr1.setText(toUTF8("《我要发·排列5》福彩3D预测报表")); hr1.setBold(true); hr1.setUnderline(UnderlinePatterns.DOT_DOT_DASH); hr1.setTextPosition(20); hr1.setFontSize(28); hr1.addBreak(); XWPFRun hr2 = header.createRun(); hr2.setText(toUTF8("共计" + wCodeReq.getwCodes().size() + "注排列5码!!! 时间:" + CommonUtils.getCurrentDateString() )); hr2.setTextPosition(10); hr2.setFontSize(18); int randPairCount = 0; int nonRandPairCount = 0; List<WCode> pairCodes = WCodeUtils.filterPairCodes(wCodeReq.getwCodes()); if(!CollectionUtils.isEmpty(pairCodes)){ Collections.sort(pairCodes); String titleString = String.format("排列5码·对子( %d 注)", pairCodes.size()); exportWCodes(doc, pairCodes, titleString); randPairCount = pairCodes.size() > 10? 10: pairCodes.size(); } List<WCode> nonPairCodes = WCodeUtils.filterNonPairCodes(wCodeReq.getwCodes()); if(!CollectionUtils.isEmpty(nonPairCodes)){ Collections.sort(nonPairCodes); String titleString = String.format("排列5码·非对子( %d 注)", nonPairCodes.size()); exportWCodes(doc, nonPairCodes, titleString); nonRandPairCount = nonPairCodes.size() > 10? 10 : nonPairCodes.size(); } XWPFParagraph sep = doc.createParagraph(); XWPFRun hr3 = header.createRun(); hr3.setText(" "); hr3.addBreak(); List<WCode> nonRandPairCodes = WCodeUtils.getRandomList(nonPairCodes, nonRandPairCount); List<WCode> nCountRandPairCodes = WCodeUtils.getRandomList(wCodeReq.getwCodes(), 5); // List<WCode> randPairCodes = WCodeUtils.getRandomList(pairCodes, randPairCount); // if(!CollectionUtils.isEmpty(randPairCodes)){ // Collections.sort(randPairCodes); // String titleString = String.format("排列5码随机·对子( %d 注)", randPairCodes.size()); // exportWCodes(doc, randPairCodes, titleString); // } if(!CollectionUtils.isEmpty(nonRandPairCodes)){ Collections.sort(nonRandPairCodes); String titleString = String.format("排列5码随机·非对子( %d 注)", nonRandPairCodes.size()); exportWCodes(doc, nonRandPairCodes, titleString); } if(!CollectionUtils.isEmpty(nCountRandPairCodes)){ Collections.sort(nCountRandPairCodes); String titleString = String.format("排列5码随机·全部( %d 注)", nCountRandPairCodes.size()); exportWCodes(doc, nCountRandPairCodes, titleString); } // List<WCode> firstAndlastNRowsInPairCodes = WCodeUtils.getFirstNRowsAndLastRowsInEveryPage(pairCodes,6, 22, 2); // List<WCode> firstAndlastNRowsInNonPairCodes = WCodeUtils.getFirstNRowsAndLastRowsInEveryPage(nonPairCodes,6, 22, 2); // // String firstAndLastRowsExport = String.format("排列5码首尾行( %d 注)", // (CollectionUtils.size(firstAndlastNRowsInNonPairCodes) + CollectionUtils.size(firstAndlastNRowsInPairCodes))); // exportWCodes(doc, firstAndlastNRowsInPairCodes, firstAndLastRowsExport); // exportWCodes(doc, firstAndlastNRowsInNonPairCodes, null); // 保存 StringBuilder sb = new StringBuilder(); sb.append(targetDirName); sb.append(File.separator); sb.append(fileName); sb.append(".docx"); FileOutputStream out = new FileOutputStream(sb.toString()); doc.write(out); out.close(); LOGGER.info("导出文件名: {}", sb.toString()); return fileName + ".docx"; } private static void exportWCodes(XWPFDocument doc, List<WCode> wCodes, String titleString){ if(CollectionUtils.isEmpty(wCodes)){ return; } XWPFParagraph paragraph = doc.createParagraph(); if(!StringUtils.isBlank(titleString)){ XWPFRun title = paragraph.createRun(); title.setFontSize(18); title.setBold(true); title.setText(toUTF8(titleString)); title.addBreak(); } XWPFRun hr = paragraph.createRun(); hr.setFontSize(10); hr.setText("----------------------------------------"); hr.addBreak(); XWPFRun content = paragraph.createRun(); content.setFontSize(14); for(WCode w3DCode : wCodes) { content.setText(w3DCode.getString() + " "); } content.addBreak(); content.setTextPosition(20); XWPFRun sep = paragraph.createRun(); sep.setTextPosition(50); } public static String saveWCodesHalf(WCodeReq wCodeReq) throws IOException { if(wCodeReq == null || CollectionUtils.isEmpty(wCodeReq.getwCodes())){ return ""; } String fileName = CommonUtils.getCurrentTimeString(); String subDirectory = fileName.substring(0,6); String targetDirName = BASE_PATH + subDirectory; if(!createDirIfNotExist(targetDirName)){ LOGGER.info("save-wCodes-create-directory-error targetDirName={}", targetDirName); throw new IOException("directory create error"); } XWPFDocument doc = new XWPFDocument(); XWPFParagraph header = doc.createParagraph(); header.setVerticalAlignment(TextAlignment.TOP); header.setWordWrap(true); header.setAlignment(ParagraphAlignment.CENTER); XWPFRun hr1 = header.createRun(); hr1.setText(toUTF8("《我要发·排列5》福彩3D预测报表(半页)")); hr1.setBold(true); hr1.setUnderline(UnderlinePatterns.DOT_DOT_DASH); hr1.setTextPosition(20); hr1.setFontSize(26); hr1.addBreak(); XWPFRun hr2 = header.createRun(); hr2.setText(toUTF8("共计" + wCodeReq.getwCodes().size() + "注排列5码!!! 时间:" + CommonUtils.getCurrentDateString() )); hr2.setTextPosition(10); hr2.setFontSize(16); List<WCode> halfPageCodes = WyfCollectionUtils.getSubList(wCodeReq.getwCodes(), 8, 4); if(!CollectionUtils.isEmpty(halfPageCodes)){ Collections.sort(halfPageCodes); String titleString = String.format("排列5码·半页码( %d 注)", halfPageCodes.size()); exportWCodes(doc, halfPageCodes, titleString); } // 保存 String prefix = "Half-"; StringBuilder sb = new StringBuilder(); sb.append(targetDirName); sb.append(File.separator); sb.append(prefix); sb.append(fileName); sb.append(".docx"); FileOutputStream out = new FileOutputStream(sb.toString()); doc.write(out); out.close(); LOGGER.info("导出文件名: {}", sb.toString()); return prefix + fileName + ".docx"; } public static void writeCodes(XWPFParagraph paragraph, List<W3DCode> w3DCodes, String titleString){ if(paragraph == null || CollectionUtils.isEmpty(w3DCodes)){ return; } XWPFRun title = paragraph.createRun(); title.setFontSize(18); title.setBold(true); title.setText(titleString); title.addBreak(); XWPFRun hr = paragraph.createRun(); hr.setFontSize(10); hr.setText("----------------------------------------"); hr.addBreak(); XWPFRun content = paragraph.createRun(); content.setFontSize(14); for(W3DCode w3DCode : w3DCodes) { content.setText(w3DCode.toString() + " "); } content.addBreak(); content.setTextPosition(20); XWPFRun sep = paragraph.createRun(); sep.setTextPosition(50); } public static void writeTitle(XWPFParagraph paragraph, String titleString){ paragraph.setPageBreak(true); XWPFRun title = paragraph.createRun(); title.setBold(true); title.setUnderline(UnderlinePatterns.DOT_DOT_DASH); title.setFontSize(24); title.setBold(true); title.setText(titleString); title.addBreak(); } public static boolean createDirIfNotExist(String destDirName) { File dir = new File(destDirName); if (dir.exists()) { return true; } if (!destDirName.endsWith(File.separator)) { destDirName = destDirName + File.separator; } //创建目录 if (dir.mkdirs()) { LOGGER.info("创建目录" + destDirName + "成功!"); return true; } else { LOGGER.info("创建目录" + destDirName + "失败!"); return false; } } public static String toUTF8(String str){ if(StringUtils.isBlank(str)){ return str; } LOGGER.info("target:{}", str); return str; // try { // return new String(str.getBytes(), "UTF-8"); // } catch (UnsupportedEncodingException e) { // return str; // } } public static void main(String[] args) throws Exception { WelfareCode welfareCode = new WelfareCode(); List<W3DCode> w3DCodes = new ArrayList<>(); W3DCode w3DCode = new W3DCode(2,3,5); w3DCodes.add(w3DCode); w3DCode = new W3DCode(2,3,5); w3DCodes.add(w3DCode); w3DCode = new W3DCode(2,2,5); w3DCodes.add(w3DCode); w3DCode = new W3DCode(2,1,5); w3DCodes.add(w3DCode); w3DCode = new W3DCode(1,3,5); w3DCodes.add(w3DCode); w3DCode = new W3DCode(1,2,5); w3DCodes.add(w3DCode); w3DCode = new W3DCode(1,1,5); w3DCodes.add(w3DCode); w3DCode = new W3DCode(2,3,4); w3DCodes.add(w3DCode); w3DCode = new W3DCode(2,2,4); w3DCodes.add(w3DCode); w3DCode = new W3DCode(2,1,4); w3DCodes.add(w3DCode); w3DCode = new W3DCode(2,3,6); w3DCodes.add(w3DCode); w3DCode = new W3DCode(2,2,6); w3DCodes.add(w3DCode); w3DCode = new W3DCode(2,1,6); w3DCodes.add(w3DCode); welfareCode.setW3DCodes(w3DCodes); String filePath = saveW3DCodes(welfareCode); LOGGER.info("file saved!!! path:{}", filePath); } }
修改随机5注和半页导出为非对子
src/main/java/org/kylin/util/DocUtils.java
修改随机5注和半页导出为非对子
<ide><path>rc/main/java/org/kylin/util/DocUtils.java <ide> hr3.addBreak(); <ide> <ide> List<WCode> nonRandPairCodes = WCodeUtils.getRandomList(nonPairCodes, nonRandPairCount); <del> List<WCode> nCountRandPairCodes = WCodeUtils.getRandomList(wCodeReq.getwCodes(), 5); <add> List<WCode> nCountRandPairCodes = WCodeUtils.getRandomList(nonPairCodes, 5); <ide> // List<WCode> randPairCodes = WCodeUtils.getRandomList(pairCodes, randPairCount); <ide> <ide> // if(!CollectionUtils.isEmpty(randPairCodes)){ <ide> <ide> if(!CollectionUtils.isEmpty(nCountRandPairCodes)){ <ide> Collections.sort(nCountRandPairCodes); <del> String titleString = String.format("排列5码随机·全部( %d 注)", nCountRandPairCodes.size()); <add> String titleString = String.format("排列5码随机·非对子( %d 注)", nCountRandPairCodes.size()); <ide> exportWCodes(doc, nCountRandPairCodes, titleString); <ide> } <ide> <ide> hr2.setTextPosition(10); <ide> hr2.setFontSize(16); <ide> <del> List<WCode> halfPageCodes = WyfCollectionUtils.getSubList(wCodeReq.getwCodes(), 8, 4); <add> List<WCode> nonPairCodes = WCodeUtils.filterNonPairCodes(wCodeReq.getwCodes()); <add> <add> List<WCode> halfPageCodes = WyfCollectionUtils.getSubList(nonPairCodes, 8, 4); <ide> if(!CollectionUtils.isEmpty(halfPageCodes)){ <ide> Collections.sort(halfPageCodes); <del> String titleString = String.format("排列5码·半页码( %d 注)", halfPageCodes.size()); <add> String titleString = String.format("排列5码·半页码(非对子 %d 注)", halfPageCodes.size()); <ide> exportWCodes(doc, halfPageCodes, titleString); <ide> } <ide>
Java
bsd-3-clause
05470aeeb217731a3ea05d9d0f6bf10e2f8622fc
0
NCIP/cadsr-semantic-tools,NCIP/cadsr-semantic-tools
/* * Copyright 2000-2003 Oracle, Inc. This software was developed in conjunction with the National Cancer Institute, and so to the extent government employees are co-authors, any rights in such works shall be subject to Title 17 of the United States Code, section 105. * Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: * * 1. Redistributions of source code must retain the above copyright notice, this list of conditions and the disclaimer of Article 3, below. Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. * * 2. The end-user documentation included with the redistribution, if any, must include the following acknowledgment: * * "This product includes software developed by Oracle, Inc. and the National Cancer Institute." * * If no such end-user documentation is to be included, this acknowledgment shall appear in the software itself, wherever such third-party acknowledgments normally appear. * * 3. The names "The National Cancer Institute", "NCI" and "Oracle" must not be used to endorse or promote products derived from this software. * * 4. This license does not authorize the incorporation of this software into any proprietary programs. This license does not authorize the recipient to use any trademarks owned by either NCI or Oracle, Inc. * * 5. THIS SOFTWARE IS PROVIDED "AS IS," AND ANY EXPRESSED OR IMPLIED WARRANTIES, (INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE) ARE DISCLAIMED. IN NO EVENT SHALL THE NATIONAL CANCER INSTITUTE, ORACLE, OR THEIR AFFILIATES BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE */ package gov.nih.nci.ncicb.cadsr.loader.ui.tree; import gov.nih.nci.ncicb.cadsr.domain.*; import gov.nih.nci.ncicb.cadsr.loader.defaults.UMLDefaults; import gov.nih.nci.ncicb.cadsr.loader.*; import gov.nih.nci.ncicb.cadsr.loader.validator.*; import gov.nih.nci.ncicb.cadsr.loader.util.*; import gov.nih.nci.ncicb.cadsr.loader.ui.event.*; import gov.nih.nci.ncicb.cadsr.loader.ReviewTracker; import java.util.*; public class TreeBuilder implements UserPreferencesListener { private ElementsLists elements; private UMLDefaults defaults = UMLDefaults.getInstance(); private UMLNode rootNode; private List<TreeListener> treeListeners = new ArrayList<TreeListener>(); private boolean inClassAssociations = false, showAssociations = true, showValueDomains = true, showInheritedAttributes = false; private ReviewTracker reviewTracker; private static TreeBuilder instance = new TreeBuilder(); private TreeBuilder() { RunMode runMode = (RunMode)(UserSelections.getInstance().getProperty("MODE")); if(runMode.equals(RunMode.Curator)) { reviewTracker = ReviewTracker.getInstance(ReviewTrackerType.Curator); } else { reviewTracker = ReviewTracker.getInstance(ReviewTrackerType.Owner); } } public static TreeBuilder getInstance() { return instance; } public void init() { UserPreferences prefs = UserPreferences.getInstance(); prefs.addUserPreferencesListener(this); UserSelections selections = UserSelections.getInstance(); inClassAssociations = new Boolean (prefs.getViewAssociationType()); // only show association node in Review Mode showAssociations = selections.getProperty("MODE").equals(RunMode.Reviewer)|| selections.getProperty("MODE").equals(RunMode.UnannotatedXmi); //showValueDomains = !selections.getProperty("MODE").equals(RunMode.Curator); showInheritedAttributes = prefs.getShowInheritedAttributes(); } public UMLNode buildTree(ElementsLists elements) { this.elements = elements; rootNode = new RootNode(); doPackages(rootNode); if(showValueDomains) { UMLNode vdNode = new PackageNode("Value Domain", "Value Domains"); doValueDomains(vdNode); if(vdNode.getChildren().size() > 0) rootNode.addChild(vdNode); } if(!inClassAssociations && showAssociations) doAssociations(rootNode); return rootNode; } /** * * @return the root node */ public UMLNode getRootNode() { return rootNode; } private List<ValidationItem> findValidationItems(Object o) { List<ValidationItem> result = new ArrayList<ValidationItem>(); ValidationItems items = ValidationItems.getInstance(); Set<ValidationError> errors = items.getErrors(); for(ValidationError error : errors) { if(error.getRootCause() == o) result.add(error); } Set<ValidationWarning> warnings = items.getWarnings(); for(ValidationWarning warning : warnings) { if(warning.getRootCause() == o) result.add(warning); } return result; } private void doPackages(UMLNode parentNode) { ClassificationSchemeItem pkg = DomainObjectFactory.newClassificationSchemeItem(); List<ClassificationSchemeItem> packages = elements.getElements(pkg); for(ClassificationSchemeItem pack : packages) { String alias = defaults.getPackageDisplay(pack.getLongName()); UMLNode node = new PackageNode(pack, alias); parentNode.addChild(node); List<ValidationItem> items = findValidationItems(pack); for(ValidationItem item : items) { ValidationNode vNode = null; if (item instanceof ValidationWarning) { vNode = new WarningNode(item); } else { vNode = new ErrorNode(item); } node.addValidationNode(vNode); } doClasses(node); } } private void doClasses(UMLNode parentNode) { // Find all classes which are in this package String packageName = parentNode.getFullPath(); ObjectClass oc = DomainObjectFactory.newObjectClass(); List<ObjectClass> ocs = elements.getElements(oc); for(ObjectClass o : ocs) { String className = null; for(AlternateName an : o.getAlternateNames()) { if(an.getType().equals(AlternateName.TYPE_CLASS_FULL_NAME)) className = an.getName(); } int ind = className.lastIndexOf("."); packageName = className.substring(0, ind); if(packageName.equals(parentNode.getFullPath())) { UMLNode node = new ClassNode(o); parentNode.addChild(node); ((ClassNode) node).setReviewed( reviewTracker.get(node.getFullPath())); doAttributes(node); if(inClassAssociations && showAssociations) doAssociations(node,o); List<ValidationItem> items = findValidationItems(o); for(ValidationItem item : items) { ValidationNode vNode = null; if (item instanceof ValidationWarning) { vNode = new WarningNode(item); } else { vNode = new ErrorNode(item); } node.addValidationNode(vNode); } } } } private void doAttributes(UMLNode parentNode) { // Find all DEs that have this OC. DataElement o = DomainObjectFactory.newDataElement(); List<DataElement> des = elements.getElements(o); List<AttributeNode> inherited = new ArrayList<AttributeNode>(); PackageNode inheritedPackage = new PackageNode("Inherited Attributes", "Inherited Attributes", true); InheritedAttributeList inheritedList = InheritedAttributeList.getInstance(); for(DataElement de : des) { try { String fullClassName = null; for(AlternateName an : de.getDataElementConcept().getObjectClass().getAlternateNames()) { if(an.getType().equals(AlternateName.TYPE_CLASS_FULL_NAME)) fullClassName = an.getName(); } if(fullClassName.equals(parentNode.getFullPath())) { UMLNode node = new AttributeNode(de); Boolean reviewed = reviewTracker.get(node.getFullPath()); if(inheritedList.isInherited(de)) { node = new InheritedAttributeNode(de); inherited.add((InheritedAttributeNode)node); } else { parentNode.addChild(node); ((AttributeNode) node).setReviewed(reviewed); } List<ValidationItem> items = findValidationItems(de.getDataElementConcept().getProperty()); for(ValidationItem item : items) { ValidationNode vNode = null; if (item instanceof ValidationWarning) { vNode = new WarningNode(item); } else { vNode = new ErrorNode(item); } node.addValidationNode(vNode); } items = findValidationItems(de); for(ValidationItem item : items) { ValidationNode vNode = null; if (item instanceof ValidationWarning) { vNode = new WarningNode(item); } else { vNode = new ErrorNode(item); } node.addValidationNode(vNode); } } } catch (NullPointerException e){ e.printStackTrace(); } // end of try-catch } if((inherited.size() > 0)) parentNode.addChild(inheritedPackage); for(AttributeNode inherit : inherited) { inheritedPackage.addChild(inherit); Boolean reviewed = reviewTracker.get(inherit.getFullPath()); if(reviewed != null) inherit.setReviewed(reviewed); } // if((inherited.size() > 0) && showInheritedAttributes) // parentNode.addChild(inheritedPackage); // if(showInheritedAttributes) { // for(AttributeNode inherit : inherited) { // inheritedPackage.addChild(inherit); // Boolean reviewed = reviewTracker.get(inherit.getFullPath()); // if(reviewed != null) // inherit.setReviewed(reviewed); // } // } } private void doValueDomains(UMLNode parentNode) { List<ValueDomain> vds = elements.getElements(DomainObjectFactory.newValueDomain()); for(ValueDomain vd : vds) { ValueDomainNode node = new ValueDomainNode(vd); parentNode.addChild(node); node.setReviewed (reviewTracker.get(LookupUtil.lookupFullName(vd))); doValueMeanings(node); List<ValidationItem> items = findValidationItems(vd); for(ValidationItem item : items) { ValidationNode vNode = null; if (item instanceof ValidationWarning) { vNode = new WarningNode(item); } else { vNode = new ErrorNode(item); } node.addValidationNode(vNode); } } } private void doValueMeanings(UMLNode parentNode) { // Find all DEs that have this OC. List<ValueMeaning> vms = elements.getElements(DomainObjectFactory.newValueMeaning()); ValueDomainNode vdNode = (ValueDomainNode)parentNode; ValueDomain parentVD = (ValueDomain)vdNode.getUserObject(); String vdFullName = LookupUtil.lookupFullName(parentVD); for(ValueMeaning vm : vms) { try { if(isInValueDomain(vdFullName, vm)) { UMLNode node = new ValueMeaningNode(vm, vdFullName); Boolean reviewed = reviewTracker.get(node.getFullPath()); if(reviewed != null) { parentNode.addChild(node); ((ValueMeaningNode) node).setReviewed(reviewed); } List<ValidationItem> items = findValidationItems(vm); for(ValidationItem item : items) { ValidationNode vNode = null; if (item instanceof ValidationWarning) { vNode = new WarningNode(item); } else { vNode = new ErrorNode(item); } node.addValidationNode(vNode); } } } catch (NullPointerException e){ e.printStackTrace(); } // end of try-catch } } private void doAssociations(UMLNode parentNode) { UMLNode assocNode = new PackageNode("Associations", "Associations"); ObjectClassRelationship o = DomainObjectFactory.newObjectClassRelationship(); List<ObjectClassRelationship> ocrs = elements.getElements(o); for(ObjectClassRelationship ocr : ocrs) { AssociationNode node = new AssociationNode(ocr); Boolean reviewed = reviewTracker.get(node.getFullPath()); if (reviewed != null) { node.setReviewed(reviewed.booleanValue()); } List<ValidationItem> items = findValidationItems(ocr); for(ValidationItem item : items) { ValidationNode vNode = null; if (item instanceof ValidationWarning) { vNode = new WarningNode(item); } else { vNode = new ErrorNode(item); } node.addValidationNode(vNode); } assocNode.addChild(node); doAssociationEnd(node, AssociationEndNode.TYPE_SOURCE); doAssociationEnd(node, AssociationEndNode.TYPE_TARGET); } parentNode.addChild(assocNode); } private void doAssociationEnd(UMLNode parentNode, int type) { ObjectClassRelationship ocr = (ObjectClassRelationship)parentNode.getUserObject(); AssociationEndNode node = new AssociationEndNode(ocr, type); Boolean reviewed = reviewTracker.get(node.getFullPath()); if (reviewed != null) { node.setReviewed(reviewed.booleanValue()); } // List<ValidationItem> items = findValidationItems(ocr); // for(ValidationItem item : items) { // ValidationNode vNode = null; // if (item instanceof ValidationWarning) { // vNode = new WarningNode(item); // } else { // vNode = new ErrorNode(item); // } // node.addValidationNode(vNode); // } parentNode.addChild(node); } private void doAssociations(UMLNode parentNode, ObjectClass oc) { UMLNode assocNode = new PackageNode("Associations for " + oc.getLongName(), "Associations"); ObjectClassRelationship o = DomainObjectFactory.newObjectClassRelationship(); List<ObjectClassRelationship> ocrs = elements.getElements(o); for(ObjectClassRelationship ocr : ocrs) { if(ocr.getSource().getLongName().equals(oc.getLongName()) | ocr.getTarget().getLongName().equals(oc.getLongName())) { UMLNode node = new AssociationNode(ocr); List<ValidationItem> items = findValidationItems(ocr); for(ValidationItem item : items) { ValidationNode vNode = null; if (item instanceof ValidationWarning) { vNode = new WarningNode(item); } else { vNode = new ErrorNode(item); } node.addValidationNode(vNode); } assocNode.addChild(node); doAssociationEnd(node, AssociationEndNode.TYPE_SOURCE); doAssociationEnd(node, AssociationEndNode.TYPE_TARGET); } } parentNode.addChild(assocNode); } public void preferenceChange(UserPreferencesEvent event) { if(event.getTypeOfEvent() == UserPreferencesEvent.VIEW_ASSOCIATION) { inClassAssociations = new Boolean (event.getValue()); buildTree(elements); TreeEvent tEvent = new TreeEvent(); fireTreeEvent(tEvent); } if(event.getTypeOfEvent() == UserPreferencesEvent.SHOW_INHERITED_ATTRIBUTES) { showInheritedAttributes = Boolean.valueOf(event.getValue()); buildTree(elements); TreeEvent treeEvent = new TreeEvent(); fireTreeEvent(treeEvent); } if(event.getTypeOfEvent() == UserPreferencesEvent.SORT_ELEMENTS) { buildTree(elements); TreeEvent treeEvent = new TreeEvent(); fireTreeEvent(treeEvent); } } public void addTreeListener(TreeListener listener) { treeListeners.add(listener); } public void fireTreeEvent(TreeEvent event) { for(TreeListener l : treeListeners) l.treeChange(event); } private boolean isInValueDomain(String vdName, ValueMeaning vm) { List<ValueDomain> vds = elements.getElements(DomainObjectFactory.newValueDomain()); for(ValueDomain vd : vds) { if(LookupUtil.lookupFullName(vd).equals(vdName)) { if(vd.getPermissibleValues() != null) for(PermissibleValue pv : vd.getPermissibleValues()) if(pv.getValueMeaning() == vm) return true; return false; } } return false; } }
src/gov/nih/nci/ncicb/cadsr/loader/ui/tree/TreeBuilder.java
/* * Copyright 2000-2003 Oracle, Inc. This software was developed in conjunction with the National Cancer Institute, and so to the extent government employees are co-authors, any rights in such works shall be subject to Title 17 of the United States Code, section 105. * Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: * * 1. Redistributions of source code must retain the above copyright notice, this list of conditions and the disclaimer of Article 3, below. Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. * * 2. The end-user documentation included with the redistribution, if any, must include the following acknowledgment: * * "This product includes software developed by Oracle, Inc. and the National Cancer Institute." * * If no such end-user documentation is to be included, this acknowledgment shall appear in the software itself, wherever such third-party acknowledgments normally appear. * * 3. The names "The National Cancer Institute", "NCI" and "Oracle" must not be used to endorse or promote products derived from this software. * * 4. This license does not authorize the incorporation of this software into any proprietary programs. This license does not authorize the recipient to use any trademarks owned by either NCI or Oracle, Inc. * * 5. THIS SOFTWARE IS PROVIDED "AS IS," AND ANY EXPRESSED OR IMPLIED WARRANTIES, (INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE) ARE DISCLAIMED. IN NO EVENT SHALL THE NATIONAL CANCER INSTITUTE, ORACLE, OR THEIR AFFILIATES BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE */ package gov.nih.nci.ncicb.cadsr.loader.ui.tree; import gov.nih.nci.ncicb.cadsr.domain.*; import gov.nih.nci.ncicb.cadsr.loader.defaults.UMLDefaults; import gov.nih.nci.ncicb.cadsr.loader.*; import gov.nih.nci.ncicb.cadsr.loader.validator.*; import gov.nih.nci.ncicb.cadsr.loader.util.*; import gov.nih.nci.ncicb.cadsr.loader.ui.event.*; import gov.nih.nci.ncicb.cadsr.loader.ReviewTracker; import java.util.*; public class TreeBuilder implements UserPreferencesListener { private ElementsLists elements; private UMLDefaults defaults = UMLDefaults.getInstance(); private UMLNode rootNode; private List<TreeListener> treeListeners = new ArrayList<TreeListener>(); private boolean inClassAssociations = false, showAssociations = true, showValueDomains = true, showInheritedAttributes = false; private ReviewTracker reviewTracker; private static TreeBuilder instance = new TreeBuilder(); private TreeBuilder() { RunMode runMode = (RunMode)(UserSelections.getInstance().getProperty("MODE")); if(runMode.equals(RunMode.Curator)) { reviewTracker = ReviewTracker.getInstance(ReviewTrackerType.Curator); } else { reviewTracker = ReviewTracker.getInstance(ReviewTrackerType.Owner); } } public static TreeBuilder getInstance() { return instance; } public void init() { UserPreferences prefs = UserPreferences.getInstance(); prefs.addUserPreferencesListener(this); UserSelections selections = UserSelections.getInstance(); inClassAssociations = new Boolean (prefs.getViewAssociationType()); // only show association node in Review Mode showAssociations = selections.getProperty("MODE").equals(RunMode.Reviewer)|| selections.getProperty("MODE").equals(RunMode.UnannotatedXmi); //showValueDomains = !selections.getProperty("MODE").equals(RunMode.Curator); showInheritedAttributes = prefs.getShowInheritedAttributes(); } public UMLNode buildTree(ElementsLists elements) { this.elements = elements; rootNode = new RootNode(); doPackages(rootNode); if(showValueDomains) { UMLNode vdNode = new PackageNode("Value Domain", "Value Domains"); doValueDomains(vdNode); if(vdNode.getChildren().size() > 0) rootNode.addChild(vdNode); } if(!inClassAssociations && showAssociations) doAssociations(rootNode); return rootNode; } /** * * @return the root node */ public UMLNode getRootNode() { return rootNode; } private List<ValidationItem> findValidationItems(Object o) { List<ValidationItem> result = new ArrayList<ValidationItem>(); ValidationItems items = ValidationItems.getInstance(); Set<ValidationError> errors = items.getErrors(); for(ValidationError error : errors) { if(error.getRootCause() == o) result.add(error); } Set<ValidationWarning> warnings = items.getWarnings(); for(ValidationWarning warning : warnings) { if(warning.getRootCause() == o) result.add(warning); } return result; } private void doPackages(UMLNode parentNode) { ClassificationSchemeItem pkg = DomainObjectFactory.newClassificationSchemeItem(); List<ClassificationSchemeItem> packages = elements.getElements(pkg); for(ClassificationSchemeItem pack : packages) { String alias = defaults.getPackageDisplay(pack.getLongName()); UMLNode node = new PackageNode(pack, alias); parentNode.addChild(node); List<ValidationItem> items = findValidationItems(pack); for(ValidationItem item : items) { ValidationNode vNode = null; if (item instanceof ValidationWarning) { vNode = new WarningNode(item); } else { vNode = new ErrorNode(item); } node.addValidationNode(vNode); } doClasses(node); } } private void doClasses(UMLNode parentNode) { // Find all classes which are in this package String packageName = parentNode.getFullPath(); ObjectClass oc = DomainObjectFactory.newObjectClass(); List<ObjectClass> ocs = elements.getElements(oc); for(ObjectClass o : ocs) { String className = null; for(AlternateName an : o.getAlternateNames()) { if(an.getType().equals(AlternateName.TYPE_CLASS_FULL_NAME)) className = an.getName(); } int ind = className.lastIndexOf("."); packageName = className.substring(0, ind); if(packageName.equals(parentNode.getFullPath())) { UMLNode node = new ClassNode(o); parentNode.addChild(node); ((ClassNode) node).setReviewed( reviewTracker.get(node.getFullPath())); doAttributes(node); if(inClassAssociations && showAssociations) doAssociations(node,o); List<ValidationItem> items = findValidationItems(o); for(ValidationItem item : items) { ValidationNode vNode = null; if (item instanceof ValidationWarning) { vNode = new WarningNode(item); } else { vNode = new ErrorNode(item); } node.addValidationNode(vNode); } } } } private void doAttributes(UMLNode parentNode) { // Find all DEs that have this OC. DataElement o = DomainObjectFactory.newDataElement(); List<DataElement> des = elements.getElements(o); List<AttributeNode> inherited = new ArrayList<AttributeNode>(); PackageNode inheritedPackage = new PackageNode("Inherited Attributes", "Inherited Attributes", true); InheritedAttributeList inheritedList = InheritedAttributeList.getInstance(); for(DataElement de : des) { try { String fullClassName = null; for(AlternateName an : de.getDataElementConcept().getObjectClass().getAlternateNames()) { if(an.getType().equals(AlternateName.TYPE_CLASS_FULL_NAME)) fullClassName = an.getName(); } if(fullClassName.equals(parentNode.getFullPath())) { UMLNode node = new AttributeNode(de); Boolean reviewed = reviewTracker.get(node.getFullPath()); if(inheritedList.isInherited(de)) { node = new InheritedAttributeNode(de); inherited.add((InheritedAttributeNode)node); } else { parentNode.addChild(node); ((AttributeNode) node).setReviewed(reviewed); } List<ValidationItem> items = findValidationItems(de.getDataElementConcept().getProperty()); for(ValidationItem item : items) { ValidationNode vNode = null; if (item instanceof ValidationWarning) { vNode = new WarningNode(item); } else { vNode = new ErrorNode(item); } node.addValidationNode(vNode); } items = findValidationItems(de); for(ValidationItem item : items) { ValidationNode vNode = null; if (item instanceof ValidationWarning) { vNode = new WarningNode(item); } else { vNode = new ErrorNode(item); } node.addValidationNode(vNode); } } } catch (NullPointerException e){ e.printStackTrace(); } // end of try-catch } if((inherited.size() > 0)) parentNode.addChild(inheritedPackage); for(AttributeNode inherit : inherited) { inheritedPackage.addChild(inherit); Boolean reviewed = reviewTracker.get(inherit.getFullPath()); if(reviewed != null) inherit.setReviewed(reviewed); } // if((inherited.size() > 0) && showInheritedAttributes) // parentNode.addChild(inheritedPackage); // if(showInheritedAttributes) { // for(AttributeNode inherit : inherited) { // inheritedPackage.addChild(inherit); // Boolean reviewed = reviewTracker.get(inherit.getFullPath()); // if(reviewed != null) // inherit.setReviewed(reviewed); // } // } } private void doValueDomains(UMLNode parentNode) { List<ValueDomain> vds = elements.getElements(DomainObjectFactory.newValueDomain()); for(ValueDomain vd : vds) { UMLNode node = new ValueDomainNode(vd); parentNode.addChild(node); ((ValueDomainNode) node).setReviewed (reviewTracker.get(node.getFullPath())); doValueMeanings(node); List<ValidationItem> items = findValidationItems(vd); for(ValidationItem item : items) { ValidationNode vNode = null; if (item instanceof ValidationWarning) { vNode = new WarningNode(item); } else { vNode = new ErrorNode(item); } node.addValidationNode(vNode); } } } private void doValueMeanings(UMLNode parentNode) { // Find all DEs that have this OC. List<ValueMeaning> vms = elements.getElements(DomainObjectFactory.newValueMeaning()); for(ValueMeaning vm : vms) { try { if(isInValueDomain(parentNode.getFullPath(), vm)) { UMLNode node = new ValueMeaningNode(vm, parentNode.getFullPath()); Boolean reviewed = reviewTracker.get(node.getFullPath()); if(reviewed != null) { parentNode.addChild(node); ((ValueMeaningNode) node).setReviewed(reviewed); } List<ValidationItem> items = findValidationItems(vm); for(ValidationItem item : items) { ValidationNode vNode = null; if (item instanceof ValidationWarning) { vNode = new WarningNode(item); } else { vNode = new ErrorNode(item); } node.addValidationNode(vNode); } } } catch (NullPointerException e){ e.printStackTrace(); } // end of try-catch } } private void doAssociations(UMLNode parentNode) { UMLNode assocNode = new PackageNode("Associations", "Associations"); ObjectClassRelationship o = DomainObjectFactory.newObjectClassRelationship(); List<ObjectClassRelationship> ocrs = elements.getElements(o); for(ObjectClassRelationship ocr : ocrs) { AssociationNode node = new AssociationNode(ocr); Boolean reviewed = reviewTracker.get(node.getFullPath()); if (reviewed != null) { node.setReviewed(reviewed.booleanValue()); } List<ValidationItem> items = findValidationItems(ocr); for(ValidationItem item : items) { ValidationNode vNode = null; if (item instanceof ValidationWarning) { vNode = new WarningNode(item); } else { vNode = new ErrorNode(item); } node.addValidationNode(vNode); } assocNode.addChild(node); doAssociationEnd(node, AssociationEndNode.TYPE_SOURCE); doAssociationEnd(node, AssociationEndNode.TYPE_TARGET); } parentNode.addChild(assocNode); } private void doAssociationEnd(UMLNode parentNode, int type) { ObjectClassRelationship ocr = (ObjectClassRelationship)parentNode.getUserObject(); AssociationEndNode node = new AssociationEndNode(ocr, type); Boolean reviewed = reviewTracker.get(node.getFullPath()); if (reviewed != null) { node.setReviewed(reviewed.booleanValue()); } // List<ValidationItem> items = findValidationItems(ocr); // for(ValidationItem item : items) { // ValidationNode vNode = null; // if (item instanceof ValidationWarning) { // vNode = new WarningNode(item); // } else { // vNode = new ErrorNode(item); // } // node.addValidationNode(vNode); // } parentNode.addChild(node); } private void doAssociations(UMLNode parentNode, ObjectClass oc) { UMLNode assocNode = new PackageNode("Associations for " + oc.getLongName(), "Associations"); ObjectClassRelationship o = DomainObjectFactory.newObjectClassRelationship(); List<ObjectClassRelationship> ocrs = elements.getElements(o); for(ObjectClassRelationship ocr : ocrs) { if(ocr.getSource().getLongName().equals(oc.getLongName()) | ocr.getTarget().getLongName().equals(oc.getLongName())) { UMLNode node = new AssociationNode(ocr); List<ValidationItem> items = findValidationItems(ocr); for(ValidationItem item : items) { ValidationNode vNode = null; if (item instanceof ValidationWarning) { vNode = new WarningNode(item); } else { vNode = new ErrorNode(item); } node.addValidationNode(vNode); } assocNode.addChild(node); doAssociationEnd(node, AssociationEndNode.TYPE_SOURCE); doAssociationEnd(node, AssociationEndNode.TYPE_TARGET); } } parentNode.addChild(assocNode); } public void preferenceChange(UserPreferencesEvent event) { if(event.getTypeOfEvent() == UserPreferencesEvent.VIEW_ASSOCIATION) { inClassAssociations = new Boolean (event.getValue()); buildTree(elements); TreeEvent tEvent = new TreeEvent(); fireTreeEvent(tEvent); } if(event.getTypeOfEvent() == UserPreferencesEvent.SHOW_INHERITED_ATTRIBUTES) { showInheritedAttributes = Boolean.valueOf(event.getValue()); buildTree(elements); TreeEvent treeEvent = new TreeEvent(); fireTreeEvent(treeEvent); } if(event.getTypeOfEvent() == UserPreferencesEvent.SORT_ELEMENTS) { buildTree(elements); TreeEvent treeEvent = new TreeEvent(); fireTreeEvent(treeEvent); } } public void addTreeListener(TreeListener listener) { treeListeners.add(listener); } public void fireTreeEvent(TreeEvent event) { for(TreeListener l : treeListeners) l.treeChange(event); } private boolean isInValueDomain(String vdName, ValueMeaning vm) { List<ValueDomain> vds = elements.getElements(DomainObjectFactory.newValueDomain()); for(ValueDomain vd : vds) { if(vd.getLongName().equals(vdName)) { if(vd.getPermissibleValues() != null) for(PermissibleValue pv : vd.getPermissibleValues()) if(pv.getValueMeaning() == vm) return true; return false; } } return false; } }
Change for VD review tracker SVN-Revision: 2275
src/gov/nih/nci/ncicb/cadsr/loader/ui/tree/TreeBuilder.java
Change for VD review tracker
<ide><path>rc/gov/nih/nci/ncicb/cadsr/loader/ui/tree/TreeBuilder.java <ide> List<ValueDomain> vds = elements.getElements(DomainObjectFactory.newValueDomain()); <ide> <ide> for(ValueDomain vd : vds) { <del> UMLNode node = new ValueDomainNode(vd); <add> ValueDomainNode node = new ValueDomainNode(vd); <ide> <ide> parentNode.addChild(node); <ide> <del> ((ValueDomainNode) node).setReviewed <del> (reviewTracker.get(node.getFullPath())); <add> node.setReviewed <add> (reviewTracker.get(LookupUtil.lookupFullName(vd))); <ide> <ide> doValueMeanings(node); <ide> <ide> // Find all DEs that have this OC. <ide> List<ValueMeaning> vms = elements.getElements(DomainObjectFactory.newValueMeaning()); <ide> <add> ValueDomainNode vdNode = (ValueDomainNode)parentNode; <add> ValueDomain parentVD = (ValueDomain)vdNode.getUserObject(); <add> <add> String vdFullName = LookupUtil.lookupFullName(parentVD); <add> <ide> for(ValueMeaning vm : vms) { <ide> try { <del> if(isInValueDomain(parentNode.getFullPath(), vm)) { <del> UMLNode node = new ValueMeaningNode(vm, parentNode.getFullPath()); <add> if(isInValueDomain(vdFullName, vm)) { <add> UMLNode node = new ValueMeaningNode(vm, vdFullName); <ide> <ide> Boolean reviewed = reviewTracker.get(node.getFullPath()); <ide> if(reviewed != null) { <ide> List<ValueDomain> vds = elements.getElements(DomainObjectFactory.newValueDomain()); <ide> <ide> for(ValueDomain vd : vds) { <del> if(vd.getLongName().equals(vdName)) { <add> if(LookupUtil.lookupFullName(vd).equals(vdName)) { <ide> if(vd.getPermissibleValues() != null) <ide> for(PermissibleValue pv : vd.getPermissibleValues()) <ide> if(pv.getValueMeaning() == vm)
Java
mit
15805d9227cac678770661b036ed3eb45d19f759
0
KimSiHun/codility
package org.shkim.codility.test; import java.util.Arrays; import java.util.HashSet; public class task4 { private static int solution2(int A[]) { int N = A.length; if (N == 1) { return 1; } HashSet<String> keys = new HashSet<>(); for (int i = 0; i < N; i++) { keys.add(String.valueOf(A[i])); } int key_size = keys.size(); StringBuilder sb = new StringBuilder(); for (int i = 0; i < N; i++) { sb.append(A[i]); } String line = new String(sb); String checker = null; int temp[] = new int[key_size]; int chk; int result = Integer.MAX_VALUE; int minus = 0; for (int i = 0; i < N; i++) { if (i > N - key_size) { break; } checker = line.substring(i); chk = 0; for (String j : keys) { temp[chk] = checker.indexOf(j); chk++; } Arrays.sort(temp); minus = temp[key_size - 1] - temp[0]; if (temp[0] != -1 && (minus + 1) < result) { result = minus + 1; } } return result; } private static int solution(int A[]) { int N = A.length; if (N == 1) { return 1; } HashSet<Integer> set = new HashSet<>(); for (int i = 0; i < N; i++) { set.add(A[i]); } HashSet<Integer> copy; int temp = Integer.MAX_VALUE; for (int i = 0; i < N; i++) { copy = new HashSet<>(); copy.addAll(set); for (int j = i; j < N; j++) { if (copy.contains(A[j])) { copy.remove(A[j]); } if (copy.isEmpty()) { if (j - i + 1 < temp) { temp = j - i + 1; } break; } } } return temp; } public static void main(String[] args) { int A[] = { 7, 3, 7, 3, 1, 3, 4, 1 }; System.out.println(solution2(A)); } }
src/org/shkim/codility/test/task4.java
package org.shkim.codility.test; import java.util.Arrays; import java.util.HashSet; public class task4 { private static int solution2(int A[]) { int N = A.length; if (N == 1) { return 1; } HashSet<String> keys = new HashSet<>(); for (int i = 0; i < N; i++) { keys.add(String.valueOf(A[i])); } int key_size = keys.size(); StringBuilder sb = new StringBuilder(); for (int i = 0; i < N; i++) { sb.append(A[i]); } String line = new String(sb); String checker = null; int temp[] = new int[key_size]; int chk; int result = Integer.MAX_VALUE; int minus = 0; for (int i = 0; i < N; i++) { if (i > N - key_size) { break; } checker = line.substring(i); chk = 0; for (String j : keys) { temp[chk] = checker.indexOf(j); chk++; } Arrays.sort(temp); minus = temp[key_size-1] - temp[0]; if (temp[0] != -1 && (minus + 1) < result) { result = minus + 1; } } return result; } private static int solution(int A[]) { int N = A.length; if (N == 1) { return 1; } HashSet<Integer> set = new HashSet<>(); for (int i = 0; i < N; i++) { set.add(A[i]); } HashSet<Integer> copy; int temp = Integer.MAX_VALUE; for (int i = 0; i < N; i++) { copy = new HashSet<>(); copy.addAll(set); for (int j = i; j < N; j++) { if (copy.contains(A[j])) { copy.remove(A[j]); } if (copy.isEmpty()) { if (j - i + 1 < temp) { temp = j - i + 1; } break; } } } return temp; } public static void main(String[] args) { int A[] = { 7, 3, 7, 3, 1, 3, 4, 1 }; System.out.println(solution2(A)); } }
task4 change
src/org/shkim/codility/test/task4.java
task4 change
<ide><path>rc/org/shkim/codility/test/task4.java <ide> <ide> public class task4 <ide> { <add> <add> <ide> <ide> private static int solution2(int A[]) <ide> { <ide> <ide> Arrays.sort(temp); <ide> <del> minus = temp[key_size-1] - temp[0]; <add> minus = temp[key_size - 1] - temp[0]; <ide> <ide> if (temp[0] != -1 && (minus + 1) < result) <ide> {
Java
mpl-2.0
ae1ef4520fb03d8f2ba24ffb987e8744755ae7af
0
carlwilson/veraPDF-library
package org.verapdf.metadata.fixer; import java.util.ArrayList; import java.util.Iterator; import java.util.List; /** * @author Evgeniy Muravitskiy */ // TODO : remove me and use source implementation public class MetadataFixerResult implements Iterable<String> { private RepairStatus status; private final List<String> appliedFixes = new ArrayList<>(); public MetadataFixerResult() { this.status = RepairStatus.NO_ACTION; } public MetadataFixerResult(RepairStatus status) { if (status == null) { throw new IllegalArgumentException("Repair status must be not null"); } this.status = status; } public RepairStatus getStatus() { return this.status; } public void setStatus(RepairStatus status) { this.status = status; } public List<String> getAppliedFixes() { return this.appliedFixes; } public void addAppliedFix(String fix) { this.appliedFixes.add(fix); } @Override public Iterator<String> iterator() { return this.appliedFixes.iterator(); } public enum RepairStatus { FAILED("Metadata repair was attempted but failed"), NO_ACTION("No action was taken because the file is already valid"), NOT_REPAIRABLE("The fixer could not determine any action that could repair the PDF/A"), SUCCESSFUL("Metadata repair was carried out successfully"); private final String value; RepairStatus(String value) { this.value = value; } public String getDescription() { return this.value; } } }
metadata-fixer/src/main/java/org/verapdf/metadata/fixer/MetadataFixerResult.java
package org.verapdf.metadata.fixer; import java.util.ArrayList; import java.util.Iterator; import java.util.List; /** * @author Evgeniy Muravitskiy */ // TODO : remove me and use source implementation public class MetadataFixerResult implements Iterable<String> { private RepairStatus status = RepairStatus.NO_ACTION; private final List<String> appliedFixes = new ArrayList<>(); public MetadataFixerResult() { } public MetadataFixerResult(RepairStatus status) { if (status == null) { throw new IllegalArgumentException("Repair status must be not null"); } this.status = status; } public RepairStatus getStatus() { return this.status; } public void setStatus(RepairStatus status) { this.status = status; } public List<String> getAppliedFixes() { return this.appliedFixes; } public void addAppliedFix(String fix) { this.appliedFixes.add(fix); } @Override public Iterator<String> iterator() { return this.appliedFixes.iterator(); } public enum RepairStatus { FAILED("Metadata repair was attempted but failed"), NO_ACTION("No action was taken because the file is already valid"), NOT_REPAIRABLE("The fixer could not determine any action that could repair the PDF/A"), SUCCESSFUL("Metadata repair was carried out successfully"); private final String value; RepairStatus(String value) { this.value = value; } public String getDescription() { return this.value; } } }
Fix in metadata fixer result
metadata-fixer/src/main/java/org/verapdf/metadata/fixer/MetadataFixerResult.java
Fix in metadata fixer result
<ide><path>etadata-fixer/src/main/java/org/verapdf/metadata/fixer/MetadataFixerResult.java <ide> // TODO : remove me and use source implementation <ide> public class MetadataFixerResult implements Iterable<String> { <ide> <del> private RepairStatus status = RepairStatus.NO_ACTION; <add> private RepairStatus status; <ide> private final List<String> appliedFixes = new ArrayList<>(); <ide> <ide> public MetadataFixerResult() { <del> <add> this.status = RepairStatus.NO_ACTION; <ide> } <ide> <ide> public MetadataFixerResult(RepairStatus status) {
Java
lgpl-2.1
826eac66baf517dfe575671a2a23448f5e688181
0
deegree/deegree3,deegree/deegree3,deegree/deegree3,deegree/deegree3,deegree/deegree3
//$HeadURL: svn+ssh://[email protected]/deegree/deegree3/tools/trunk/src/org/deegree/tools/rendering/OpenGLEventHandler.java $ /*---------------------------------------------------------------------------- This file is part of deegree, http://deegree.org/ Copyright (C) 2001-2009 by: Department of Geography, University of Bonn and lat/lon GmbH 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 Contact information: lat/lon GmbH Aennchenstr. 19, 53177 Bonn Germany http://lat-lon.de/ Department of Geography, University of Bonn Prof. Dr. Klaus Greve Postfach 1147, 53001 Bonn Germany http://www.geographie.uni-bonn.de/deegree/ e-mail: [email protected] ----------------------------------------------------------------------------*/ package org.deegree.rendering.r3d.opengl.display; import java.util.ArrayList; import java.util.List; import javax.media.opengl.DebugGL; import javax.media.opengl.GL; import javax.media.opengl.GLAutoDrawable; import javax.media.opengl.GLEventListener; import javax.media.opengl.glu.GLU; import javax.vecmath.Point3d; import javax.vecmath.Vector3d; import org.deegree.commons.utils.math.Vectors3f; import org.deegree.geometry.Envelope; import org.deegree.geometry.GeometryFactory; import org.deegree.rendering.r3d.ViewFrustum; import org.deegree.rendering.r3d.ViewParams; import org.deegree.rendering.r3d.opengl.JOGLUtils; import org.deegree.rendering.r3d.opengl.rendering.RenderContext; import org.deegree.rendering.r3d.opengl.rendering.model.geometry.WorldRenderableObject; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import com.sun.opengl.util.GLUT; /** * The <code>OpenGLEventHandler</code> class renders a list of DataObjects and handles opengl callback functions * delivered by a GLCanvas. It possesses a trackball which can roate the scene. * * @author <a href="mailto:[email protected]">Rutger Bezema</a> * * @author last edited by: $Author: rbezema $ * * @version $Revision: 15632 $, $Date: 2009-01-14 13:12:54 +0100 (Mi, 14 Jan 2009) $ * */ public class OpenGLEventHandler implements GLEventListener { private final static Logger LOG = LoggerFactory.getLogger( OpenGLEventHandler.class ); private List<WorldRenderableObject> worldRenderableObjects = new ArrayList<WorldRenderableObject>(); // The trackball private TrackBall trackBall; private float[] centroid; private float[] lookAt; private float[] eye; private boolean renderTestObject; private Envelope bbox; // Distance to end of scene private float farClippingPlane; private final float testObjectSize = 10f; private final float cubeHalf = testObjectSize * 0.5f; private final float sphereSize = testObjectSize - ( testObjectSize * 0.25f ); private final float[][] cubeData = { { -cubeHalf, -cubeHalf, cubeHalf }, { cubeHalf, -cubeHalf, cubeHalf }, { cubeHalf, cubeHalf, cubeHalf }, { -cubeHalf, cubeHalf, cubeHalf }, { -cubeHalf, -cubeHalf, -cubeHalf }, { cubeHalf, -cubeHalf, -cubeHalf }, { cubeHalf, cubeHalf, -cubeHalf }, { -cubeHalf, cubeHalf, -cubeHalf } }; private GLU glu = new GLU(); private GLUT glut = new GLUT(); private int width; private int height; private float fov = 60; private double nearClippingPlane; /** * * @param renderTestObject */ public OpenGLEventHandler( boolean renderTestObject ) { trackBall = new TrackBall(); centroid = new float[3]; lookAt = new float[3]; eye = new float[3]; this.renderTestObject = renderTestObject; bbox = getDefaultBBox(); calcViewParameters(); } private Envelope getDefaultBBox() { return new GeometryFactory().createEnvelope( new double[] { -sphereSize, -sphereSize, -sphereSize }, new double[] { sphereSize, sphereSize, sphereSize }, null ); } /** * */ public void calcViewParameters() { centroid = new float[] { (float) bbox.getCentroid().get0(), (float) bbox.getCentroid().get1(), (float) bbox.getCentroid().get2() }; lookAt = new float[] { centroid[0], centroid[1], centroid[2] }; eye = calcOptimalEye( bbox ); float dist = Vectors3f.distance( centroid, eye ); farClippingPlane = 2 * dist; nearClippingPlane = 0.01 * farClippingPlane; trackBall.reset(); } private float[] calcOptimalEye( Envelope bBox ) { float[] eye = new float[] { 0, 1, 1 }; if ( bBox != null ) { double[] min = bBox.getMin().getAsArray(); double[] max = bBox.getMax().getAsArray(); double centerX = min[0] + ( ( max[0] - min[0] ) * 0.5f ); double centerY = min[1] + ( ( max[1] - min[1] ) * 0.5f ); // float centerZ = bBox[2] + ( ( bBox[2] - bBox[5] ) * 0.5f ); double eyeZ = 2 * ( ( Math.max( bBox.getSpan0(), bBox.getSpan1() ) / 2 ) / Math.tan( Math.toRadians( fov * 0.5 ) ) ); eye = new float[] { (float) centerX, (float) centerY, (float) eyeZ }; } return eye; } @Override public void display( GLAutoDrawable theDrawable ) { GL gl = theDrawable.getGL(); gl.glClear( GL.GL_COLOR_BUFFER_BIT | GL.GL_DEPTH_BUFFER_BIT ); gl.glLoadIdentity(); glu.gluLookAt( eye[0], eye[1], eye[2], lookAt[0], lookAt[1], lookAt[2], 0, 1, 0 ); trackBall.multModelMatrix( gl, centroid ); float[] newEye = JOGLUtils.getEyeFromModelView( gl ); if ( LOG.isDebugEnabled() ) { LOG.debug( "farClippingPlane:" + farClippingPlane ); LOG.debug( "centroid:" + centroid[0] + "," + centroid[1] + "," + centroid[2] ); LOG.debug( "lookAt:" + lookAt[0] + "," + lookAt[1] + "," + lookAt[2] ); LOG.debug( "eye:" + eye[0] + "," + eye[1] + "," + eye[2] ); LOG.debug( "Eye in model space: " + Vectors3f.asString( newEye ) ); } Point3d newEyeP = new Point3d( newEye[0], newEye[1], newEye[2] ); Point3d center = new Point3d( lookAt[0], lookAt[1], lookAt[2] ); Vector3d up = new Vector3d( 0, 0, 1 ); ViewFrustum vf = new ViewFrustum( newEyeP, center, up, fov, (double) width / height, nearClippingPlane, farClippingPlane ); ViewParams params = new ViewParams( vf, width, height ); RenderContext context = new RenderContext( params ); context.setContext( gl ); for ( WorldRenderableObject dObj : worldRenderableObjects ) { dObj.render( context ); } if ( renderTestObject ) { gl.glTranslatef( centroid[0], centroid[1], centroid[2] ); drawCube( gl ); glut.glutSolidSphere( sphereSize, 15, 15 ); } } /** * Add the given branch group to the scene and set the appropriate distance etc. After adding the branch group to * the rotation group which is controlled by the mouse rotator. * * @param b */ public void addDataObjectToScene( List<WorldRenderableObject> w ) { if ( w != null ) { for ( WorldRenderableObject b : w ) { Envelope env = b.getBbox(); if ( env != null ) { if ( isDefaultBBox() ) { bbox = env; } else { bbox = bbox.merge( env ); } } worldRenderableObjects.add( b ); } calcViewParameters(); } } private boolean isDefaultBBox() { Envelope env = getDefaultBBox(); return ( Math.abs( bbox.getSpan0() - env.getSpan0() ) < 1E-11 ) && ( Math.abs( bbox.getSpan1() - env.getSpan1() ) < 1E-11 ) && ( Math.abs( bbox.getMin().get0() - env.getMin().get0() ) < 1E-11 ) && ( Math.abs( bbox.getMin().get1() - env.getMin().get1() ) < 1E-11 ) && ( Math.abs( bbox.getMin().get2() - env.getMin().get2() ) < 1E-11 ); } /** * Update the view by evaluating the given key, * * @param keyTyped * r/R(reset view), all others will be ignored. * @return true if the view should be redrawn, false otherwise. */ public boolean updateView( char keyTyped ) { boolean changed = true; if ( keyTyped == 'r' || keyTyped == 'R' ) { calcViewParameters(); changed = true; } return changed; } /* * Draws a colored cube with cubeHalf length defined by the ObjectSize. */ private void drawCube( GL gl ) { gl.glPushAttrib( GL.GL_CURRENT_BIT | GL.GL_LIGHTING_BIT ); gl.glDisable( GL.GL_BLEND ); float[] color = new float[] { 1, 0, 0 }; gl.glMaterialfv( GL.GL_FRONT, GL.GL_AMBIENT_AND_DIFFUSE, color, 0 ); gl.glBegin( GL.GL_QUADS ); // Front face gl.glNormal3f( 0, 0, 1 ); gl.glVertex3fv( cubeData[0], 0 ); gl.glVertex3fv( cubeData[1], 0 ); gl.glVertex3fv( cubeData[2], 0 ); gl.glVertex3fv( cubeData[3], 0 ); // Back face gl.glNormal3f( 0, 0, -1 ); gl.glVertex3fv( cubeData[5], 0 ); gl.glVertex3fv( cubeData[4], 0 ); gl.glVertex3fv( cubeData[7], 0 ); gl.glVertex3fv( cubeData[6], 0 ); gl.glEnd(); color = new float[] { 0, 1, 0 }; gl.glMaterialfv( GL.GL_FRONT, GL.GL_AMBIENT_AND_DIFFUSE, color, 0 ); gl.glBegin( GL.GL_QUADS ); // Left face gl.glNormal3f( -1, 0, 0 ); gl.glVertex3fv( cubeData[4], 0 ); gl.glVertex3fv( cubeData[0], 0 ); gl.glVertex3fv( cubeData[3], 0 ); gl.glVertex3fv( cubeData[7], 0 ); // Right face gl.glNormal3f( 1, 0, 0 ); gl.glVertex3fv( cubeData[1], 0 ); gl.glVertex3fv( cubeData[5], 0 ); gl.glVertex3fv( cubeData[6], 0 ); gl.glVertex3fv( cubeData[2], 0 ); gl.glEnd(); color = new float[] { 0, 0, 1 }; gl.glMaterialfv( GL.GL_FRONT, GL.GL_AMBIENT_AND_DIFFUSE, color, 0 ); gl.glBegin( GL.GL_QUADS ); // Top face gl.glNormal3f( 0, 1, 0 ); gl.glVertex3fv( cubeData[3], 0 ); gl.glVertex3fv( cubeData[2], 0 ); gl.glVertex3fv( cubeData[6], 0 ); gl.glVertex3fv( cubeData[7], 0 ); // Bottom face gl.glNormal3f( 0, -1, 0 ); gl.glVertex3fv( cubeData[4], 0 ); gl.glVertex3fv( cubeData[5], 0 ); gl.glVertex3fv( cubeData[1], 0 ); gl.glVertex3fv( cubeData[0], 0 ); gl.glEnd(); gl.glEnable( GL.GL_BLEND ); gl.glPopAttrib(); } @Override public void displayChanged( GLAutoDrawable d, boolean modeChanged, boolean deviceChanged ) { // nothing to do } @Override public void init( GLAutoDrawable d ) { d.setGL( new DebugGL( d.getGL() ) ); GL gl = d.getGL(); gl.glClearColor( 0.7f, 0.7f, 1f, 0 ); float[] lightAmbient = { 0.4f, 0.4f, 0.4f, 1.0f }; float[] lightDiffuse = { 0.8f, 0.8f, 0.8f, 1.0f }; float[] lightSpecular = { 1.0f, 1.0f, 1.0f, 1.0f }; float[] lightPosition = { 0.0f, 0.0f, 10.0f, 1.0f }; gl.glLightfv( GL.GL_LIGHT0, GL.GL_AMBIENT, lightAmbient, 0 ); gl.glLightfv( GL.GL_LIGHT0, GL.GL_DIFFUSE, lightDiffuse, 0 ); gl.glLightfv( GL.GL_LIGHT0, GL.GL_SPECULAR, lightSpecular, 0 ); gl.glLightfv( GL.GL_LIGHT0, GL.GL_POSITION, lightPosition, 0 ); gl.glEnable( GL.GL_DEPTH_TEST ); gl.glEnable( GL.GL_LIGHT0 ); gl.glEnable( GL.GL_LIGHTING ); gl.glEnable( GL.GL_BLEND ); // enable color and texture blending gl.glBlendFunc( GL.GL_SRC_ALPHA, GL.GL_ONE_MINUS_SRC_ALPHA ); gl.glMatrixMode( GL.GL_MODELVIEW ); gl.glLoadIdentity(); gl.glEnableClientState( GL.GL_NORMAL_ARRAY ); gl.glEnableClientState( GL.GL_VERTEX_ARRAY ); } @Override public void reshape( GLAutoDrawable d, int x, int y, int width, int height ) { this.width = width; this.height = height; GL gl = d.getGL(); gl.glMatrixMode( GL.GL_PROJECTION ); gl.glLoadIdentity(); glu.gluPerspective( fov, (float) width / height, nearClippingPlane, farClippingPlane ); gl.glMatrixMode( GL.GL_MODELVIEW ); } /** * @return the trackBall */ public TrackBall getTrackBall() { return trackBall; } /** * */ public void removeAllData() { worldRenderableObjects.clear(); bbox = getDefaultBBox(); calcViewParameters(); } /** * @return the renderTestObject */ public final boolean isTestObjectRendered() { return renderTestObject; } /** * @param renderTestObject * the renderTestObject to set */ public final void renderTestObject( boolean renderTestObject ) { this.renderTestObject = renderTestObject; } }
deegree-core/src/main/java/org/deegree/rendering/r3d/opengl/display/OpenGLEventHandler.java
//$HeadURL: svn+ssh://[email protected]/deegree/deegree3/tools/trunk/src/org/deegree/tools/rendering/OpenGLEventHandler.java $ /*---------------------------------------------------------------------------- This file is part of deegree, http://deegree.org/ Copyright (C) 2001-2009 by: Department of Geography, University of Bonn and lat/lon GmbH 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 Contact information: lat/lon GmbH Aennchenstr. 19, 53177 Bonn Germany http://lat-lon.de/ Department of Geography, University of Bonn Prof. Dr. Klaus Greve Postfach 1147, 53001 Bonn Germany http://www.geographie.uni-bonn.de/deegree/ e-mail: [email protected] ----------------------------------------------------------------------------*/ package org.deegree.rendering.r3d.opengl.display; import java.util.ArrayList; import java.util.List; import javax.media.opengl.DebugGL; import javax.media.opengl.GL; import javax.media.opengl.GLAutoDrawable; import javax.media.opengl.GLEventListener; import javax.media.opengl.glu.GLU; import javax.vecmath.Point3d; import javax.vecmath.Vector3d; import org.deegree.commons.utils.math.Vectors3f; import org.deegree.geometry.Envelope; import org.deegree.geometry.GeometryFactory; import org.deegree.rendering.r3d.ViewFrustum; import org.deegree.rendering.r3d.ViewParams; import org.deegree.rendering.r3d.opengl.JOGLUtils; import org.deegree.rendering.r3d.opengl.rendering.RenderContext; import org.deegree.rendering.r3d.opengl.rendering.model.geometry.WorldRenderableObject; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import com.sun.opengl.util.GLUT; /** * The <code>OpenGLEventHandler</code> class renders a list of DataObjects and handles opengl callback functions * delivered by a GLCanvas. It possesses a trackball which can roate the scene. * * @author <a href="mailto:[email protected]">Rutger Bezema</a> * * @author last edited by: $Author: rbezema $ * * @version $Revision: 15632 $, $Date: 2009-01-14 13:12:54 +0100 (Mi, 14 Jan 2009) $ * */ public class OpenGLEventHandler implements GLEventListener { private final static Logger LOG = LoggerFactory.getLogger( OpenGLEventHandler.class ); private List<WorldRenderableObject> worldRenderableObjects = new ArrayList<WorldRenderableObject>(); // The trackball private TrackBall trackBall; private float[] centroid; private float[] lookAt; private float[] eye; private boolean renderTestObject; private Envelope bbox; // Distance to end of scene private float farClippingPlane; private final float testObjectSize = 10f; private final float cubeHalf = testObjectSize * 0.5f; private final float sphereSize = testObjectSize - ( testObjectSize * 0.25f ); private final float[][] cubeData = { { -cubeHalf, -cubeHalf, cubeHalf }, { cubeHalf, -cubeHalf, cubeHalf }, { cubeHalf, cubeHalf, cubeHalf }, { -cubeHalf, cubeHalf, cubeHalf }, { -cubeHalf, -cubeHalf, -cubeHalf }, { cubeHalf, -cubeHalf, -cubeHalf }, { cubeHalf, cubeHalf, -cubeHalf }, { -cubeHalf, cubeHalf, -cubeHalf } }; private GLU glu = new GLU(); private GLUT glut = new GLUT(); private int width; private int height; private float fov = 60; private double nearClippingPlane; /** * * @param renderTestObject */ public OpenGLEventHandler( boolean renderTestObject ) { trackBall = new TrackBall(); centroid = new float[3]; lookAt = new float[3]; eye = new float[3]; this.renderTestObject = renderTestObject; bbox = getDefaultBBox(); calcViewParameters(); } private Envelope getDefaultBBox() { return new GeometryFactory().createEnvelope( new double[] { -sphereSize, -sphereSize, -sphereSize }, new double[] { sphereSize, sphereSize, sphereSize }, null ); } /** * */ public void calcViewParameters() { centroid = new float[] { (float) bbox.getCentroid().get0(), (float) bbox.getCentroid().get1(), (float) bbox.getCentroid().get2() }; lookAt = new float[] { centroid[0], centroid[1], centroid[2] }; eye = calcOptimalEye( bbox ); float dist = Vectors3f.distance( centroid, eye ); farClippingPlane = 2 * dist; nearClippingPlane = 0.01 * farClippingPlane; trackBall.reset(); } private float[] calcOptimalEye( Envelope bBox ) { float[] eye = new float[] { 0, 1, 1 }; if ( bBox != null ) { double[] min = bBox.getMin().getAsArray(); double[] max = bBox.getMax().getAsArray(); double centerX = min[0] + ( ( max[0] - min[0] ) * 0.5f ); double centerY = min[1] + ( ( max[1] - min[1] ) * 0.5f ); // float centerZ = bBox[2] + ( ( bBox[2] - bBox[5] ) * 0.5f ); double eyeZ = 2 * ( ( Math.max( bBox.getSpan0(), bBox.getSpan1() ) / 2 ) / Math.tan( Math.toRadians( fov * 0.5 ) ) ); eye = new float[] { (float) centerX, (float) centerY, (float) eyeZ }; } return eye; } @Override public void display( GLAutoDrawable theDrawable ) { GL gl = theDrawable.getGL(); gl.glClear( GL.GL_COLOR_BUFFER_BIT | GL.GL_DEPTH_BUFFER_BIT ); gl.glLoadIdentity(); glu.gluLookAt( eye[0], eye[1], eye[2], lookAt[0], lookAt[1], lookAt[2], 0, 1, 0 ); trackBall.multModelMatrix( gl, centroid ); float[] newEye = JOGLUtils.getEyeFromModelView( gl ); if ( LOG.isDebugEnabled() ) { LOG.debug( "farClippingPlane:" + farClippingPlane ); LOG.debug( "centroid:" + centroid[0] + "," + centroid[1] + "," + centroid[2] ); LOG.debug( "lookAt:" + lookAt[0] + "," + lookAt[1] + "," + lookAt[2] ); LOG.debug( "eye:" + eye[0] + "," + eye[1] + "," + eye[2] ); LOG.debug( "Eye in model space: " + Vectors3f.asString( newEye ) ); } Point3d newEyeP = new Point3d( newEye[0], newEye[1], newEye[2] ); Point3d center = new Point3d( lookAt[0], lookAt[1], lookAt[2] ); Vector3d up = new Vector3d( 0, 0, 1 ); ViewFrustum vf = new ViewFrustum( newEyeP, center, up, fov, (double) width / height, nearClippingPlane, farClippingPlane ); ViewParams params = new ViewParams( vf, width, height ); RenderContext context = new RenderContext( params ); context.setContext( gl ); for ( WorldRenderableObject dObj : worldRenderableObjects ) { dObj.render( context ); } if ( renderTestObject ) { gl.glTranslatef( centroid[0], centroid[1], centroid[2] ); drawCube( gl ); glut.glutSolidSphere( sphereSize, 15, 15 ); } } /** * Add the given branch group to the scene and set the appropriate distance etc. After adding the branch group to * the rotation group which is controlled by the mouse rotator. * * @param b */ public void addDataObjectToScene( WorldRenderableObject b ) { if ( b != null ) { Envelope env = b.getBbox(); if ( env != null ) { if ( isDefaultBBox() ) { bbox = env; } else { bbox.merge( env ); } } calcViewParameters(); worldRenderableObjects.add( b ); } } private boolean isDefaultBBox() { Envelope env = getDefaultBBox(); return ( Math.abs( bbox.getSpan0() - env.getSpan0() ) < 1E-11 ) && ( Math.abs( bbox.getSpan1() - env.getSpan1() ) < 1E-11 ) && ( Math.abs( bbox.getMin().get0() - env.getMin().get0() ) < 1E-11 ) && ( Math.abs( bbox.getMin().get1() - env.getMin().get1() ) < 1E-11 ) && ( Math.abs( bbox.getMin().get2() - env.getMin().get2() ) < 1E-11 ); } /** * Update the view by evaluating the given key, * * @param keyTyped * r/R(reset view), all others will be ignored. * @return true if the view should be redrawn, false otherwise. */ public boolean updateView( char keyTyped ) { boolean changed = true; if ( keyTyped == 'r' || keyTyped == 'R' ) { calcViewParameters(); changed = true; } return changed; } /* * Draws a colored cube with cubeHalf length defined by the ObjectSize. */ private void drawCube( GL gl ) { gl.glPushAttrib( GL.GL_CURRENT_BIT | GL.GL_LIGHTING_BIT ); gl.glDisable( GL.GL_BLEND ); float[] color = new float[] { 1, 0, 0 }; gl.glMaterialfv( GL.GL_FRONT, GL.GL_AMBIENT_AND_DIFFUSE, color, 0 ); gl.glBegin( GL.GL_QUADS ); // Front face gl.glNormal3f( 0, 0, 1 ); gl.glVertex3fv( cubeData[0], 0 ); gl.glVertex3fv( cubeData[1], 0 ); gl.glVertex3fv( cubeData[2], 0 ); gl.glVertex3fv( cubeData[3], 0 ); // Back face gl.glNormal3f( 0, 0, -1 ); gl.glVertex3fv( cubeData[5], 0 ); gl.glVertex3fv( cubeData[4], 0 ); gl.glVertex3fv( cubeData[7], 0 ); gl.glVertex3fv( cubeData[6], 0 ); gl.glEnd(); color = new float[] { 0, 1, 0 }; gl.glMaterialfv( GL.GL_FRONT, GL.GL_AMBIENT_AND_DIFFUSE, color, 0 ); gl.glBegin( GL.GL_QUADS ); // Left face gl.glNormal3f( -1, 0, 0 ); gl.glVertex3fv( cubeData[4], 0 ); gl.glVertex3fv( cubeData[0], 0 ); gl.glVertex3fv( cubeData[3], 0 ); gl.glVertex3fv( cubeData[7], 0 ); // Right face gl.glNormal3f( 1, 0, 0 ); gl.glVertex3fv( cubeData[1], 0 ); gl.glVertex3fv( cubeData[5], 0 ); gl.glVertex3fv( cubeData[6], 0 ); gl.glVertex3fv( cubeData[2], 0 ); gl.glEnd(); color = new float[] { 0, 0, 1 }; gl.glMaterialfv( GL.GL_FRONT, GL.GL_AMBIENT_AND_DIFFUSE, color, 0 ); gl.glBegin( GL.GL_QUADS ); // Top face gl.glNormal3f( 0, 1, 0 ); gl.glVertex3fv( cubeData[3], 0 ); gl.glVertex3fv( cubeData[2], 0 ); gl.glVertex3fv( cubeData[6], 0 ); gl.glVertex3fv( cubeData[7], 0 ); // Bottom face gl.glNormal3f( 0, -1, 0 ); gl.glVertex3fv( cubeData[4], 0 ); gl.glVertex3fv( cubeData[5], 0 ); gl.glVertex3fv( cubeData[1], 0 ); gl.glVertex3fv( cubeData[0], 0 ); gl.glEnd(); gl.glEnable( GL.GL_BLEND ); gl.glPopAttrib(); } @Override public void displayChanged( GLAutoDrawable d, boolean modeChanged, boolean deviceChanged ) { // nothing to do } @Override public void init( GLAutoDrawable d ) { d.setGL( new DebugGL( d.getGL() ) ); GL gl = d.getGL(); gl.glClearColor( 0.7f, 0.7f, 1f, 0 ); float[] lightAmbient = { 0.4f, 0.4f, 0.4f, 1.0f }; float[] lightDiffuse = { 0.8f, 0.8f, 0.8f, 1.0f }; float[] lightSpecular = { 1.0f, 1.0f, 1.0f, 1.0f }; float[] lightPosition = { 0.0f, 0.0f, 10.0f, 1.0f }; gl.glLightfv( GL.GL_LIGHT0, GL.GL_AMBIENT, lightAmbient, 0 ); gl.glLightfv( GL.GL_LIGHT0, GL.GL_DIFFUSE, lightDiffuse, 0 ); gl.glLightfv( GL.GL_LIGHT0, GL.GL_SPECULAR, lightSpecular, 0 ); gl.glLightfv( GL.GL_LIGHT0, GL.GL_POSITION, lightPosition, 0 ); gl.glEnable( GL.GL_DEPTH_TEST ); gl.glEnable( GL.GL_LIGHT0 ); gl.glEnable( GL.GL_LIGHTING ); gl.glEnable( GL.GL_BLEND ); // enable color and texture blending gl.glBlendFunc( GL.GL_SRC_ALPHA, GL.GL_ONE_MINUS_SRC_ALPHA ); gl.glMatrixMode( GL.GL_MODELVIEW ); gl.glLoadIdentity(); gl.glEnableClientState( GL.GL_NORMAL_ARRAY ); gl.glEnableClientState( GL.GL_VERTEX_ARRAY ); } @Override public void reshape( GLAutoDrawable d, int x, int y, int width, int height ) { this.width = width; this.height = height; GL gl = d.getGL(); gl.glMatrixMode( GL.GL_PROJECTION ); gl.glLoadIdentity(); glu.gluPerspective( fov, (float) width / height, nearClippingPlane, farClippingPlane ); gl.glMatrixMode( GL.GL_MODELVIEW ); } /** * @return the trackBall */ public TrackBall getTrackBall() { return trackBall; } /** * */ public void removeAllData() { worldRenderableObjects.clear(); bbox = getDefaultBBox(); calcViewParameters(); } /** * @return the renderTestObject */ public final boolean isTestObjectRendered() { return renderTestObject; } /** * @param renderTestObject * the renderTestObject to set */ public final void renderTestObject( boolean renderTestObject ) { this.renderTestObject = renderTestObject; } }
topic: code enhanced module: deegree-core, renderingAPI_3D description: the eyeView-centroid is set to the merged boundingbox now
deegree-core/src/main/java/org/deegree/rendering/r3d/opengl/display/OpenGLEventHandler.java
topic: code enhanced module: deegree-core, renderingAPI_3D description: the eyeView-centroid is set to the merged boundingbox now
<ide><path>eegree-core/src/main/java/org/deegree/rendering/r3d/opengl/display/OpenGLEventHandler.java <ide> * <ide> * @param b <ide> */ <del> public void addDataObjectToScene( WorldRenderableObject b ) { <del> if ( b != null ) { <del> Envelope env = b.getBbox(); <del> if ( env != null ) { <del> if ( isDefaultBBox() ) { <del> bbox = env; <del> } else { <del> bbox.merge( env ); <add> public void addDataObjectToScene( List<WorldRenderableObject> w ) { <add> if ( w != null ) { <add> for ( WorldRenderableObject b : w ) { <add> Envelope env = b.getBbox(); <add> if ( env != null ) { <add> if ( isDefaultBBox() ) { <add> bbox = env; <add> } else { <add> bbox = bbox.merge( env ); <add> } <ide> } <add> worldRenderableObjects.add( b ); <ide> } <ide> calcViewParameters(); <del> worldRenderableObjects.add( b ); <add> <ide> } <ide> } <ide>
Java
agpl-3.0
2a1a3cd151d7031d77397ad3e121ad4575d0f9db
0
deepstupid/sphinx5
/* * Copyright 1999-2002 Carnegie Mellon University. * Portions Copyright 2002 Sun Microsystems, Inc. * Portions Copyright 2002 Mitsubishi Electronic Research Laboratories. * All Rights Reserved. Use is subject to license terms. * * See the file "license.terms" for information on usage and * redistribution of this file, and for a DISCLAIMER OF ALL * WARRANTIES. * */ package edu.cmu.sphinx.knowledge.acoustic; import edu.cmu.sphinx.frontend.Feature; import edu.cmu.sphinx.util.Utilities; import edu.cmu.sphinx.util.LogMath; import java.util.List; import java.util.ArrayList; import java.io.Serializable; /** * Represents a single state in an HMM */ public class HMMState implements Serializable { private HMM hmm; private int state; HMMStateArc[] arcs; private boolean isEmitting; private Senone senone; private static int objectCount; /** * Constructs an HMMState * * @param hmm the hmm for this state * @param which the index for this particular state */ HMMState(HMM hmm, int which) { this.hmm = hmm; this.state = which; this.isEmitting = ((hmm.getTransitionMatrix().length - 1) != state); Utilities.objectTracker("HMMState", objectCount++); } /** * Gets the HMM associated with this state * * @return the HMM */ public HMM getHMM() { return hmm; } /** * Gets the state * * @return the state */ public int getState() { return state; } /** * Gets the score for this HMM state * * @param feature the feature to be scored * * @return the acoustic score for this state. */ public float getScore(Feature feature) { return getSenone().getScore(feature); } /** * Gets the scores for each mixture component in this HMM state * * @param feature the feature to be scored * * @return the acoustic scores for the components of this state. */ public float[] calculateComponentScore(Feature feature) { SenoneSequence ss = hmm.getSenoneSequence(); return ss.getSenones()[state].calculateComponentScore(feature); } /** * Gets the senone for this HMM state * * @return the senone for this state. */ public Senone getSenone() { if (senone == null) { SenoneSequence ss = hmm.getSenoneSequence(); senone = ss.getSenones()[state]; } return senone; } /** * Determines if two HMMStates are equal * * @param other the state to compare this one to * * @return true if the states are equal */ public boolean equals(Object other) { if (this == other) { return true; } else if (!(other instanceof HMMState)) { return false; } else { HMMState otherState = (HMMState) other; return this.hmm == otherState.hmm && this.state == otherState.state; } } /** * Returns the hashcode for this state * * @return the hashcode */ public int hashCode() { return hmm.hashCode() + state; } /** * Determines if this HMMState is an emittting state * * @return true if the state is an emitting state */ // TODO: We may have non-emitting entry states as well. public final boolean isEmitting() { return isEmitting; // return !isExitState(); } /** * Retrieves the state of successor states for this state * * @return the set of successor state arcs */ public HMMStateArc[] getSuccessors() { if (arcs == null) { List list = new ArrayList(); float[][] transitionMatrix = hmm.getTransitionMatrix(); // dumpMatrix("arc", transitionMatrix); for (int i = 0; i < transitionMatrix.length; i++) { if (transitionMatrix[state][i] > LogMath.getLogZero()) { HMMStateArc arc = new HMMStateArc(hmm.getState(i), transitionMatrix[state][i]); list.add(arc); } } arcs = (HMMStateArc[]) list.toArray(new HMMStateArc[list.size()]); } return arcs; } /** * Dumps out a matrix * * @param title the title for the dump * @param matrix the matrix to dump */ private void dumpMatrix(String title, float[][] matrix) { System.out.println(" -- " + title + " --- "); for (int i = 0; i < matrix.length; i++) { for (int j = 0; j < matrix[i].length; j++) { System.out.print(" " + matrix[i][j]); } System.out.println(); } } /** * Determines if this state is an exit state of the HMM * * @return true if the state is an exit state */ public boolean isExitState() { // return (hmm.getTransitionMatrix().length - 1) == state; return !isEmitting; } /** * returns a string represntation of this object * * @return a string representation */ public String toString() { return "HMMS " + hmm + " state " + state; } }
edu/cmu/sphinx/knowledge/acoustic/HMMState.java
/* * Copyright 1999-2002 Carnegie Mellon University. * Portions Copyright 2002 Sun Microsystems, Inc. * Portions Copyright 2002 Mitsubishi Electronic Research Laboratories. * All Rights Reserved. Use is subject to license terms. * * See the file "license.terms" for information on usage and * redistribution of this file, and for a DISCLAIMER OF ALL * WARRANTIES. * */ package edu.cmu.sphinx.knowledge.acoustic; import edu.cmu.sphinx.frontend.Feature; import edu.cmu.sphinx.util.Utilities; import edu.cmu.sphinx.util.LogMath; import java.util.List; import java.util.ArrayList; import java.io.Serializable; /** * Represents a single state in an HMM */ public class HMMState implements Serializable { private HMM hmm; private int state; HMMStateArc[] arcs; private boolean isEmitting; private static int objectCount; /** * Constructs an HMMState * * @param hmm the hmm for this state * @param which the index for this particular state */ HMMState(HMM hmm, int which) { this.hmm = hmm; this.state = which; this.isEmitting = ((hmm.getTransitionMatrix().length - 1) != state); Utilities.objectTracker("HMMState", objectCount++); } /** * Gets the HMM associated with this state * * @return the HMM */ public HMM getHMM() { return hmm; } /** * Gets the state * * @return the state */ public int getState() { return state; } /** * Gets the score for this HMM state * * @param feature the feature to be scored * * @return the acoustic score for this state. */ public float getScore(Feature feature) { SenoneSequence ss = hmm.getSenoneSequence(); return ss.getSenones()[state].getScore(feature); } /** * Gets the scores for each mixture component in this HMM state * * @param feature the feature to be scored * * @return the acoustic scores for the components of this state. */ public float[] calculateComponentScore(Feature feature) { SenoneSequence ss = hmm.getSenoneSequence(); return ss.getSenones()[state].calculateComponentScore(feature); } /** * Gets the senone for this HMM state * * @return the senone for this state. */ public Senone getSenone() { SenoneSequence ss = hmm.getSenoneSequence(); return ss.getSenones()[state]; } /** * Determines if two HMMStates are equal * * @param other the state to compare this one to * * @return true if the states are equal */ public boolean equals(Object other) { if (this == other) { return true; } else if (!(other instanceof HMMState)) { return false; } else { HMMState otherState = (HMMState) other; return this.hmm == otherState.hmm && this.state == otherState.state; } } /** * Returns the hashcode for this state * * @return the hashcode */ public int hashCode() { return hmm.hashCode() + state; } /** * Determines if this HMMState is an emittting state * * @return true if the state is an emitting state */ // TODO: We may have non-emitting entry states as well. public final boolean isEmitting() { return isEmitting; // return !isExitState(); } /** * Retrieves the state of successor states for this state * * @return the set of successor state arcs */ public HMMStateArc[] getSuccessors() { if (arcs == null) { List list = new ArrayList(); float[][] transitionMatrix = hmm.getTransitionMatrix(); // dumpMatrix("arc", transitionMatrix); for (int i = 0; i < transitionMatrix.length; i++) { if (transitionMatrix[state][i] > LogMath.getLogZero()) { HMMStateArc arc = new HMMStateArc(hmm.getState(i), transitionMatrix[state][i]); list.add(arc); } } arcs = (HMMStateArc[]) list.toArray(new HMMStateArc[list.size()]); } return arcs; } /** * Dumps out a matrix * * @param title the title for the dump * @param matrix the matrix to dump */ private void dumpMatrix(String title, float[][] matrix) { System.out.println(" -- " + title + " --- "); for (int i = 0; i < matrix.length; i++) { for (int j = 0; j < matrix[i].length; j++) { System.out.print(" " + matrix[i][j]); } System.out.println(); } } /** * Determines if this state is an exit state of the HMM * * @return true if the state is an exit state */ public boolean isExitState() { // return (hmm.getTransitionMatrix().length - 1) == state; return !isEmitting; } /** * returns a string represntation of this object * * @return a string representation */ public String toString() { return "HMMS " + hmm + " state " + state; } }
Caches the reference to the senone of an HMMState. git-svn-id: a8b04003a33e1d3e001b9d20391fa392a9f62d91@1833 94700074-3cef-4d97-a70e-9c8c206c02f5
edu/cmu/sphinx/knowledge/acoustic/HMMState.java
Caches the reference to the senone of an HMMState.
<ide><path>du/cmu/sphinx/knowledge/acoustic/HMMState.java <ide> private int state; <ide> HMMStateArc[] arcs; <ide> private boolean isEmitting; <add> private Senone senone; <ide> <ide> private static int objectCount; <ide> <ide> * @return the acoustic score for this state. <ide> */ <ide> public float getScore(Feature feature) { <del> SenoneSequence ss = hmm.getSenoneSequence(); <del> return ss.getSenones()[state].getScore(feature); <add> return getSenone().getScore(feature); <ide> } <ide> <ide> <ide> * @return the senone for this state. <ide> */ <ide> public Senone getSenone() { <del> SenoneSequence ss = hmm.getSenoneSequence(); <del> return ss.getSenones()[state]; <add> if (senone == null) { <add> SenoneSequence ss = hmm.getSenoneSequence(); <add> senone = ss.getSenones()[state]; <add> } <add> return senone; <ide> } <ide> <ide>
Java
agpl-3.0
5734d0f8ee48a0e840676a456c63447d7f65d1cd
0
duaneking/rockstar_test,duaneking/rockstar_test,duaneking/rockstar_test,duaneking/rockstar_test,duaneking/rockstar_test,duaneking/rockstar_test,duaneking/rockstar_test,duaneking/rockstar_test,duaneking/rockstar_test,duaneking/rockstar_test
3d377c1c-2e60-11e5-9284-b827eb9e62be
hello.java
3d3212c2-2e60-11e5-9284-b827eb9e62be
3d377c1c-2e60-11e5-9284-b827eb9e62be
hello.java
3d377c1c-2e60-11e5-9284-b827eb9e62be
<ide><path>ello.java <del>3d3212c2-2e60-11e5-9284-b827eb9e62be <add>3d377c1c-2e60-11e5-9284-b827eb9e62be
Java
mit
8b0a596af067ee59065daa037f07a2471974088a
0
marcermarc/DockerMinecraft,marcermarc/DockerMinecraft
import java.io.File; import java.io.OutputStream; public class Start { private static Process process; private static OutputStream output; private static boolean restart = true; public static void main(String args[]) { if (args.length != 2) { System.out.println("Two Arguments needed, first command, second path"); return; } Runtime.getRuntime().addShutdownHook(new Thread() { // get the signal to stop the process @Override public void run() { try { restart = false; // stop the endless loop for restarting the server output.write(new byte[]{(byte) 0x73, (byte) 0x74, (byte) 0x6f, (byte) 0x70, (byte) 0x0d, (byte) 0x0a}); // The byte-array represents "stop" and a return char output.flush(); // write the buffer to the process process.waitFor(); // wait for the server-stop Runtime.getRuntime().halt(0); // retrun 0 so the process end is succsessfull } catch (Exception ex) { System.out.println("Stop Failed: " + ex.getMessage()); } } }); while (restart) { try { ProcessBuilder pb = new ProcessBuilder(args[0]); pb = pb.directory(new File(args[1])); pb = pb.redirectOutput(ProcessBuilder.Redirect.INHERIT); pb.environment().putAll(System.getenv()); process = pb.start(); // init the process output = process.getOutputStream(); // get the output-stream to write commands to the process process.waitFor(); // wait for server-stop } catch (Exception ex) { System.out.println("Execution Failed: " + ex.getMessage()); } } } }
StartProgram/Start.java
import java.io.File; import java.io.OutputStream; public class Start { private static Process process; private static OutputStream output; private static boolean restart = true; public static void main(String args[]) { if (args.length != 2) { System.out.println("Two Arguments needed, first command, second path"); return; } Runtime.getRuntime().addShutdownHook(new Thread() { // get the signal to stop the process @Override public void run() { try { restart = false; // stop the endless loop for restarting the server output.write(new byte[]{(byte) 0x73, (byte) 0x74, (byte) 0x6f, (byte) 0x70, (byte) 0x0d, (byte) 0x0a}); // The byte-array represents "stop" and a return char output.flush(); // write the buffer to the process process.waitFor(); // wait for the server-stop Runtime.getRuntime().halt(0); // retrun 0 so the process end is succsessfull } catch (Exception ex) { System.out.println("Stop Failed: " + ex.getMessage()); } } }); while (restart) { try { ProcessBuilder pb = new ProcessBuilder(args[0]); pb = pb.directory(new File(args[1])); pb = pb.redirectOutput(ProcessBuilder.Redirect.INHERIT); process = pb.start(); // init the process output = process.getOutputStream(); // get the output-stream to write commands to the process process.waitFor(); // wait for server-stop } catch (Exception ex) { System.out.println("Execution Failed: " + ex.getMessage()); } } } }
Set Enviroment
StartProgram/Start.java
Set Enviroment
<ide><path>tartProgram/Start.java <ide> ProcessBuilder pb = new ProcessBuilder(args[0]); <ide> pb = pb.directory(new File(args[1])); <ide> pb = pb.redirectOutput(ProcessBuilder.Redirect.INHERIT); <add> pb.environment().putAll(System.getenv()); <ide> process = pb.start(); // init the process <ide> output = process.getOutputStream(); // get the output-stream to write commands to the process <ide> process.waitFor(); // wait for server-stop
Java
apache-2.0
43aa7dbaf1a041e282d5ff90cdc03a034d7b9a63
0
shakuzen/spring-boot,philwebb/spring-boot,tsachev/spring-boot,ihoneymon/spring-boot,vpavic/spring-boot,shakuzen/spring-boot,wilkinsona/spring-boot,chrylis/spring-boot,habuma/spring-boot,drumonii/spring-boot,scottfrederick/spring-boot,NetoDevel/spring-boot,habuma/spring-boot,ilayaperumalg/spring-boot,royclarkson/spring-boot,NetoDevel/spring-boot,joshiste/spring-boot,habuma/spring-boot,shakuzen/spring-boot,lburgazzoli/spring-boot,tiarebalbi/spring-boot,yangdd1205/spring-boot,rweisleder/spring-boot,htynkn/spring-boot,vpavic/spring-boot,Buzzardo/spring-boot,mbenson/spring-boot,ihoneymon/spring-boot,eddumelendez/spring-boot,michael-simons/spring-boot,jxblum/spring-boot,michael-simons/spring-boot,wilkinsona/spring-boot,rweisleder/spring-boot,rweisleder/spring-boot,eddumelendez/spring-boot,donhuvy/spring-boot,royclarkson/spring-boot,royclarkson/spring-boot,joshiste/spring-boot,mdeinum/spring-boot,drumonii/spring-boot,dreis2211/spring-boot,donhuvy/spring-boot,aahlenst/spring-boot,drumonii/spring-boot,yangdd1205/spring-boot,mdeinum/spring-boot,lburgazzoli/spring-boot,eddumelendez/spring-boot,philwebb/spring-boot,Buzzardo/spring-boot,tiarebalbi/spring-boot,spring-projects/spring-boot,shakuzen/spring-boot,spring-projects/spring-boot,mdeinum/spring-boot,tsachev/spring-boot,htynkn/spring-boot,lburgazzoli/spring-boot,royclarkson/spring-boot,tsachev/spring-boot,lburgazzoli/spring-boot,aahlenst/spring-boot,isopov/spring-boot,isopov/spring-boot,ptahchiev/spring-boot,jxblum/spring-boot,htynkn/spring-boot,spring-projects/spring-boot,chrylis/spring-boot,tsachev/spring-boot,dreis2211/spring-boot,joshiste/spring-boot,kdvolder/spring-boot,bclozel/spring-boot,ptahchiev/spring-boot,felipeg48/spring-boot,ptahchiev/spring-boot,kdvolder/spring-boot,rweisleder/spring-boot,chrylis/spring-boot,jxblum/spring-boot,ptahchiev/spring-boot,aahlenst/spring-boot,royclarkson/spring-boot,felipeg48/spring-boot,ihoneymon/spring-boot,spring-projects/spring-boot,NetoDevel/spring-boot,spring-projects/spring-boot,isopov/spring-boot,drumonii/spring-boot,hello2009chen/spring-boot,ilayaperumalg/spring-boot,philwebb/spring-boot,rweisleder/spring-boot,vpavic/spring-boot,Buzzardo/spring-boot,dreis2211/spring-boot,mbenson/spring-boot,wilkinsona/spring-boot,ihoneymon/spring-boot,ptahchiev/spring-boot,isopov/spring-boot,bclozel/spring-boot,donhuvy/spring-boot,shakuzen/spring-boot,drumonii/spring-boot,dreis2211/spring-boot,bclozel/spring-boot,aahlenst/spring-boot,eddumelendez/spring-boot,mdeinum/spring-boot,tsachev/spring-boot,tiarebalbi/spring-boot,ptahchiev/spring-boot,vpavic/spring-boot,spring-projects/spring-boot,bclozel/spring-boot,mbenson/spring-boot,tiarebalbi/spring-boot,hello2009chen/spring-boot,lburgazzoli/spring-boot,michael-simons/spring-boot,htynkn/spring-boot,ilayaperumalg/spring-boot,joshiste/spring-boot,wilkinsona/spring-boot,vpavic/spring-boot,NetoDevel/spring-boot,eddumelendez/spring-boot,Buzzardo/spring-boot,mdeinum/spring-boot,rweisleder/spring-boot,bclozel/spring-boot,chrylis/spring-boot,tsachev/spring-boot,zhanhb/spring-boot,jxblum/spring-boot,zhanhb/spring-boot,shakuzen/spring-boot,aahlenst/spring-boot,joshiste/spring-boot,scottfrederick/spring-boot,eddumelendez/spring-boot,zhanhb/spring-boot,mdeinum/spring-boot,chrylis/spring-boot,hello2009chen/spring-boot,mbenson/spring-boot,scottfrederick/spring-boot,kdvolder/spring-boot,donhuvy/spring-boot,mbenson/spring-boot,wilkinsona/spring-boot,ilayaperumalg/spring-boot,kdvolder/spring-boot,hello2009chen/spring-boot,donhuvy/spring-boot,kdvolder/spring-boot,isopov/spring-boot,donhuvy/spring-boot,jxblum/spring-boot,dreis2211/spring-boot,felipeg48/spring-boot,hello2009chen/spring-boot,bclozel/spring-boot,mbenson/spring-boot,aahlenst/spring-boot,ilayaperumalg/spring-boot,zhanhb/spring-boot,yangdd1205/spring-boot,tiarebalbi/spring-boot,Buzzardo/spring-boot,philwebb/spring-boot,felipeg48/spring-boot,kdvolder/spring-boot,dreis2211/spring-boot,isopov/spring-boot,felipeg48/spring-boot,wilkinsona/spring-boot,ihoneymon/spring-boot,NetoDevel/spring-boot,scottfrederick/spring-boot,felipeg48/spring-boot,zhanhb/spring-boot,chrylis/spring-boot,habuma/spring-boot,scottfrederick/spring-boot,tiarebalbi/spring-boot,zhanhb/spring-boot,htynkn/spring-boot,drumonii/spring-boot,michael-simons/spring-boot,philwebb/spring-boot,scottfrederick/spring-boot,ilayaperumalg/spring-boot,habuma/spring-boot,jxblum/spring-boot,habuma/spring-boot,Buzzardo/spring-boot,joshiste/spring-boot,michael-simons/spring-boot,vpavic/spring-boot,philwebb/spring-boot,htynkn/spring-boot,michael-simons/spring-boot,ihoneymon/spring-boot
/* * Copyright 2012-2017 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.springframework.boot.actuate.endpoint.mvc; import java.util.Map; import org.springframework.boot.actuate.endpoint.LoggersEndpoint; import org.springframework.boot.actuate.endpoint.LoggersEndpoint.LoggerLevels; import org.springframework.boot.context.properties.ConfigurationProperties; import org.springframework.boot.logging.LogLevel; import org.springframework.http.HttpStatus; import org.springframework.http.ResponseEntity; import org.springframework.web.bind.annotation.PathVariable; import org.springframework.web.bind.annotation.RequestBody; import org.springframework.web.bind.annotation.ResponseBody; import org.springframework.web.bind.annotation.ResponseStatus; /** * Adapter to expose {@link LoggersEndpoint} as an {@link MvcEndpoint}. * * @author Ben Hale * @author Kazuki Shimizu * @author Eddú Meléndez * @since 1.5.0 */ @ConfigurationProperties(prefix = "endpoints.loggers") public class LoggersMvcEndpoint extends EndpointMvcAdapter { private final LoggersEndpoint delegate; public LoggersMvcEndpoint(LoggersEndpoint delegate) { super(delegate); this.delegate = delegate; } @ActuatorGetMapping("/{name:.*}") @ResponseBody @HypermediaDisabled public Object get(@PathVariable String name) { if (!this.delegate.isEnabled()) { // Shouldn't happen - MVC endpoint shouldn't be registered when delegate's // disabled return getDisabledResponse(); } LoggerLevels levels = this.delegate.invoke(name); return (levels == null ? ResponseEntity.notFound().build() : levels); } @ActuatorPostMapping("/{name:.*}") @ResponseBody @HypermediaDisabled public Object set(@PathVariable String name, @RequestBody Map<String, String> configuration) { if (!this.delegate.isEnabled()) { // Shouldn't happen - MVC endpoint shouldn't be registered when delegate's // disabled return getDisabledResponse(); } LogLevel logLevel = getLogLevel(configuration); this.delegate.setLogLevel(name, logLevel); return ResponseEntity.ok().build(); } private LogLevel getLogLevel(Map<String, String> configuration) { String level = configuration.get("configuredLevel"); try { return (level == null ? null : LogLevel.valueOf(level.toUpperCase())); } catch (IllegalArgumentException ex) { throw new InvalidLogLevelException(level); } } /** * Exception thrown when the specified log level cannot be found. */ @SuppressWarnings("serial") @ResponseStatus(value = HttpStatus.BAD_REQUEST, reason = "No such log level") public static class InvalidLogLevelException extends RuntimeException { public InvalidLogLevelException(String level) { super("Log level '" + level + "' is invalid"); } } }
spring-boot-actuator/src/main/java/org/springframework/boot/actuate/endpoint/mvc/LoggersMvcEndpoint.java
/* * Copyright 2012-2017 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.springframework.boot.actuate.endpoint.mvc; import java.util.Map; import org.springframework.boot.actuate.endpoint.LoggersEndpoint; import org.springframework.boot.actuate.endpoint.LoggersEndpoint.LoggerLevels; import org.springframework.boot.context.properties.ConfigurationProperties; import org.springframework.boot.logging.LogLevel; import org.springframework.http.HttpStatus; import org.springframework.http.ResponseEntity; import org.springframework.web.bind.annotation.PathVariable; import org.springframework.web.bind.annotation.RequestBody; import org.springframework.web.bind.annotation.ResponseBody; import org.springframework.web.bind.annotation.ResponseStatus; /** * Adapter to expose {@link LoggersEndpoint} as an {@link MvcEndpoint}. * * @author Ben Hale * @author Kazuki Shimizu * @author Eddú Meléndez * @since 1.5.0 */ @ConfigurationProperties(prefix = "endpoints.loggers") public class LoggersMvcEndpoint extends EndpointMvcAdapter { private final LoggersEndpoint delegate; public LoggersMvcEndpoint(LoggersEndpoint delegate) { super(delegate); this.delegate = delegate; } @ActuatorGetMapping("/{name:.*}") @ResponseBody @HypermediaDisabled public Object get(@PathVariable String name) { if (!this.delegate.isEnabled()) { // Shouldn't happen - MVC endpoint shouldn't be registered when delegate's // disabled return getDisabledResponse(); } LoggerLevels levels = this.delegate.invoke(name); return (levels == null ? ResponseEntity.notFound().build() : levels); } @ActuatorPostMapping("/{name:.*}") @ResponseBody @HypermediaDisabled public Object set(@PathVariable String name, @RequestBody Map<String, String> configuration) { if (!this.delegate.isEnabled()) { // Shouldn't happen - MVC endpoint shouldn't be registered when delegate's // disabled return getDisabledResponse(); } try { LogLevel logLevel = getLogLevel(configuration); this.delegate.setLogLevel(name, logLevel); return ResponseEntity.ok().build(); } catch (IllegalArgumentException ex) { throw new InvalidLogLevelException("No such log level " + configuration.get("configuredLevel")); } } private LogLevel getLogLevel(Map<String, String> configuration) { String level = configuration.get("configuredLevel"); return (level == null ? null : LogLevel.valueOf(level.toUpperCase())); } /** * Exception thrown when the specified log level cannot be found. */ @SuppressWarnings("serial") @ResponseStatus(value = HttpStatus.BAD_REQUEST, reason = "No such log level") public static class InvalidLogLevelException extends RuntimeException { public InvalidLogLevelException(String string) { super(string); } } }
Polish "Provide informative reason when rejecting request with invalid level" See gh-10588
spring-boot-actuator/src/main/java/org/springframework/boot/actuate/endpoint/mvc/LoggersMvcEndpoint.java
Polish "Provide informative reason when rejecting request with invalid level"
<ide><path>pring-boot-actuator/src/main/java/org/springframework/boot/actuate/endpoint/mvc/LoggersMvcEndpoint.java <ide> // disabled <ide> return getDisabledResponse(); <ide> } <del> try { <del> LogLevel logLevel = getLogLevel(configuration); <del> this.delegate.setLogLevel(name, logLevel); <del> return ResponseEntity.ok().build(); <del> } <del> catch (IllegalArgumentException ex) { <del> throw new InvalidLogLevelException("No such log level " + configuration.get("configuredLevel")); <del> } <add> LogLevel logLevel = getLogLevel(configuration); <add> this.delegate.setLogLevel(name, logLevel); <add> return ResponseEntity.ok().build(); <ide> } <ide> <ide> private LogLevel getLogLevel(Map<String, String> configuration) { <ide> String level = configuration.get("configuredLevel"); <del> return (level == null ? null : LogLevel.valueOf(level.toUpperCase())); <add> try { <add> return (level == null ? null : LogLevel.valueOf(level.toUpperCase())); <add> } <add> catch (IllegalArgumentException ex) { <add> throw new InvalidLogLevelException(level); <add> } <ide> } <ide> <ide> /** <ide> @ResponseStatus(value = HttpStatus.BAD_REQUEST, reason = "No such log level") <ide> public static class InvalidLogLevelException extends RuntimeException { <ide> <del> public InvalidLogLevelException(String string) { <del> super(string); <add> public InvalidLogLevelException(String level) { <add> super("Log level '" + level + "' is invalid"); <ide> } <ide> <ide> }
Java
apache-2.0
70dec49f9e6facdad92a30a8c701c81c658b8b61
0
Nickname0806/Test_Q4,apache/tomcat,Nickname0806/Test_Q4,Nickname0806/Test_Q4,apache/tomcat,Nickname0806/Test_Q4,apache/tomcat,apache/tomcat,apache/tomcat
/* * 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 javax.servlet.http; import java.io.IOException; import java.util.Collection; import java.util.Enumeration; import javax.servlet.ServletException; import javax.servlet.ServletRequest; /** * Extends the {@link javax.servlet.ServletRequest} interface to provide request * information for HTTP servlets. * <p> * The servlet container creates an <code>HttpServletRequest</code> object and * passes it as an argument to the servlet's service methods * (<code>doGet</code>, <code>doPost</code>, etc). */ public interface HttpServletRequest extends ServletRequest { /** * String identifier for Basic authentication. Value "BASIC" */ public static final String BASIC_AUTH = "BASIC"; /** * String identifier for Form authentication. Value "FORM" */ public static final String FORM_AUTH = "FORM"; /** * String identifier for Client Certificate authentication. Value * "CLIENT_CERT" */ public static final String CLIENT_CERT_AUTH = "CLIENT_CERT"; /** * String identifier for Digest authentication. Value "DIGEST" */ public static final String DIGEST_AUTH = "DIGEST"; /** * Returns the name of the authentication scheme used to protect the * servlet. All servlet containers support basic, form and client * certificate authentication, and may additionally support digest * authentication. If the servlet is not authenticated <code>null</code> is * returned. * <p> * Same as the value of the CGI variable AUTH_TYPE. * * @return one of the static members BASIC_AUTH, FORM_AUTH, CLIENT_CERT_AUTH, * DIGEST_AUTH (suitable for == comparison) or the * container-specific string indicating the authentication scheme, * or <code>null</code> if the request was not authenticated. */ public String getAuthType(); /** * Returns an array containing all of the <code>Cookie</code> objects the * client sent with this request. This method returns <code>null</code> if * no cookies were sent. * * @return an array of all the <code>Cookies</code> included with this * request, or <code>null</code> if the request has no cookies */ public Cookie[] getCookies(); /** * Returns the value of the specified request header as a <code>long</code> * value that represents a <code>Date</code> object. Use this method with * headers that contain dates, such as <code>If-Modified-Since</code>. * <p> * The date is returned as the number of milliseconds since January 1, 1970 * GMT. The header name is case insensitive. * <p> * If the request did not have a header of the specified name, this method * returns -1. If the header can't be converted to a date, the method throws * an <code>IllegalArgumentException</code>. * * @param name * a <code>String</code> specifying the name of the header * @return a <code>long</code> value representing the date specified in the * header expressed as the number of milliseconds since January 1, * 1970 GMT, or -1 if the named header was not included with the * request * @exception IllegalArgumentException * If the header value can't be converted to a date */ public long getDateHeader(String name); /** * Returns the value of the specified request header as a * <code>String</code>. If the request did not include a header of the * specified name, this method returns <code>null</code>. If there are * multiple headers with the same name, this method returns the first head * in the request. The header name is case insensitive. You can use this * method with any request header. * * @param name * a <code>String</code> specifying the header name * @return a <code>String</code> containing the value of the requested * header, or <code>null</code> if the request does not have a * header of that name */ public String getHeader(String name); /** * Returns all the values of the specified request header as an * <code>Enumeration</code> of <code>String</code> objects. * <p> * Some headers, such as <code>Accept-Language</code> can be sent by clients * as several headers each with a different value rather than sending the * header as a comma separated list. * <p> * If the request did not include any headers of the specified name, this * method returns an empty <code>Enumeration</code>. The header name is case * insensitive. You can use this method with any request header. * * @param name * a <code>String</code> specifying the header name * @return an <code>Enumeration</code> containing the values of the requested * header. If the request does not have any headers of that name * return an empty enumeration. If the container does not allow * access to header information, return null */ public Enumeration<String> getHeaders(String name); /** * Returns an enumeration of all the header names this request contains. If * the request has no headers, this method returns an empty enumeration. * <p> * Some servlet containers do not allow servlets to access headers using * this method, in which case this method returns <code>null</code> * * @return an enumeration of all the header names sent with this request; if * the request has no headers, an empty enumeration; if the servlet * container does not allow servlets to use this method, * <code>null</code> */ public Enumeration<String> getHeaderNames(); /** * Returns the value of the specified request header as an <code>int</code>. * If the request does not have a header of the specified name, this method * returns -1. If the header cannot be converted to an integer, this method * throws a <code>NumberFormatException</code>. * <p> * The header name is case insensitive. * * @param name * a <code>String</code> specifying the name of a request header * @return an integer expressing the value of the request header or -1 if the * request doesn't have a header of this name * @exception NumberFormatException * If the header value can't be converted to an * <code>int</code> */ public int getIntHeader(String name); /** * Returns the name of the HTTP method with which this request was made, for * example, GET, POST, or PUT. Same as the value of the CGI variable * REQUEST_METHOD. * * @return a <code>String</code> specifying the name of the method with * which this request was made */ public String getMethod(); /** * Returns any extra path information associated with the URL the client * sent when it made this request. The extra path information follows the * servlet path but precedes the query string and will start with a "/" * character. * <p> * This method returns <code>null</code> if there was no extra path * information. * <p> * Same as the value of the CGI variable PATH_INFO. * * @return a <code>String</code>, decoded by the web container, specifying * extra path information that comes after the servlet path but * before the query string in the request URL; or <code>null</code> * if the URL does not have any extra path information */ public String getPathInfo(); /** * Returns any extra path information after the servlet name but before the * query string, and translates it to a real path. Same as the value of the * CGI variable PATH_TRANSLATED. * <p> * If the URL does not have any extra path information, this method returns * <code>null</code> or the servlet container cannot translate the virtual * path to a real path for any reason (such as when the web application is * executed from an archive). The web container does not decode this string. * * @return a <code>String</code> specifying the real path, or * <code>null</code> if the URL does not have any extra path * information */ public String getPathTranslated(); /** * Obtain a builder for generating push requests. {@link PushBuilder} * documents how this request will be used as the basis for a push request. * Each call to this method will return a new instance, independent of any * previous instance obtained. * * @return A builder that can be used to generate push requests based on * this request. * * @since Servlet 4.0 */ public default PushBuilder getPushBuilder() { return null; } /** * Returns the portion of the request URI that indicates the context of the * request. The context path always comes first in a request URI. The path * starts with a "/" character but does not end with a "/" character. For * servlets in the default (root) context, this method returns "". The * container does not decode this string. * * @return a <code>String</code> specifying the portion of the request URI * that indicates the context of the request */ public String getContextPath(); /** * Returns the query string that is contained in the request URL after the * path. This method returns <code>null</code> if the URL does not have a * query string. Same as the value of the CGI variable QUERY_STRING. * * @return a <code>String</code> containing the query string or * <code>null</code> if the URL contains no query string. The value * is not decoded by the container. */ public String getQueryString(); /** * Returns the login of the user making this request, if the user has been * authenticated, or <code>null</code> if the user has not been * authenticated. Whether the user name is sent with each subsequent request * depends on the browser and type of authentication. Same as the value of * the CGI variable REMOTE_USER. * * @return a <code>String</code> specifying the login of the user making * this request, or <code>null</code> if the user login is not known */ public String getRemoteUser(); /** * Returns a boolean indicating whether the authenticated user is included * in the specified logical "role". Roles and role membership can be defined * using deployment descriptors. If the user has not been authenticated, the * method returns <code>false</code>. * * @param role * a <code>String</code> specifying the name of the role * @return a <code>boolean</code> indicating whether the user making this * request belongs to a given role; <code>false</code> if the user * has not been authenticated */ public boolean isUserInRole(String role); /** * Returns a <code>java.security.Principal</code> object containing the name * of the current authenticated user. If the user has not been * authenticated, the method returns <code>null</code>. * * @return a <code>java.security.Principal</code> containing the name of the * user making this request; <code>null</code> if the user has not * been authenticated */ public java.security.Principal getUserPrincipal(); /** * Returns the session ID specified by the client. This may not be the same * as the ID of the current valid session for this request. If the client * did not specify a session ID, this method returns <code>null</code>. * * @return a <code>String</code> specifying the session ID, or * <code>null</code> if the request did not specify a session ID * @see #isRequestedSessionIdValid */ public String getRequestedSessionId(); /** * Returns the part of this request's URL from the protocol name up to the * query string in the first line of the HTTP request. The web container * does not decode this String. For example: * <table summary="Examples of Returned Values"> * <tr align=left> * <th>First line of HTTP request</th> * <th>Returned Value</th> * <tr> * <td>POST /some/path.html HTTP/1.1 * <td> * <td>/some/path.html * <tr> * <td>GET http://foo.bar/a.html HTTP/1.0 * <td> * <td>/a.html * <tr> * <td>HEAD /xyz?a=b HTTP/1.1 * <td> * <td>/xyz * </table> * <p> * To reconstruct an URL with a scheme and host, use * {@link #getRequestURL}. * * @return a <code>String</code> containing the part of the URL from the * protocol name up to the query string * @see #getRequestURL */ public String getRequestURI(); /** * Reconstructs the URL the client used to make the request. The returned * URL contains a protocol, server name, port number, and server path, but * it does not include query string parameters. * <p> * Because this method returns a <code>StringBuffer</code>, not a string, * you can modify the URL easily, for example, to append query parameters. * <p> * This method is useful for creating redirect messages and for reporting * errors. * * @return a <code>StringBuffer</code> object containing the reconstructed * URL */ public StringBuffer getRequestURL(); /** * Returns the part of this request's URL that calls the servlet. This path * starts with a "/" character and includes either the servlet name or a * path to the servlet, but does not include any extra path information or a * query string. Same as the value of the CGI variable SCRIPT_NAME. * <p> * This method will return an empty string ("") if the servlet used to * process this request was matched using the "/*" pattern. * * @return a <code>String</code> containing the name or path of the servlet * being called, as specified in the request URL, decoded, or an * empty string if the servlet used to process the request is * matched using the "/*" pattern. */ public String getServletPath(); /** * Returns the current <code>HttpSession</code> associated with this request * or, if there is no current session and <code>create</code> is true, * returns a new session. * <p> * If <code>create</code> is <code>false</code> and the request has no valid * <code>HttpSession</code>, this method returns <code>null</code>. * <p> * To make sure the session is properly maintained, you must call this * method before the response is committed. If the container is using * cookies to maintain session integrity and is asked to create a new * session when the response is committed, an IllegalStateException is * thrown. * * @param create * <code>true</code> to create a new session for this request if * necessary; <code>false</code> to return <code>null</code> if * there's no current session * @return the <code>HttpSession</code> associated with this request or * <code>null</code> if <code>create</code> is <code>false</code> * and the request has no valid session * @see #getSession() */ public HttpSession getSession(boolean create); /** * Returns the current session associated with this request, or if the * request does not have a session, creates one. * * @return the <code>HttpSession</code> associated with this request * @see #getSession(boolean) */ public HttpSession getSession(); /** * Changes the session ID of the session associated with this request. This * method does not create a new session object it only changes the ID of the * current session. * * @return the new session ID allocated to the session * @see HttpSessionIdListener * @since Servlet 3.1 */ public String changeSessionId(); /** * Checks whether the requested session ID is still valid. * * @return <code>true</code> if this request has an id for a valid session * in the current session context; <code>false</code> otherwise * @see #getRequestedSessionId * @see #getSession */ public boolean isRequestedSessionIdValid(); /** * Checks whether the requested session ID came in as a cookie. * * @return <code>true</code> if the session ID came in as a cookie; * otherwise, <code>false</code> * @see #getSession */ public boolean isRequestedSessionIdFromCookie(); /** * Checks whether the requested session ID came in as part of the request * URL. * * @return <code>true</code> if the session ID came in as part of a URL; * otherwise, <code>false</code> * @see #getSession */ public boolean isRequestedSessionIdFromURL(); /** * @return {@link #isRequestedSessionIdFromURL()} * @deprecated As of Version 2.1 of the Java Servlet API, use * {@link #isRequestedSessionIdFromURL} instead. */ @Deprecated public boolean isRequestedSessionIdFromUrl(); /** * Triggers the same authentication process as would be triggered if the * request is for a resource that is protected by a security constraint. * * @param response The response to use to return any authentication * challenge * @return <code>true</code> if the user is successfully authenticated and * <code>false</code> if not * * @throws IOException if the authentication process attempted to read from * the request or write to the response and an I/O error occurred * @throws IllegalStateException if the authentication process attempted to * write to the response after it had been committed * @throws ServletException if the authentication failed and the caller is * expected to handle the failure * @since Servlet 3.0 */ public boolean authenticate(HttpServletResponse response) throws IOException, ServletException; /** * Authenticate the provided user name and password and then associated the * authenticated user with the request. * * @param username The user name to authenticate * @param password The password to use to authenticate the user * * @throws ServletException * If any of {@link #getRemoteUser()}, * {@link #getUserPrincipal()} or {@link #getAuthType()} are * non-null, if the configured authenticator does not support * user name and password authentication or if the * authentication fails * @since Servlet 3.0 */ public void login(String username, String password) throws ServletException; /** * Removes any authenticated user from the request. * * @throws ServletException * If the logout fails * @since Servlet 3.0 */ public void logout() throws ServletException; /** * Return a collection of all uploaded Parts. * * @return A collection of all uploaded Parts. * @throws IOException * if an I/O error occurs * @throws IllegalStateException * if size limits are exceeded or no multipart configuration is * provided * @throws ServletException * if the request is not multipart/form-data * @since Servlet 3.0 */ public Collection<Part> getParts() throws IOException, ServletException; /** * Gets the named Part or null if the Part does not exist. Triggers upload * of all Parts. * * @param name The name of the Part to obtain * * @return The named Part or null if the Part does not exist * @throws IOException * if an I/O error occurs * @throws IllegalStateException * if size limits are exceeded * @throws ServletException * if the request is not multipart/form-data * @since Servlet 3.0 */ public Part getPart(String name) throws IOException, ServletException; /** * Start the HTTP upgrade process and pass the connection to the provided * protocol handler once the current request/response pair has completed * processing. Calling this method sets the response status to {@link * HttpServletResponse#SC_SWITCHING_PROTOCOLS} and flushes the response. * Protocol specific headers must have already been set before this method * is called. * * @param <T> The type of the upgrade handler * @param httpUpgradeHandlerClass The class that implements the upgrade * handler * * @return A newly created instance of the specified upgrade handler type * * @throws IOException * if an I/O error occurred during the upgrade * @throws ServletException * if the given httpUpgradeHandlerClass fails to be instantiated * @since Servlet 3.1 */ public <T extends HttpUpgradeHandler> T upgrade( Class<T> httpUpgradeHandlerClass) throws java.io.IOException, ServletException; }
java/javax/servlet/http/HttpServletRequest.java
/* * 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 javax.servlet.http; import java.io.IOException; import java.util.Collection; import java.util.Enumeration; import javax.servlet.ServletException; import javax.servlet.ServletRequest; /** * Extends the {@link javax.servlet.ServletRequest} interface to provide request * information for HTTP servlets. * <p> * The servlet container creates an <code>HttpServletRequest</code> object and * passes it as an argument to the servlet's service methods * (<code>doGet</code>, <code>doPost</code>, etc). */ public interface HttpServletRequest extends ServletRequest { /** * String identifier for Basic authentication. Value "BASIC" */ public static final String BASIC_AUTH = "BASIC"; /** * String identifier for Form authentication. Value "FORM" */ public static final String FORM_AUTH = "FORM"; /** * String identifier for Client Certificate authentication. Value * "CLIENT_CERT" */ public static final String CLIENT_CERT_AUTH = "CLIENT_CERT"; /** * String identifier for Digest authentication. Value "DIGEST" */ public static final String DIGEST_AUTH = "DIGEST"; /** * Returns the name of the authentication scheme used to protect the * servlet. All servlet containers support basic, form and client * certificate authentication, and may additionally support digest * authentication. If the servlet is not authenticated <code>null</code> is * returned. * <p> * Same as the value of the CGI variable AUTH_TYPE. * * @return one of the static members BASIC_AUTH, FORM_AUTH, CLIENT_CERT_AUTH, * DIGEST_AUTH (suitable for == comparison) or the * container-specific string indicating the authentication scheme, * or <code>null</code> if the request was not authenticated. */ public String getAuthType(); /** * Returns an array containing all of the <code>Cookie</code> objects the * client sent with this request. This method returns <code>null</code> if * no cookies were sent. * * @return an array of all the <code>Cookies</code> included with this * request, or <code>null</code> if the request has no cookies */ public Cookie[] getCookies(); /** * Returns the value of the specified request header as a <code>long</code> * value that represents a <code>Date</code> object. Use this method with * headers that contain dates, such as <code>If-Modified-Since</code>. * <p> * The date is returned as the number of milliseconds since January 1, 1970 * GMT. The header name is case insensitive. * <p> * If the request did not have a header of the specified name, this method * returns -1. If the header can't be converted to a date, the method throws * an <code>IllegalArgumentException</code>. * * @param name * a <code>String</code> specifying the name of the header * @return a <code>long</code> value representing the date specified in the * header expressed as the number of milliseconds since January 1, * 1970 GMT, or -1 if the named header was not included with the * request * @exception IllegalArgumentException * If the header value can't be converted to a date */ public long getDateHeader(String name); /** * Returns the value of the specified request header as a * <code>String</code>. If the request did not include a header of the * specified name, this method returns <code>null</code>. If there are * multiple headers with the same name, this method returns the first head * in the request. The header name is case insensitive. You can use this * method with any request header. * * @param name * a <code>String</code> specifying the header name * @return a <code>String</code> containing the value of the requested * header, or <code>null</code> if the request does not have a * header of that name */ public String getHeader(String name); /** * Returns all the values of the specified request header as an * <code>Enumeration</code> of <code>String</code> objects. * <p> * Some headers, such as <code>Accept-Language</code> can be sent by clients * as several headers each with a different value rather than sending the * header as a comma separated list. * <p> * If the request did not include any headers of the specified name, this * method returns an empty <code>Enumeration</code>. The header name is case * insensitive. You can use this method with any request header. * * @param name * a <code>String</code> specifying the header name * @return an <code>Enumeration</code> containing the values of the requested * header. If the request does not have any headers of that name * return an empty enumeration. If the container does not allow * access to header information, return null */ public Enumeration<String> getHeaders(String name); /** * Returns an enumeration of all the header names this request contains. If * the request has no headers, this method returns an empty enumeration. * <p> * Some servlet containers do not allow servlets to access headers using * this method, in which case this method returns <code>null</code> * * @return an enumeration of all the header names sent with this request; if * the request has no headers, an empty enumeration; if the servlet * container does not allow servlets to use this method, * <code>null</code> */ public Enumeration<String> getHeaderNames(); /** * Returns the value of the specified request header as an <code>int</code>. * If the request does not have a header of the specified name, this method * returns -1. If the header cannot be converted to an integer, this method * throws a <code>NumberFormatException</code>. * <p> * The header name is case insensitive. * * @param name * a <code>String</code> specifying the name of a request header * @return an integer expressing the value of the request header or -1 if the * request doesn't have a header of this name * @exception NumberFormatException * If the header value can't be converted to an * <code>int</code> */ public int getIntHeader(String name); /** * Returns the name of the HTTP method with which this request was made, for * example, GET, POST, or PUT. Same as the value of the CGI variable * REQUEST_METHOD. * * @return a <code>String</code> specifying the name of the method with * which this request was made */ public String getMethod(); /** * Returns any extra path information associated with the URL the client * sent when it made this request. The extra path information follows the * servlet path but precedes the query string and will start with a "/" * character. * <p> * This method returns <code>null</code> if there was no extra path * information. * <p> * Same as the value of the CGI variable PATH_INFO. * * @return a <code>String</code>, decoded by the web container, specifying * extra path information that comes after the servlet path but * before the query string in the request URL; or <code>null</code> * if the URL does not have any extra path information */ public String getPathInfo(); /** * Returns any extra path information after the servlet name but before the * query string, and translates it to a real path. Same as the value of the * CGI variable PATH_TRANSLATED. * <p> * If the URL does not have any extra path information, this method returns * <code>null</code> or the servlet container cannot translate the virtual * path to a real path for any reason (such as when the web application is * executed from an archive). The web container does not decode this string. * * @return a <code>String</code> specifying the real path, or * <code>null</code> if the URL does not have any extra path * information */ public String getPathTranslated(); /** * Obtain a builder for generating push requests. {@link PushBuilder} * documents how this request will be used as the basis for a push request. * Each call to this method will return a new instance, independent of any * previous instance obtained. * * @return A builder than can be used to generate push requests based on * this request. * * @since Servlet 4.0 */ public default PushBuilder getPushBuilder() { return null; } /** * Returns the portion of the request URI that indicates the context of the * request. The context path always comes first in a request URI. The path * starts with a "/" character but does not end with a "/" character. For * servlets in the default (root) context, this method returns "". The * container does not decode this string. * * @return a <code>String</code> specifying the portion of the request URI * that indicates the context of the request */ public String getContextPath(); /** * Returns the query string that is contained in the request URL after the * path. This method returns <code>null</code> if the URL does not have a * query string. Same as the value of the CGI variable QUERY_STRING. * * @return a <code>String</code> containing the query string or * <code>null</code> if the URL contains no query string. The value * is not decoded by the container. */ public String getQueryString(); /** * Returns the login of the user making this request, if the user has been * authenticated, or <code>null</code> if the user has not been * authenticated. Whether the user name is sent with each subsequent request * depends on the browser and type of authentication. Same as the value of * the CGI variable REMOTE_USER. * * @return a <code>String</code> specifying the login of the user making * this request, or <code>null</code> if the user login is not known */ public String getRemoteUser(); /** * Returns a boolean indicating whether the authenticated user is included * in the specified logical "role". Roles and role membership can be defined * using deployment descriptors. If the user has not been authenticated, the * method returns <code>false</code>. * * @param role * a <code>String</code> specifying the name of the role * @return a <code>boolean</code> indicating whether the user making this * request belongs to a given role; <code>false</code> if the user * has not been authenticated */ public boolean isUserInRole(String role); /** * Returns a <code>java.security.Principal</code> object containing the name * of the current authenticated user. If the user has not been * authenticated, the method returns <code>null</code>. * * @return a <code>java.security.Principal</code> containing the name of the * user making this request; <code>null</code> if the user has not * been authenticated */ public java.security.Principal getUserPrincipal(); /** * Returns the session ID specified by the client. This may not be the same * as the ID of the current valid session for this request. If the client * did not specify a session ID, this method returns <code>null</code>. * * @return a <code>String</code> specifying the session ID, or * <code>null</code> if the request did not specify a session ID * @see #isRequestedSessionIdValid */ public String getRequestedSessionId(); /** * Returns the part of this request's URL from the protocol name up to the * query string in the first line of the HTTP request. The web container * does not decode this String. For example: * <table summary="Examples of Returned Values"> * <tr align=left> * <th>First line of HTTP request</th> * <th>Returned Value</th> * <tr> * <td>POST /some/path.html HTTP/1.1 * <td> * <td>/some/path.html * <tr> * <td>GET http://foo.bar/a.html HTTP/1.0 * <td> * <td>/a.html * <tr> * <td>HEAD /xyz?a=b HTTP/1.1 * <td> * <td>/xyz * </table> * <p> * To reconstruct an URL with a scheme and host, use * {@link #getRequestURL}. * * @return a <code>String</code> containing the part of the URL from the * protocol name up to the query string * @see #getRequestURL */ public String getRequestURI(); /** * Reconstructs the URL the client used to make the request. The returned * URL contains a protocol, server name, port number, and server path, but * it does not include query string parameters. * <p> * Because this method returns a <code>StringBuffer</code>, not a string, * you can modify the URL easily, for example, to append query parameters. * <p> * This method is useful for creating redirect messages and for reporting * errors. * * @return a <code>StringBuffer</code> object containing the reconstructed * URL */ public StringBuffer getRequestURL(); /** * Returns the part of this request's URL that calls the servlet. This path * starts with a "/" character and includes either the servlet name or a * path to the servlet, but does not include any extra path information or a * query string. Same as the value of the CGI variable SCRIPT_NAME. * <p> * This method will return an empty string ("") if the servlet used to * process this request was matched using the "/*" pattern. * * @return a <code>String</code> containing the name or path of the servlet * being called, as specified in the request URL, decoded, or an * empty string if the servlet used to process the request is * matched using the "/*" pattern. */ public String getServletPath(); /** * Returns the current <code>HttpSession</code> associated with this request * or, if there is no current session and <code>create</code> is true, * returns a new session. * <p> * If <code>create</code> is <code>false</code> and the request has no valid * <code>HttpSession</code>, this method returns <code>null</code>. * <p> * To make sure the session is properly maintained, you must call this * method before the response is committed. If the container is using * cookies to maintain session integrity and is asked to create a new * session when the response is committed, an IllegalStateException is * thrown. * * @param create * <code>true</code> to create a new session for this request if * necessary; <code>false</code> to return <code>null</code> if * there's no current session * @return the <code>HttpSession</code> associated with this request or * <code>null</code> if <code>create</code> is <code>false</code> * and the request has no valid session * @see #getSession() */ public HttpSession getSession(boolean create); /** * Returns the current session associated with this request, or if the * request does not have a session, creates one. * * @return the <code>HttpSession</code> associated with this request * @see #getSession(boolean) */ public HttpSession getSession(); /** * Changes the session ID of the session associated with this request. This * method does not create a new session object it only changes the ID of the * current session. * * @return the new session ID allocated to the session * @see HttpSessionIdListener * @since Servlet 3.1 */ public String changeSessionId(); /** * Checks whether the requested session ID is still valid. * * @return <code>true</code> if this request has an id for a valid session * in the current session context; <code>false</code> otherwise * @see #getRequestedSessionId * @see #getSession */ public boolean isRequestedSessionIdValid(); /** * Checks whether the requested session ID came in as a cookie. * * @return <code>true</code> if the session ID came in as a cookie; * otherwise, <code>false</code> * @see #getSession */ public boolean isRequestedSessionIdFromCookie(); /** * Checks whether the requested session ID came in as part of the request * URL. * * @return <code>true</code> if the session ID came in as part of a URL; * otherwise, <code>false</code> * @see #getSession */ public boolean isRequestedSessionIdFromURL(); /** * @return {@link #isRequestedSessionIdFromURL()} * @deprecated As of Version 2.1 of the Java Servlet API, use * {@link #isRequestedSessionIdFromURL} instead. */ @Deprecated public boolean isRequestedSessionIdFromUrl(); /** * Triggers the same authentication process as would be triggered if the * request is for a resource that is protected by a security constraint. * * @param response The response to use to return any authentication * challenge * @return <code>true</code> if the user is successfully authenticated and * <code>false</code> if not * * @throws IOException if the authentication process attempted to read from * the request or write to the response and an I/O error occurred * @throws IllegalStateException if the authentication process attempted to * write to the response after it had been committed * @throws ServletException if the authentication failed and the caller is * expected to handle the failure * @since Servlet 3.0 */ public boolean authenticate(HttpServletResponse response) throws IOException, ServletException; /** * Authenticate the provided user name and password and then associated the * authenticated user with the request. * * @param username The user name to authenticate * @param password The password to use to authenticate the user * * @throws ServletException * If any of {@link #getRemoteUser()}, * {@link #getUserPrincipal()} or {@link #getAuthType()} are * non-null, if the configured authenticator does not support * user name and password authentication or if the * authentication fails * @since Servlet 3.0 */ public void login(String username, String password) throws ServletException; /** * Removes any authenticated user from the request. * * @throws ServletException * If the logout fails * @since Servlet 3.0 */ public void logout() throws ServletException; /** * Return a collection of all uploaded Parts. * * @return A collection of all uploaded Parts. * @throws IOException * if an I/O error occurs * @throws IllegalStateException * if size limits are exceeded or no multipart configuration is * provided * @throws ServletException * if the request is not multipart/form-data * @since Servlet 3.0 */ public Collection<Part> getParts() throws IOException, ServletException; /** * Gets the named Part or null if the Part does not exist. Triggers upload * of all Parts. * * @param name The name of the Part to obtain * * @return The named Part or null if the Part does not exist * @throws IOException * if an I/O error occurs * @throws IllegalStateException * if size limits are exceeded * @throws ServletException * if the request is not multipart/form-data * @since Servlet 3.0 */ public Part getPart(String name) throws IOException, ServletException; /** * Start the HTTP upgrade process and pass the connection to the provided * protocol handler once the current request/response pair has completed * processing. Calling this method sets the response status to {@link * HttpServletResponse#SC_SWITCHING_PROTOCOLS} and flushes the response. * Protocol specific headers must have already been set before this method * is called. * * @param <T> The type of the upgrade handler * @param httpUpgradeHandlerClass The class that implements the upgrade * handler * * @return A newly created instance of the specified upgrade handler type * * @throws IOException * if an I/O error occurred during the upgrade * @throws ServletException * if the given httpUpgradeHandlerClass fails to be instantiated * @since Servlet 3.1 */ public <T extends HttpUpgradeHandler> T upgrade( Class<T> httpUpgradeHandlerClass) throws java.io.IOException, ServletException; }
Fix typo git-svn-id: 79cef5a5a257cc9dbe40a45ac190115b4780e2d0@1708100 13f79535-47bb-0310-9956-ffa450edef68
java/javax/servlet/http/HttpServletRequest.java
Fix typo
<ide><path>ava/javax/servlet/http/HttpServletRequest.java <ide> * Each call to this method will return a new instance, independent of any <ide> * previous instance obtained. <ide> * <del> * @return A builder than can be used to generate push requests based on <add> * @return A builder that can be used to generate push requests based on <ide> * this request. <ide> * <ide> * @since Servlet 4.0
Java
apache-2.0
2c455273b09d876576a4f698675a6329bea349eb
0
krasa/FrameSwitcher
package krasa.frameswitcher; import java.awt.*; import java.io.File; import java.io.IOException; import javax.imageio.ImageIO; import javax.swing.*; import org.jetbrains.annotations.Nullable; import org.jetbrains.annotations.SystemIndependent; import com.intellij.openapi.diagnostic.Logger; import com.intellij.util.IconUtil; import com.intellij.util.SVGLoader; import com.intellij.util.ui.JBImageIcon; import com.intellij.util.ui.UIUtil; public class IconResolver { private final static Logger LOG = Logger.getInstance(FrameSwitchAction.class); public static Icon resolveIcon(@SystemIndependent String basepath, boolean loadProjectIcon) { try { if (!loadProjectIcon) { return null; } File base = new File(basepath); if (!base.exists()) { return null; } if (base.isFile()) { base = base.getParentFile(); } if (base.getName().startsWith(".")) { base = base.getParentFile(); } if (!base.exists()) { return null; } Icon icon = null; icon = getIcon(base, ".idea/icon.png"); if (icon != null) { return icon; } // icon = getIcon(base, ".idea/icon.svg"); // if (icon != null) { // return icon; // } icon = getIcon(base, "src/main/resources/META-INF/pluginIcon.svg"); if (icon != null) { return icon; } icon = getIcon(base, "resources/META-INF/pluginIcon.svg"); if (icon != null) { return icon; } icon = getIcon(base, "META-INF/pluginIcon.svg"); if (icon != null) { return icon; } icon = getIcon(base, "icon.png"); if (icon != null) { return icon; } icon = getIcon(base, "icon.svg"); if (icon != null) { return icon; } return icon; } catch (Throwable e) { LOG.debug(e); return null; } } @Nullable public static Icon getIcon(File base, String subpath) { File file = null; try { Icon icon = null; if (UIUtil.isUnderDarcula()) { File darcula = new File(base, subpath.replace(".svg", "_dark.svg").replace(".png", "_dark.png")); if (darcula.exists()) { file = darcula; } } if (file == null) { file = new File(base, subpath); } if (file.exists()) { icon = new JBImageIcon(loadImage(file)); if (icon != null && icon.getIconHeight() > 1 && icon.getIconHeight() != FrameSwitchAction.empty.getIconHeight()) { icon = IconUtil.scale(icon, null, (float) FrameSwitchAction.empty.getIconHeight() / icon.getIconHeight()); } // material-theme-jetbrains needs to be scaled 2x if (icon != null && icon.getIconHeight() > 1 && icon.getIconHeight() != FrameSwitchAction.empty.getIconHeight()) { icon = IconUtil.scale(icon, null, (float) FrameSwitchAction.empty.getIconHeight() / icon.getIconHeight()); } if (icon.getIconHeight() > FrameSwitchAction.empty.getIconHeight()) { LOG.error("Scaling failed, wrong icon size: " + file.getAbsolutePath() + " " + icon.getIconHeight() + "x" + icon.getIconWidth()); return null; } } return icon; } catch (Throwable e) { LOG.debug(String.valueOf(file), e); return null; } } public static Image loadImage(File file) throws IOException { if (file.getName().endsWith(".svg")) { return SVGLoader.load(file.toURI().toURL(), 1.0f); } else { return ImageIO.read(file); } } }
src/krasa/frameswitcher/IconResolver.java
package krasa.frameswitcher; import com.intellij.openapi.diagnostic.Logger; import com.intellij.util.IconUtil; import com.intellij.util.SVGLoader; import com.intellij.util.ui.JBImageIcon; import com.intellij.util.ui.UIUtil; import org.jetbrains.annotations.Nullable; import org.jetbrains.annotations.SystemIndependent; import javax.imageio.ImageIO; import javax.swing.*; import java.awt.*; import java.io.File; import java.io.IOException; public class IconResolver { private final static Logger LOG = Logger.getInstance(FrameSwitchAction.class); public static Icon resolveIcon(@SystemIndependent String basepath, boolean loadProjectIcon) { try { if (!loadProjectIcon) { return null; } File base = new File(basepath); if (!base.exists()) { return null; } if (base.isFile()) { base = base.getParentFile(); } if (base.getName().startsWith(".")) { base = base.getParentFile(); } if (!base.exists()) { return null; } Icon icon = null; icon = getIcon(base, ".idea/icon.png"); if (icon != null) { return icon; } // icon = getIcon(base, ".idea/icon.svg"); // if (icon != null) { // return icon; // } icon = getIcon(base, "src/main/resources/META-INF/pluginIcon.svg"); if (icon != null) { return icon; } icon = getIcon(base, "resources/META-INF/pluginIcon.svg"); if (icon != null) { return icon; } icon = getIcon(base, "META-INF/pluginIcon.svg"); if (icon != null) { return icon; } icon = getIcon(base, "icon.png"); if (icon != null) { return icon; } icon = getIcon(base, "icon.svg"); if (icon != null) { return icon; } return icon; } catch (Throwable e) { LOG.debug(e); return null; } } @Nullable public static Icon getIcon(File base, String subpath) { File file = null; try { Icon icon = null; if (UIUtil.isUnderDarcula()) { File darcula = new File(base, subpath.replace(".svg", "_dark.svg").replace(".png", "_dark.png")); if (darcula.exists()) { file = darcula; } } if (file == null) { file = new File(base, subpath); } if (file.exists()) { icon = new JBImageIcon(loadImage(file)); if (icon != null && icon.getIconHeight() > 1 && icon.getIconHeight() != FrameSwitchAction.empty.getIconHeight()) { icon = IconUtil.scale(icon, null, (float) FrameSwitchAction.empty.getIconHeight() / icon.getIconHeight()); } //material-theme-jetbrains needs to be scaled 2x if (icon != null && icon.getIconHeight() > 1 && icon.getIconHeight() != FrameSwitchAction.empty.getIconHeight()) { icon = IconUtil.scale(icon, null, (float) FrameSwitchAction.empty.getIconHeight() / icon.getIconHeight()); } if (icon.getIconHeight() > FrameSwitchAction.empty.getIconHeight()) { LOG.error("Scaling failed, wrong icon size: " + file.getAbsolutePath() + " " + icon.getIconHeight() + "x" + icon.getIconWidth()); return null; } } return icon; } catch (Throwable e) { LOG.debug(String.valueOf(file), e); return null; } } public static Image loadImage(File file) throws IOException { if (file.getName().endsWith(".svg")) { return SVGLoader.load(file.toURI().toURL(), 1.0f); } else { return ImageIO.read(file); } } }
notes fix
src/krasa/frameswitcher/IconResolver.java
notes fix
<ide><path>rc/krasa/frameswitcher/IconResolver.java <ide> package krasa.frameswitcher; <add> <add>import java.awt.*; <add>import java.io.File; <add>import java.io.IOException; <add> <add>import javax.imageio.ImageIO; <add>import javax.swing.*; <add> <add>import org.jetbrains.annotations.Nullable; <add>import org.jetbrains.annotations.SystemIndependent; <ide> <ide> import com.intellij.openapi.diagnostic.Logger; <ide> import com.intellij.util.IconUtil; <ide> import com.intellij.util.SVGLoader; <ide> import com.intellij.util.ui.JBImageIcon; <ide> import com.intellij.util.ui.UIUtil; <del>import org.jetbrains.annotations.Nullable; <del>import org.jetbrains.annotations.SystemIndependent; <del> <del>import javax.imageio.ImageIO; <del>import javax.swing.*; <del>import java.awt.*; <del>import java.io.File; <del>import java.io.IOException; <ide> <ide> public class IconResolver { <ide> private final static Logger LOG = Logger.getInstance(FrameSwitchAction.class); <ide> return null; <ide> } <ide> <del> <ide> Icon icon = null; <ide> icon = getIcon(base, ".idea/icon.png"); <ide> if (icon != null) { <ide> return icon; <ide> } <del>// icon = getIcon(base, ".idea/icon.svg"); <del>// if (icon != null) { <del>// return icon; <del>// } <add> // icon = getIcon(base, ".idea/icon.svg"); <add> // if (icon != null) { <add> // return icon; <add> // } <ide> icon = getIcon(base, "src/main/resources/META-INF/pluginIcon.svg"); <ide> if (icon != null) { <ide> return icon; <ide> <ide> if (file.exists()) { <ide> icon = new JBImageIcon(loadImage(file)); <del> if (icon != null && icon.getIconHeight() > 1 && icon.getIconHeight() != FrameSwitchAction.empty.getIconHeight()) { <del> icon = IconUtil.scale(icon, null, (float) FrameSwitchAction.empty.getIconHeight() / icon.getIconHeight()); <add> if (icon != null && icon.getIconHeight() > 1 <add> && icon.getIconHeight() != FrameSwitchAction.empty.getIconHeight()) { <add> icon = IconUtil.scale(icon, null, <add> (float) FrameSwitchAction.empty.getIconHeight() / icon.getIconHeight()); <ide> } <del> //material-theme-jetbrains needs to be scaled 2x <del> if (icon != null && icon.getIconHeight() > 1 && icon.getIconHeight() != FrameSwitchAction.empty.getIconHeight()) { <del> icon = IconUtil.scale(icon, null, (float) FrameSwitchAction.empty.getIconHeight() / icon.getIconHeight()); <add> // material-theme-jetbrains needs to be scaled 2x <add> if (icon != null && icon.getIconHeight() > 1 <add> && icon.getIconHeight() != FrameSwitchAction.empty.getIconHeight()) { <add> icon = IconUtil.scale(icon, null, <add> (float) FrameSwitchAction.empty.getIconHeight() / icon.getIconHeight()); <ide> } <ide> if (icon.getIconHeight() > FrameSwitchAction.empty.getIconHeight()) { <del> LOG.error("Scaling failed, wrong icon size: " + file.getAbsolutePath() + " " + icon.getIconHeight() + "x" + icon.getIconWidth()); <add> LOG.error("Scaling failed, wrong icon size: " + file.getAbsolutePath() + " " + icon.getIconHeight() <add> + "x" + icon.getIconWidth()); <ide> return null; <ide> } <ide> }
Java
mit
41f7d2e8a447b93911181218c067235194a4f019
0
Nunnery/MythicDrops
package net.nunnerycode.bukkit.mythicdrops.spawning; import mkremins.fanciful.FancyMessage; import net.nunnerycode.bukkit.mythicdrops.MythicDropsPlugin; import net.nunnerycode.bukkit.mythicdrops.api.MythicDrops; import net.nunnerycode.bukkit.mythicdrops.api.items.CustomItem; import net.nunnerycode.bukkit.mythicdrops.api.items.ItemGenerationReason; import net.nunnerycode.bukkit.mythicdrops.api.names.NameType; import net.nunnerycode.bukkit.mythicdrops.api.tiers.Tier; import net.nunnerycode.bukkit.mythicdrops.events.EntitySpawningEvent; import net.nunnerycode.bukkit.mythicdrops.identification.IdentityTome; import net.nunnerycode.bukkit.mythicdrops.identification.UnidentifiedItem; import net.nunnerycode.bukkit.mythicdrops.items.CustomItemMap; import net.nunnerycode.bukkit.mythicdrops.names.NameMap; import net.nunnerycode.bukkit.mythicdrops.socketting.SocketGem; import net.nunnerycode.bukkit.mythicdrops.socketting.SocketItem; import net.nunnerycode.bukkit.mythicdrops.utils.CustomItemUtil; import net.nunnerycode.bukkit.mythicdrops.utils.EntityUtil; import net.nunnerycode.bukkit.mythicdrops.utils.ItemStackUtil; import net.nunnerycode.bukkit.mythicdrops.utils.SocketGemUtil; import net.nunnerycode.bukkit.mythicdrops.utils.TierUtil; import org.apache.commons.lang.math.RandomUtils; import org.bukkit.Bukkit; import org.bukkit.Location; import org.bukkit.Material; import org.bukkit.World; import org.bukkit.entity.Entity; import org.bukkit.entity.LivingEntity; import org.bukkit.entity.Monster; import org.bukkit.entity.Player; import org.bukkit.entity.Skeleton; import org.bukkit.event.EventHandler; import org.bukkit.event.EventPriority; import org.bukkit.event.Listener; import org.bukkit.event.entity.CreatureSpawnEvent; import org.bukkit.event.entity.EntityDamageEvent; import org.bukkit.event.entity.EntityDeathEvent; import org.bukkit.inventory.ItemStack; import java.util.ArrayList; import java.util.Collection; import java.util.HashMap; import java.util.List; import java.util.Map; public final class ItemSpawningListener implements Listener { private MythicDrops mythicDrops; public ItemSpawningListener(MythicDropsPlugin mythicDrops) { this.mythicDrops = mythicDrops; } public MythicDrops getMythicDrops() { return mythicDrops; } @EventHandler(priority = EventPriority.LOWEST) public void onCreatureSpawnEventLowest(CreatureSpawnEvent event) { if (!(event.getEntity() instanceof Monster) || event.isCancelled()) { return; } if (!mythicDrops.getConfigSettings().getEnabledWorlds().contains(event.getEntity().getWorld() .getName())) { return; } if (mythicDrops.getConfigSettings().isGiveAllMobsNames()) { nameMobs(event.getEntity()); } if (mythicDrops.getConfigSettings().isBlankMobSpawnEnabled()) { event.getEntity().getEquipment().clear(); if (event.getEntity() instanceof Skeleton && !mythicDrops.getConfigSettings() .isSkeletonsSpawnWithoutBows()) { event.getEntity().getEquipment().setItemInHand(new ItemStack(Material.BOW, 1)); } } if (event.getSpawnReason() == CreatureSpawnEvent.SpawnReason.SPAWNER && mythicDrops.getCreatureSpawningSettings().isPreventSpawner()) { event.getEntity() .setCanPickupItems(mythicDrops.getConfigSettings().isMobsPickupEquipment()); return; } if (event.getSpawnReason() == CreatureSpawnEvent.SpawnReason.SPAWNER_EGG && mythicDrops.getCreatureSpawningSettings().isPreventSpawnEgg()) { event.getEntity() .setCanPickupItems(mythicDrops.getConfigSettings().isMobsPickupEquipment()); return; } if (event.getSpawnReason() == CreatureSpawnEvent.SpawnReason.CUSTOM && mythicDrops.getCreatureSpawningSettings().isPreventCustom()) { event.getEntity() .setCanPickupItems(mythicDrops.getConfigSettings().isMobsPickupEquipment()); return; } if (event.getEntity().getLocation().getY() > mythicDrops.getCreatureSpawningSettings() .getSpawnHeightLimit(event.getEntity ().getWorld().getName())) { event.getEntity() .setCanPickupItems(mythicDrops.getConfigSettings().isMobsPickupEquipment()); return; } event.getEntity() .setCanPickupItems(mythicDrops.getConfigSettings().isMobsPickupEquipment()); } private void nameMobs(LivingEntity livingEntity) { if (mythicDrops.getConfigSettings().isGiveMobsNames()) { String generalName = NameMap.getInstance().getRandom(NameType.MOB_NAME, ""); String specificName = NameMap.getInstance().getRandom(NameType.MOB_NAME, "." + livingEntity.getType()); if (specificName != null && !specificName.isEmpty()) { livingEntity.setCustomName(specificName); } else { livingEntity.setCustomName(generalName); } livingEntity.setCustomNameVisible(true); } } @EventHandler(priority = EventPriority.LOW) public void onCreatureSpawnEvent(CreatureSpawnEvent event) { if (!(event.getEntity() instanceof Monster) || event.isCancelled()) { return; } if (!mythicDrops.getConfigSettings().getEnabledWorlds().contains(event.getEntity().getWorld() .getName())) { return; } if (event.getSpawnReason() == CreatureSpawnEvent.SpawnReason.SPAWNER && mythicDrops.getCreatureSpawningSettings().isPreventSpawner()) { return; } if (event.getSpawnReason() == CreatureSpawnEvent.SpawnReason.SPAWNER_EGG && mythicDrops.getCreatureSpawningSettings().isPreventSpawnEgg()) { return; } if (event.getSpawnReason() == CreatureSpawnEvent.SpawnReason.CUSTOM && mythicDrops.getCreatureSpawningSettings().isPreventSpawner()) { return; } if (mythicDrops.getCreatureSpawningSettings() .getSpawnHeightLimit(event.getEntity().getWorld().getName()) <= event .getEntity().getLocation().getY()) { return; } if (!mythicDrops.getConfigSettings().isDisplayMobEquipment()) { return; } // Start off with the random item chance. If the mob doesn't pass that, it gets no items. double chanceToGetDrop = mythicDrops.getConfigSettings().getItemChance() * mythicDrops .getCreatureSpawningSettings().getEntityTypeChanceToSpawn(event.getEntity().getType()); if (RandomUtils.nextDouble() > chanceToGetDrop) { return; } // Choose a tier for the item that the mob is given. If the tier is null, it gets no items. Tier tier = getTierForEntity(event.getEntity()); if (tier == null) { return; } // Create the item for the mob. ItemStack itemStack = MythicDropsPlugin.getNewDropBuilder().withItemGenerationReason( ItemGenerationReason.MONSTER_SPAWN).useDurability(false).withTier(tier).build(); if (itemStack == null) { return; } // Begin to check for socket gem, identity tome, and unidentified. double customItemChance = mythicDrops.getConfigSettings().getCustomItemChance(); double socketGemChance = mythicDrops.getConfigSettings().getSocketGemChance(); double unidentifiedItemChance = mythicDrops.getConfigSettings().getUnidentifiedItemChance(); double identityTomeChance = mythicDrops.getConfigSettings().getIdentityTomeChance(); boolean sockettingEnabled = mythicDrops.getConfigSettings().isSockettingEnabled(); boolean identifyingEnabled = mythicDrops.getConfigSettings().isIdentifyingEnabled(); if (RandomUtils.nextDouble() <= customItemChance) { CustomItem customItem = CustomItemMap.getInstance().getRandomWithChance(); if (customItem != null) { itemStack = customItem.toItemStack(); } } else if (sockettingEnabled && RandomUtils.nextDouble() <= socketGemChance) { SocketGem socketGem = SocketGemUtil.getRandomSocketGemWithChance(); Material material = SocketGemUtil.getRandomSocketGemMaterial(); if (socketGem != null && material != null) { itemStack = new SocketItem(material, socketGem); } } else if (identifyingEnabled && RandomUtils.nextDouble() <= unidentifiedItemChance) { Material material = itemStack.getType(); itemStack = new UnidentifiedItem(material); } else if (identifyingEnabled && RandomUtils.nextDouble() <= identityTomeChance) { itemStack = new IdentityTome(); } EntitySpawningEvent ese = new EntitySpawningEvent(event.getEntity()); Bukkit.getPluginManager().callEvent(ese); EntityUtil.equipEntity(event.getEntity(), itemStack); nameMobs(event.getEntity()); } private Tier getTierForEntity(Entity entity) { Collection<Tier> allowableTiers = mythicDrops.getCreatureSpawningSettings() .getEntityTypeTiers(entity.getType()); Map<Tier, Double> chanceMap = new HashMap<>(); int distFromSpawn = (int) entity.getLocation().distance(entity.getWorld().getSpawnLocation()); for (Tier t : allowableTiers) { if (t.getMaximumDistance() == -1 || t.getOptimalDistance() == -1) { chanceMap.put(t, t.getSpawnChance()); continue; } double weightMultiplier; int difference = Math.abs(distFromSpawn - t.getOptimalDistance()); int maximumDistance = Math.abs(t.getMaximumDistance()); if (difference < maximumDistance) { weightMultiplier = 1D - ((difference * 1D) / maximumDistance); } else { weightMultiplier = 0D; } double weight = t.getSpawnChance() * weightMultiplier; chanceMap.put(t, weight); } return TierUtil.randomTierWithChance(chanceMap); } @EventHandler public void onEntityDeath(EntityDeathEvent event) { if (event.getEntity() instanceof Player || event.getEntity().getLastDamageCause() == null || event.getEntity().getLastDamageCause().isCancelled()) { return; } if (!mythicDrops.getConfigSettings().getEnabledWorlds().contains(event.getEntity().getWorld() .getName())) { return; } EntityDamageEvent.DamageCause damageCause = event.getEntity().getLastDamageCause().getCause(); switch (damageCause) { case CONTACT: case SUFFOCATION: case FALL: case FIRE_TICK: case MELTING: case LAVA: case DROWNING: case BLOCK_EXPLOSION: case VOID: case LIGHTNING: case SUICIDE: case STARVATION: case WITHER: case FALLING_BLOCK: case CUSTOM: return; } if (mythicDrops.getConfigSettings().isDisplayMobEquipment()) { handleEntityDyingWithGive(event); } else { handleEntityDyingWithoutGive(event); } } private void handleEntityDyingWithoutGive(EntityDeathEvent event) { // Start off with the random item chance. If the mob doesn't pass that, it gets no items. double chanceToGetDrop = mythicDrops.getConfigSettings().getItemChance() * mythicDrops .getCreatureSpawningSettings().getEntityTypeChanceToSpawn(event.getEntity().getType()); if (RandomUtils.nextDouble() > chanceToGetDrop) { return; } // Choose a tier for the item that the mob is given. If the tier is null, it gets no items. Tier tier = getTierForEntity(event.getEntity()); if (tier == null) { return; } // Create the item for the mob. ItemStack itemStack = MythicDropsPlugin.getNewDropBuilder().withItemGenerationReason( ItemGenerationReason.MONSTER_SPAWN).useDurability(true).withTier(tier).build(); // Begin to check for socket gem, identity tome, and unidentified. double customItemChance = mythicDrops.getConfigSettings().getCustomItemChance(); double socketGemChance = mythicDrops.getConfigSettings().getSocketGemChance(); double unidentifiedItemChance = mythicDrops.getConfigSettings().getUnidentifiedItemChance(); double identityTomeChance = mythicDrops.getConfigSettings().getIdentityTomeChance(); boolean sockettingEnabled = mythicDrops.getConfigSettings().isSockettingEnabled(); boolean identifyingEnabled = mythicDrops.getConfigSettings().isIdentifyingEnabled(); if (RandomUtils.nextDouble() <= customItemChance) { CustomItem ci = CustomItemMap.getInstance().getRandomWithChance(); if (ci != null) { itemStack = ci.toItemStack(); if (ci.isBroadcastOnFind()) { broadcastMessage(event.getEntity().getKiller(), itemStack); } } } else if (sockettingEnabled && RandomUtils.nextDouble() <= socketGemChance) { SocketGem socketGem = SocketGemUtil.getRandomSocketGemWithChance(); Material material = SocketGemUtil.getRandomSocketGemMaterial(); if (socketGem != null && material != null) { itemStack = new SocketItem(material, socketGem); } } else if (identifyingEnabled && RandomUtils.nextDouble() <= unidentifiedItemChance) { Material material = itemStack.getType(); itemStack = new UnidentifiedItem(material); } else if (identifyingEnabled && RandomUtils.nextDouble() <= identityTomeChance) { itemStack = new IdentityTome(); } else if (tier.isBroadcastOnFind()) { broadcastMessage(event.getEntity().getKiller(), itemStack); } event.getEntity().getEquipment().setBootsDropChance(0.0F); event.getEntity().getEquipment().setLeggingsDropChance(0.0F); event.getEntity().getEquipment().setChestplateDropChance(0.0F); event.getEntity().getEquipment().setHelmetDropChance(0.0F); event.getEntity().getEquipment().setItemInHandDropChance(0.0F); World w = event.getEntity().getWorld(); Location l = event.getEntity().getLocation(); w.dropItemNaturally(l, itemStack); } private void broadcastMessage(Player player, ItemStack itemStack) { String locale = mythicDrops.getConfigSettings().getFormattedLanguageString("command" + ".found-item-broadcast", new String[][]{{"%receiver%", player.getName()}}); String[] messages = locale.split("%item%"); FancyMessage fancyMessage = new FancyMessage(""); for (int i1 = 0; i1 < messages.length; i1++) { String key = messages[i1]; if (i1 < messages.length - 1) { fancyMessage.then(key).then(itemStack.getItemMeta().getDisplayName()).itemTooltip(itemStack); } else { fancyMessage.then(key); } } for (Player p : player.getWorld().getPlayers()) { fancyMessage.send(p); } } private void handleEntityDyingWithGive(EntityDeathEvent event) { List<ItemStack> newDrops = new ArrayList<>(); ItemStack[] array = new ItemStack[5]; System.arraycopy(event.getEntity().getEquipment().getArmorContents(), 0, array, 0, 4); array[4] = event.getEntity().getEquipment().getItemInHand(); event.getEntity().getEquipment().setBootsDropChance(0.0F); event.getEntity().getEquipment().setLeggingsDropChance(0.0F); event.getEntity().getEquipment().setChestplateDropChance(0.0F); event.getEntity().getEquipment().setHelmetDropChance(0.0F); event.getEntity().getEquipment().setItemInHandDropChance(0.0F); for (ItemStack is : array) { if (is == null || is.getType() == Material.AIR || !is.hasItemMeta()) { continue; } CustomItem ci = CustomItemUtil.getCustomItemFromItemStack(is); if (ci != null) { newDrops.add(ci.toItemStack()); if (ci.isBroadcastOnFind() && event.getEntity().getKiller() != null) { broadcastMessage(event.getEntity().getKiller(), ci.toItemStack()); } continue; } SocketGem socketGem = SocketGemUtil.getSocketGemFromItemStack(is); if (socketGem != null) { newDrops.add(new SocketItem(is.getType(), socketGem)); continue; } IdentityTome identityTome = new IdentityTome(); if (is.isSimilar(identityTome)) { newDrops.add(identityTome); continue; } UnidentifiedItem unidentifiedItem = new UnidentifiedItem(is.getType()); if (is.isSimilar(unidentifiedItem)) { newDrops.add(unidentifiedItem); continue; } Tier t = TierUtil.getTierFromItemStack(is); if (t != null && RandomUtils.nextDouble() < t.getDropChance()) { ItemStack nis = is.getData().toItemStack(1); nis.setItemMeta(is.getItemMeta()); nis.setDurability(ItemStackUtil.getDurabilityForMaterial(is.getType(), t.getMinimumDurabilityPercentage (), t.getMaximumDurabilityPercentage() )); if (t.isBroadcastOnFind()) { broadcastMessage(event.getEntity().getKiller(), nis); } newDrops.add(nis); } } for (ItemStack itemStack : newDrops) { if (itemStack.getType() == Material.AIR) { continue; } World w = event.getEntity().getWorld(); Location l = event.getEntity().getLocation(); w.dropItemNaturally(l, itemStack); } } }
src/main/java/net/nunnerycode/bukkit/mythicdrops/spawning/ItemSpawningListener.java
package net.nunnerycode.bukkit.mythicdrops.spawning; import mkremins.fanciful.FancyMessage; import net.nunnerycode.bukkit.mythicdrops.MythicDropsPlugin; import net.nunnerycode.bukkit.mythicdrops.api.MythicDrops; import net.nunnerycode.bukkit.mythicdrops.api.items.CustomItem; import net.nunnerycode.bukkit.mythicdrops.api.items.ItemGenerationReason; import net.nunnerycode.bukkit.mythicdrops.api.names.NameType; import net.nunnerycode.bukkit.mythicdrops.api.tiers.Tier; import net.nunnerycode.bukkit.mythicdrops.events.EntitySpawningEvent; import net.nunnerycode.bukkit.mythicdrops.identification.IdentityTome; import net.nunnerycode.bukkit.mythicdrops.identification.UnidentifiedItem; import net.nunnerycode.bukkit.mythicdrops.items.CustomItemMap; import net.nunnerycode.bukkit.mythicdrops.names.NameMap; import net.nunnerycode.bukkit.mythicdrops.socketting.SocketGem; import net.nunnerycode.bukkit.mythicdrops.socketting.SocketItem; import net.nunnerycode.bukkit.mythicdrops.utils.CustomItemUtil; import net.nunnerycode.bukkit.mythicdrops.utils.EntityUtil; import net.nunnerycode.bukkit.mythicdrops.utils.ItemStackUtil; import net.nunnerycode.bukkit.mythicdrops.utils.SocketGemUtil; import net.nunnerycode.bukkit.mythicdrops.utils.TierUtil; import org.apache.commons.lang.math.RandomUtils; import org.bukkit.Bukkit; import org.bukkit.Location; import org.bukkit.Material; import org.bukkit.World; import org.bukkit.entity.LivingEntity; import org.bukkit.entity.Monster; import org.bukkit.entity.Player; import org.bukkit.entity.Skeleton; import org.bukkit.event.EventHandler; import org.bukkit.event.EventPriority; import org.bukkit.event.Listener; import org.bukkit.event.entity.CreatureSpawnEvent; import org.bukkit.event.entity.EntityDamageEvent; import org.bukkit.event.entity.EntityDeathEvent; import org.bukkit.inventory.ItemStack; import java.util.ArrayList; import java.util.Collection; import java.util.HashMap; import java.util.List; import java.util.Map; public final class ItemSpawningListener implements Listener { private MythicDrops mythicDrops; public ItemSpawningListener(MythicDropsPlugin mythicDrops) { this.mythicDrops = mythicDrops; } public MythicDrops getMythicDrops() { return mythicDrops; } @EventHandler(priority = EventPriority.LOWEST) public void onCreatureSpawnEventLowest(CreatureSpawnEvent event) { if (!(event.getEntity() instanceof Monster) || event.isCancelled()) { return; } if (!mythicDrops.getConfigSettings().getEnabledWorlds().contains(event.getEntity().getWorld() .getName())) { return; } if (mythicDrops.getConfigSettings().isGiveAllMobsNames()) { nameMobs(event.getEntity()); } if (mythicDrops.getConfigSettings().isBlankMobSpawnEnabled()) { event.getEntity().getEquipment().clear(); if (event.getEntity() instanceof Skeleton && !mythicDrops.getConfigSettings() .isSkeletonsSpawnWithoutBows()) { event.getEntity().getEquipment().setItemInHand(new ItemStack(Material.BOW, 1)); } } if (event.getSpawnReason() == CreatureSpawnEvent.SpawnReason.SPAWNER && mythicDrops.getCreatureSpawningSettings().isPreventSpawner()) { event.getEntity() .setCanPickupItems(mythicDrops.getConfigSettings().isMobsPickupEquipment()); return; } if (event.getSpawnReason() == CreatureSpawnEvent.SpawnReason.SPAWNER_EGG && mythicDrops.getCreatureSpawningSettings().isPreventSpawnEgg()) { event.getEntity() .setCanPickupItems(mythicDrops.getConfigSettings().isMobsPickupEquipment()); return; } if (event.getSpawnReason() == CreatureSpawnEvent.SpawnReason.CUSTOM && mythicDrops.getCreatureSpawningSettings().isPreventCustom()) { event.getEntity() .setCanPickupItems(mythicDrops.getConfigSettings().isMobsPickupEquipment()); return; } if (event.getEntity().getLocation().getY() > mythicDrops.getCreatureSpawningSettings() .getSpawnHeightLimit(event.getEntity ().getWorld().getName())) { event.getEntity() .setCanPickupItems(mythicDrops.getConfigSettings().isMobsPickupEquipment()); return; } event.getEntity() .setCanPickupItems(mythicDrops.getConfigSettings().isMobsPickupEquipment()); } private void nameMobs(LivingEntity livingEntity) { if (mythicDrops.getConfigSettings().isGiveMobsNames()) { String generalName = NameMap.getInstance().getRandom(NameType.MOB_NAME, ""); String specificName = NameMap.getInstance().getRandom(NameType.MOB_NAME, "." + livingEntity.getType()); if (specificName != null && !specificName.isEmpty()) { livingEntity.setCustomName(specificName); } else { livingEntity.setCustomName(generalName); } livingEntity.setCustomNameVisible(true); } } @EventHandler(priority = EventPriority.LOW) public void onCreatureSpawnEvent(CreatureSpawnEvent event) { if (!(event.getEntity() instanceof Monster) || event.isCancelled()) { return; } if (!mythicDrops.getConfigSettings().getEnabledWorlds().contains(event.getEntity().getWorld() .getName())) { return; } if (event.getSpawnReason() == CreatureSpawnEvent.SpawnReason.SPAWNER && mythicDrops.getCreatureSpawningSettings().isPreventSpawner()) { return; } if (event.getSpawnReason() == CreatureSpawnEvent.SpawnReason.SPAWNER_EGG && mythicDrops.getCreatureSpawningSettings().isPreventSpawnEgg()) { return; } if (event.getSpawnReason() == CreatureSpawnEvent.SpawnReason.CUSTOM && mythicDrops.getCreatureSpawningSettings().isPreventSpawner()) { return; } if (mythicDrops.getCreatureSpawningSettings() .getSpawnHeightLimit(event.getEntity().getWorld().getName()) <= event .getEntity().getLocation().getY()) { return; } if (!mythicDrops.getConfigSettings().isDisplayMobEquipment()) { return; } // Start off with the random item chance. If the mob doesn't pass that, it gets no items. double chanceToGetDrop = mythicDrops.getConfigSettings().getItemChance() * mythicDrops .getCreatureSpawningSettings().getEntityTypeChanceToSpawn(event.getEntity().getType()); if (RandomUtils.nextDouble() > chanceToGetDrop) { return; } // Choose a tier for the item that the mob is given. If the tier is null, it gets no items. Tier tier = getTierForEvent(event); if (tier == null) { return; } // Create the item for the mob. ItemStack itemStack = MythicDropsPlugin.getNewDropBuilder().withItemGenerationReason( ItemGenerationReason.MONSTER_SPAWN).useDurability(false).withTier(tier).build(); if (itemStack == null) { return; } // Begin to check for socket gem, identity tome, and unidentified. double customItemChance = mythicDrops.getConfigSettings().getCustomItemChance(); double socketGemChance = mythicDrops.getConfigSettings().getSocketGemChance(); double unidentifiedItemChance = mythicDrops.getConfigSettings().getUnidentifiedItemChance(); double identityTomeChance = mythicDrops.getConfigSettings().getIdentityTomeChance(); boolean sockettingEnabled = mythicDrops.getConfigSettings().isSockettingEnabled(); boolean identifyingEnabled = mythicDrops.getConfigSettings().isIdentifyingEnabled(); if (RandomUtils.nextDouble() <= customItemChance) { CustomItem customItem = CustomItemMap.getInstance().getRandomWithChance(); if (customItem != null) { itemStack = customItem.toItemStack(); } } else if (sockettingEnabled && RandomUtils.nextDouble() <= socketGemChance) { SocketGem socketGem = SocketGemUtil.getRandomSocketGemWithChance(); Material material = SocketGemUtil.getRandomSocketGemMaterial(); if (socketGem != null && material != null) { itemStack = new SocketItem(material, socketGem); } } else if (identifyingEnabled && RandomUtils.nextDouble() <= unidentifiedItemChance) { Material material = itemStack.getType(); itemStack = new UnidentifiedItem(material); } else if (identifyingEnabled && RandomUtils.nextDouble() <= identityTomeChance) { itemStack = new IdentityTome(); } EntitySpawningEvent ese = new EntitySpawningEvent(event.getEntity()); Bukkit.getPluginManager().callEvent(ese); EntityUtil.equipEntity(event.getEntity(), itemStack); nameMobs(event.getEntity()); } private Tier getTierForEvent(CreatureSpawnEvent event) { Collection<Tier> allowableTiers = mythicDrops.getCreatureSpawningSettings() .getEntityTypeTiers(event.getEntity().getType()); Map<Tier, Double> chanceMap = new HashMap<>(); int distFromSpawn = (int) event.getEntity().getLocation().distance(event.getEntity().getWorld() .getSpawnLocation()); for (Tier t : allowableTiers) { if (t.getMaximumDistance() == -1 || t.getOptimalDistance() == -1) { chanceMap.put(t, t.getSpawnChance()); continue; } double weightMultiplier; int difference = Math.abs(distFromSpawn - t.getOptimalDistance()); int maximumDistance = Math.abs(t.getMaximumDistance()); if (difference < maximumDistance) { weightMultiplier = 1D - ((difference * 1D) / maximumDistance); } else { weightMultiplier = 0D; } double weight = t.getSpawnChance() * weightMultiplier; chanceMap.put(t, weight); } return TierUtil.randomTierWithChance(chanceMap); } @EventHandler public void onEntityDeath(EntityDeathEvent event) { if (event.getEntity() instanceof Player || event.getEntity().getLastDamageCause() == null || event.getEntity().getLastDamageCause().isCancelled()) { return; } if (!mythicDrops.getConfigSettings().getEnabledWorlds().contains(event.getEntity().getWorld() .getName())) { return; } EntityDamageEvent.DamageCause damageCause = event.getEntity().getLastDamageCause().getCause(); switch (damageCause) { case CONTACT: case SUFFOCATION: case FALL: case FIRE_TICK: case MELTING: case LAVA: case DROWNING: case BLOCK_EXPLOSION: case VOID: case LIGHTNING: case SUICIDE: case STARVATION: case WITHER: case FALLING_BLOCK: case CUSTOM: return; } if (mythicDrops.getConfigSettings().isDisplayMobEquipment()) { handleEntityDyingWithGive(event); } else { handleEntityDyingWithoutGive(event); } } private void handleEntityDyingWithoutGive(EntityDeathEvent event) { // Start off with the random item chance. If the mob doesn't pass that, it gets no items. double chanceToGetDrop = mythicDrops.getConfigSettings().getItemChance() * mythicDrops .getCreatureSpawningSettings().getEntityTypeChanceToSpawn(event.getEntity().getType()); if (RandomUtils.nextDouble() > chanceToGetDrop) { return; } // Choose a tier for the item that the mob is given. If the tier is null, it gets no items. Collection<Tier> allowableTiers = mythicDrops.getCreatureSpawningSettings() .getEntityTypeTiers(event.getEntity().getType()); Tier tier = TierUtil.randomTierWithChance(allowableTiers); if (tier == null) { return; } // Create the item for the mob. ItemStack itemStack = MythicDropsPlugin.getNewDropBuilder().withItemGenerationReason( ItemGenerationReason.MONSTER_SPAWN).useDurability(true).withTier(tier).build(); // Begin to check for socket gem, identity tome, and unidentified. double customItemChance = mythicDrops.getConfigSettings().getCustomItemChance(); double socketGemChance = mythicDrops.getConfigSettings().getSocketGemChance(); double unidentifiedItemChance = mythicDrops.getConfigSettings().getUnidentifiedItemChance(); double identityTomeChance = mythicDrops.getConfigSettings().getIdentityTomeChance(); boolean sockettingEnabled = mythicDrops.getConfigSettings().isSockettingEnabled(); boolean identifyingEnabled = mythicDrops.getConfigSettings().isIdentifyingEnabled(); if (RandomUtils.nextDouble() <= customItemChance) { CustomItem ci = CustomItemMap.getInstance().getRandomWithChance(); if (ci != null) { itemStack = ci.toItemStack(); if (ci.isBroadcastOnFind()) { broadcastMessage(event.getEntity().getKiller(), itemStack); } } } else if (sockettingEnabled && RandomUtils.nextDouble() <= socketGemChance) { SocketGem socketGem = SocketGemUtil.getRandomSocketGemWithChance(); Material material = SocketGemUtil.getRandomSocketGemMaterial(); if (socketGem != null && material != null) { itemStack = new SocketItem(material, socketGem); } } else if (identifyingEnabled && RandomUtils.nextDouble() <= unidentifiedItemChance) { Material material = itemStack.getType(); itemStack = new UnidentifiedItem(material); } else if (identifyingEnabled && RandomUtils.nextDouble() <= identityTomeChance) { itemStack = new IdentityTome(); } else if (tier.isBroadcastOnFind()) { broadcastMessage(event.getEntity().getKiller(), itemStack); } event.getEntity().getEquipment().setBootsDropChance(0.0F); event.getEntity().getEquipment().setLeggingsDropChance(0.0F); event.getEntity().getEquipment().setChestplateDropChance(0.0F); event.getEntity().getEquipment().setHelmetDropChance(0.0F); event.getEntity().getEquipment().setItemInHandDropChance(0.0F); World w = event.getEntity().getWorld(); Location l = event.getEntity().getLocation(); w.dropItemNaturally(l, itemStack); } private void broadcastMessage(Player player, ItemStack itemStack) { String locale = mythicDrops.getConfigSettings().getFormattedLanguageString("command" + ".found-item-broadcast", new String[][]{{"%receiver%", player.getName()}}); String[] messages = locale.split("%item%"); FancyMessage fancyMessage = new FancyMessage(""); for (int i1 = 0; i1 < messages.length; i1++) { String key = messages[i1]; if (i1 < messages.length - 1) { fancyMessage.then(key).then(itemStack.getItemMeta().getDisplayName()).itemTooltip(itemStack); } else { fancyMessage.then(key); } } for (Player p : player.getWorld().getPlayers()) { fancyMessage.send(p); } } private void handleEntityDyingWithGive(EntityDeathEvent event) { List<ItemStack> newDrops = new ArrayList<>(); ItemStack[] array = new ItemStack[5]; System.arraycopy(event.getEntity().getEquipment().getArmorContents(), 0, array, 0, 4); array[4] = event.getEntity().getEquipment().getItemInHand(); event.getEntity().getEquipment().setBootsDropChance(0.0F); event.getEntity().getEquipment().setLeggingsDropChance(0.0F); event.getEntity().getEquipment().setChestplateDropChance(0.0F); event.getEntity().getEquipment().setHelmetDropChance(0.0F); event.getEntity().getEquipment().setItemInHandDropChance(0.0F); for (ItemStack is : array) { if (is == null || is.getType() == Material.AIR || !is.hasItemMeta()) { continue; } CustomItem ci = CustomItemUtil.getCustomItemFromItemStack(is); if (ci != null) { newDrops.add(ci.toItemStack()); if (ci.isBroadcastOnFind() && event.getEntity().getKiller() != null) { broadcastMessage(event.getEntity().getKiller(), ci.toItemStack()); } continue; } SocketGem socketGem = SocketGemUtil.getSocketGemFromItemStack(is); if (socketGem != null) { newDrops.add(new SocketItem(is.getType(), socketGem)); continue; } IdentityTome identityTome = new IdentityTome(); if (is.isSimilar(identityTome)) { newDrops.add(identityTome); continue; } UnidentifiedItem unidentifiedItem = new UnidentifiedItem(is.getType()); if (is.isSimilar(unidentifiedItem)) { newDrops.add(unidentifiedItem); continue; } Tier t = TierUtil.getTierFromItemStack(is); if (t != null && RandomUtils.nextDouble() < t.getDropChance()) { ItemStack nis = is.getData().toItemStack(1); nis.setItemMeta(is.getItemMeta()); nis.setDurability(ItemStackUtil.getDurabilityForMaterial(is.getType(), t.getMinimumDurabilityPercentage (), t.getMaximumDurabilityPercentage() )); if (t.isBroadcastOnFind()) { broadcastMessage(event.getEntity().getKiller(), nis); } newDrops.add(nis); } } for (ItemStack itemStack : newDrops) { if (itemStack.getType() == Material.AIR) { continue; } World w = event.getEntity().getWorld(); Location l = event.getEntity().getLocation(); w.dropItemNaturally(l, itemStack); } } }
fix for distance weights when display-mob-equipment is false
src/main/java/net/nunnerycode/bukkit/mythicdrops/spawning/ItemSpawningListener.java
fix for distance weights when display-mob-equipment is false
<ide><path>rc/main/java/net/nunnerycode/bukkit/mythicdrops/spawning/ItemSpawningListener.java <ide> import org.bukkit.Location; <ide> import org.bukkit.Material; <ide> import org.bukkit.World; <add>import org.bukkit.entity.Entity; <ide> import org.bukkit.entity.LivingEntity; <ide> import org.bukkit.entity.Monster; <ide> import org.bukkit.entity.Player; <ide> } <ide> <ide> // Choose a tier for the item that the mob is given. If the tier is null, it gets no items. <del> Tier tier = getTierForEvent(event); <add> Tier tier = getTierForEntity(event.getEntity()); <ide> if (tier == null) { <ide> return; <ide> } <ide> nameMobs(event.getEntity()); <ide> } <ide> <del> private Tier getTierForEvent(CreatureSpawnEvent event) { <add> private Tier getTierForEntity(Entity entity) { <ide> Collection<Tier> allowableTiers = mythicDrops.getCreatureSpawningSettings() <del> .getEntityTypeTiers(event.getEntity().getType()); <add> .getEntityTypeTiers(entity.getType()); <ide> Map<Tier, Double> chanceMap = new HashMap<>(); <del> int distFromSpawn = (int) event.getEntity().getLocation().distance(event.getEntity().getWorld() <del> .getSpawnLocation()); <add> int distFromSpawn = (int) entity.getLocation().distance(entity.getWorld().getSpawnLocation()); <ide> for (Tier t : allowableTiers) { <ide> if (t.getMaximumDistance() == -1 || t.getOptimalDistance() == -1) { <ide> chanceMap.put(t, t.getSpawnChance()); <ide> } <ide> <ide> // Choose a tier for the item that the mob is given. If the tier is null, it gets no items. <del> Collection<Tier> allowableTiers = mythicDrops.getCreatureSpawningSettings() <del> .getEntityTypeTiers(event.getEntity().getType()); <del> Tier tier = TierUtil.randomTierWithChance(allowableTiers); <add> Tier tier = getTierForEntity(event.getEntity()); <ide> if (tier == null) { <ide> return; <ide> }
Java
apache-2.0
0e46713510eb95fa892b2c7337a9c98fbeb6a938
0
bhb27/KA27,bhb27/KA27
/* * Copyright (C) 2015 Willi Ye * * 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.grarak.kerneladiutor.utils; import com.grarak.kerneladiutor.BuildConfig; import com.grarak.kerneladiutor.elements.DAdapter; import java.util.ArrayList; import java.util.List; /** * Created by willi on 30.11.14. */ public interface Constants { String TAG = "Kernel Adiutor"; String VERSION_NAME = BuildConfig.VERSION_NAME; int VERSION_CODE = BuildConfig.VERSION_CODE; String PREF_NAME = "prefs"; String GAMMA_URL = "https://raw.githubusercontent.com/Grarak/KernelAdiutor/master/gamma_profiles.json"; List<DAdapter.DView> ITEMS = new ArrayList<>(); List<DAdapter.DView> VISIBLE_ITEMS = new ArrayList<>(); // Kernel Informations String PROC_VERSION = "/proc/version"; String PROC_CPUINFO = "/proc/cpuinfo"; String PROC_MEMINFO = "/proc/meminfo"; // CPU String CPU_CUR_FREQ = "/sys/devices/system/cpu/cpu%d/cpufreq/scaling_cur_freq"; String CPU_TEMP_ZONE0 = "/sys/class/thermal/thermal_zone0/temp"; String CPU_TEMP_ZONE1 = "/sys/class/thermal/thermal_zone1/temp"; String CPU_CORE_ONLINE = "/sys/devices/system/cpu/cpu%d/online"; String CPU_MAX_FREQ = "/sys/devices/system/cpu/cpu%d/cpufreq/scaling_max_freq"; String CPU_MAX_FREQ_KT = "/sys/devices/system/cpu/cpu%d/cpufreq/scaling_max_freq_kt"; String CPU_ENABLE_OC = "/sys/devices/system/cpu/cpu%d/cpufreq/enable_oc"; String CPU_MIN_FREQ = "/sys/devices/system/cpu/cpu%d/cpufreq/scaling_min_freq"; String CPU_MAX_SCREEN_OFF_FREQ = "/sys/devices/system/cpu/cpu%d/cpufreq/screen_off_max_freq"; String CPU_MSM_CPUFREQ_LIMIT = "/sys/kernel/msm_cpufreq_limit/cpufreq_limit"; String CPU_AVAILABLE_FREQS = "/sys/devices/system/cpu/cpu%d/cpufreq/scaling_available_frequencies"; String CPU_TIME_STATE = "/sys/devices/system/cpu/cpufreq/stats/cpu%d/time_in_state"; String CPU_TIME_STATE_2 = "/sys/devices/system/cpu/cpu%d/cpufreq/stats/time_in_state"; String CPU_SCALING_GOVERNOR = "/sys/devices/system/cpu/cpu%d/cpufreq/scaling_governor"; String CPU_AVAILABLE_GOVERNORS = "/sys/devices/system/cpu/cpu0/cpufreq/scaling_available_governors"; String CPU_GOVERNOR_TUNABLES = "/sys/devices/system/cpu/cpufreq"; String CPU_GOVERNOR_TUNABLES_CORE = "/sys/devices/system/cpu/cpu%d/cpufreq"; String CPU_MC_POWER_SAVING = "/sys/devices/system/cpu/sched_mc_power_savings"; String CPU_WQ_POWER_SAVING = "/sys/module/workqueue/parameters/power_efficient"; String CPU_AVAILABLE_CFS_SCHEDULERS = "/sys/devices/system/cpu/sched_balance_policy/available_sched_balance_policy"; String CPU_CURRENT_CFS_SCHEDULER = "/sys/devices/system/cpu/sched_balance_policy/current_sched_balance_policy"; String CPU_QUIET = "/sys/devices/system/cpu/cpuquiet"; String CPU_QUIET_ENABLE = CPU_QUIET + "/cpuquiet_driver/enabled"; String CPU_QUIET_AVAILABLE_GOVERNORS = CPU_QUIET + "/available_governors"; String CPU_QUIET_CURRENT_GOVERNOR = CPU_QUIET + "/current_governor"; String CPU_BOOST = "/sys/module/cpu_boost/parameters"; String CPU_BOOST_ENABLE = CPU_BOOST + "/cpu_boost"; String CPU_BOOST_ENABLE_2 = CPU_BOOST + "/cpuboost_enable"; String CPU_BOOST_DEBUG_MASK = CPU_BOOST + "/debug_mask"; String CPU_BOOST_MS = CPU_BOOST + "/boost_ms"; String CPU_BOOST_SYNC_THRESHOLD = CPU_BOOST + "/sync_threshold"; String CPU_BOOST_INPUT_MS = CPU_BOOST + "/input_boost_ms"; String CPU_BOOST_INPUT_BOOST_FREQ = CPU_BOOST + "/input_boost_freq"; String CPU_BOOST_WAKEUP = CPU_BOOST + "/wakeup_boost"; String CPU_BOOST_HOTPLUG = CPU_BOOST + "/hotplug_boost"; String CPU_TOUCH_BOOST = "/sys/module/msm_performance/parameters/touchboost"; String[] CPU_ARRAY = {CPU_CUR_FREQ, CPU_TEMP_ZONE0, CPU_TEMP_ZONE1, CPU_CORE_ONLINE, CPU_MAX_FREQ, CPU_MAX_FREQ_KT, CPU_ENABLE_OC, CPU_MIN_FREQ, CPU_MAX_SCREEN_OFF_FREQ, CPU_MSM_CPUFREQ_LIMIT, CPU_AVAILABLE_FREQS, CPU_TIME_STATE, CPU_SCALING_GOVERNOR, CPU_AVAILABLE_GOVERNORS, CPU_GOVERNOR_TUNABLES, CPU_GOVERNOR_TUNABLES_CORE, CPU_MC_POWER_SAVING, CPU_WQ_POWER_SAVING, CPU_AVAILABLE_CFS_SCHEDULERS, CPU_CURRENT_CFS_SCHEDULER, CPU_QUIET, CPU_BOOST, CPU_TOUCH_BOOST}; // CPU Voltage String CPU_VOLTAGE = "/sys/devices/system/cpu/cpu0/cpufreq/UV_mV_table"; String CPU_VDD_VOLTAGE = "/sys/devices/system/cpu/cpu0/cpufreq/vdd_levels"; String CPU_FAUX_VOLTAGE = "/sys/devices/system/cpu/cpufreq/vdd_table/vdd_levels"; String CPU_OVERRIDE_VMIN = "/sys/devices/system/cpu/cpu0/cpufreq/override_vmin"; String[] CPU_VOLTAGE_ARRAY = {CPU_VOLTAGE, CPU_VDD_VOLTAGE, CPU_FAUX_VOLTAGE, CPU_OVERRIDE_VMIN}; // CPU Hotplug String HOTPLUG_MPDEC = "mpdecision"; String HOTPLUG_INTELLI_PLUG = "/sys/module/intelli_plug/parameters"; String HOTPLUG_INTELLI_PLUG_ENABLE = HOTPLUG_INTELLI_PLUG + "/intelli_plug_active"; String HOTPLUG_INTELLI_PLUG_PROFILE = HOTPLUG_INTELLI_PLUG + "/nr_run_profile_sel"; String HOTPLUG_INTELLI_PLUG_ECO = HOTPLUG_INTELLI_PLUG + "/eco_mode_active"; String HOTPLUG_INTELLI_PLUG_TOUCH_BOOST = HOTPLUG_INTELLI_PLUG + "/touch_boost_active"; String HOTPLUG_INTELLI_PLUG_HYSTERESIS = HOTPLUG_INTELLI_PLUG + "/nr_run_hysteresis"; String HOTPLUG_INTELLI_PLUG_THRESHOLD = HOTPLUG_INTELLI_PLUG + "/cpu_nr_run_threshold"; String HOTPLUG_INTELLI_PLUG_SCREEN_OFF_MAX = HOTPLUG_INTELLI_PLUG + "/screen_off_max"; String HOTPLUG_INTELLI_PLUG_INSANITY = HOTPLUG_INTELLI_PLUG + "/is_insanity"; String HOTPLUG_INTELLI_PLUG_5 = "/sys/kernel/intelli_plug"; String HOTPLUG_INTELLI_PLUG_5_ENABLE = HOTPLUG_INTELLI_PLUG_5 + "/intelli_plug_active"; String HOTPLUG_INTELLI_PLUG_5_DEBUG = HOTPLUG_INTELLI_PLUG_5 + "/debug_intelli_plug"; String HOTPLUG_INTELLI_PLUG_5_PROFILE = HOTPLUG_INTELLI_PLUG_5 + "/full_mode_profile"; String HOTPLUG_INTELLI_PLUG_5_SUSPEND = HOTPLUG_INTELLI_PLUG_5 + "/hotplug_suspend"; String HOTPLUG_INTELLI_PLUG_5_CPUS_BOOSTED = HOTPLUG_INTELLI_PLUG_5 + "/cpus_boosted"; String HOTPLUG_INTELLI_PLUG_5_HYSTERESIS = HOTPLUG_INTELLI_PLUG_5 + "/nr_run_hysteresis"; String HOTPLUG_INTELLI_PLUG_5_MIN_CPUS_ONLINE = HOTPLUG_INTELLI_PLUG_5 + "/min_cpus_online"; String HOTPLUG_INTELLI_PLUG_5_MAX_CPUS_ONLINE = HOTPLUG_INTELLI_PLUG_5 + "/max_cpus_online"; String HOTPLUG_INTELLI_PLUG_5_MAX_CPUS_ONLINE_SUSP = HOTPLUG_INTELLI_PLUG_5 + "/max_cpus_online_susp"; String HOTPLUG_INTELLI_PLUG_5_SUSPEND_DEFER_TIME = HOTPLUG_INTELLI_PLUG_5 + "/suspend_defer_time"; String HOTPLUG_INTELLI_PLUG_5_DEFER_SAMPLING = HOTPLUG_INTELLI_PLUG_5 + "/def_sampling_ms"; String HOTPLUG_INTELLI_PLUG_5_BOOST_LOCK_DURATION = HOTPLUG_INTELLI_PLUG_5 + "/boost_lock_duration"; String HOTPLUG_INTELLI_PLUG_5_DOWN_LOCK_DURATION = HOTPLUG_INTELLI_PLUG_5 + "/down_lock_duration"; String HOTPLUG_INTELLI_PLUG_5_THRESHOLD = HOTPLUG_INTELLI_PLUG_5 + "/cpu_nr_run_threshold"; String HOTPLUG_INTELLI_PLUG_5_FSHIFT = HOTPLUG_INTELLI_PLUG_5 + "/nr_fshift"; String HOTPLUG_INTELLI_PLUG_5_SCREEN_OFF_MAX = HOTPLUG_INTELLI_PLUG_5 + "/screen_off_max"; String[] INTELLIPLUG_ARRAY = {HOTPLUG_INTELLI_PLUG, HOTPLUG_INTELLI_PLUG_5}; String HOTPLUG_BLU_PLUG = "/sys/module/blu_plug/parameters"; String HOTPLUG_BLU_PLUG_ENABLE = HOTPLUG_BLU_PLUG + "/enabled"; String HOTPLUG_BLU_PLUG_POWERSAVER_MODE = HOTPLUG_BLU_PLUG + "/powersaver_mode"; String HOTPLUG_BLU_PLUG_MIN_ONLINE = HOTPLUG_BLU_PLUG + "/min_online"; String HOTPLUG_BLU_PLUG_MAX_ONLINE = HOTPLUG_BLU_PLUG + "/max_online"; String HOTPLUG_BLU_PLUG_MAX_CORES_SCREEN_OFF = HOTPLUG_BLU_PLUG + "/max_cores_screenoff"; String HOTPLUG_BLU_PLUG_MAX_FREQ_SCREEN_OFF = HOTPLUG_BLU_PLUG + "/max_freq_screenoff"; String HOTPLUG_BLU_PLUG_UP_THRESHOLD = HOTPLUG_BLU_PLUG + "/up_threshold"; String HOTPLUG_BLU_PLUG_UP_TIMER_CNT = HOTPLUG_BLU_PLUG + "/up_timer_cnt"; String HOTPLUG_BLU_PLUG_DOWN_TIMER_CNT = HOTPLUG_BLU_PLUG + "/down_timer_cnt"; String[] BLU_PLUG_ARRAY = {HOTPLUG_BLU_PLUG}; String HOTPLUG_MSM = "/sys/module/msm_hotplug"; String HOTPLUG_MSM_ENABLE = HOTPLUG_MSM + "/enabled"; String HOTPLUG_MSM_ENABLE_2 = HOTPLUG_MSM + "/msm_enabled"; String HOTPLUG_MSM_DEBUG_MASK = HOTPLUG_MSM + "/parameters/debug_mask"; String HOTPLUG_MSM_MIN_CPUS_ONLINE = HOTPLUG_MSM + "/min_cpus_online"; String HOTPLUG_MSM_MAX_CPUS_ONLINE = HOTPLUG_MSM + "/max_cpus_online"; String HOTPLUG_MSM_CPUS_BOOSTED = HOTPLUG_MSM + "/cpus_boosted"; String HOTPLUG_MSM_MAX_CPUS_ONLINE_SUSP = HOTPLUG_MSM + "/max_cpus_online_susp"; String HOTPLUG_MSM_BOOST_LOCK_DURATION = HOTPLUG_MSM + "/boost_lock_duration"; String HOTPLUG_MSM_DOWN_LOCK_DURATION = HOTPLUG_MSM + "/down_lock_duration"; String HOTPLUG_MSM_HISTORY_SIZE = HOTPLUG_MSM + "/history_size"; String HOTPLUG_MSM_UPDATE_RATE = HOTPLUG_MSM + "/update_rate"; String HOTPLUG_MSM_UPDATE_RATES = HOTPLUG_MSM + "/update_rates"; String HOTPLUG_MSM_FAST_LANE_LOAD = HOTPLUG_MSM + "/fast_lane_load"; String HOTPLUG_MSM_FAST_LANE_MIN_FREQ = HOTPLUG_MSM + "/fast_lane_min_freq"; String HOTPLUG_MSM_OFFLINE_LOAD = HOTPLUG_MSM + "/offline_load"; String HOTPLUG_MSM_IO_IS_BUSY = HOTPLUG_MSM + "/io_is_busy"; String HOTPLUG_MSM_HP_IO_IS_BUSY = HOTPLUG_MSM + "/hp_io_is_busy"; String HOTPLUG_MSM_SUSPEND_MAX_CPUS = HOTPLUG_MSM + "/suspend_max_cpus"; String HOTPLUG_MSM_SUSPEND_FREQ = HOTPLUG_MSM + "/suspend_freq"; String HOTPLUG_MSM_SUSPEND_MAX_FREQ = HOTPLUG_MSM + "/suspend_max_freq"; String HOTPLUG_MSM_SUSPEND_DEFER_TIME = HOTPLUG_MSM + "/suspend_defer_time"; String[] HOTPLUG_MSM_ARRAY = {HOTPLUG_MSM}; String MAKO_HOTPLUG = "/sys/class/misc/mako_hotplug_control"; String MAKO_HOTPLUG_ENABLED = MAKO_HOTPLUG + "/enabled"; String MAKO_HOTPLUG_CORES_ON_TOUCH = MAKO_HOTPLUG + "/cores_on_touch"; String MAKO_HOTPLUG_CPUFREQ_UNPLUG_LIMIT = MAKO_HOTPLUG + "/cpufreq_unplug_limit"; String MAKO_HOTPLUG_FIRST_LEVEL = MAKO_HOTPLUG + "/first_level"; String MAKO_HOTPLUG_HIGH_LOAD_COUNTER = MAKO_HOTPLUG + "/high_load_counter"; String MAKO_HOTPLUG_LOAD_THRESHOLD = MAKO_HOTPLUG + "/load_threshold"; String MAKO_HOTPLUG_MAX_LOAD_COUNTER = MAKO_HOTPLUG + "/max_load_counter"; String MAKO_HOTPLUG_MIN_TIME_CPU_ONLINE = MAKO_HOTPLUG + "/min_time_cpu_online"; String MAKO_HOTPLUG_MIN_CORES_ONLINE = MAKO_HOTPLUG + "/min_cores_online"; String MAKO_HOTPLUG_TIMER = MAKO_HOTPLUG + "/timer"; String MAKO_HOTPLUG_SUSPEND_FREQ = MAKO_HOTPLUG + "/suspend_frequency"; String[] MAKO_HOTPLUG_ARRAY = {MAKO_HOTPLUG}; String MSM_MPDECISION_HOTPLUG = "/sys/kernel/msm_mpdecision/conf"; String BRICKED_HOTPLUG = "/sys/kernel/bricked_hotplug/conf"; String MB_ENABLED = "enabled"; String MB_SCROFF_SINGLE_CORE = "scroff_single_core"; String MB_MIN_CPUS = "min_cpus"; String MB_MAX_CPUS = "max_cpus"; String MB_MIN_CPUS_ONLINE = "min_cpus_online"; String MB_MAX_CPUS_ONLINE = "max_cpus_online"; String MB_CPUS_ONLINE_SUSP = "max_cpus_online_susp"; String MB_IDLE_FREQ = "idle_freq"; String MB_BOOST_ENABLED = "boost_enabled"; String MB_BOOST_TIME = "boost_time"; String MB_CPUS_BOOSTED = "cpus_boosted"; String MB_BOOST_FREQS = "boost_freqs"; String MB_STARTDELAY = "startdelay"; String MB_DELAY = "delay"; String MB_PAUSE = "pause"; String BRICKED_NWNS = "nwns_threshold"; String BRICKED_TWTS = "twts_threshold"; String BRICKED_DOWN_LOCK_DURATION = "down_lock_duration"; String[] MB_HOTPLUG_ARRAY = {MSM_MPDECISION_HOTPLUG, BRICKED_HOTPLUG}; String ALUCARD_HOTPLUG = "/sys/kernel/alucard_hotplug"; String ALUCARD_HOTPLUG_ENABLE = ALUCARD_HOTPLUG + "/hotplug_enable"; String ALUCARD_HOTPLUG_HP_IO_IS_BUSY = ALUCARD_HOTPLUG + "/hp_io_is_busy"; String ALUCARD_HOTPLUG_SAMPLING_RATE = ALUCARD_HOTPLUG + "/hotplug_sampling_rate"; String ALUCARD_HOTPLUG_SUSPEND = ALUCARD_HOTPLUG + "/hotplug_suspend"; String ALUCARD_HOTPLUG_MIN_CPUS_ONLINE = ALUCARD_HOTPLUG + "/min_cpus_online"; String ALUCARD_HOTPLUG_MAX_CORES_LIMIT = ALUCARD_HOTPLUG + "/maxcoreslimit"; String ALUCARD_HOTPLUG_MAX_CORES_LIMIT_SLEEP = ALUCARD_HOTPLUG + "/maxcoreslimit_sleep"; String ALUCARD_HOTPLUG_CPU_DOWN_RATE = ALUCARD_HOTPLUG + "/cpu_down_rate"; String ALUCARD_HOTPLUG_CPU_UP_RATE = ALUCARD_HOTPLUG + "/cpu_up_rate"; String[] ALUCARD_HOTPLUG_ARRAY = {ALUCARD_HOTPLUG}; String HOTPLUG_THUNDER_PLUG = "/sys/kernel/thunderplug"; String HOTPLUG_THUNDER_PLUG_ENABLE = HOTPLUG_THUNDER_PLUG + "/hotplug_enabled"; String HOTPLUG_THUNDER_PLUG_SUSPEND_CPUS = HOTPLUG_THUNDER_PLUG + "/suspend_cpus"; String HOTPLUG_THUNDER_PLUG_ENDURANCE_LEVEL = HOTPLUG_THUNDER_PLUG + "/endurance_level"; String HOTPLUG_THUNDER_PLUG_SAMPLING_RATE = HOTPLUG_THUNDER_PLUG + "/sampling_rate"; String HOTPLUG_THUNDER_PLUG_LOAD_THRESHOLD = HOTPLUG_THUNDER_PLUG + "/load_threshold"; String HOTPLUG_THUNDER_PLUG_TOUCH_BOOST = HOTPLUG_THUNDER_PLUG + "/touch_boost"; String[] HOTPLUG_THUNDER_PLUG_ARRAY = {HOTPLUG_THUNDER_PLUG}; String HOTPLUG_ZEN_DECISION = "/sys/kernel/zen_decision"; String HOTPLUG_ZEN_DECISION_ENABLE = HOTPLUG_ZEN_DECISION + "/enabled"; String HOTPLUG_ZEN_DECISION_WAKE_WAIT_TIME = HOTPLUG_ZEN_DECISION + "/wake_wait_time"; String HOTPLUG_ZEN_DECISION_BAT_THRESHOLD_IGNORE = HOTPLUG_ZEN_DECISION + "/bat_threshold_ignore"; String[] HOTPLUG_ZEN_DECISION_ARRAY = {HOTPLUG_ZEN_DECISION}; String HOTPLUG_AUTOSMP_PARAMETERS = "/sys/module/autosmp/parameters"; String HOTPLUG_AUTOSMP_CONF = "/sys/kernel/autosmp/conf"; String HOTPLUG_AUTOSMP_ENABLE = HOTPLUG_AUTOSMP_PARAMETERS + "/enabled"; String HOTPLUG_AUTOSMP_CPUFREQ_DOWN = HOTPLUG_AUTOSMP_CONF + "/cpufreq_down"; String HOTPLUG_AUTOSMP_CPUFREQ_UP = HOTPLUG_AUTOSMP_CONF + "/cpufreq_up"; String HOTPLUG_AUTOSMP_CYCLE_DOWN = HOTPLUG_AUTOSMP_CONF + "/cycle_down"; String HOTPLUG_AUTOSMP_CYCLE_UP = HOTPLUG_AUTOSMP_CONF + "/cycle_up"; String HOTPLUG_AUTOSMP_DELAY = HOTPLUG_AUTOSMP_CONF + "/delay"; String HOTPLUG_AUTOSMP_MAX_CPUS = HOTPLUG_AUTOSMP_CONF + "/max_cpus"; String HOTPLUG_AUTOSMP_MIN_CPUS = HOTPLUG_AUTOSMP_CONF + "/min_cpus"; String HOTPLUG_AUTOSMP_SCROFF_SINGLE_CORE = HOTPLUG_AUTOSMP_CONF + "/scroff_single_core"; String[] HOTPLUG_AUTOSMP_ARRAY = {HOTPLUG_AUTOSMP_PARAMETERS, HOTPLUG_AUTOSMP_CONF}; String MSM_SLEEPER = "/sys/devices/platform/msm_sleeper"; String MSM_SLEEPER_ENABLE = MSM_SLEEPER + "/enabled"; String MSM_SLEEPER_UP_THRESHOLD = MSM_SLEEPER + "/up_threshold"; String MSM_SLEEPER_MAX_ONLINE = MSM_SLEEPER + "/max_online"; String MSM_SLEEPER_SUSPEND_MAX_ONLINE = MSM_SLEEPER + "/suspend_max_online"; String MSM_SLEEPER_UP_COUNT_MAX = MSM_SLEEPER + "/up_count_max"; String MSM_SLEEPER_DOWN_COUNT_MAX = MSM_SLEEPER + "/down_count_max"; String[][] CPU_HOTPLUG_ARRAY = {{HOTPLUG_MPDEC, MSM_SLEEPER}, INTELLIPLUG_ARRAY, BLU_PLUG_ARRAY, HOTPLUG_MSM_ARRAY, MAKO_HOTPLUG_ARRAY, MB_HOTPLUG_ARRAY, ALUCARD_HOTPLUG_ARRAY, HOTPLUG_THUNDER_PLUG_ARRAY, HOTPLUG_ZEN_DECISION_ARRAY, HOTPLUG_AUTOSMP_ARRAY}; // Thermal String THERMALD = "thermald"; String MSM_THERMAL = "/sys/module/msm_thermal"; String MSM_THERMAL_V2 = "/sys/module/msm_thermal_v2"; String PARAMETERS_ENABLED = "parameters/enabled"; String PARAMETERS_INTELLI_ENABLED = "parameters/intelli_enabled"; String PARAMETERS_THERMAL_DEBUG_MODE = "parameters/thermal_debug_mode"; String CORE_CONTROL_ENABLED = "core_control/enabled"; String CORE_CONTROL_ENABLED_2 = "core_control/core_control"; String VDD_RESTRICTION_ENABLED = "vdd_restriction/enabled"; String PARAMETERS_LIMIT_TEMP_DEGC = "parameters/limit_temp_degC"; String PARAMETERS_CORE_LIMIT_TEMP_DEGC = "parameters/core_limit_temp_degC"; String PARAMETERS_CORE_TEMP_HYSTERESIS_DEGC = "parameters/core_temp_hysteresis_degC"; String PARAMETERS_FREQ_STEP = "parameters/freq_step"; String PARAMETERS_IMMEDIATELY_LIMIT_STOP = "parameters/immediately_limit_stop"; String PARAMETERS_POLL_MS = "parameters/poll_ms"; String PARAMETERS_TEMP_HYSTERESIS_DEGC = "parameters/temp_hysteresis_degC"; String PARAMETERS_THERMAL_LIMIT_LOW = "parameters/thermal_limit_low"; String PARAMETERS_THERMAL_LIMIT_HIGH = "parameters/thermal_limit_high"; String PARAMETERS_TEMP_SAFETY = "parameters/temp_safety"; String MSM_THERMAL_TEMP_THROTTLE = MSM_THERMAL + "/" + PARAMETERS_ENABLED; String MSM_THERMAL_THROTTLE_TEMP = MSM_THERMAL + "/parameters/throttle_temp"; String MSM_THERMAL_TEMP_MAX = MSM_THERMAL + "/parameters/temp_max"; String MSM_THERMAL_TEMP_THRESHOLD = MSM_THERMAL + "/parameters/temp_threshold"; String MSM_THERMAL_FREQ_LIMIT_DEBUG = MSM_THERMAL + "/parameters/freq_limit_debug"; String MSM_THERMAL_MIN_FREQ_INDEX = MSM_THERMAL + "/parameters/min_freq_index"; String TEMPCONTROL_TEMP_LIMIT = "/sys/class/misc/tempcontrol/templimit"; String[] TEMP_LIMIT_ARRAY = {MSM_THERMAL_THROTTLE_TEMP, MSM_THERMAL_TEMP_MAX, MSM_THERMAL_TEMP_THRESHOLD, MSM_THERMAL_FREQ_LIMIT_DEBUG, MSM_THERMAL_MIN_FREQ_INDEX, TEMPCONTROL_TEMP_LIMIT}; String MSM_THERMAL_CONF = "/sys/kernel/msm_thermal/conf"; String CONF_ENABLED = MSM_THERMAL_CONF + "/enabled"; String CONF_ALLOWED_LOW_LOW = MSM_THERMAL_CONF + "/allowed_low_low"; String CONF_ALLOWED_LOW_HIGH = MSM_THERMAL_CONF + "/allowed_low_high"; String CONF_ALLOWED_LOW_FREQ = MSM_THERMAL_CONF + "/allowed_low_freq"; String CONF_ALLOWED_MID_LOW = MSM_THERMAL_CONF + "/allowed_mid_low"; String CONF_ALLOWED_MID_HIGH = MSM_THERMAL_CONF + "/allowed_mid_high"; String CONF_ALLOWED_MID_FREQ = MSM_THERMAL_CONF + "/allowed_mid_freq"; String CONF_ALLOWED_MAX_LOW = MSM_THERMAL_CONF + "/allowed_max_low"; String CONF_ALLOWED_MAX_HIGH = MSM_THERMAL_CONF + "/allowed_max_high"; String CONF_ALLOWED_MAX_FREQ = MSM_THERMAL_CONF + "/allowed_max_freq"; String CONF_CHECK_INTERVAL_MS = MSM_THERMAL_CONF + "/check_interval_ms"; String CONF_SHUTDOWN_TEMP = MSM_THERMAL_CONF + "/shutdown_temp"; // Sultan's 8X60 Ones String CONF_START = MSM_THERMAL_CONF + "/start"; String CONF_RESET_LOW_THRESH = MSM_THERMAL_CONF + "/reset_low_thresh"; String CONF_TRIP_LOW_THRESH = MSM_THERMAL_CONF + "/trip_low_thresh"; String CONF_FREQ_LOW_THRESH = MSM_THERMAL_CONF + "/freq_low_thresh"; String CONF_RESET_MID_THRESH = MSM_THERMAL_CONF + "/reset_mid_thresh"; String CONF_TRIP_MID_THRESH = MSM_THERMAL_CONF + "/trip_mid_thresh"; String CONF_FREQ_MID_THRESH = MSM_THERMAL_CONF + "/freq_mid_thresh"; String CONF_RESET_HIGH_THRESH = MSM_THERMAL_CONF + "/reset_high_thresh"; String CONF_TRIP_HIGH_THRESH = MSM_THERMAL_CONF + "/trip_high_thresh"; String CONF_FREQ_HIGH_THRESH = MSM_THERMAL_CONF + "/freq_high_thresh"; String CONF_POLL_MS = MSM_THERMAL_CONF + "/poll_ms"; String[] THERMAL_ARRAY = {MSM_THERMAL, MSM_THERMAL_V2}; String[][] THERMAL_ARRAYS = {THERMAL_ARRAY, TEMP_LIMIT_ARRAY, {MSM_THERMAL_CONF}}; // GPU String GPU_GENERIC_GOVERNORS = "performance powersave ondemand simple conservative"; String GPU_CUR_KGSL2D0_QCOM_FREQ = "/sys/devices/platform/kgsl-2d0.0/kgsl/kgsl-2d0/gpuclk"; String GPU_MAX_KGSL2D0_QCOM_FREQ = "/sys/devices/platform/kgsl-2d0.0/kgsl/kgsl-2d0/max_gpuclk"; String GPU_AVAILABLE_KGSL2D0_QCOM_FREQS = "/sys/devices/platform/kgsl-2d0.0/kgsl/kgsl-2d0/gpu_available_frequencies"; String GPU_SCALING_KGSL2D0_QCOM_GOVERNOR = "/sys/devices/platform/kgsl-2d0.0/kgsl/kgsl-2d0/pwrscale/trustzone/governor"; String GPU_CUR_KGSL3D0_QCOM_FREQ = "/sys/devices/platform/kgsl-3d0.0/kgsl/kgsl-3d0/gpuclk"; String GPU_MAX_KGSL3D0_QCOM_FREQ = "/sys/devices/platform/kgsl-3d0.0/kgsl/kgsl-3d0/max_gpuclk"; String GPU_AVAILABLE_KGSL3D0_QCOM_FREQS = "/sys/devices/platform/kgsl-3d0.0/kgsl/kgsl-3d0/gpu_available_frequencies"; String GPU_SCALING_KGSL3D0_QCOM_GOVERNOR = "/sys/devices/platform/kgsl-3d0.0/kgsl/kgsl-3d0/pwrscale/trustzone/governor"; String GPU_CUR_FDB00000_QCOM_FREQ = "/sys/devices/fdb00000.qcom,kgsl-3d0/kgsl/kgsl-3d0/gpuclk"; String GPU_MAX_FDB00000_QCOM_FREQ = "/sys/devices/fdb00000.qcom,kgsl-3d0/kgsl/kgsl-3d0/max_gpuclk"; String GPU_MIN_FDB00000_QCOM_FREQ = "/sys/class/kgsl/kgsl-3d0/devfreq/min_freq"; String GPU_AVAILABLE_FDB00000_QCOM_FREQS = "/sys/devices/fdb00000.qcom,kgsl-3d0/kgsl/kgsl-3d0/gpu_available_frequencies"; String GPU_SCALING_FDB00000_QCOM_GOVERNOR = "/sys/devices/fdb00000.qcom,kgsl-3d0/kgsl/kgsl-3d0/devfreq/governor"; String GPU_SCALING_PWRSCALE_GOVERNOR = "/sys/class/kgsl/kgsl-3d0/pwrscale/trustzone/governor"; String GPU_AVAILABLE_FDB00000_QCOM_GOVERNORS = "/sys/devices/fdb00000.qcom,kgsl-3d0/kgsl/kgsl-3d0/devfreq/available_governors"; String GPU_CUR_FDC00000_QCOM_FREQ = "/sys/devices/fdc00000.qcom,kgsl-3d0/kgsl/kgsl-3d0/gpuclk"; String GPU_MAX_FDC00000_QCOM_FREQ = "/sys/devices/fdc00000.qcom,kgsl-3d0/kgsl/kgsl-3d0/max_gpuclk"; String GPU_AVAILABLE_FDC00000_QCOM_FREQS = "/sys/devices/fdc00000.qcom,kgsl-3d0/kgsl/kgsl-3d0/gpu_available_frequencies"; String GPU_SCALING_FDC00000_QCOM_GOVERNOR = "/sys/devices/fdc00000.qcom,kgsl-3d0/kgsl/kgsl-3d0/devfreq/governor"; String GPU_AVAILABLE_FDC00000_QCOM_GOVERNORS = "/sys/devices/fdc00000.qcom,kgsl-3d0/kgsl/kgsl-3d0/devfreq/available_governors"; String GPU_CUR_SOC0_FDB00000_QCOM_FREQ = "/sys/devices/soc.0/fdb00000.qcom,kgsl-3d0/kgsl/kgsl-3d0/gpuclk"; String GPU_MAX_SOC0_FDB00000_QCOM_FREQ = "/sys/devices/soc.0/fdb00000.qcom,kgsl-3d0/kgsl/kgsl-3d0/max_gpuclk"; String GPU_AVAILABLE_SOC0_FDB00000_QCOM_FREQS = "/sys/devices/soc.0/fdb00000.qcom,kgsl-3d0/kgsl/kgsl-3d0/gpu_available_frequencies"; String GPU_SCALING_SOC0_FDB00000_QCOM_GOVERNOR = "/sys/devices/soc.0/fdb00000.qcom,kgsl-3d0/devfreq/fdb00000.qcom,kgsl-3d0/governor"; String GPU_AVAILABLE_SOC0_FDB00000_QCOM_GOVERNORS = "/sys/devices/soc.0/fdb00000.qcom,kgsl-3d0/kgsl/kgsl-3d0/devfreq/available_governors"; String GPU_CUR_1C00000_QCOM_FREQ = "/sys/devices/soc.0/1c00000.qcom,kgsl-3d0/kgsl/kgsl-3d0/max_gpuclk"; String GPU_MAX_1C00000_QCOM_FREQ = "/sys/devices/soc.0/1c00000.qcom,kgsl-3d0/kgsl/kgsl-3d0/max_gpuclk"; String GPU_AVAILABLE_1C00000_QCOM_FREQ = "/sys/devices/soc.0/1c00000.qcom,kgsl-3d0/kgsl/kgsl-3d0/gpu_available_frequencies"; String GPU_SCALING_1C00000_QCOM_GOVERNOR = "/sys/devices/soc.0/1c00000.qcom,kgsl-3d0/devfreq/1c00000.qcom,kgsl-3d0/governor"; String GPU_AVAILABLE_1C00000_QCOM_GOVERNORS = "/sys/devices/soc.0/1c00000.qcom,kgsl-3d0/devfreq/1c00000.qcom,kgsl-3d0/available_governors"; String GPU_CUR_OMAP_FREQ = "/sys/devices/platform/omap/pvrsrvkm.0/sgxfreq/frequency"; String GPU_MAX_OMAP_FREQ = "/sys/devices/platform/omap/pvrsrvkm.0/sgxfreq/frequency_limit"; String GPU_AVAILABLE_OMAP_FREQS = "/sys/devices/platform/omap/pvrsrvkm.0/sgxfreq/frequency_list"; String GPU_SCALING_OMAP_GOVERNOR = "/sys/devices/platform/omap/pvrsrvkm.0/sgxfreq/governor"; String GPU_AVAILABLE_OMAP_GOVERNORS = "/sys/devices/platform/omap/pvrsrvkm.0/sgxfreq/governor_list"; String GPU_CUR_TEGRA_FREQ = "/sys/kernel/tegra_gpu/gpu_rate"; String GPU_MAX_TEGRA_FREQ = "/sys/kernel/tegra_gpu/gpu_cap_rate"; String GPU_MIN_TEGRA_FREQ = "/sys/kernel/tegra_gpu/gpu_floor_rate"; String GPU_AVAILABLE_TEGRA_FREQS = "/sys/kernel/tegra_gpu/gpu_available_rates"; String GPU_MIN_POWER_LEVEL = "/sys/devices/fdb00000.qcom,kgsl-3d0/kgsl/kgsl-3d0/min_pwrlevel"; String[] GPU_2D_CUR_FREQ_ARRAY = {GPU_CUR_KGSL2D0_QCOM_FREQ}; String[] GPU_2D_MAX_FREQ_ARRAY = {GPU_MAX_KGSL2D0_QCOM_FREQ}; String[] GPU_2D_AVAILABLE_FREQS_ARRAY = {GPU_AVAILABLE_KGSL2D0_QCOM_FREQS}; String[] GPU_2D_SCALING_GOVERNOR_ARRAY = {GPU_SCALING_KGSL2D0_QCOM_GOVERNOR}; String[] GPU_CUR_FREQ_ARRAY = {GPU_CUR_KGSL3D0_QCOM_FREQ, GPU_CUR_FDB00000_QCOM_FREQ, GPU_CUR_FDC00000_QCOM_FREQ, GPU_CUR_SOC0_FDB00000_QCOM_FREQ, GPU_CUR_1C00000_QCOM_FREQ, GPU_CUR_OMAP_FREQ, GPU_CUR_TEGRA_FREQ}; String[] GPU_MAX_FREQ_ARRAY = {GPU_MAX_KGSL3D0_QCOM_FREQ, GPU_MAX_FDB00000_QCOM_FREQ, GPU_MAX_FDC00000_QCOM_FREQ, GPU_MAX_SOC0_FDB00000_QCOM_FREQ, GPU_MAX_1C00000_QCOM_FREQ, GPU_MAX_OMAP_FREQ, GPU_MAX_TEGRA_FREQ}; String[] GPU_MIN_FREQ_ARRAY = {GPU_MIN_FDB00000_QCOM_FREQ, GPU_MIN_TEGRA_FREQ}; String[] GPU_AVAILABLE_FREQS_ARRAY = {GPU_AVAILABLE_KGSL3D0_QCOM_FREQS, GPU_AVAILABLE_FDB00000_QCOM_FREQS, GPU_AVAILABLE_SOC0_FDB00000_QCOM_FREQS, GPU_AVAILABLE_FDC00000_QCOM_FREQS, GPU_AVAILABLE_1C00000_QCOM_FREQ, GPU_AVAILABLE_OMAP_FREQS, GPU_AVAILABLE_TEGRA_FREQS}; String[] GPU_SCALING_GOVERNOR_ARRAY = {GPU_SCALING_KGSL3D0_QCOM_GOVERNOR, GPU_SCALING_FDB00000_QCOM_GOVERNOR, GPU_SCALING_PWRSCALE_GOVERNOR, GPU_SCALING_FDC00000_QCOM_GOVERNOR, GPU_SCALING_SOC0_FDB00000_QCOM_GOVERNOR, GPU_SCALING_1C00000_QCOM_GOVERNOR, GPU_SCALING_OMAP_GOVERNOR}; String[] GPU_AVAILABLE_GOVERNORS_ARRAY = {GPU_AVAILABLE_FDB00000_QCOM_GOVERNORS, GPU_AVAILABLE_FDC00000_QCOM_GOVERNORS, GPU_AVAILABLE_SOC0_FDB00000_QCOM_GOVERNORS, GPU_AVAILABLE_1C00000_QCOM_GOVERNORS, GPU_AVAILABLE_OMAP_GOVERNORS}; // Simple GPU String SIMPLE_GPU_PARAMETERS = "/sys/module/simple_gpu_algorithm/parameters"; String SIMPLE_GPU_ACTIVATE = SIMPLE_GPU_PARAMETERS + "/simple_gpu_activate"; String SIMPLE_GPU_LAZINESS = SIMPLE_GPU_PARAMETERS + "/simple_laziness"; String SIMPLE_RAMP_THRESHOLD = SIMPLE_GPU_PARAMETERS + "/simple_ramp_threshold"; // Adreno Idler String ADRENO_IDLER_PARAMETERS = "/sys/module/adreno_idler/parameters/"; String ADRENO_IDLER_ACTIVATE = ADRENO_IDLER_PARAMETERS + "adreno_idler_active"; String ADRENO_IDLER_DOWNDIFFERENTIAL = ADRENO_IDLER_PARAMETERS + "/adreno_idler_downdifferential"; String ADRENO_IDLER_IDLEWAIT = ADRENO_IDLER_PARAMETERS + "/adreno_idler_idlewait"; String ADRENO_IDLER_IDLEWORKLOAD = ADRENO_IDLER_PARAMETERS + "/adreno_idler_idleworkload"; String[][] GPU_ARRAY = {GPU_2D_CUR_FREQ_ARRAY, GPU_2D_MAX_FREQ_ARRAY, GPU_2D_AVAILABLE_FREQS_ARRAY, GPU_2D_SCALING_GOVERNOR_ARRAY, GPU_CUR_FREQ_ARRAY, GPU_MAX_FREQ_ARRAY, GPU_MIN_FREQ_ARRAY, GPU_AVAILABLE_FREQS_ARRAY, GPU_SCALING_GOVERNOR_ARRAY, {SIMPLE_GPU_PARAMETERS, ADRENO_IDLER_PARAMETERS, GPU_MIN_POWER_LEVEL}}; // Screen String SCREEN_KCAL = "/sys/devices/platform/kcal_ctrl.0"; String SCREEN_KCAL_CTRL = SCREEN_KCAL + "/kcal"; String SCREEN_KCAL_CTRL_CTRL = SCREEN_KCAL + "/kcal_ctrl"; String SCREEN_KCAL_CTRL_ENABLE = SCREEN_KCAL + "/kcal_enable"; String SCREEN_KCAL_CTRL_MIN = SCREEN_KCAL + "/kcal_min"; String SCREEN_KCAL_CTRL_INVERT = SCREEN_KCAL + "/kcal_invert"; String SCREEN_KCAL_CTRL_SAT = SCREEN_KCAL + "/kcal_sat"; String SCREEN_KCAL_CTRL_HUE = SCREEN_KCAL + "/kcal_hue"; String SCREEN_KCAL_CTRL_VAL = SCREEN_KCAL + "/kcal_val"; String SCREEN_KCAL_CTRL_CONT = SCREEN_KCAL + "/kcal_cont"; String[] SCREEN_KCAL_CTRL_NEW_ARRAY = {SCREEN_KCAL_CTRL_ENABLE, SCREEN_KCAL_CTRL_INVERT, SCREEN_KCAL_CTRL_SAT, SCREEN_KCAL_CTRL_HUE, SCREEN_KCAL_CTRL_VAL, SCREEN_KCAL_CTRL_CONT}; String SCREEN_DIAG0 = "/sys/devices/platform/DIAG0.0"; String SCREEN_DIAG0_POWER = SCREEN_DIAG0 + "/power_rail"; String SCREEN_DIAG0_POWER_CTRL = SCREEN_DIAG0 + "/power_rail_ctrl"; String SCREEN_COLOR = "/sys/class/misc/colorcontrol"; String SCREEN_COLOR_CONTROL = SCREEN_COLOR + "/multiplier"; String SCREEN_COLOR_CONTROL_CTRL = SCREEN_COLOR + "/safety_enabled"; String SCREEN_SAMOLED_COLOR = "/sys/class/misc/samoled_color"; String SCREEN_SAMOLED_COLOR_RED = SCREEN_SAMOLED_COLOR + "/red_multiplier"; String SCREEN_SAMOLED_COLOR_GREEN = SCREEN_SAMOLED_COLOR + "/green_multiplier"; String SCREEN_SAMOLED_COLOR_BLUE = SCREEN_SAMOLED_COLOR + "/blue_multiplier"; String SCREEN_FB0_RGB = "/sys/class/graphics/fb0/rgb"; String SCREEN_FB_KCAL = "/sys/devices/virtual/graphics/fb0/kcal"; String[] SCREEN_RGB_ARRAY = {SCREEN_KCAL_CTRL, SCREEN_DIAG0_POWER, SCREEN_COLOR_CONTROL, SCREEN_SAMOLED_COLOR, SCREEN_FB0_RGB, SCREEN_FB_KCAL}; String[] SCREEN_RGB_CTRL_ARRAY = {SCREEN_KCAL_CTRL_ENABLE, SCREEN_KCAL_CTRL_CTRL, SCREEN_DIAG0_POWER_CTRL, SCREEN_COLOR_CONTROL_CTRL}; String SCREEN_HBM = "/sys/devices/virtual/graphics/fb0/hbm"; // Gamma String K_GAMMA_R = "/sys/devices/platform/mipi_lgit.1537/kgamma_r"; String K_GAMMA_G = "/sys/devices/platform/mipi_lgit.1537/kgamma_g"; String K_GAMMA_B = "/sys/devices/platform/mipi_lgit.1537/kgamma_b"; String K_GAMMA_RED = "/sys/devices/platform/mipi_lgit.1537/kgamma_red"; String K_GAMMA_GREEN = "/sys/devices/platform/mipi_lgit.1537/kgamma_green"; String K_GAMMA_BLUE = "/sys/devices/platform/mipi_lgit.1537/kgamma_blue"; String[] K_GAMMA_ARRAY = {K_GAMMA_R, K_GAMMA_G, K_GAMMA_B, K_GAMMA_RED, K_GAMMA_GREEN, K_GAMMA_BLUE}; String GAMMACONTROL = "/sys/class/misc/gammacontrol"; String GAMMACONTROL_RED_GREYS = GAMMACONTROL + "/red_greys"; String GAMMACONTROL_RED_MIDS = GAMMACONTROL + "/red_mids"; String GAMMACONTROL_RED_BLACKS = GAMMACONTROL + "/red_blacks"; String GAMMACONTROL_RED_WHITES = GAMMACONTROL + "/red_whites"; String GAMMACONTROL_GREEN_GREYS = GAMMACONTROL + "/green_greys"; String GAMMACONTROL_GREEN_MIDS = GAMMACONTROL + "/green_mids"; String GAMMACONTROL_GREEN_BLACKS = GAMMACONTROL + "/green_blacks"; String GAMMACONTROL_GREEN_WHITES = GAMMACONTROL + "/green_whites"; String GAMMACONTROL_BLUE_GREYS = GAMMACONTROL + "/blue_greys"; String GAMMACONTROL_BLUE_MIDS = GAMMACONTROL + "/blue_mids"; String GAMMACONTROL_BLUE_BLACKS = GAMMACONTROL + "/blue_blacks"; String GAMMACONTROL_BLUE_WHITES = GAMMACONTROL + "/blue_whites"; String GAMMACONTROL_CONTRAST = GAMMACONTROL + "/contrast"; String GAMMACONTROL_BRIGHTNESS = GAMMACONTROL + "/brightness"; String GAMMACONTROL_SATURATION = GAMMACONTROL + "/saturation"; String DSI_PANEL_RP = "/sys/module/dsi_panel/kgamma_rp"; String DSI_PANEL_RN = "/sys/module/dsi_panel/kgamma_rn"; String DSI_PANEL_GP = "/sys/module/dsi_panel/kgamma_gp"; String DSI_PANEL_GN = "/sys/module/dsi_panel/kgamma_gn"; String DSI_PANEL_BP = "/sys/module/dsi_panel/kgamma_bp"; String DSI_PANEL_BN = "/sys/module/dsi_panel/kgamma_bn"; String DSI_PANEL_W = "/sys/module/dsi_panel/kgamma_w"; String[] DSI_PANEL_ARRAY = {DSI_PANEL_RP, DSI_PANEL_RN, DSI_PANEL_GP, DSI_PANEL_GN, DSI_PANEL_BP, DSI_PANEL_BN, DSI_PANEL_W}; // LCD Backlight String LM3530_BRIGTHNESS_MODE = "/sys/devices/i2c-0/0-0038/lm3530_br_mode"; String LM3530_MIN_BRIGHTNESS = "/sys/devices/i2c-0/0-0038/lm3530_min_br"; String LM3530_MAX_BRIGHTNESS = "/sys/devices/i2c-0/0-0038/lm3530_max_br"; // Backlight Dimmer String LM3630_BACKLIGHT_DIMMER = "/sys/module/lm3630_bl/parameters/backlight_dimmer"; String LM3630_MIN_BRIGHTNESS = "/sys/module/lm3630_bl/parameters/min_brightness"; String LM3630_BACKLIGHT_DIMMER_THRESHOLD = "/sys/module/lm3630_bl/parameters/backlight_threshold"; String LM3630_BACKLIGHT_DIMMER_OFFSET = "/sys/module/lm3630_bl/parameters/backlight_offset"; String MSM_BACKLIGHT_DIMMER = "/sys/module/msm_fb/parameters/backlight_dimmer"; String[] MIN_BRIGHTNESS_ARRAY = {LM3630_MIN_BRIGHTNESS, MSM_BACKLIGHT_DIMMER}; String NEGATIVE_TOGGLE = "/sys/module/cypress_touchkey/parameters/mdnie_shortcut_enabled"; String REGISTER_HOOK = "/sys/class/misc/mdnie/hook_intercept"; String MASTER_SEQUENCE = "/sys/class/misc/mdnie/sequence_intercept"; String GLOVE_MODE = "/sys/devices/virtual/touchscreen/touchscreen_dev/mode"; String[][] SCREEN_ARRAY = {SCREEN_RGB_ARRAY, SCREEN_RGB_CTRL_ARRAY, SCREEN_KCAL_CTRL_NEW_ARRAY, K_GAMMA_ARRAY, DSI_PANEL_ARRAY, MIN_BRIGHTNESS_ARRAY, {GAMMACONTROL, SCREEN_KCAL_CTRL_MIN, SCREEN_HBM, LM3530_BRIGTHNESS_MODE, LM3530_MIN_BRIGHTNESS, LM3530_MAX_BRIGHTNESS, LM3630_BACKLIGHT_DIMMER, LM3630_BACKLIGHT_DIMMER_THRESHOLD, LM3630_BACKLIGHT_DIMMER_OFFSET, NEGATIVE_TOGGLE, REGISTER_HOOK, MASTER_SEQUENCE, GLOVE_MODE}}; // Wake // DT2W String LGE_TOUCH_DT2W = "/sys/devices/virtual/input/lge_touch/dt_wake_enabled"; String LGE_TOUCH_CORE_DT2W = "/sys/module/lge_touch_core/parameters/doubletap_to_wake"; String LGE_TOUCH_GESTURE = "/sys/devices/virtual/input/lge_touch/touch_gesture"; String DT2W = "/sys/android_touch/doubletap2wake"; String DT2W_2 = "/sys/android_touch2/doubletap2wake"; String TOUCH_PANEL_DT2W = "/proc/touchpanel/double_tap_enable"; String DT2W_WAKEUP_GESTURE = "/sys/devices/virtual/input/input1/wakeup_gesture"; String DT2W_ENABLE = "/sys/devices/platform/s3c2440-i2c.3/i2c-3/3-004a/dt2w_enable"; String DT2W_WAKE_GESTURE = "/sys/devices/platform/spi-tegra114.2/spi_master/spi2/spi2.0/input/input0/wake_gesture"; String DT2W_WAKE_GESTURE_2 = "/sys/devices/soc.0/f9924000.i2c/i2c-2/2-0070/input/input0/wake_gesture"; String[] DT2W_ARRAY = {LGE_TOUCH_DT2W, LGE_TOUCH_CORE_DT2W, LGE_TOUCH_GESTURE, DT2W, DT2W_2, TOUCH_PANEL_DT2W, DT2W_WAKEUP_GESTURE, DT2W_ENABLE, DT2W_WAKE_GESTURE, DT2W_WAKE_GESTURE_2}; // S2W String S2W_ONLY = "/sys/android_touch/s2w_s2sonly"; String SW2 = "/sys/android_touch/sweep2wake"; String SW2_2 = "/sys/android_touch2/sweep2wake"; String[] S2W_ARRY = {S2W_ONLY, SW2, SW2_2}; // S2W Leniency String LENIENT = "/sys/android_touch/sweep2wake_sensitive"; // T2W String TSP_T2W = "/sys/devices/f9966000.i2c/i2c-1/1-004a/tsp"; String TOUCHWAKE_T2W = "/sys/class/misc/touchwake/enabled"; String[] T2W_ARRAY = {TSP_T2W, TOUCHWAKE_T2W}; // Wake Misc String SCREEN_WAKE_OPTIONS = "/sys/devices/f9924000.i2c/i2c-2/2-0020/input/input2/screen_wake_options"; String[] WAKE_MISC_ARRAY = {SCREEN_WAKE_OPTIONS}; // Sleep Misc String S2S = "/sys/android_touch/sweep2sleep"; String S2S_2 = "/sys/android_touch2/sweep2sleep"; String SCREEN_SLEEP_OPTIONS = "/sys/devices/f9924000.i2c/i2c-2/2-0020/input/input2/screen_sleep_options"; String[] SLEEP_MISC_ARRAY = {S2S, S2S_2, SCREEN_SLEEP_OPTIONS}; // DT2S String DT2S = "/sys/android_touch2/doubletap2sleep"; String[] DT2S_ARRAY = {DT2S}; // Gesture String GESTURE_CRTL = "/sys/devices/virtual/touchscreen/touchscreen_dev/gesture_ctrl"; Integer[] GESTURE_HEX_VALUES = {1, 2, 4, 8, 16, 32, 64, 128, 256, 512}; String[] GESTURE_STRING_VALUES = {"up", "down", "left", "right", "e", "o", "w", "c", "m", "double_click"}; // Camera Gesture String CAMERA_GESTURE = "/sys/android_touch/camera_gesture"; // Pocket mode for Gesture String POCKET_MODE = "/sys/android_touch/pocket_mode"; String POCKET_DETECT = "/sys/android_touch/pocket_detect"; String[] POCKET_MODE_ARRAY = { POCKET_MODE, POCKET_DETECT }; String WAKE_TIMEOUT = "/sys/android_touch/wake_timeout"; String WAKE_TIMEOUT_2 = "/sys/android_touch2/wake_timeout"; String[] WAKE_TIMEOUT_ARRAY = { WAKE_TIMEOUT, WAKE_TIMEOUT_2 }; String POWER_KEY_SUSPEND = "/sys/module/qpnp_power_on/parameters/pwrkey_suspend"; String[][] WAKE_ARRAY = {DT2W_ARRAY, S2W_ARRY, T2W_ARRAY, WAKE_MISC_ARRAY, SLEEP_MISC_ARRAY, WAKE_TIMEOUT_ARRAY, POCKET_MODE_ARRAY, {LENIENT, GESTURE_CRTL, CAMERA_GESTURE, POWER_KEY_SUSPEND}}; // Sound String SOUND_CONTROL_ENABLE = "/sys/module/snd_soc_wcd9320/parameters/enable_fs"; String WCD_HIGHPERF_MODE_ENABLE = "/sys/module/snd_soc_wcd9320/parameters/high_perf_mode"; String WCD_SPKR_DRV_WRND = "/sys/module/snd_soc_wcd9320/parameters/spkr_drv_wrnd"; String FAUX_SOUND = "/sys/kernel/sound_control_3"; String HEADPHONE_GAIN = "/sys/kernel/sound_control_3/gpl_headphone_gain"; String HANDSET_MICROPONE_GAIN = "/sys/kernel/sound_control_3/gpl_mic_gain"; String CAM_MICROPHONE_GAIN = "/sys/kernel/sound_control_3/gpl_cam_mic_gain"; String SPEAKER_GAIN = "/sys/kernel/sound_control_3/gpl_speaker_gain"; String HEADPHONE_POWERAMP_GAIN = "/sys/kernel/sound_control_3/gpl_headphone_pa_gain"; String FRANCO_SOUND = "/sys/devices/virtual/misc/soundcontrol"; String HIGHPERF_MODE_ENABLE = "/sys/devices/virtual/misc/soundcontrol/highperf_enabled"; String MIC_BOOST = "/sys/devices/virtual/misc/soundcontrol/mic_boost"; String SPEAKER_BOOST = "/sys/devices/virtual/misc/soundcontrol/speaker_boost"; String VOLUME_BOOST = "/sys/devices/virtual/misc/soundcontrol/volume_boost"; String[] SPEAKER_GAIN_ARRAY = {SPEAKER_GAIN, SPEAKER_BOOST}; String[][] SOUND_ARRAY = {SPEAKER_GAIN_ARRAY, {SOUND_CONTROL_ENABLE, HIGHPERF_MODE_ENABLE, HEADPHONE_GAIN, HANDSET_MICROPONE_GAIN, CAM_MICROPHONE_GAIN, HEADPHONE_POWERAMP_GAIN, MIC_BOOST, VOLUME_BOOST, WCD_HIGHPERF_MODE_ENABLE, WCD_SPKR_DRV_WRND}}; // Battery String FORCE_FAST_CHARGE = "/sys/kernel/fast_charge/force_fast_charge"; String BLX = "/sys/devices/virtual/misc/batterylifeextender/charging_limit"; String CHARGE_RATE = "sys/kernel/thundercharge_control"; String CHARGE_RATE_ENABLE = CHARGE_RATE + "/enabled"; String CUSTOM_CHARGING_RATE = CHARGE_RATE + "/custom_current"; // C-States String C0STATE = "/sys/module/msm_pm/modes/cpu0/wfi/idle_enabled"; String C1STATE = "/sys/module/msm_pm/modes/cpu0/retention/idle_enabled"; String C2STATE = "/sys/module/msm_pm/modes/cpu0/standalone_power_collapse/idle_enabled"; String C3STATE = "/sys/module/msm_pm/modes/cpu0/power_collapse/idle_enabled"; String[] BATTERY_ARRAY = {FORCE_FAST_CHARGE, BLX, CHARGE_RATE, C0STATE, C1STATE, C2STATE, C3STATE}; // I/O String IO_INTERNAL_SCHEDULER = "/sys/block/mmcblk0/queue/scheduler"; String IO_EXTERNAL_SCHEDULER = "/sys/block/mmcblk1/queue/scheduler"; String IO_INTERNAL_SCHEDULER_TUNABLE = "/sys/block/mmcblk0/queue/iosched"; String IO_EXTERNAL_SCHEDULER_TUNABLE = "/sys/block/mmcblk1/queue/iosched"; String IO_INTERNAL_READ_AHEAD = "/sys/block/mmcblk0/queue/read_ahead_kb"; String IO_EXTERNAL_READ_AHEAD = "/sys/block/mmcblk1/queue/read_ahead_kb"; String IO_ROTATIONAL = "/sys/block/mmcblk0/queue/rotational"; String IO_STATS = "/sys/block/mmcblk0/queue/iostats"; String IO_RANDOM = "/sys/block/mmcblk0/queue/add_random"; String IO_AFFINITY = "/sys/block/mmcblk0/queue/rq_affinity"; String[] IO_ARRAY = {IO_INTERNAL_SCHEDULER, IO_EXTERNAL_SCHEDULER, IO_INTERNAL_SCHEDULER_TUNABLE, IO_EXTERNAL_SCHEDULER_TUNABLE, IO_INTERNAL_READ_AHEAD, IO_EXTERNAL_READ_AHEAD, IO_ROTATIONAL, IO_STATS, IO_RANDOM, IO_AFFINITY }; // Kernel Samepage Merging String KSM_FOLDER = "/sys/kernel/mm/ksm"; String UKSM_FOLDER = "/sys/kernel/mm/uksm"; String FULL_SCANS = "full_scans"; String PAGES_SHARED = "pages_shared"; String PAGES_SHARING = "pages_sharing"; String PAGES_UNSHARED = "pages_unshared"; String PAGES_VOLATILE = "pages_volatile"; String RUN = "run"; String DEFERRED_TIMER = "deferred_timer"; String PAGES_TO_SCAN = "pages_to_scan"; String SLEEP_MILLISECONDS = "sleep_millisecs"; String UKSM_CPU_USE = "max_cpu_percentage"; String[] KSM_INFOS = {FULL_SCANS, PAGES_SHARED, PAGES_SHARING, PAGES_UNSHARED, PAGES_VOLATILE}; String[] KSM_ARRAY = {KSM_FOLDER, UKSM_FOLDER}; // Low Memory Killer String LMK_MINFREE = "/sys/module/lowmemorykiller/parameters/minfree"; String LMK_ADAPTIVE = "/sys/module/lowmemorykiller/parameters/enable_adaptive_lmk"; // Virtual Memory String VM_PATH = "/proc/sys/vm"; String VM_DIRTY_RATIO = VM_PATH + "/dirty_ratio"; String VM_DIRTY_BACKGROUND_RATIO = VM_PATH + "/dirty_background_ratio"; String VM_DIRTY_EXPIRE_CENTISECS = VM_PATH + "/dirty_expire_centisecs"; String VM_DIRTY_WRITEBACK_CENTISECS = VM_PATH + "/dirty_writeback_centisecs"; String VM_DYNAMIC_DIRTY_WRITEBACK = VM_PATH + "/dynamic_dirty_writeback"; String VM_DIRTY_WRITEBACK_SUSPEND_CENTISECS = VM_PATH + "/dirty_writeback_suspend_centisecs"; String VM_DIRTY_WRITEBACK_ACTIVE_CENTISECS = VM_PATH + "/dirty_writeback_active_centisecs"; String VM_MIN_FREE_KBYTES = VM_PATH + "/min_free_kbytes"; String VM_OVERCOMMIT_RATIO = VM_PATH + "/overcommit_ratio"; String VM_SWAPPINESS = VM_PATH + "/swappiness"; String VM_VFS_CACHE_PRESSURE = VM_PATH + "/vfs_cache_pressure"; String VM_LAPTOP_MODE = VM_PATH + "/laptop_mode"; String VM_EXTRA_FREE_KBYTES = VM_PATH + "/extra_free_kbytes"; String ZRAM = "/sys/block/zram0"; String ZRAM_BLOCK = "/dev/block/zram0"; String ZRAM_DISKSIZE = "/sys/block/zram0/disksize"; String ZRAM_RESET = "/sys/block/zram0/reset"; String[] VM_ARRAY = {ZRAM_BLOCK, ZRAM_DISKSIZE, ZRAM_RESET, VM_DIRTY_RATIO, VM_DIRTY_BACKGROUND_RATIO, VM_DIRTY_EXPIRE_CENTISECS, VM_DIRTY_WRITEBACK_CENTISECS, VM_MIN_FREE_KBYTES, VM_OVERCOMMIT_RATIO, VM_SWAPPINESS, VM_VFS_CACHE_PRESSURE, VM_LAPTOP_MODE, VM_EXTRA_FREE_KBYTES, VM_DYNAMIC_DIRTY_WRITEBACK, VM_DIRTY_WRITEBACK_SUSPEND_CENTISECS,VM_DIRTY_WRITEBACK_ACTIVE_CENTISECS, LMK_MINFREE, LMK_ADAPTIVE }; // Entropy String PROC_RANDOM = "/proc/sys/kernel/random"; String PROC_RANDOM_ENTROPY_AVAILABLE = PROC_RANDOM + "/entropy_avail"; String PROC_RANDOM_ENTROPY_POOLSIZE = PROC_RANDOM + "/poolsize"; String PROC_RANDOM_ENTROPY_READ = PROC_RANDOM + "/read_wakeup_threshold"; String PROC_RANDOM_ENTROPY_WRITE = PROC_RANDOM + "/write_wakeup_threshold"; String[] ENTROPY_ARRAY = {PROC_RANDOM}; // Misc // Vibration Object[][] VIBRATION_ARRAY = { // {Path, Max, Min} {"/sys/class/timed_output/vibrator/amp", 100, 0}, {"/sys/class/timed_output/vibrator/level", 31, 12}, {"/sys/class/timed_output/vibrator/pwm_value", 100, 0}, // Read MAX MIN from sys {"/sys/class/timed_output/vibrator/pwm_value_1p", 99, 53}, {"/sys/class/timed_output/vibrator/voltage_level", 3199, 1200}, {"/sys/class/timed_output/vibrator/vtg_level", 31, 12}, // Read MAX MIN from sys {"/sys/class/timed_output/vibrator/vmax_mv", 3596, 116}, {"/sys/class/timed_output/vibrator/vmax_mv_strong", 3596, 116}, // Needs VIB_LIGHT path {"/sys/devices/platform/tspdrv/nforce_timed", 127, 1}, {"/sys/devices/i2c-3/3-0033/vibrator/vib0/vib_duty_cycle", 100, 25}, // Needs enable path {"/sys/module/qpnp_vibrator/parameters/vib_voltage", 31, 12}, {"/sys/vibrator/pwmvalue", 127, 0} }; String VIB_LIGHT = "/sys/devices/virtual/timed_output/vibrator/vmax_mv_light"; String VIB_ENABLE = "/sys/devices/i2c-3/3-0033/vibrator/vib0/vib_enable"; // Wakelock String[] SMB135X_WAKELOCKS = { "/sys/module/smb135x_charger/parameters/use_wlock", "/sys/module/wakeup/parameters/enable_smb135x_wake_ws" }; String SENSOR_IND_WAKELOCK = "/sys/module/wakeup/parameters/enable_si_ws"; String MSM_HSIC_HOST_WAKELOCK = "/sys/module/wakeup/parameters/enable_msm_hsic_ws"; String[] WLAN_RX_WAKELOCKS = { "/sys/module/wakeup/parameters/wlan_rx_wake", "/sys/module/wakeup/parameters/enable_wlan_rx_wake_ws" }; String[] WLAN_CTRL_WAKELOCKS = { "/sys/module/wakeup/parameters/wlan_ctrl_wake", "/sys/module/wakeup/parameters/enable_wlan_ctrl_wake_ws" }; String[] WLAN_WAKELOCKS = { "/sys/module/wakeup/parameters/wlan_wake", "/sys/module/wakeup/parameters/enable_wlan_wake_ws" }; String WLAN_RX_WAKELOCK_DIVIDER = "/sys/module/bcmdhd/parameters/wl_divide"; String MSM_HSIC_WAKELOCK_DIVIDER = "/sys/module/xhci_hcd/parameters/wl_divide"; // Logging String LOGGER_MODE = "/sys/kernel/logger_mode/logger_mode"; String LOGGER_ENABLED = "/sys/module/logger/parameters/enabled"; String LOGGER_LOG_ENABLED = "/sys/module/logger/parameters/log_enabled"; String[] LOGGER_ARRAY = {LOGGER_MODE, LOGGER_ENABLED, LOGGER_LOG_ENABLED}; // BCL String[] BCL_ARRAY = {"/sys/devices/qcom,bcl.38/mode","/sys/devices/qcom,bcl.39/mode", "/sys/devices/soc.0/qcom,bcl.60/mode" }; String BCL_HOTPLUG = "/sys/module/battery_current_limit/parameters/bcl_hotplug_enable"; // CRC String[] CRC_ARRAY = { "/sys/module/mmc_core/parameters/crc", "/sys/module/mmc_core/parameters/use_spi_crc" }; // Fsync String[] FSYNC_ARRAY = { "/sys/devices/virtual/misc/fsynccontrol/fsync_enabled", "/sys/module/sync/parameters/fsync_enabled" }; String DYNAMIC_FSYNC = "/sys/kernel/dyn_fsync/Dyn_fsync_active"; // Gentle fair sleepers String GENTLE_FAIR_SLEEPERS = "/sys/kernel/sched/gentle_fair_sleepers"; // Power suspend String POWER_SUSPEND = "/sys/kernel/power_suspend"; String POWER_SUSPEND_MODE = POWER_SUSPEND + "/power_suspend_mode"; String POWER_SUSPEND_STATE = POWER_SUSPEND + "/power_suspend_state"; String POWER_SUSPEND_VERSION = POWER_SUSPEND + "/power_suspend_version"; // Network String TCP_AVAILABLE_CONGESTIONS = "/proc/sys/net/ipv4/tcp_available_congestion_control"; String HOSTNAME_KEY = "net.hostname"; String ADB_OVER_WIFI = "service.adb.tcp.port"; String GETENFORCE = "getenforce"; String SETENFORCE = "setenforce"; Object[][] MISC_ARRAY = { VIBRATION_ARRAY, {VIB_LIGHT, VIB_ENABLE, SENSOR_IND_WAKELOCK, MSM_HSIC_HOST_WAKELOCK, WLAN_RX_WAKELOCK_DIVIDER, MSM_HSIC_WAKELOCK_DIVIDER, LOGGER_ENABLED, DYNAMIC_FSYNC, GENTLE_FAIR_SLEEPERS, POWER_SUSPEND_MODE, POWER_SUSPEND_STATE, BCL_HOTPLUG, TCP_AVAILABLE_CONGESTIONS, HOSTNAME_KEY, GETENFORCE, SETENFORCE, ADB_OVER_WIFI}, SMB135X_WAKELOCKS, WLAN_RX_WAKELOCKS, WLAN_CTRL_WAKELOCKS, WLAN_WAKELOCKS, CRC_ARRAY, FSYNC_ARRAY, BCL_ARRAY}; // Build prop String BUILD_PROP = "/system/build.prop"; // Init.d String INITD = "/system/etc/init.d"; }
app/src/main/java/com/grarak/kerneladiutor/utils/Constants.java
/* * Copyright (C) 2015 Willi Ye * * 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.grarak.kerneladiutor.utils; import com.grarak.kerneladiutor.BuildConfig; import com.grarak.kerneladiutor.elements.DAdapter; import java.util.ArrayList; import java.util.List; /** * Created by willi on 30.11.14. */ public interface Constants { String TAG = "Kernel Adiutor"; String VERSION_NAME = BuildConfig.VERSION_NAME; int VERSION_CODE = BuildConfig.VERSION_CODE; String PREF_NAME = "prefs"; String GAMMA_URL = "https://raw.githubusercontent.com/Grarak/KernelAdiutor/master/gamma_profiles.json"; List<DAdapter.DView> ITEMS = new ArrayList<>(); List<DAdapter.DView> VISIBLE_ITEMS = new ArrayList<>(); // Kernel Informations String PROC_VERSION = "/proc/version"; String PROC_CPUINFO = "/proc/cpuinfo"; String PROC_MEMINFO = "/proc/meminfo"; // CPU String CPU_CUR_FREQ = "/sys/devices/system/cpu/cpu%d/cpufreq/scaling_cur_freq"; String CPU_TEMP_ZONE0 = "/sys/class/thermal/thermal_zone0/temp"; String CPU_TEMP_ZONE1 = "/sys/class/thermal/thermal_zone1/temp"; String CPU_CORE_ONLINE = "/sys/devices/system/cpu/cpu%d/online"; String CPU_MAX_FREQ = "/sys/devices/system/cpu/cpu%d/cpufreq/scaling_max_freq"; String CPU_MAX_FREQ_KT = "/sys/devices/system/cpu/cpu%d/cpufreq/scaling_max_freq_kt"; String CPU_ENABLE_OC = "/sys/devices/system/cpu/cpu%d/cpufreq/enable_oc"; String CPU_MIN_FREQ = "/sys/devices/system/cpu/cpu%d/cpufreq/scaling_min_freq"; String CPU_MAX_SCREEN_OFF_FREQ = "/sys/devices/system/cpu/cpu%d/cpufreq/screen_off_max_freq"; String CPU_MSM_CPUFREQ_LIMIT = "/sys/kernel/msm_cpufreq_limit/cpufreq_limit"; String CPU_AVAILABLE_FREQS = "/sys/devices/system/cpu/cpu%d/cpufreq/scaling_available_frequencies"; String CPU_TIME_STATE = "/sys/devices/system/cpu/cpufreq/stats/cpu%d/time_in_state"; String CPU_TIME_STATE_2 = "/sys/devices/system/cpu/cpu%d/cpufreq/stats/time_in_state"; String CPU_SCALING_GOVERNOR = "/sys/devices/system/cpu/cpu%d/cpufreq/scaling_governor"; String CPU_AVAILABLE_GOVERNORS = "/sys/devices/system/cpu/cpu0/cpufreq/scaling_available_governors"; String CPU_GOVERNOR_TUNABLES = "/sys/devices/system/cpu/cpufreq"; String CPU_GOVERNOR_TUNABLES_CORE = "/sys/devices/system/cpu/cpu%d/cpufreq"; String CPU_MC_POWER_SAVING = "/sys/devices/system/cpu/sched_mc_power_savings"; String CPU_WQ_POWER_SAVING = "/sys/module/workqueue/parameters/power_efficient"; String CPU_AVAILABLE_CFS_SCHEDULERS = "/sys/devices/system/cpu/sched_balance_policy/available_sched_balance_policy"; String CPU_CURRENT_CFS_SCHEDULER = "/sys/devices/system/cpu/sched_balance_policy/current_sched_balance_policy"; String CPU_QUIET = "/sys/devices/system/cpu/cpuquiet"; String CPU_QUIET_ENABLE = CPU_QUIET + "/cpuquiet_driver/enabled"; String CPU_QUIET_AVAILABLE_GOVERNORS = CPU_QUIET + "/available_governors"; String CPU_QUIET_CURRENT_GOVERNOR = CPU_QUIET + "/current_governor"; String CPU_BOOST = "/sys/module/cpu_boost/parameters"; String CPU_BOOST_ENABLE = CPU_BOOST + "/cpu_boost"; String CPU_BOOST_ENABLE_2 = CPU_BOOST + "/cpuboost_enable"; String CPU_BOOST_DEBUG_MASK = CPU_BOOST + "/debug_mask"; String CPU_BOOST_MS = CPU_BOOST + "/boost_ms"; String CPU_BOOST_SYNC_THRESHOLD = CPU_BOOST + "/sync_threshold"; String CPU_BOOST_INPUT_MS = CPU_BOOST + "/input_boost_ms"; String CPU_BOOST_INPUT_BOOST_FREQ = CPU_BOOST + "/input_boost_freq"; String CPU_BOOST_WAKEUP = CPU_BOOST + "/wakeup_boost"; String CPU_BOOST_HOTPLUG = CPU_BOOST + "/hotplug_boost"; String CPU_TOUCH_BOOST = "/sys/module/msm_performance/parameters/touchboost"; String[] CPU_ARRAY = {CPU_CUR_FREQ, CPU_TEMP_ZONE0, CPU_TEMP_ZONE1, CPU_CORE_ONLINE, CPU_MAX_FREQ, CPU_MAX_FREQ_KT, CPU_ENABLE_OC, CPU_MIN_FREQ, CPU_MAX_SCREEN_OFF_FREQ, CPU_MSM_CPUFREQ_LIMIT, CPU_AVAILABLE_FREQS, CPU_TIME_STATE, CPU_SCALING_GOVERNOR, CPU_AVAILABLE_GOVERNORS, CPU_GOVERNOR_TUNABLES, CPU_GOVERNOR_TUNABLES_CORE, CPU_MC_POWER_SAVING, CPU_WQ_POWER_SAVING, CPU_AVAILABLE_CFS_SCHEDULERS, CPU_CURRENT_CFS_SCHEDULER, CPU_QUIET, CPU_BOOST, CPU_TOUCH_BOOST}; // CPU Voltage String CPU_VOLTAGE = "/sys/devices/system/cpu/cpu0/cpufreq/UV_mV_table"; String CPU_VDD_VOLTAGE = "/sys/devices/system/cpu/cpu0/cpufreq/vdd_levels"; String CPU_FAUX_VOLTAGE = "/sys/devices/system/cpu/cpufreq/vdd_table/vdd_levels"; String CPU_OVERRIDE_VMIN = "/sys/devices/system/cpu/cpu0/cpufreq/override_vmin"; String[] CPU_VOLTAGE_ARRAY = {CPU_VOLTAGE, CPU_VDD_VOLTAGE, CPU_FAUX_VOLTAGE, CPU_OVERRIDE_VMIN}; // CPU Hotplug String HOTPLUG_MPDEC = "mpdecision"; String HOTPLUG_INTELLI_PLUG = "/sys/module/intelli_plug/parameters"; String HOTPLUG_INTELLI_PLUG_ENABLE = HOTPLUG_INTELLI_PLUG + "/intelli_plug_active"; String HOTPLUG_INTELLI_PLUG_PROFILE = HOTPLUG_INTELLI_PLUG + "/nr_run_profile_sel"; String HOTPLUG_INTELLI_PLUG_ECO = HOTPLUG_INTELLI_PLUG + "/eco_mode_active"; String HOTPLUG_INTELLI_PLUG_TOUCH_BOOST = HOTPLUG_INTELLI_PLUG + "/touch_boost_active"; String HOTPLUG_INTELLI_PLUG_HYSTERESIS = HOTPLUG_INTELLI_PLUG + "/nr_run_hysteresis"; String HOTPLUG_INTELLI_PLUG_THRESHOLD = HOTPLUG_INTELLI_PLUG + "/cpu_nr_run_threshold"; String HOTPLUG_INTELLI_PLUG_SCREEN_OFF_MAX = HOTPLUG_INTELLI_PLUG + "/screen_off_max"; String HOTPLUG_INTELLI_PLUG_INSANITY = HOTPLUG_INTELLI_PLUG + "/is_insanity"; String HOTPLUG_INTELLI_PLUG_5 = "/sys/kernel/intelli_plug"; String HOTPLUG_INTELLI_PLUG_5_ENABLE = HOTPLUG_INTELLI_PLUG_5 + "/intelli_plug_active"; String HOTPLUG_INTELLI_PLUG_5_DEBUG = HOTPLUG_INTELLI_PLUG_5 + "/debug_intelli_plug"; String HOTPLUG_INTELLI_PLUG_5_PROFILE = HOTPLUG_INTELLI_PLUG_5 + "/full_mode_profile"; String HOTPLUG_INTELLI_PLUG_5_SUSPEND = HOTPLUG_INTELLI_PLUG_5 + "/hotplug_suspend"; String HOTPLUG_INTELLI_PLUG_5_CPUS_BOOSTED = HOTPLUG_INTELLI_PLUG_5 + "/cpus_boosted"; String HOTPLUG_INTELLI_PLUG_5_HYSTERESIS = HOTPLUG_INTELLI_PLUG_5 + "/nr_run_hysteresis"; String HOTPLUG_INTELLI_PLUG_5_MIN_CPUS_ONLINE = HOTPLUG_INTELLI_PLUG_5 + "/min_cpus_online"; String HOTPLUG_INTELLI_PLUG_5_MAX_CPUS_ONLINE = HOTPLUG_INTELLI_PLUG_5 + "/max_cpus_online"; String HOTPLUG_INTELLI_PLUG_5_MAX_CPUS_ONLINE_SUSP = HOTPLUG_INTELLI_PLUG_5 + "/max_cpus_online_susp"; String HOTPLUG_INTELLI_PLUG_5_SUSPEND_DEFER_TIME = HOTPLUG_INTELLI_PLUG_5 + "/suspend_defer_time"; String HOTPLUG_INTELLI_PLUG_5_DEFER_SAMPLING = HOTPLUG_INTELLI_PLUG_5 + "/def_sampling_ms"; String HOTPLUG_INTELLI_PLUG_5_BOOST_LOCK_DURATION = HOTPLUG_INTELLI_PLUG_5 + "/boost_lock_duration"; String HOTPLUG_INTELLI_PLUG_5_DOWN_LOCK_DURATION = HOTPLUG_INTELLI_PLUG_5 + "/down_lock_duration"; String HOTPLUG_INTELLI_PLUG_5_THRESHOLD = HOTPLUG_INTELLI_PLUG_5 + "/cpu_nr_run_threshold"; String HOTPLUG_INTELLI_PLUG_5_FSHIFT = HOTPLUG_INTELLI_PLUG_5 + "/nr_fshift"; String HOTPLUG_INTELLI_PLUG_5_SCREEN_OFF_MAX = HOTPLUG_INTELLI_PLUG_5 + "/screen_off_max"; String[] INTELLIPLUG_ARRAY = {HOTPLUG_INTELLI_PLUG, HOTPLUG_INTELLI_PLUG_5}; String HOTPLUG_BLU_PLUG = "/sys/module/blu_plug/parameters"; String HOTPLUG_BLU_PLUG_ENABLE = HOTPLUG_BLU_PLUG + "/enabled"; String HOTPLUG_BLU_PLUG_POWERSAVER_MODE = HOTPLUG_BLU_PLUG + "/powersaver_mode"; String HOTPLUG_BLU_PLUG_MIN_ONLINE = HOTPLUG_BLU_PLUG + "/min_online"; String HOTPLUG_BLU_PLUG_MAX_ONLINE = HOTPLUG_BLU_PLUG + "/max_online"; String HOTPLUG_BLU_PLUG_MAX_CORES_SCREEN_OFF = HOTPLUG_BLU_PLUG + "/max_cores_screenoff"; String HOTPLUG_BLU_PLUG_MAX_FREQ_SCREEN_OFF = HOTPLUG_BLU_PLUG + "/max_freq_screenoff"; String HOTPLUG_BLU_PLUG_UP_THRESHOLD = HOTPLUG_BLU_PLUG + "/up_threshold"; String HOTPLUG_BLU_PLUG_UP_TIMER_CNT = HOTPLUG_BLU_PLUG + "/up_timer_cnt"; String HOTPLUG_BLU_PLUG_DOWN_TIMER_CNT = HOTPLUG_BLU_PLUG + "/down_timer_cnt"; String[] BLU_PLUG_ARRAY = {HOTPLUG_BLU_PLUG}; String HOTPLUG_MSM = "/sys/module/msm_hotplug"; String HOTPLUG_MSM_ENABLE = HOTPLUG_MSM + "/enabled"; String HOTPLUG_MSM_ENABLE_2 = HOTPLUG_MSM + "/msm_enabled"; String HOTPLUG_MSM_DEBUG_MASK = HOTPLUG_MSM + "/parameters/debug_mask"; String HOTPLUG_MSM_MIN_CPUS_ONLINE = HOTPLUG_MSM + "/min_cpus_online"; String HOTPLUG_MSM_MAX_CPUS_ONLINE = HOTPLUG_MSM + "/max_cpus_online"; String HOTPLUG_MSM_CPUS_BOOSTED = HOTPLUG_MSM + "/cpus_boosted"; String HOTPLUG_MSM_MAX_CPUS_ONLINE_SUSP = HOTPLUG_MSM + "/max_cpus_online_susp"; String HOTPLUG_MSM_BOOST_LOCK_DURATION = HOTPLUG_MSM + "/boost_lock_duration"; String HOTPLUG_MSM_DOWN_LOCK_DURATION = HOTPLUG_MSM + "/down_lock_duration"; String HOTPLUG_MSM_HISTORY_SIZE = HOTPLUG_MSM + "/history_size"; String HOTPLUG_MSM_UPDATE_RATE = HOTPLUG_MSM + "/update_rate"; String HOTPLUG_MSM_UPDATE_RATES = HOTPLUG_MSM + "/update_rates"; String HOTPLUG_MSM_FAST_LANE_LOAD = HOTPLUG_MSM + "/fast_lane_load"; String HOTPLUG_MSM_FAST_LANE_MIN_FREQ = HOTPLUG_MSM + "/fast_lane_min_freq"; String HOTPLUG_MSM_OFFLINE_LOAD = HOTPLUG_MSM + "/offline_load"; String HOTPLUG_MSM_IO_IS_BUSY = HOTPLUG_MSM + "/io_is_busy"; String HOTPLUG_MSM_HP_IO_IS_BUSY = HOTPLUG_MSM + "/hp_io_is_busy"; String HOTPLUG_MSM_SUSPEND_MAX_CPUS = HOTPLUG_MSM + "/suspend_max_cpus"; String HOTPLUG_MSM_SUSPEND_FREQ = HOTPLUG_MSM + "/suspend_freq"; String HOTPLUG_MSM_SUSPEND_MAX_FREQ = HOTPLUG_MSM + "/suspend_max_freq"; String HOTPLUG_MSM_SUSPEND_DEFER_TIME = HOTPLUG_MSM + "/suspend_defer_time"; String[] HOTPLUG_MSM_ARRAY = {HOTPLUG_MSM}; String MAKO_HOTPLUG = "/sys/class/misc/mako_hotplug_control"; String MAKO_HOTPLUG_ENABLED = MAKO_HOTPLUG + "/enabled"; String MAKO_HOTPLUG_CORES_ON_TOUCH = MAKO_HOTPLUG + "/cores_on_touch"; String MAKO_HOTPLUG_CPUFREQ_UNPLUG_LIMIT = MAKO_HOTPLUG + "/cpufreq_unplug_limit"; String MAKO_HOTPLUG_FIRST_LEVEL = MAKO_HOTPLUG + "/first_level"; String MAKO_HOTPLUG_HIGH_LOAD_COUNTER = MAKO_HOTPLUG + "/high_load_counter"; String MAKO_HOTPLUG_LOAD_THRESHOLD = MAKO_HOTPLUG + "/load_threshold"; String MAKO_HOTPLUG_MAX_LOAD_COUNTER = MAKO_HOTPLUG + "/max_load_counter"; String MAKO_HOTPLUG_MIN_TIME_CPU_ONLINE = MAKO_HOTPLUG + "/min_time_cpu_online"; String MAKO_HOTPLUG_MIN_CORES_ONLINE = MAKO_HOTPLUG + "/min_cores_online"; String MAKO_HOTPLUG_TIMER = MAKO_HOTPLUG + "/timer"; String MAKO_HOTPLUG_SUSPEND_FREQ = MAKO_HOTPLUG + "/suspend_frequency"; String[] MAKO_HOTPLUG_ARRAY = {MAKO_HOTPLUG}; String MSM_MPDECISION_HOTPLUG = "/sys/kernel/msm_mpdecision/conf"; String BRICKED_HOTPLUG = "/sys/kernel/bricked_hotplug/conf"; String MB_ENABLED = "enabled"; String MB_SCROFF_SINGLE_CORE = "scroff_single_core"; String MB_MIN_CPUS = "min_cpus"; String MB_MAX_CPUS = "max_cpus"; String MB_MIN_CPUS_ONLINE = "min_cpus_online"; String MB_MAX_CPUS_ONLINE = "max_cpus_online"; String MB_CPUS_ONLINE_SUSP = "max_cpus_online_susp"; String MB_IDLE_FREQ = "idle_freq"; String MB_BOOST_ENABLED = "boost_enabled"; String MB_BOOST_TIME = "boost_time"; String MB_CPUS_BOOSTED = "cpus_boosted"; String MB_BOOST_FREQS = "boost_freqs"; String MB_STARTDELAY = "startdelay"; String MB_DELAY = "delay"; String MB_PAUSE = "pause"; String BRICKED_NWNS = "nwns_threshold"; String BRICKED_TWTS = "twts_threshold"; String BRICKED_DOWN_LOCK_DURATION = "down_lock_duration"; String[] MB_HOTPLUG_ARRAY = {MSM_MPDECISION_HOTPLUG, BRICKED_HOTPLUG}; String ALUCARD_HOTPLUG = "/sys/kernel/alucard_hotplug"; String ALUCARD_HOTPLUG_ENABLE = ALUCARD_HOTPLUG + "/hotplug_enable"; String ALUCARD_HOTPLUG_HP_IO_IS_BUSY = ALUCARD_HOTPLUG + "/hp_io_is_busy"; String ALUCARD_HOTPLUG_SAMPLING_RATE = ALUCARD_HOTPLUG + "/hotplug_sampling_rate"; String ALUCARD_HOTPLUG_SUSPEND = ALUCARD_HOTPLUG + "/hotplug_suspend"; String ALUCARD_HOTPLUG_MIN_CPUS_ONLINE = ALUCARD_HOTPLUG + "/min_cpus_online"; String ALUCARD_HOTPLUG_MAX_CORES_LIMIT = ALUCARD_HOTPLUG + "/maxcoreslimit"; String ALUCARD_HOTPLUG_MAX_CORES_LIMIT_SLEEP = ALUCARD_HOTPLUG + "/maxcoreslimit_sleep"; String ALUCARD_HOTPLUG_CPU_DOWN_RATE = ALUCARD_HOTPLUG + "/cpu_down_rate"; String ALUCARD_HOTPLUG_CPU_UP_RATE = ALUCARD_HOTPLUG + "/cpu_up_rate"; String[] ALUCARD_HOTPLUG_ARRAY = {ALUCARD_HOTPLUG}; String HOTPLUG_THUNDER_PLUG = "/sys/kernel/thunderplug"; String HOTPLUG_THUNDER_PLUG_ENABLE = HOTPLUG_THUNDER_PLUG + "/hotplug_enabled"; String HOTPLUG_THUNDER_PLUG_SUSPEND_CPUS = HOTPLUG_THUNDER_PLUG + "/suspend_cpus"; String HOTPLUG_THUNDER_PLUG_ENDURANCE_LEVEL = HOTPLUG_THUNDER_PLUG + "/endurance_level"; String HOTPLUG_THUNDER_PLUG_SAMPLING_RATE = HOTPLUG_THUNDER_PLUG + "/sampling_rate"; String HOTPLUG_THUNDER_PLUG_LOAD_THRESHOLD = HOTPLUG_THUNDER_PLUG + "/load_threshold"; String HOTPLUG_THUNDER_PLUG_TOUCH_BOOST = HOTPLUG_THUNDER_PLUG + "/touch_boost"; String[] HOTPLUG_THUNDER_PLUG_ARRAY = {HOTPLUG_THUNDER_PLUG}; String HOTPLUG_ZEN_DECISION = "/sys/kernel/zen_decision"; String HOTPLUG_ZEN_DECISION_ENABLE = HOTPLUG_ZEN_DECISION + "/enabled"; String HOTPLUG_ZEN_DECISION_WAKE_WAIT_TIME = HOTPLUG_ZEN_DECISION + "/wake_wait_time"; String HOTPLUG_ZEN_DECISION_BAT_THRESHOLD_IGNORE = HOTPLUG_ZEN_DECISION + "/bat_threshold_ignore"; String[] HOTPLUG_ZEN_DECISION_ARRAY = {HOTPLUG_ZEN_DECISION}; String HOTPLUG_AUTOSMP_PARAMETERS = "/sys/module/autosmp/parameters"; String HOTPLUG_AUTOSMP_CONF = "/sys/kernel/autosmp/conf"; String HOTPLUG_AUTOSMP_ENABLE = HOTPLUG_AUTOSMP_PARAMETERS + "/enabled"; String HOTPLUG_AUTOSMP_CPUFREQ_DOWN = HOTPLUG_AUTOSMP_CONF + "/cpufreq_down"; String HOTPLUG_AUTOSMP_CPUFREQ_UP = HOTPLUG_AUTOSMP_CONF + "/cpufreq_up"; String HOTPLUG_AUTOSMP_CYCLE_DOWN = HOTPLUG_AUTOSMP_CONF + "/cycle_down"; String HOTPLUG_AUTOSMP_CYCLE_UP = HOTPLUG_AUTOSMP_CONF + "/cycle_up"; String HOTPLUG_AUTOSMP_DELAY = HOTPLUG_AUTOSMP_CONF + "/delay"; String HOTPLUG_AUTOSMP_MAX_CPUS = HOTPLUG_AUTOSMP_CONF + "/max_cpus"; String HOTPLUG_AUTOSMP_MIN_CPUS = HOTPLUG_AUTOSMP_CONF + "/min_cpus"; String HOTPLUG_AUTOSMP_SCROFF_SINGLE_CORE = HOTPLUG_AUTOSMP_CONF + "/scroff_single_core"; String[] HOTPLUG_AUTOSMP_ARRAY = {HOTPLUG_AUTOSMP_PARAMETERS, HOTPLUG_AUTOSMP_CONF}; String MSM_SLEEPER = "/sys/devices/platform/msm_sleeper"; String MSM_SLEEPER_ENABLE = MSM_SLEEPER + "/enabled"; String MSM_SLEEPER_UP_THRESHOLD = MSM_SLEEPER + "/up_threshold"; String MSM_SLEEPER_MAX_ONLINE = MSM_SLEEPER + "/max_online"; String MSM_SLEEPER_SUSPEND_MAX_ONLINE = MSM_SLEEPER + "/suspend_max_online"; String MSM_SLEEPER_UP_COUNT_MAX = MSM_SLEEPER + "/up_count_max"; String MSM_SLEEPER_DOWN_COUNT_MAX = MSM_SLEEPER + "/down_count_max"; String[][] CPU_HOTPLUG_ARRAY = {{HOTPLUG_MPDEC, MSM_SLEEPER}, INTELLIPLUG_ARRAY, BLU_PLUG_ARRAY, HOTPLUG_MSM_ARRAY, MAKO_HOTPLUG_ARRAY, MB_HOTPLUG_ARRAY, ALUCARD_HOTPLUG_ARRAY, HOTPLUG_THUNDER_PLUG_ARRAY, HOTPLUG_ZEN_DECISION_ARRAY, HOTPLUG_AUTOSMP_ARRAY}; // Thermal String THERMALD = "thermald"; String MSM_THERMAL = "/sys/module/msm_thermal"; String MSM_THERMAL_V2 = "/sys/module/msm_thermal_v2"; String PARAMETERS_ENABLED = "parameters/enabled"; String PARAMETERS_INTELLI_ENABLED = "parameters/intelli_enabled"; String PARAMETERS_THERMAL_DEBUG_MODE = "parameters/thermal_debug_mode"; String CORE_CONTROL_ENABLED = "core_control/enabled"; String CORE_CONTROL_ENABLED_2 = "core_control/core_control"; String VDD_RESTRICTION_ENABLED = "vdd_restriction/enabled"; String PARAMETERS_LIMIT_TEMP_DEGC = "parameters/limit_temp_degC"; String PARAMETERS_CORE_LIMIT_TEMP_DEGC = "parameters/core_limit_temp_degC"; String PARAMETERS_CORE_TEMP_HYSTERESIS_DEGC = "parameters/core_temp_hysteresis_degC"; String PARAMETERS_FREQ_STEP = "parameters/freq_step"; String PARAMETERS_IMMEDIATELY_LIMIT_STOP = "parameters/immediately_limit_stop"; String PARAMETERS_POLL_MS = "parameters/poll_ms"; String PARAMETERS_TEMP_HYSTERESIS_DEGC = "parameters/temp_hysteresis_degC"; String PARAMETERS_THERMAL_LIMIT_LOW = "parameters/thermal_limit_low"; String PARAMETERS_THERMAL_LIMIT_HIGH = "parameters/thermal_limit_high"; String PARAMETERS_TEMP_SAFETY = "parameters/temp_safety"; String MSM_THERMAL_TEMP_THROTTLE = MSM_THERMAL + "/" + PARAMETERS_ENABLED; String MSM_THERMAL_THROTTLE_TEMP = MSM_THERMAL + "/parameters/throttle_temp"; String MSM_THERMAL_TEMP_MAX = MSM_THERMAL + "/parameters/temp_max"; String MSM_THERMAL_TEMP_THRESHOLD = MSM_THERMAL + "/parameters/temp_threshold"; String MSM_THERMAL_FREQ_LIMIT_DEBUG = MSM_THERMAL + "/parameters/freq_limit_debug"; String MSM_THERMAL_MIN_FREQ_INDEX = MSM_THERMAL + "/parameters/min_freq_index"; String TEMPCONTROL_TEMP_LIMIT = "/sys/class/misc/tempcontrol/templimit"; String[] TEMP_LIMIT_ARRAY = {MSM_THERMAL_THROTTLE_TEMP, MSM_THERMAL_TEMP_MAX, MSM_THERMAL_TEMP_THRESHOLD, MSM_THERMAL_FREQ_LIMIT_DEBUG, MSM_THERMAL_MIN_FREQ_INDEX, TEMPCONTROL_TEMP_LIMIT}; String MSM_THERMAL_CONF = "/sys/kernel/msm_thermal/conf"; String CONF_ENABLED = MSM_THERMAL_CONF + "/enabled"; String CONF_ALLOWED_LOW_LOW = MSM_THERMAL_CONF + "/allowed_low_low"; String CONF_ALLOWED_LOW_HIGH = MSM_THERMAL_CONF + "/allowed_low_high"; String CONF_ALLOWED_LOW_FREQ = MSM_THERMAL_CONF + "/allowed_low_freq"; String CONF_ALLOWED_MID_LOW = MSM_THERMAL_CONF + "/allowed_mid_low"; String CONF_ALLOWED_MID_HIGH = MSM_THERMAL_CONF + "/allowed_mid_high"; String CONF_ALLOWED_MID_FREQ = MSM_THERMAL_CONF + "/allowed_mid_freq"; String CONF_ALLOWED_MAX_LOW = MSM_THERMAL_CONF + "/allowed_max_low"; String CONF_ALLOWED_MAX_HIGH = MSM_THERMAL_CONF + "/allowed_max_high"; String CONF_ALLOWED_MAX_FREQ = MSM_THERMAL_CONF + "/allowed_max_freq"; String CONF_CHECK_INTERVAL_MS = MSM_THERMAL_CONF + "/check_interval_ms"; String CONF_SHUTDOWN_TEMP = MSM_THERMAL_CONF + "/shutdown_temp"; // Sultan's 8X60 Ones String CONF_START = MSM_THERMAL_CONF + "/start"; String CONF_RESET_LOW_THRESH = MSM_THERMAL_CONF + "/reset_low_thresh"; String CONF_TRIP_LOW_THRESH = MSM_THERMAL_CONF + "/trip_low_thresh"; String CONF_FREQ_LOW_THRESH = MSM_THERMAL_CONF + "/freq_low_thresh"; String CONF_RESET_MID_THRESH = MSM_THERMAL_CONF + "/reset_mid_thresh"; String CONF_TRIP_MID_THRESH = MSM_THERMAL_CONF + "/trip_mid_thresh"; String CONF_FREQ_MID_THRESH = MSM_THERMAL_CONF + "/freq_mid_thresh"; String CONF_RESET_HIGH_THRESH = MSM_THERMAL_CONF + "/reset_high_thresh"; String CONF_TRIP_HIGH_THRESH = MSM_THERMAL_CONF + "/trip_high_thresh"; String CONF_FREQ_HIGH_THRESH = MSM_THERMAL_CONF + "/freq_high_thresh"; String CONF_POLL_MS = MSM_THERMAL_CONF + "/poll_ms"; String[] THERMAL_ARRAY = {MSM_THERMAL, MSM_THERMAL_V2}; String[][] THERMAL_ARRAYS = {THERMAL_ARRAY, TEMP_LIMIT_ARRAY, {MSM_THERMAL_CONF}}; // GPU String GPU_GENERIC_GOVERNORS = "performance powersave ondemand simple conservative"; String GPU_CUR_KGSL2D0_QCOM_FREQ = "/sys/devices/platform/kgsl-2d0.0/kgsl/kgsl-2d0/gpuclk"; String GPU_MAX_KGSL2D0_QCOM_FREQ = "/sys/devices/platform/kgsl-2d0.0/kgsl/kgsl-2d0/max_gpuclk"; String GPU_AVAILABLE_KGSL2D0_QCOM_FREQS = "/sys/devices/platform/kgsl-2d0.0/kgsl/kgsl-2d0/gpu_available_frequencies"; String GPU_SCALING_KGSL2D0_QCOM_GOVERNOR = "/sys/devices/platform/kgsl-2d0.0/kgsl/kgsl-2d0/pwrscale/trustzone/governor"; String GPU_CUR_KGSL3D0_QCOM_FREQ = "/sys/devices/platform/kgsl-3d0.0/kgsl/kgsl-3d0/gpuclk"; String GPU_MAX_KGSL3D0_QCOM_FREQ = "/sys/devices/platform/kgsl-3d0.0/kgsl/kgsl-3d0/max_gpuclk"; String GPU_AVAILABLE_KGSL3D0_QCOM_FREQS = "/sys/devices/platform/kgsl-3d0.0/kgsl/kgsl-3d0/gpu_available_frequencies"; String GPU_SCALING_KGSL3D0_QCOM_GOVERNOR = "/sys/devices/platform/kgsl-3d0.0/kgsl/kgsl-3d0/pwrscale/trustzone/governor"; String GPU_CUR_FDB00000_QCOM_FREQ = "/sys/devices/fdb00000.qcom,kgsl-3d0/kgsl/kgsl-3d0/gpuclk"; String GPU_MAX_FDB00000_QCOM_FREQ = "/sys/devices/fdb00000.qcom,kgsl-3d0/kgsl/kgsl-3d0/max_gpuclk"; String GPU_MIN_FDB00000_QCOM_FREQ = "/sys/class/kgsl/kgsl-3d0/devfreq/min_freq"; String GPU_AVAILABLE_FDB00000_QCOM_FREQS = "/sys/devices/fdb00000.qcom,kgsl-3d0/kgsl/kgsl-3d0/gpu_available_frequencies"; String GPU_SCALING_FDB00000_QCOM_GOVERNOR = "/sys/devices/fdb00000.qcom,kgsl-3d0/kgsl/kgsl-3d0/devfreq/governor"; String GPU_SCALING_PWRSCALE_GOVERNOR = "/sys/class/kgsl/kgsl-3d0/pwrscale/trustzone/governor"; String GPU_AVAILABLE_FDB00000_QCOM_GOVERNORS = "/sys/devices/fdb00000.qcom,kgsl-3d0/kgsl/kgsl-3d0/devfreq/available_governors"; String GPU_CUR_FDC00000_QCOM_FREQ = "/sys/devices/fdc00000.qcom,kgsl-3d0/kgsl/kgsl-3d0/gpuclk"; String GPU_MAX_FDC00000_QCOM_FREQ = "/sys/devices/fdc00000.qcom,kgsl-3d0/kgsl/kgsl-3d0/max_gpuclk"; String GPU_AVAILABLE_FDC00000_QCOM_FREQS = "/sys/devices/fdc00000.qcom,kgsl-3d0/kgsl/kgsl-3d0/gpu_available_frequencies"; String GPU_SCALING_FDC00000_QCOM_GOVERNOR = "/sys/devices/fdc00000.qcom,kgsl-3d0/kgsl/kgsl-3d0/devfreq/governor"; String GPU_AVAILABLE_FDC00000_QCOM_GOVERNORS = "/sys/devices/fdc00000.qcom,kgsl-3d0/kgsl/kgsl-3d0/devfreq/available_governors"; String GPU_CUR_SOC0_FDB00000_QCOM_FREQ = "/sys/devices/soc.0/fdb00000.qcom,kgsl-3d0/kgsl/kgsl-3d0/gpuclk"; String GPU_MAX_SOC0_FDB00000_QCOM_FREQ = "/sys/devices/soc.0/fdb00000.qcom,kgsl-3d0/kgsl/kgsl-3d0/max_gpuclk"; String GPU_AVAILABLE_SOC0_FDB00000_QCOM_FREQS = "/sys/devices/soc.0/fdb00000.qcom,kgsl-3d0/kgsl/kgsl-3d0/gpu_available_frequencies"; String GPU_SCALING_SOC0_FDB00000_QCOM_GOVERNOR = "/sys/devices/soc.0/fdb00000.qcom,kgsl-3d0/devfreq/fdb00000.qcom,kgsl-3d0/governor"; String GPU_AVAILABLE_SOC0_FDB00000_QCOM_GOVERNORS = "/sys/devices/soc.0/fdb00000.qcom,kgsl-3d0/kgsl/kgsl-3d0/devfreq/available_governors"; String GPU_CUR_1C00000_QCOM_FREQ = "/sys/devices/soc.0/1c00000.qcom,kgsl-3d0/kgsl/kgsl-3d0/max_gpuclk"; String GPU_MAX_1C00000_QCOM_FREQ = "/sys/devices/soc.0/1c00000.qcom,kgsl-3d0/kgsl/kgsl-3d0/max_gpuclk"; String GPU_AVAILABLE_1C00000_QCOM_FREQ = "/sys/devices/soc.0/1c00000.qcom,kgsl-3d0/kgsl/kgsl-3d0/gpu_available_frequencies"; String GPU_SCALING_1C00000_QCOM_GOVERNOR = "/sys/devices/soc.0/1c00000.qcom,kgsl-3d0/devfreq/1c00000.qcom,kgsl-3d0/governor"; String GPU_AVAILABLE_1C00000_QCOM_GOVERNORS = "/sys/devices/soc.0/1c00000.qcom,kgsl-3d0/devfreq/1c00000.qcom,kgsl-3d0/available_governors"; String GPU_CUR_OMAP_FREQ = "/sys/devices/platform/omap/pvrsrvkm.0/sgxfreq/frequency"; String GPU_MAX_OMAP_FREQ = "/sys/devices/platform/omap/pvrsrvkm.0/sgxfreq/frequency_limit"; String GPU_AVAILABLE_OMAP_FREQS = "/sys/devices/platform/omap/pvrsrvkm.0/sgxfreq/frequency_list"; String GPU_SCALING_OMAP_GOVERNOR = "/sys/devices/platform/omap/pvrsrvkm.0/sgxfreq/governor"; String GPU_AVAILABLE_OMAP_GOVERNORS = "/sys/devices/platform/omap/pvrsrvkm.0/sgxfreq/governor_list"; String GPU_CUR_TEGRA_FREQ = "/sys/kernel/tegra_gpu/gpu_rate"; String GPU_MAX_TEGRA_FREQ = "/sys/kernel/tegra_gpu/gpu_cap_rate"; String GPU_MIN_TEGRA_FREQ = "/sys/kernel/tegra_gpu/gpu_floor_rate"; String GPU_AVAILABLE_TEGRA_FREQS = "/sys/kernel/tegra_gpu/gpu_available_rates"; String GPU_MIN_POWER_LEVEL = "/sys/devices/fdb00000.qcom,kgsl-3d0/kgsl/kgsl-3d0/min_pwrlevel"; String[] GPU_2D_CUR_FREQ_ARRAY = {GPU_CUR_KGSL2D0_QCOM_FREQ}; String[] GPU_2D_MAX_FREQ_ARRAY = {GPU_MAX_KGSL2D0_QCOM_FREQ}; String[] GPU_2D_AVAILABLE_FREQS_ARRAY = {GPU_AVAILABLE_KGSL2D0_QCOM_FREQS}; String[] GPU_2D_SCALING_GOVERNOR_ARRAY = {GPU_SCALING_KGSL2D0_QCOM_GOVERNOR}; String[] GPU_CUR_FREQ_ARRAY = {GPU_CUR_KGSL3D0_QCOM_FREQ, GPU_CUR_FDB00000_QCOM_FREQ, GPU_CUR_FDC00000_QCOM_FREQ, GPU_CUR_SOC0_FDB00000_QCOM_FREQ, GPU_CUR_1C00000_QCOM_FREQ, GPU_CUR_OMAP_FREQ, GPU_CUR_TEGRA_FREQ}; String[] GPU_MAX_FREQ_ARRAY = {GPU_MAX_KGSL3D0_QCOM_FREQ, GPU_MAX_FDB00000_QCOM_FREQ, GPU_MAX_FDC00000_QCOM_FREQ, GPU_MAX_SOC0_FDB00000_QCOM_FREQ, GPU_MAX_1C00000_QCOM_FREQ, GPU_MAX_OMAP_FREQ, GPU_MAX_TEGRA_FREQ}; String[] GPU_MIN_FREQ_ARRAY = {GPU_MIN_FDB00000_QCOM_FREQ, GPU_MIN_TEGRA_FREQ}; String[] GPU_AVAILABLE_FREQS_ARRAY = {GPU_AVAILABLE_KGSL3D0_QCOM_FREQS, GPU_AVAILABLE_FDB00000_QCOM_FREQS, GPU_AVAILABLE_SOC0_FDB00000_QCOM_FREQS, GPU_AVAILABLE_FDC00000_QCOM_FREQS, GPU_AVAILABLE_1C00000_QCOM_FREQ, GPU_AVAILABLE_OMAP_FREQS, GPU_AVAILABLE_TEGRA_FREQS}; String[] GPU_SCALING_GOVERNOR_ARRAY = {GPU_SCALING_KGSL3D0_QCOM_GOVERNOR, GPU_SCALING_FDB00000_QCOM_GOVERNOR, GPU_SCALING_PWRSCALE_GOVERNOR, GPU_SCALING_FDC00000_QCOM_GOVERNOR, GPU_SCALING_SOC0_FDB00000_QCOM_GOVERNOR, GPU_SCALING_1C00000_QCOM_GOVERNOR, GPU_SCALING_OMAP_GOVERNOR}; String[] GPU_AVAILABLE_GOVERNORS_ARRAY = {GPU_AVAILABLE_FDB00000_QCOM_GOVERNORS, GPU_AVAILABLE_FDC00000_QCOM_GOVERNORS, GPU_AVAILABLE_SOC0_FDB00000_QCOM_GOVERNORS, GPU_AVAILABLE_1C00000_QCOM_GOVERNORS, GPU_AVAILABLE_OMAP_GOVERNORS}; // Simple GPU String SIMPLE_GPU_PARAMETERS = "/sys/module/simple_gpu_algorithm/parameters"; String SIMPLE_GPU_ACTIVATE = SIMPLE_GPU_PARAMETERS + "/simple_gpu_activate"; String SIMPLE_GPU_LAZINESS = SIMPLE_GPU_PARAMETERS + "/simple_laziness"; String SIMPLE_RAMP_THRESHOLD = SIMPLE_GPU_PARAMETERS + "/simple_ramp_threshold"; // Adreno Idler String ADRENO_IDLER_PARAMETERS = "/sys/module/adreno_idler/parameters/"; String ADRENO_IDLER_ACTIVATE = ADRENO_IDLER_PARAMETERS + "adreno_idler_active"; String ADRENO_IDLER_DOWNDIFFERENTIAL = ADRENO_IDLER_PARAMETERS + "/adreno_idler_downdifferential"; String ADRENO_IDLER_IDLEWAIT = ADRENO_IDLER_PARAMETERS + "/adreno_idler_idlewait"; String ADRENO_IDLER_IDLEWORKLOAD = ADRENO_IDLER_PARAMETERS + "/adreno_idler_idleworkload"; String[][] GPU_ARRAY = {GPU_2D_CUR_FREQ_ARRAY, GPU_2D_MAX_FREQ_ARRAY, GPU_2D_AVAILABLE_FREQS_ARRAY, GPU_2D_SCALING_GOVERNOR_ARRAY, GPU_CUR_FREQ_ARRAY, GPU_MAX_FREQ_ARRAY, GPU_MIN_FREQ_ARRAY, GPU_AVAILABLE_FREQS_ARRAY, GPU_SCALING_GOVERNOR_ARRAY, {SIMPLE_GPU_PARAMETERS, ADRENO_IDLER_PARAMETERS, GPU_MIN_POWER_LEVEL}}; // Screen String SCREEN_KCAL = "/sys/devices/platform/kcal_ctrl.0"; String SCREEN_KCAL_CTRL = SCREEN_KCAL + "/kcal"; String SCREEN_KCAL_CTRL_CTRL = SCREEN_KCAL + "/kcal_ctrl"; String SCREEN_KCAL_CTRL_ENABLE = SCREEN_KCAL + "/kcal_enable"; String SCREEN_KCAL_CTRL_MIN = SCREEN_KCAL + "/kcal_min"; String SCREEN_KCAL_CTRL_INVERT = SCREEN_KCAL + "/kcal_invert"; String SCREEN_KCAL_CTRL_SAT = SCREEN_KCAL + "/kcal_sat"; String SCREEN_KCAL_CTRL_HUE = SCREEN_KCAL + "/kcal_hue"; String SCREEN_KCAL_CTRL_VAL = SCREEN_KCAL + "/kcal_val"; String SCREEN_KCAL_CTRL_CONT = SCREEN_KCAL + "/kcal_cont"; String[] SCREEN_KCAL_CTRL_NEW_ARRAY = {SCREEN_KCAL_CTRL_ENABLE, SCREEN_KCAL_CTRL_INVERT, SCREEN_KCAL_CTRL_SAT, SCREEN_KCAL_CTRL_HUE, SCREEN_KCAL_CTRL_VAL, SCREEN_KCAL_CTRL_CONT}; String SCREEN_DIAG0 = "/sys/devices/platform/DIAG0.0"; String SCREEN_DIAG0_POWER = SCREEN_DIAG0 + "/power_rail"; String SCREEN_DIAG0_POWER_CTRL = SCREEN_DIAG0 + "/power_rail_ctrl"; String SCREEN_COLOR = "/sys/class/misc/colorcontrol"; String SCREEN_COLOR_CONTROL = SCREEN_COLOR + "/multiplier"; String SCREEN_COLOR_CONTROL_CTRL = SCREEN_COLOR + "/safety_enabled"; String SCREEN_SAMOLED_COLOR = "/sys/class/misc/samoled_color"; String SCREEN_SAMOLED_COLOR_RED = SCREEN_SAMOLED_COLOR + "/red_multiplier"; String SCREEN_SAMOLED_COLOR_GREEN = SCREEN_SAMOLED_COLOR + "/green_multiplier"; String SCREEN_SAMOLED_COLOR_BLUE = SCREEN_SAMOLED_COLOR + "/blue_multiplier"; String SCREEN_FB0_RGB = "/sys/class/graphics/fb0/rgb"; String SCREEN_FB_KCAL = "/sys/devices/virtual/graphics/fb0/kcal"; String[] SCREEN_RGB_ARRAY = {SCREEN_KCAL_CTRL, SCREEN_DIAG0_POWER, SCREEN_COLOR_CONTROL, SCREEN_SAMOLED_COLOR, SCREEN_FB0_RGB, SCREEN_FB_KCAL}; String[] SCREEN_RGB_CTRL_ARRAY = {SCREEN_KCAL_CTRL_ENABLE, SCREEN_KCAL_CTRL_CTRL, SCREEN_DIAG0_POWER_CTRL, SCREEN_COLOR_CONTROL_CTRL}; String SCREEN_HBM = "/sys/devices/virtual/graphics/fb0/hbm"; // Gamma String K_GAMMA_R = "/sys/devices/platform/mipi_lgit.1537/kgamma_r"; String K_GAMMA_G = "/sys/devices/platform/mipi_lgit.1537/kgamma_g"; String K_GAMMA_B = "/sys/devices/platform/mipi_lgit.1537/kgamma_b"; String K_GAMMA_RED = "/sys/devices/platform/mipi_lgit.1537/kgamma_red"; String K_GAMMA_GREEN = "/sys/devices/platform/mipi_lgit.1537/kgamma_green"; String K_GAMMA_BLUE = "/sys/devices/platform/mipi_lgit.1537/kgamma_blue"; String[] K_GAMMA_ARRAY = {K_GAMMA_R, K_GAMMA_G, K_GAMMA_B, K_GAMMA_RED, K_GAMMA_GREEN, K_GAMMA_BLUE}; String GAMMACONTROL = "/sys/class/misc/gammacontrol"; String GAMMACONTROL_RED_GREYS = GAMMACONTROL + "/red_greys"; String GAMMACONTROL_RED_MIDS = GAMMACONTROL + "/red_mids"; String GAMMACONTROL_RED_BLACKS = GAMMACONTROL + "/red_blacks"; String GAMMACONTROL_RED_WHITES = GAMMACONTROL + "/red_whites"; String GAMMACONTROL_GREEN_GREYS = GAMMACONTROL + "/green_greys"; String GAMMACONTROL_GREEN_MIDS = GAMMACONTROL + "/green_mids"; String GAMMACONTROL_GREEN_BLACKS = GAMMACONTROL + "/green_blacks"; String GAMMACONTROL_GREEN_WHITES = GAMMACONTROL + "/green_whites"; String GAMMACONTROL_BLUE_GREYS = GAMMACONTROL + "/blue_greys"; String GAMMACONTROL_BLUE_MIDS = GAMMACONTROL + "/blue_mids"; String GAMMACONTROL_BLUE_BLACKS = GAMMACONTROL + "/blue_blacks"; String GAMMACONTROL_BLUE_WHITES = GAMMACONTROL + "/blue_whites"; String GAMMACONTROL_CONTRAST = GAMMACONTROL + "/contrast"; String GAMMACONTROL_BRIGHTNESS = GAMMACONTROL + "/brightness"; String GAMMACONTROL_SATURATION = GAMMACONTROL + "/saturation"; String DSI_PANEL_RP = "/sys/module/dsi_panel/kgamma_rp"; String DSI_PANEL_RN = "/sys/module/dsi_panel/kgamma_rn"; String DSI_PANEL_GP = "/sys/module/dsi_panel/kgamma_gp"; String DSI_PANEL_GN = "/sys/module/dsi_panel/kgamma_gn"; String DSI_PANEL_BP = "/sys/module/dsi_panel/kgamma_bp"; String DSI_PANEL_BN = "/sys/module/dsi_panel/kgamma_bn"; String DSI_PANEL_W = "/sys/module/dsi_panel/kgamma_w"; String[] DSI_PANEL_ARRAY = {DSI_PANEL_RP, DSI_PANEL_RN, DSI_PANEL_GP, DSI_PANEL_GN, DSI_PANEL_BP, DSI_PANEL_BN, DSI_PANEL_W}; // LCD Backlight String LM3530_BRIGTHNESS_MODE = "/sys/devices/i2c-0/0-0038/lm3530_br_mode"; String LM3530_MIN_BRIGHTNESS = "/sys/devices/i2c-0/0-0038/lm3530_min_br"; String LM3530_MAX_BRIGHTNESS = "/sys/devices/i2c-0/0-0038/lm3530_max_br"; // Backlight Dimmer String LM3630_BACKLIGHT_DIMMER = "/sys/module/lm3630_bl/parameters/backlight_dimmer"; String LM3630_MIN_BRIGHTNESS = "/sys/module/lm3630_bl/parameters/min_brightness"; String LM3630_BACKLIGHT_DIMMER_THRESHOLD = "/sys/module/lm3630_bl/parameters/backlight_threshold"; String LM3630_BACKLIGHT_DIMMER_OFFSET = "/sys/module/lm3630_bl/parameters/backlight_offset"; String MSM_BACKLIGHT_DIMMER = "/sys/module/msm_fb/parameters/backlight_dimmer"; String[] MIN_BRIGHTNESS_ARRAY = {LM3630_MIN_BRIGHTNESS, MSM_BACKLIGHT_DIMMER}; String NEGATIVE_TOGGLE = "/sys/module/cypress_touchkey/parameters/mdnie_shortcut_enabled"; String REGISTER_HOOK = "/sys/class/misc/mdnie/hook_intercept"; String MASTER_SEQUENCE = "/sys/class/misc/mdnie/sequence_intercept"; String GLOVE_MODE = "/sys/devices/virtual/touchscreen/touchscreen_dev/mode"; String[][] SCREEN_ARRAY = {SCREEN_RGB_ARRAY, SCREEN_RGB_CTRL_ARRAY, SCREEN_KCAL_CTRL_NEW_ARRAY, K_GAMMA_ARRAY, DSI_PANEL_ARRAY, MIN_BRIGHTNESS_ARRAY, {GAMMACONTROL, SCREEN_KCAL_CTRL_MIN, SCREEN_HBM, LM3530_BRIGTHNESS_MODE, LM3530_MIN_BRIGHTNESS, LM3530_MAX_BRIGHTNESS, LM3630_BACKLIGHT_DIMMER, LM3630_BACKLIGHT_DIMMER_THRESHOLD, LM3630_BACKLIGHT_DIMMER_OFFSET, NEGATIVE_TOGGLE, REGISTER_HOOK, MASTER_SEQUENCE, GLOVE_MODE}}; // Wake // DT2W String LGE_TOUCH_DT2W = "/sys/devices/virtual/input/lge_touch/dt_wake_enabled"; String LGE_TOUCH_CORE_DT2W = "/sys/module/lge_touch_core/parameters/doubletap_to_wake"; String LGE_TOUCH_GESTURE = "/sys/devices/virtual/input/lge_touch/touch_gesture"; String DT2W = "/sys/android_touch/doubletap2wake"; String DT2W_2 = "/sys/android_touch2/doubletap2wake"; String TOUCH_PANEL_DT2W = "/proc/touchpanel/double_tap_enable"; String DT2W_WAKEUP_GESTURE = "/sys/devices/virtual/input/input1/wakeup_gesture"; String DT2W_ENABLE = "/sys/devices/platform/s3c2440-i2c.3/i2c-3/3-004a/dt2w_enable"; String DT2W_WAKE_GESTURE = "/sys/devices/platform/spi-tegra114.2/spi_master/spi2/spi2.0/input/input0/wake_gesture"; String DT2W_WAKE_GESTURE_2 = "/sys/devices/soc.0/f9924000.i2c/i2c-2/2-0070/input/input0/wake_gesture"; String[] DT2W_ARRAY = {LGE_TOUCH_DT2W, LGE_TOUCH_CORE_DT2W, LGE_TOUCH_GESTURE, DT2W, DT2W_2, TOUCH_PANEL_DT2W, DT2W_WAKEUP_GESTURE, DT2W_ENABLE, DT2W_WAKE_GESTURE, DT2W_WAKE_GESTURE_2}; // S2W String S2W_ONLY = "/sys/android_touch/s2w_s2sonly"; String SW2 = "/sys/android_touch/sweep2wake"; String SW2_2 = "/sys/android_touch2/sweep2wake"; String[] S2W_ARRY = {S2W_ONLY, SW2, SW2_2}; // S2W Leniency String LENIENT = "/sys/android_touch/sweep2wake_sensitive"; // T2W String TSP_T2W = "/sys/devices/error/i2c-1/1-004a/tsp"; String TOUCHWAKE_T2W = "/sys/class/misc/touchwake/enabled"; String[] T2W_ARRAY = {TSP_T2W, TOUCHWAKE_T2W}; // Wake Misc String SCREEN_WAKE_OPTIONS = "/sys/devices/f9924000.i2c/i2c-2/2-0020/input/input2/screen_wake_options"; String[] WAKE_MISC_ARRAY = {SCREEN_WAKE_OPTIONS}; // Sleep Misc String S2S = "/sys/android_touch/erro"; String S2S_2 = "/sys/android_touch2/erro"; String SCREEN_SLEEP_OPTIONS = "/sys/devices/erro/i2c-2/2-0020/input/input2/screen_sleep_options"; String[] SLEEP_MISC_ARRAY = {S2S, S2S_2, SCREEN_SLEEP_OPTIONS}; // DT2S String DT2S = "/sys/android_touch2/doubletap2sleep"; String[] DT2S_ARRAY = {DT2S}; // Gesture String GESTURE_CRTL = "/sys/devices/virtual/touchscreen/touchscreen_dev/gesture_ctrl"; Integer[] GESTURE_HEX_VALUES = {1, 2, 4, 8, 16, 32, 64, 128, 256, 512}; String[] GESTURE_STRING_VALUES = {"up", "down", "left", "right", "e", "o", "w", "c", "m", "double_click"}; // Camera Gesture String CAMERA_GESTURE = "/sys/android_touch/camera_gesture"; // Pocket mode for Gesture String POCKET_MODE = "/sys/android_touch/pocket_mode"; String POCKET_DETECT = "/sys/android_touch/pocket_detect"; String[] POCKET_MODE_ARRAY = { POCKET_MODE, POCKET_DETECT }; String WAKE_TIMEOUT = "/sys/android_touch/wake_timeout"; String WAKE_TIMEOUT_2 = "/sys/android_touch2/wake_timeout"; String[] WAKE_TIMEOUT_ARRAY = { WAKE_TIMEOUT, WAKE_TIMEOUT_2 }; String POWER_KEY_SUSPEND = "/sys/module/qpnp_power_on/parameters/pwrkey_suspend"; String[][] WAKE_ARRAY = {DT2W_ARRAY, S2W_ARRY, T2W_ARRAY, WAKE_MISC_ARRAY, SLEEP_MISC_ARRAY, WAKE_TIMEOUT_ARRAY, POCKET_MODE_ARRAY, {LENIENT, GESTURE_CRTL, CAMERA_GESTURE, POWER_KEY_SUSPEND}}; // Sound String SOUND_CONTROL_ENABLE = "/sys/module/snd_soc_wcd9320/parameters/enable_fs"; String WCD_HIGHPERF_MODE_ENABLE = "/sys/module/snd_soc_wcd9320/parameters/high_perf_mode"; String WCD_SPKR_DRV_WRND = "/sys/module/snd_soc_wcd9320/parameters/spkr_drv_wrnd"; String FAUX_SOUND = "/sys/kernel/sound_control_3"; String HEADPHONE_GAIN = "/sys/kernel/sound_control_3/gpl_headphone_gain"; String HANDSET_MICROPONE_GAIN = "/sys/kernel/sound_control_3/gpl_mic_gain"; String CAM_MICROPHONE_GAIN = "/sys/kernel/sound_control_3/gpl_cam_mic_gain"; String SPEAKER_GAIN = "/sys/kernel/sound_control_3/gpl_speaker_gain"; String HEADPHONE_POWERAMP_GAIN = "/sys/kernel/sound_control_3/gpl_headphone_pa_gain"; String FRANCO_SOUND = "/sys/devices/virtual/misc/soundcontrol"; String HIGHPERF_MODE_ENABLE = "/sys/devices/virtual/misc/soundcontrol/highperf_enabled"; String MIC_BOOST = "/sys/devices/virtual/misc/soundcontrol/mic_boost"; String SPEAKER_BOOST = "/sys/devices/virtual/misc/soundcontrol/speaker_boost"; String VOLUME_BOOST = "/sys/devices/virtual/misc/soundcontrol/volume_boost"; String[] SPEAKER_GAIN_ARRAY = {SPEAKER_GAIN, SPEAKER_BOOST}; String[][] SOUND_ARRAY = {SPEAKER_GAIN_ARRAY, {SOUND_CONTROL_ENABLE, HIGHPERF_MODE_ENABLE, HEADPHONE_GAIN, HANDSET_MICROPONE_GAIN, CAM_MICROPHONE_GAIN, HEADPHONE_POWERAMP_GAIN, MIC_BOOST, VOLUME_BOOST, WCD_HIGHPERF_MODE_ENABLE, WCD_SPKR_DRV_WRND}}; // Battery String FORCE_FAST_CHARGE = "/sys/kernel/fast_charge/force_fast_charge"; String BLX = "/sys/devices/virtual/misc/batterylifeextender/charging_limit"; String CHARGE_RATE = "sys/kernel/thundercharge_control"; String CHARGE_RATE_ENABLE = CHARGE_RATE + "/enabled"; String CUSTOM_CHARGING_RATE = CHARGE_RATE + "/custom_current"; // C-States String C0STATE = "/sys/module/msm_pm/modes/cpu0/wfi/idle_enabled"; String C1STATE = "/sys/module/msm_pm/modes/cpu0/retention/idle_enabled"; String C2STATE = "/sys/module/msm_pm/modes/cpu0/standalone_power_collapse/idle_enabled"; String C3STATE = "/sys/module/msm_pm/modes/cpu0/power_collapse/idle_enabled"; String[] BATTERY_ARRAY = {FORCE_FAST_CHARGE, BLX, CHARGE_RATE, C0STATE, C1STATE, C2STATE, C3STATE}; // I/O String IO_INTERNAL_SCHEDULER = "/sys/block/mmcblk0/queue/scheduler"; String IO_EXTERNAL_SCHEDULER = "/sys/block/mmcblk1/queue/scheduler"; String IO_INTERNAL_SCHEDULER_TUNABLE = "/sys/block/mmcblk0/queue/iosched"; String IO_EXTERNAL_SCHEDULER_TUNABLE = "/sys/block/mmcblk1/queue/iosched"; String IO_INTERNAL_READ_AHEAD = "/sys/block/mmcblk0/queue/read_ahead_kb"; String IO_EXTERNAL_READ_AHEAD = "/sys/block/mmcblk1/queue/read_ahead_kb"; String IO_ROTATIONAL = "/sys/block/mmcblk0/queue/rotational"; String IO_STATS = "/sys/block/mmcblk0/queue/iostats"; String IO_RANDOM = "/sys/block/mmcblk0/queue/add_random"; String IO_AFFINITY = "/sys/block/mmcblk0/queue/rq_affinity"; String[] IO_ARRAY = {IO_INTERNAL_SCHEDULER, IO_EXTERNAL_SCHEDULER, IO_INTERNAL_SCHEDULER_TUNABLE, IO_EXTERNAL_SCHEDULER_TUNABLE, IO_INTERNAL_READ_AHEAD, IO_EXTERNAL_READ_AHEAD, IO_ROTATIONAL, IO_STATS, IO_RANDOM, IO_AFFINITY }; // Kernel Samepage Merging String KSM_FOLDER = "/sys/kernel/mm/ksm"; String UKSM_FOLDER = "/sys/kernel/mm/uksm"; String FULL_SCANS = "full_scans"; String PAGES_SHARED = "pages_shared"; String PAGES_SHARING = "pages_sharing"; String PAGES_UNSHARED = "pages_unshared"; String PAGES_VOLATILE = "pages_volatile"; String RUN = "run"; String DEFERRED_TIMER = "deferred_timer"; String PAGES_TO_SCAN = "pages_to_scan"; String SLEEP_MILLISECONDS = "sleep_millisecs"; String UKSM_CPU_USE = "max_cpu_percentage"; String[] KSM_INFOS = {FULL_SCANS, PAGES_SHARED, PAGES_SHARING, PAGES_UNSHARED, PAGES_VOLATILE}; String[] KSM_ARRAY = {KSM_FOLDER, UKSM_FOLDER}; // Low Memory Killer String LMK_MINFREE = "/sys/module/lowmemorykiller/parameters/minfree"; String LMK_ADAPTIVE = "/sys/module/lowmemorykiller/parameters/enable_adaptive_lmk"; // Virtual Memory String VM_PATH = "/proc/sys/vm"; String VM_DIRTY_RATIO = VM_PATH + "/dirty_ratio"; String VM_DIRTY_BACKGROUND_RATIO = VM_PATH + "/dirty_background_ratio"; String VM_DIRTY_EXPIRE_CENTISECS = VM_PATH + "/dirty_expire_centisecs"; String VM_DIRTY_WRITEBACK_CENTISECS = VM_PATH + "/dirty_writeback_centisecs"; String VM_DYNAMIC_DIRTY_WRITEBACK = VM_PATH + "/dynamic_dirty_writeback"; String VM_DIRTY_WRITEBACK_SUSPEND_CENTISECS = VM_PATH + "/dirty_writeback_suspend_centisecs"; String VM_DIRTY_WRITEBACK_ACTIVE_CENTISECS = VM_PATH + "/dirty_writeback_active_centisecs"; String VM_MIN_FREE_KBYTES = VM_PATH + "/min_free_kbytes"; String VM_OVERCOMMIT_RATIO = VM_PATH + "/overcommit_ratio"; String VM_SWAPPINESS = VM_PATH + "/swappiness"; String VM_VFS_CACHE_PRESSURE = VM_PATH + "/vfs_cache_pressure"; String VM_LAPTOP_MODE = VM_PATH + "/laptop_mode"; String VM_EXTRA_FREE_KBYTES = VM_PATH + "/extra_free_kbytes"; String ZRAM = "/sys/block/zram0"; String ZRAM_BLOCK = "/dev/block/zram0"; String ZRAM_DISKSIZE = "/sys/block/zram0/disksize"; String ZRAM_RESET = "/sys/block/zram0/reset"; String[] VM_ARRAY = {ZRAM_BLOCK, ZRAM_DISKSIZE, ZRAM_RESET, VM_DIRTY_RATIO, VM_DIRTY_BACKGROUND_RATIO, VM_DIRTY_EXPIRE_CENTISECS, VM_DIRTY_WRITEBACK_CENTISECS, VM_MIN_FREE_KBYTES, VM_OVERCOMMIT_RATIO, VM_SWAPPINESS, VM_VFS_CACHE_PRESSURE, VM_LAPTOP_MODE, VM_EXTRA_FREE_KBYTES, VM_DYNAMIC_DIRTY_WRITEBACK, VM_DIRTY_WRITEBACK_SUSPEND_CENTISECS,VM_DIRTY_WRITEBACK_ACTIVE_CENTISECS, LMK_MINFREE, LMK_ADAPTIVE }; // Entropy String PROC_RANDOM = "/proc/sys/kernel/random"; String PROC_RANDOM_ENTROPY_AVAILABLE = PROC_RANDOM + "/entropy_avail"; String PROC_RANDOM_ENTROPY_POOLSIZE = PROC_RANDOM + "/poolsize"; String PROC_RANDOM_ENTROPY_READ = PROC_RANDOM + "/read_wakeup_threshold"; String PROC_RANDOM_ENTROPY_WRITE = PROC_RANDOM + "/write_wakeup_threshold"; String[] ENTROPY_ARRAY = {PROC_RANDOM}; // Misc // Vibration Object[][] VIBRATION_ARRAY = { // {Path, Max, Min} {"/sys/class/timed_output/vibrator/amp", 100, 0}, {"/sys/class/timed_output/vibrator/level", 31, 12}, {"/sys/class/timed_output/vibrator/pwm_value", 100, 0}, // Read MAX MIN from sys {"/sys/class/timed_output/vibrator/pwm_value_1p", 99, 53}, {"/sys/class/timed_output/vibrator/voltage_level", 3199, 1200}, {"/sys/class/timed_output/vibrator/vtg_level", 31, 12}, // Read MAX MIN from sys {"/sys/class/timed_output/vibrator/vmax_mv", 3596, 116}, {"/sys/class/timed_output/vibrator/vmax_mv_strong", 3596, 116}, // Needs VIB_LIGHT path {"/sys/devices/platform/tspdrv/nforce_timed", 127, 1}, {"/sys/devices/i2c-3/3-0033/vibrator/vib0/vib_duty_cycle", 100, 25}, // Needs enable path {"/sys/module/qpnp_vibrator/parameters/vib_voltage", 31, 12}, {"/sys/vibrator/pwmvalue", 127, 0} }; String VIB_LIGHT = "/sys/devices/virtual/timed_output/vibrator/vmax_mv_light"; String VIB_ENABLE = "/sys/devices/i2c-3/3-0033/vibrator/vib0/vib_enable"; // Wakelock String[] SMB135X_WAKELOCKS = { "/sys/module/smb135x_charger/parameters/use_wlock", "/sys/module/wakeup/parameters/enable_smb135x_wake_ws" }; String SENSOR_IND_WAKELOCK = "/sys/module/wakeup/parameters/enable_si_ws"; String MSM_HSIC_HOST_WAKELOCK = "/sys/module/wakeup/parameters/enable_msm_hsic_ws"; String[] WLAN_RX_WAKELOCKS = { "/sys/module/wakeup/parameters/wlan_rx_wake", "/sys/module/wakeup/parameters/enable_wlan_rx_wake_ws" }; String[] WLAN_CTRL_WAKELOCKS = { "/sys/module/wakeup/parameters/wlan_ctrl_wake", "/sys/module/wakeup/parameters/enable_wlan_ctrl_wake_ws" }; String[] WLAN_WAKELOCKS = { "/sys/module/wakeup/parameters/wlan_wake", "/sys/module/wakeup/parameters/enable_wlan_wake_ws" }; String WLAN_RX_WAKELOCK_DIVIDER = "/sys/module/bcmdhd/parameters/wl_divide"; String MSM_HSIC_WAKELOCK_DIVIDER = "/sys/module/xhci_hcd/parameters/wl_divide"; // Logging String LOGGER_MODE = "/sys/kernel/logger_mode/logger_mode"; String LOGGER_ENABLED = "/sys/module/logger/parameters/enabled"; String LOGGER_LOG_ENABLED = "/sys/module/logger/parameters/log_enabled"; String[] LOGGER_ARRAY = {LOGGER_MODE, LOGGER_ENABLED, LOGGER_LOG_ENABLED}; // BCL String[] BCL_ARRAY = {"/sys/devices/qcom,bcl.38/mode","/sys/devices/qcom,bcl.39/mode", "/sys/devices/soc.0/qcom,bcl.60/mode" }; String BCL_HOTPLUG = "/sys/module/battery_current_limit/parameters/bcl_hotplug_enable"; // CRC String[] CRC_ARRAY = { "/sys/module/mmc_core/parameters/crc", "/sys/module/mmc_core/parameters/use_spi_crc" }; // Fsync String[] FSYNC_ARRAY = { "/sys/devices/virtual/misc/fsynccontrol/fsync_enabled", "/sys/module/sync/parameters/fsync_enabled" }; String DYNAMIC_FSYNC = "/sys/kernel/dyn_fsync/Dyn_fsync_active"; // Gentle fair sleepers String GENTLE_FAIR_SLEEPERS = "/sys/kernel/sched/gentle_fair_sleepers"; // Power suspend String POWER_SUSPEND = "/sys/kernel/power_suspend"; String POWER_SUSPEND_MODE = POWER_SUSPEND + "/power_suspend_mode"; String POWER_SUSPEND_STATE = POWER_SUSPEND + "/power_suspend_state"; String POWER_SUSPEND_VERSION = POWER_SUSPEND + "/power_suspend_version"; // Network String TCP_AVAILABLE_CONGESTIONS = "/proc/sys/net/ipv4/tcp_available_congestion_control"; String HOSTNAME_KEY = "net.hostname"; String ADB_OVER_WIFI = "service.adb.tcp.port"; String GETENFORCE = "getenforce"; String SETENFORCE = "setenforce"; Object[][] MISC_ARRAY = { VIBRATION_ARRAY, {VIB_LIGHT, VIB_ENABLE, SENSOR_IND_WAKELOCK, MSM_HSIC_HOST_WAKELOCK, WLAN_RX_WAKELOCK_DIVIDER, MSM_HSIC_WAKELOCK_DIVIDER, LOGGER_ENABLED, DYNAMIC_FSYNC, GENTLE_FAIR_SLEEPERS, POWER_SUSPEND_MODE, POWER_SUSPEND_STATE, BCL_HOTPLUG, TCP_AVAILABLE_CONGESTIONS, HOSTNAME_KEY, GETENFORCE, SETENFORCE, ADB_OVER_WIFI}, SMB135X_WAKELOCKS, WLAN_RX_WAKELOCKS, WLAN_CTRL_WAKELOCKS, WLAN_WAKELOCKS, CRC_ARRAY, FSYNC_ARRAY, BCL_ARRAY}; // Build prop String BUILD_PROP = "/system/build.prop"; // Init.d String INITD = "/system/etc/init.d"; }
Revert "Fix t2w and sleep" This reverts commit 69592dce907f1ed86bbe1619ac00c1fab083aa5c.
app/src/main/java/com/grarak/kerneladiutor/utils/Constants.java
Revert "Fix t2w and sleep"
<ide><path>pp/src/main/java/com/grarak/kerneladiutor/utils/Constants.java <ide> String LENIENT = "/sys/android_touch/sweep2wake_sensitive"; <ide> <ide> // T2W <del> String TSP_T2W = "/sys/devices/error/i2c-1/1-004a/tsp"; <add> String TSP_T2W = "/sys/devices/f9966000.i2c/i2c-1/1-004a/tsp"; <ide> String TOUCHWAKE_T2W = "/sys/class/misc/touchwake/enabled"; <ide> <ide> String[] T2W_ARRAY = {TSP_T2W, TOUCHWAKE_T2W}; <ide> String[] WAKE_MISC_ARRAY = {SCREEN_WAKE_OPTIONS}; <ide> <ide> // Sleep Misc <del> String S2S = "/sys/android_touch/erro"; <del> String S2S_2 = "/sys/android_touch2/erro"; <del> String SCREEN_SLEEP_OPTIONS = "/sys/devices/erro/i2c-2/2-0020/input/input2/screen_sleep_options"; <add> String S2S = "/sys/android_touch/sweep2sleep"; <add> String S2S_2 = "/sys/android_touch2/sweep2sleep"; <add> String SCREEN_SLEEP_OPTIONS = "/sys/devices/f9924000.i2c/i2c-2/2-0020/input/input2/screen_sleep_options"; <ide> <ide> String[] SLEEP_MISC_ARRAY = {S2S, S2S_2, SCREEN_SLEEP_OPTIONS}; <ide>
Java
lgpl-2.1
8a036d8da9ee9a15fc64fa32f3a99756f90e1cc3
0
SensorsINI/jaer,SensorsINI/jaer,SensorsINI/jaer,SensorsINI/jaer,SensorsINI/jaer,SensorsINI/jaer,SensorsINI/jaer,SensorsINI/jaer
/* ClassChooserPanel2.java * * Created on May 13, 2007, 3:46 PM */ package net.sf.jaer.util; import java.awt.Color; import java.awt.Component; import java.awt.Cursor; import java.awt.Desktop; import java.awt.event.ActionEvent; import java.awt.event.KeyEvent; import java.awt.event.MouseAdapter; import java.awt.event.MouseEvent; import java.beans.PropertyChangeEvent; import java.beans.PropertyChangeListener; import java.io.IOException; import java.net.URI; import java.util.ArrayList; import java.util.Collections; import java.util.Comparator; import java.util.Enumeration; import java.util.HashMap; import java.util.List; import java.util.Vector; import java.util.logging.Level; import java.util.logging.Logger; import javax.swing.AbstractAction; import javax.swing.Action; import javax.swing.DefaultListModel; import javax.swing.InputMap; import javax.swing.JLabel; import javax.swing.JList; import javax.swing.JOptionPane; import javax.swing.KeyStroke; import javax.swing.ListCellRenderer; import javax.swing.ProgressMonitor; import javax.swing.SwingWorker; import javax.swing.event.HyperlinkEvent; import javax.swing.event.HyperlinkListener; import javax.swing.event.ListDataEvent; import javax.swing.event.ListDataListener; import net.sf.jaer.Description; import net.sf.jaer.DevelopmentStatus; /** * A panel that finds subclasses of a class, displays them in a left list, * displays another list given as a parameter in the right panel, and accepts a * list of default class names. The user can choose which classes and these are * returned by a call to getList. The list of available classes is built in the * background. * * @author tobi */ public class ClassChooserPanel extends javax.swing.JPanel { private static final Logger log = Logger.getLogger("net.sf.jaer.util"); private static final String MISSING_DESCRIPTION_MESSAGE = "<html>No description available - provide one using @Description annotation, as in <pre>@Description(\"Example class\") \n public class MyClass</pre></html>"; private FilterableListModel chosenClassesListModel, availClassesListModel; private ArrayList<ClassNameWithDescriptionAndDevelopmentStatus> availAllList; private ArrayList<String> revertCopy, defaultClassNames; private DescriptionMap descriptionMap = new DescriptionMap(); private Class superClass = null; // the classes available will be subclasses of this class private class ClassDescription { String description = null; DevelopmentStatus.Status developmentStatus = null; public ClassDescription(String description, DevelopmentStatus.Status developmentStatus) { this.description = description; this.developmentStatus = developmentStatus; } } class DescriptionMap extends HashMap<String, ClassDescription> { ClassDescription get(String name) { if (name == null) { return null; } if (super.get(name) == null) { put(name); } return super.get(name); } void put(String name) { if (name == null) { return; } if (containsKey(name)) { return; } try { Class c = Class.forName(name); if (c == null) { log.warning("tried to put class " + name + " but there is no such class"); return; } String descriptionString = null; if (c.isAnnotationPresent(Description.class)) { Description des = (Description) c.getAnnotation(Description.class); descriptionString = des.value(); } DevelopmentStatus.Status devStatus = null; if (c.isAnnotationPresent(DevelopmentStatus.class)) { DevelopmentStatus des = (DevelopmentStatus) c.getAnnotation(DevelopmentStatus.class); devStatus = des.value(); } ClassDescription des = new ClassDescription(descriptionString, devStatus); put(name, des); } catch (Exception e) { log.warning("trying to put class named " + name + " caught " + e.toString()); } } } private class AddAction extends AbstractAction { @Override public void actionPerformed(ActionEvent e) { Object o = availClassJList.getSelectedValue(); if (o == null) { return; } if (containsClass(chosenClassesListModel, o)) { boolean addIt = checkIfAddDuplicate(o); if (!addIt) { return; } } int last = chosenClassesListModel.getSize() - 1; chosenClassesListModel.add(last + 1, o); classJList.setSelectedIndex(last + 1); } }; /** * Creates new form ClassChooserPanel * * @param superClass a Class that will be used to search the classpath for * subclasses of subClassOf. * @param classNames a list of names, which is filled in by the actions of * the user with the chosen classes * @param defaultClassNames the list on the right is replaced by this list * if the user pushes the Defaults button. */ public ClassChooserPanel(final Class superClass, ArrayList<String> classNames, ArrayList<String> defaultClassNames) { initComponents(); this.superClass = superClass; includeExperimentalCB.setEnabled(onlyStableCB.isSelected()); availFilterTextField.requestFocusInWindow(); this.defaultClassNames = defaultClassNames; final DefaultListModel tmpList = new DefaultListModel(); tmpList.addElement("scanning..."); availClassJList.setModel(tmpList); try { availAllList = new ArrayList<ClassNameWithDescriptionAndDevelopmentStatus>(); availClassesListModel = new FilterableListModel(availAllList); availClassJList.setModel(availClassesListModel); availClassJList.setCellRenderer(new MyCellRenderer()); // addAction(availClassJList, new AddAction()); filterAvailable(); // user typed while list is populated availClassesListModel.addListDataListener(new ListDataListener() { @Override public void intervalAdded(ListDataEvent lde) { filterAvailable(); } @Override public void intervalRemoved(ListDataEvent lde) { } @Override public void contentsChanged(ListDataEvent lde) { } }); } catch (Exception ex) { Logger.getLogger(ClassChooserPanel.class.getName()).log(Level.SEVERE, null, ex); } finally { setCursor(Cursor.getDefaultCursor()); } Action removeAction = new AbstractAction() { @Override public void actionPerformed(final ActionEvent e) { int index = classJList.getSelectedIndex(); chosenClassesListModel.removeElementAt(index); int size = chosenClassesListModel.getSize(); if (size == 0) { //Nobody's left, disable firing. removeClassButton.setEnabled(false); } else { //Select an index. if (index == chosenClassesListModel.getSize()) { //removed item in last position index--; } classJList.setSelectedIndex(index); classJList.ensureIndexIsVisible(index); } } }; addAction(classJList, removeAction); populateAvailableClassesListModel(superClass, true); revertCopy = new ArrayList<>(classNames); chosenClassesListModel = new FilterableListModel(classNames); classJList.setModel(chosenClassesListModel); classJList.setCellRenderer(new MyCellRenderer()); descPane.addHyperlinkListener(new HyperlinkListener() { @Override public void hyperlinkUpdate(HyperlinkEvent event) { if (event.getEventType() == HyperlinkEvent.EventType.ACTIVATED) { String url = event.getURL().toString(); try { Desktop.getDesktop().browse(URI.create(url)); } catch (IOException ex) { Logger.getLogger(ClassChooserPanel.class.getName()).log(Level.SEVERE, null, ex); } } } }); } private void populateAvailableClassesListModel(final Class subclassOf, boolean useCache) { final ProgressMonitor progressMonitor = new ProgressMonitor(this, "Finding classes", "", 0, 100); progressMonitor.setMillisToPopup(10); final SubclassFinder.SubclassFinderWorker worker = new SubclassFinder.SubclassFinderWorker(subclassOf, availClassesListModel, useCache); worker.addPropertyChangeListener(new PropertyChangeListener() { @Override public void propertyChange(PropertyChangeEvent evt) { // System.out.println(evt.getPropertyName() + " " + evt.getNewValue()); if ("progress" == evt.getPropertyName()) { int progress = (Integer) evt.getNewValue(); progressMonitor.setProgress(progress); String message = String.format("Completed %d%%.\n", progress); progressMonitor.setNote(message); if (progressMonitor.isCanceled() || worker.isDone()) { if (progressMonitor.isCanceled()) { worker.cancel(true); } } } if ((evt != null) && evt.getNewValue().equals(SwingWorker.StateValue.DONE)) { try { availAllList = worker.get(); if (availAllList == null) { log.warning("got empty list of classes - something wrong here, aborting dialog"); return; } Collections.sort(availAllList, new ClassNameSorter()); availClassesListModel = new FilterableListModel(availAllList); availClassJList.setModel(availClassesListModel); availClassJList.setCellRenderer(new MyCellRenderer()); addAction(availClassJList, new AddAction()); filterAvailable(); } catch (Exception ex) { Logger.getLogger(ClassChooserPanel.class.getName()).log(Level.SEVERE, null, ex); } finally { setCursor(Cursor.getDefaultCursor()); } } } }); setCursor(Cursor.getPredefinedCursor(Cursor.WAIT_CURSOR)); worker.execute(); } private boolean containsClass(FilterableListModel model, Object obj) { for (Object o : model.toArray()) { if (o instanceof String && ((String) o) .equals(((ClassNameWithDescriptionAndDevelopmentStatus) obj).getClassName())) { return true; } else if (o instanceof ClassNameWithDescriptionAndDevelopmentStatus && ((ClassNameWithDescriptionAndDevelopmentStatus) o).getClassName() .equals(((ClassNameWithDescriptionAndDevelopmentStatus) obj).getClassName())) { return true; } } return false; } private class ClassNameSorter implements Comparator { @Override public int compare(Object o1, Object o2) { if ((o1 instanceof ClassNameWithDescriptionAndDevelopmentStatus) && (o2 instanceof ClassNameWithDescriptionAndDevelopmentStatus)) { ClassNameWithDescriptionAndDevelopmentStatus c1 = (ClassNameWithDescriptionAndDevelopmentStatus) o1; ClassNameWithDescriptionAndDevelopmentStatus c2 = (ClassNameWithDescriptionAndDevelopmentStatus) o2; return shortName(c1.getClassName()).compareTo(shortName(c2.getClassName())); } else { return -1; } } } private DevelopmentStatus.Status getClassDevelopmentStatus(String className) { ClassDescription des = descriptionMap.get(className); if (des == null) { return null; } return des.developmentStatus; } private String getClassDescription(String className) { ClassDescription des = descriptionMap.get(className); if (des == null) { return null; } return des.description; } private class MyCellRenderer extends JLabel implements ListCellRenderer { // This is the only method defined by ListCellRenderer. // We just reconfigure the JLabel each time we're called. /** * @param list The JList we're painting. * @param value The value returned by * list.getModel().getElementAt(index). * @param index The cells index. * @param isSelected True if the specified cell was selected. * @param cellHasFocus True if the specified cell has the focus. */ @Override public Component getListCellRendererComponent(JList list, Object obj, int index, boolean isSelected, boolean cellHasFocus) { String fullclassname = obj.toString(); String shortname = shortName(fullclassname);//.substring(fullclassname.lastIndexOf('.') + 1); setText(shortname); Color foreground, background; if (isSelected) { background = list.getSelectionBackground(); DevelopmentStatus.Status develStatus = getClassDevelopmentStatus(fullclassname); String des = getClassDescription(fullclassname); ClassNameTF.setText(fullclassname); if (develStatus == DevelopmentStatus.Status.Experimental) { foreground = Color.BLACK; develStatusTF.setText(develStatus.toString()); } else if (develStatus == DevelopmentStatus.Status.InDevelopment) { foreground = Color.BLACK; develStatusTF.setText(develStatus.toString()); } else if (develStatus == DevelopmentStatus.Status.Stable) { foreground = Color. BLACK; develStatusTF.setText(develStatus.toString()); } else { foreground = Color.BLACK; develStatusTF.setText("unknown"); } if (des != null) { if (des.startsWith("<html>")) { setToolTipText(des); } else { setToolTipText(fullclassname + ": " + des); } descPane.setContentType("text/html"); descPane.setText("<html>" + shortname + ": " + des); } else { foreground = Color.GRAY; setToolTipText(fullclassname); descPane.setText(MISSING_DESCRIPTION_MESSAGE); } } else { background = list.getBackground(); DevelopmentStatus.Status develStatus = getClassDevelopmentStatus(fullclassname); if (develStatus == DevelopmentStatus.Status.Experimental) { foreground = Color.ORANGE.darker(); } else if (develStatus == DevelopmentStatus.Status.InDevelopment) { foreground = Color.DARK_GRAY; } else if (develStatus == DevelopmentStatus.Status.Stable) { foreground = Color.BLUE; } else { foreground = Color.GRAY; } if (getClassDescription(fullclassname) == null) { foreground = Color.LIGHT_GRAY; } } setEnabled(list.isEnabled()); setOpaque(true); setForeground(foreground); setBackground(background); return this; } } private String shortName(String s) { if (s == null) { return "null"; } int i = s.lastIndexOf('.'); if ((i < 0) || (i == (s.length() - 1))) { return s; } return s.substring(i + 1); } // extends DefaultListModel to add a text filter public class FilterableListModel<ClassNameWithDescriptionAndDevelopmentStatus> extends DefaultListModel<ClassNameWithDescriptionAndDevelopmentStatus> { Vector<ClassNameWithDescriptionAndDevelopmentStatus> origList = new Vector(); String filterString = null; FilterableListModel(List<ClassNameWithDescriptionAndDevelopmentStatus> list) { super(); for (ClassNameWithDescriptionAndDevelopmentStatus s : list) { this.addElement(s); } origList.addAll(list); } synchronized void resetList() { clear(); for (ClassNameWithDescriptionAndDevelopmentStatus o : origList) { addElement(o); } } synchronized void filter(String s) { boolean onlyStable = onlyStableCB.isSelected(); if (((s == null) || s.equals("")) && !onlyStable) { resetList(); return; } boolean passAllStable = false; if (onlyStable && ((s == null) || s.equals(""))) { passAllStable = true; // pass all stable filters } boolean includeExperimental = includeExperimentalCB.isSelected(); filterString = s.toLowerCase(); resetList(); Vector v = new Vector(); // list to prune out // must build a list of stuff to prune, then prune Enumeration en = elements(); while (en.hasMoreElements()) { // add all elements that should be filtered out Object o = en.nextElement(); net.sf.jaer.util.ClassNameWithDescriptionAndDevelopmentStatus cn; cn = (net.sf.jaer.util.ClassNameWithDescriptionAndDevelopmentStatus) o; String str = null; boolean isStable = false; DevelopmentStatus ds = cn.getDevelopmentStatus(); if (ds != null && (ds.value().equals(DevelopmentStatus.Status.Stable) || (includeExperimental && ds.value().equals(DevelopmentStatus.Status.Experimental)))) { isStable = true; // this class is stable } if (passAllStable) { if (!isStable) { v.add(o); // filter out this class because it not stable and we are passing all stable filters only } } else { // add (filter out) depending on if strings don't match or if !isStable and onlyStable is true if (onlyStable && !isStable) { v.add(o); continue; } if (includeDescriptionCB.isSelected()) { str = (cn.toString() + cn.getDescription()).toLowerCase(); } else { str = cn.toString(); } int ind = str.indexOf(filterString); if (ind == -1 || (!isStable && onlyStable)) { v.add(o); } } } // prune list for (Object o : v) { removeElement(o); } } synchronized void clearFilter() { filter(null); } } public FilterableListModel getChosenClassesListModel() { return chosenClassesListModel; } /** * This method is called from within the constructor to initialize the form. * WARNING: Do NOT modify this code. The content of this method is always * regenerated by the Form Editor. */ // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents private void initComponents() { availClassPanel = new javax.swing.JPanel(); availClassDesciptionPanel = new javax.swing.JScrollPane(); availClassJList = new javax.swing.JList(); onlyStableCB = new javax.swing.JCheckBox(); includeExperimentalCB = new javax.swing.JCheckBox(); filterLabel = new javax.swing.JLabel(); availFilterTextField = new javax.swing.JTextField(); clearFilterBut = new javax.swing.JButton(); includeDescriptionCB = new javax.swing.JCheckBox(); refrreshButton = new javax.swing.JButton(); chosenClassPanel = new javax.swing.JPanel(); jScrollPane3 = new javax.swing.JScrollPane(); classJList = new javax.swing.JList(); descPanel = new javax.swing.JPanel(); ClassDescSP = new javax.swing.JScrollPane(); descPane = new javax.swing.JTextPane(); devlStatusLbl = new javax.swing.JLabel(); develStatusTF = new javax.swing.JTextField(); ClassNameLbl = new javax.swing.JLabel(); ClassNameTF = new javax.swing.JTextField(); jPanel1 = new javax.swing.JPanel(); addClassButton = new javax.swing.JButton(); removeClassButton = new javax.swing.JButton(); removeAllButton = new javax.swing.JButton(); moveUpButton = new javax.swing.JButton(); moveDownButton = new javax.swing.JButton(); revertButton = new javax.swing.JButton(); defaultsButton = new javax.swing.JButton(); setPreferredSize(new java.awt.Dimension(580, 686)); availClassPanel.setBorder(javax.swing.BorderFactory.createTitledBorder("Available classes")); availClassPanel.setToolTipText("<html>If your class doesn't show up here, rebuild the project to get it into jAER.jar (or some other jar on the classpath). <p> Yyour class must be concrete (not abstract). <p> Finally, if your class lives in a separate JAR archive, make sure your archive classpath is not on the excluded list in the class ListClasses."); availClassPanel.setPreferredSize(new java.awt.Dimension(400, 300)); availClassDesciptionPanel.setBorder(null); availClassJList.setToolTipText("If your class doesn't show up here, rebuild the project to get it into jAER.jar (or some other jar on the classpath) and hit the Refresh button to rescan classpath."); availClassDesciptionPanel.setViewportView(availClassJList); availClassJList.getAccessibleContext().setAccessibleDescription(""); onlyStableCB.setText("Only Stable"); onlyStableCB.setToolTipText("Show only items with DevelopmentStatus.Stable"); onlyStableCB.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { onlyStableCBActionPerformed(evt); } }); includeExperimentalCB.setText("Include Experimental"); includeExperimentalCB.setToolTipText("Include Experimental classes in search results"); includeExperimentalCB.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { includeExperimentalCBActionPerformed(evt); } }); filterLabel.setText("Filter"); availFilterTextField.setToolTipText("type any part of your filter name or description here to filter list"); availFilterTextField.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { availFilterTextFieldActionPerformed(evt); } }); availFilterTextField.addKeyListener(new java.awt.event.KeyAdapter() { public void keyTyped(java.awt.event.KeyEvent evt) { availFilterTextFieldKeyTyped(evt); } }); clearFilterBut.setText("X"); clearFilterBut.setIconTextGap(0); clearFilterBut.setMargin(new java.awt.Insets(2, 1, 1, 2)); clearFilterBut.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { clearFilterButActionPerformed(evt); } }); includeDescriptionCB.setSelected(true); includeDescriptionCB.setText("Include descriptions"); includeDescriptionCB.setToolTipText("Include class Descriptions in filter results"); includeDescriptionCB.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { includeDescriptionCBActionPerformed(evt); } }); refrreshButton.setText("Refresh list"); refrreshButton.setToolTipText("<html> <p>Scans entire classpath for possible classes</p><p>(needs to be refreshed if new classes are added)</p>"); refrreshButton.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { refrreshButtonActionPerformed(evt); } }); javax.swing.GroupLayout availClassPanelLayout = new javax.swing.GroupLayout(availClassPanel); availClassPanel.setLayout(availClassPanelLayout); availClassPanelLayout.setHorizontalGroup( availClassPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(availClassPanelLayout.createSequentialGroup() .addContainerGap() .addGroup(availClassPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addComponent(availClassDesciptionPanel, javax.swing.GroupLayout.PREFERRED_SIZE, 222, javax.swing.GroupLayout.PREFERRED_SIZE) .addComponent(includeExperimentalCB) .addGroup(availClassPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING, false) .addGroup(availClassPanelLayout.createSequentialGroup() .addComponent(onlyStableCB) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE) .addComponent(includeDescriptionCB)) .addGroup(availClassPanelLayout.createSequentialGroup() .addComponent(filterLabel) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addComponent(availFilterTextField, javax.swing.GroupLayout.PREFERRED_SIZE, 116, javax.swing.GroupLayout.PREFERRED_SIZE) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addComponent(clearFilterBut) .addGap(44, 44, 44))))) .addComponent(refrreshButton) ); availClassPanelLayout.setVerticalGroup( availClassPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, availClassPanelLayout.createSequentialGroup() .addComponent(refrreshButton) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addGroup(availClassPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE) .addComponent(filterLabel) .addComponent(availFilterTextField, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE) .addComponent(clearFilterBut)) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED) .addGroup(availClassPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE) .addComponent(onlyStableCB) .addComponent(includeDescriptionCB)) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addComponent(includeExperimentalCB) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED) .addComponent(availClassDesciptionPanel) .addContainerGap()) ); chosenClassPanel.setBorder(javax.swing.BorderFactory.createTitledBorder("Selected classes")); chosenClassPanel.setToolTipText("These classes will be available to choose."); chosenClassPanel.setPreferredSize(new java.awt.Dimension(400, 300)); jScrollPane3.setBorder(null); classJList.setSelectionMode(javax.swing.ListSelectionModel.SINGLE_SELECTION); classJList.setToolTipText("These classes will be available to choose."); classJList.addMouseListener(new java.awt.event.MouseAdapter() { public void mouseClicked(java.awt.event.MouseEvent evt) { classJListMouseClicked(evt); } }); jScrollPane3.setViewportView(classJList); classJList.getAccessibleContext().setAccessibleDescription(""); javax.swing.GroupLayout chosenClassPanelLayout = new javax.swing.GroupLayout(chosenClassPanel); chosenClassPanel.setLayout(chosenClassPanelLayout); chosenClassPanelLayout.setHorizontalGroup( chosenClassPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addComponent(jScrollPane3, javax.swing.GroupLayout.PREFERRED_SIZE, 0, Short.MAX_VALUE) ); chosenClassPanelLayout.setVerticalGroup( chosenClassPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addComponent(jScrollPane3) ); descPanel.setBorder(javax.swing.BorderFactory.createTitledBorder("Class description")); ClassDescSP.setBorder(null); descPane.setEditable(false); descPane.setBorder(null); ClassDescSP.setViewportView(descPane); devlStatusLbl.setHorizontalAlignment(javax.swing.SwingConstants.RIGHT); devlStatusLbl.setText("Development status:"); develStatusTF.setEditable(false); develStatusTF.setBackground(new java.awt.Color(255, 255, 255)); develStatusTF.setToolTipText("Shows DevelopmentStatus of class as annotated with DevelopmentStatus"); develStatusTF.setBorder(null); ClassNameLbl.setHorizontalAlignment(javax.swing.SwingConstants.RIGHT); ClassNameLbl.setText("Full class name:"); ClassNameTF.setEditable(false); ClassNameTF.setBackground(new java.awt.Color(255, 255, 255)); ClassNameTF.setToolTipText("Shows the full classname of a class and hence its location in the jAER project"); ClassNameTF.setBorder(null); javax.swing.GroupLayout descPanelLayout = new javax.swing.GroupLayout(descPanel); descPanel.setLayout(descPanelLayout); descPanelLayout.setHorizontalGroup( descPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(descPanelLayout.createSequentialGroup() .addGap(2, 2, 2) .addGroup(descPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(descPanelLayout.createSequentialGroup() .addComponent(ClassDescSP, javax.swing.GroupLayout.DEFAULT_SIZE, 642, Short.MAX_VALUE) .addGap(2, 2, 2)) .addGroup(descPanelLayout.createSequentialGroup() .addGroup(descPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addComponent(devlStatusLbl) .addComponent(ClassNameLbl, javax.swing.GroupLayout.PREFERRED_SIZE, 100, javax.swing.GroupLayout.PREFERRED_SIZE)) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addGroup(descPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addComponent(ClassNameTF, javax.swing.GroupLayout.DEFAULT_SIZE, 442, Short.MAX_VALUE) .addComponent(develStatusTF, javax.swing.GroupLayout.DEFAULT_SIZE, 442, Short.MAX_VALUE)) .addContainerGap()))) ); descPanelLayout.setVerticalGroup( descPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(descPanelLayout.createSequentialGroup() .addComponent(ClassDescSP, javax.swing.GroupLayout.PREFERRED_SIZE, 34, javax.swing.GroupLayout.PREFERRED_SIZE) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED) .addGroup(descPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE) .addComponent(devlStatusLbl) .addComponent(develStatusTF, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)) .addGap(5, 5, 5) .addGroup(descPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE) .addComponent(ClassNameLbl) .addComponent(ClassNameTF, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))) ); addClassButton.setMnemonic('a'); addClassButton.setText(">"); addClassButton.setToolTipText("Add the filter to the list of available filters"); addClassButton.setMargin(new java.awt.Insets(2, 5, 2, 5)); addClassButton.setMaximumSize(null); addClassButton.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { addClassButtonActionPerformed(evt); } }); removeClassButton.setMnemonic('r'); removeClassButton.setText("<"); removeClassButton.setToolTipText("Remove the filter from the list of selected filters"); removeClassButton.setMargin(new java.awt.Insets(2, 5, 2, 5)); removeClassButton.setMaximumSize(null); removeClassButton.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { removeClassButtonActionPerformed(evt); } }); removeAllButton.setText("<<"); removeAllButton.setToolTipText("Remove all filters from the list of selected filters"); removeAllButton.setMargin(new java.awt.Insets(2, 5, 2, 5)); removeAllButton.setMaximumSize(null); removeAllButton.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { removeAllButtonActionPerformed(evt); } }); moveUpButton.setMnemonic('u'); moveUpButton.setText("Move up"); moveUpButton.setMargin(new java.awt.Insets(2, 5, 2, 5)); moveUpButton.setMaximumSize(null); moveUpButton.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { moveUpButtonActionPerformed(evt); } }); moveDownButton.setMnemonic('d'); moveDownButton.setText("Move down"); moveDownButton.setMargin(new java.awt.Insets(2, 5, 2, 5)); moveDownButton.setMaximumSize(null); moveDownButton.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { moveDownButtonActionPerformed(evt); } }); revertButton.setMnemonic('e'); revertButton.setText("Revert"); revertButton.setToolTipText("Revert changes to the list"); revertButton.setMargin(new java.awt.Insets(2, 5, 2, 5)); revertButton.setMaximumSize(null); revertButton.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { revertButtonActionPerformed(evt); } }); defaultsButton.setMnemonic('d'); defaultsButton.setText("Add Defaults"); defaultsButton.setToolTipText("Adds the defaults to the end of the selected classes list"); defaultsButton.setMargin(new java.awt.Insets(2, 5, 2, 5)); defaultsButton.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { defaultsButtonActionPerformed(evt); } }); javax.swing.GroupLayout jPanel1Layout = new javax.swing.GroupLayout(jPanel1); jPanel1.setLayout(jPanel1Layout); jPanel1Layout.setHorizontalGroup( jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, jPanel1Layout.createSequentialGroup() .addContainerGap() .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addComponent(defaultsButton, javax.swing.GroupLayout.DEFAULT_SIZE, 116, Short.MAX_VALUE) .addComponent(removeClassButton, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE) .addComponent(removeAllButton, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE) .addComponent(moveUpButton, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE) .addComponent(revertButton, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE) .addComponent(moveDownButton, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE) .addComponent(addClassButton, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)) .addContainerGap()) ); jPanel1Layout.setVerticalGroup( jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(jPanel1Layout.createSequentialGroup() .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE) .addComponent(addClassButton, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addComponent(removeClassButton, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addComponent(removeAllButton, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE) .addGap(18, 18, 18) .addComponent(moveUpButton, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addComponent(moveDownButton, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE) .addGap(18, 18, 18) .addComponent(revertButton, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addComponent(defaultsButton)) ); javax.swing.GroupLayout layout = new javax.swing.GroupLayout(this); this.setLayout(layout); layout.setHorizontalGroup( layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup() .addContainerGap() .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING) .addComponent(descPanel, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE) .addGroup(layout.createSequentialGroup() .addComponent(availClassPanel, javax.swing.GroupLayout.PREFERRED_SIZE, 240, javax.swing.GroupLayout.PREFERRED_SIZE) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED) .addComponent(jPanel1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addComponent(chosenClassPanel, javax.swing.GroupLayout.DEFAULT_SIZE, 178, Short.MAX_VALUE)))) ); layout.setVerticalGroup( layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(layout.createSequentialGroup() .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(layout.createSequentialGroup() .addContainerGap() .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addComponent(chosenClassPanel, javax.swing.GroupLayout.DEFAULT_SIZE, 563, Short.MAX_VALUE) .addComponent(availClassPanel, javax.swing.GroupLayout.Alignment.TRAILING, javax.swing.GroupLayout.DEFAULT_SIZE, 563, Short.MAX_VALUE))) .addGroup(layout.createSequentialGroup() .addGap(40, 40, 40) .addComponent(jPanel1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, 135, Short.MAX_VALUE))) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED) .addComponent(descPanel, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE) .addContainerGap()) ); }// </editor-fold>//GEN-END:initComponents private void classJListMouseClicked(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_classJListMouseClicked moveDownButton.setEnabled(true); moveUpButton.setEnabled(true); }//GEN-LAST:event_classJListMouseClicked private void clearFilterButActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_clearFilterButActionPerformed availFilterTextField.setText(""); availClassesListModel.clearFilter(); }//GEN-LAST:event_clearFilterButActionPerformed private void availFilterTextFieldKeyTyped(java.awt.event.KeyEvent evt) {//GEN-FIRST:event_availFilterTextFieldKeyTyped filterAvailable(); }//GEN-LAST:event_availFilterTextFieldKeyTyped private void availFilterTextFieldActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_availFilterTextFieldActionPerformed filterAvailable(); }//GEN-LAST:event_availFilterTextFieldActionPerformed private void filterAvailable() { if (availClassesListModel == null) { return; } String s = availFilterTextField.getText(); availClassesListModel.filter(s); } private void includeDescriptionCBActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_includeDescriptionCBActionPerformed String s = availFilterTextField.getText(); availClassesListModel.filter(s); }//GEN-LAST:event_includeDescriptionCBActionPerformed private void onlyStableCBActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_onlyStableCBActionPerformed if (availClassesListModel == null) { return; // not ready yet } includeExperimentalCB.setEnabled(onlyStableCB.isSelected()); String s = availFilterTextField.getText(); availClassesListModel.filter(s); }//GEN-LAST:event_onlyStableCBActionPerformed private void includeExperimentalCBActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_includeExperimentalCBActionPerformed String s = availFilterTextField.getText(); availClassesListModel.filter(s); }//GEN-LAST:event_includeExperimentalCBActionPerformed private void defaultsButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_defaultsButtonActionPerformed // chosenClassesListModel.clear(); int i = 0; if (defaultClassNames == null) { log.warning("No default classes to add"); return; } for (String s : defaultClassNames) { // add them in reverse order because they were added to the list chosenClassesListModel.insertElementAt(s, i++); // chosenClassesListModel.addElement(s); } }//GEN-LAST:event_defaultsButtonActionPerformed private void revertButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_revertButtonActionPerformed chosenClassesListModel.clear(); for (String s : revertCopy) { chosenClassesListModel.addElement(s); } }//GEN-LAST:event_revertButtonActionPerformed private void moveDownButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_moveDownButtonActionPerformed int last = chosenClassesListModel.getSize() - 1; int index = classJList.getSelectedIndex(); if (index == last) { return; } Object o = chosenClassesListModel.getElementAt(index); chosenClassesListModel.removeElementAt(index); chosenClassesListModel.insertElementAt(o, index + 1); classJList.setSelectedIndex(index + 1); }//GEN-LAST:event_moveDownButtonActionPerformed private void moveUpButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_moveUpButtonActionPerformed int index = classJList.getSelectedIndex(); if (index == 0) { return; } Object o = chosenClassesListModel.getElementAt(index); chosenClassesListModel.removeElementAt(index); chosenClassesListModel.insertElementAt(o, index - 1); classJList.setSelectedIndex(index - 1); }//GEN-LAST:event_moveUpButtonActionPerformed private void removeAllButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_removeAllButtonActionPerformed chosenClassesListModel.clear(); }//GEN-LAST:event_removeAllButtonActionPerformed private void removeClassButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_removeClassButtonActionPerformed int index = classJList.getSelectedIndex(); chosenClassesListModel.removeElementAt(index); int size = chosenClassesListModel.getSize(); if (size == 0) { //Nobody's left, disable firing. removeClassButton.setEnabled(false); } else { //Select an index. if (index == chosenClassesListModel.getSize()) { //removed item in last position index--; } classJList.setSelectedIndex(index); classJList.ensureIndexIsVisible(index); } }//GEN-LAST:event_removeClassButtonActionPerformed private void addClassButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_addClassButtonActionPerformed Object o = availClassJList.getSelectedValue(); if (o == null) { return; } if (containsClass(chosenClassesListModel, o)) { boolean addIt = checkIfAddDuplicate(o); if (!addIt) { return; } } int last = chosenClassesListModel.getSize() - 1; int selectedIdx=classJList.getSelectedIndex(); if(selectedIdx>0) last=selectedIdx; chosenClassesListModel.add(last + 1, o); classJList.setSelectedIndex(last + 1); }//GEN-LAST:event_addClassButtonActionPerformed private void refrreshButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_refrreshButtonActionPerformed populateAvailableClassesListModel(superClass, false); }//GEN-LAST:event_refrreshButtonActionPerformed private boolean checkIfAddDuplicate(Object o) { int retVal = JOptionPane.showOptionDialog(this, "List already contains " + o.toString() + "; add it anyway?", "Confirm addition", JOptionPane.YES_NO_OPTION, JOptionPane.QUESTION_MESSAGE, null, new String[]{"Yes", "No"}, "Yes"); return retVal == JOptionPane.YES_OPTION; } // Variables declaration - do not modify//GEN-BEGIN:variables private javax.swing.JScrollPane ClassDescSP; private javax.swing.JLabel ClassNameLbl; private javax.swing.JTextField ClassNameTF; private javax.swing.JButton addClassButton; private javax.swing.JScrollPane availClassDesciptionPanel; private javax.swing.JList availClassJList; private javax.swing.JPanel availClassPanel; private javax.swing.JTextField availFilterTextField; private javax.swing.JPanel chosenClassPanel; private javax.swing.JList classJList; private javax.swing.JButton clearFilterBut; private javax.swing.JButton defaultsButton; private javax.swing.JTextPane descPane; private javax.swing.JPanel descPanel; private javax.swing.JTextField develStatusTF; private javax.swing.JLabel devlStatusLbl; private javax.swing.JLabel filterLabel; private javax.swing.JCheckBox includeDescriptionCB; private javax.swing.JCheckBox includeExperimentalCB; private javax.swing.JPanel jPanel1; private javax.swing.JScrollPane jScrollPane3; private javax.swing.JButton moveDownButton; private javax.swing.JButton moveUpButton; private javax.swing.JCheckBox onlyStableCB; private javax.swing.JButton refrreshButton; private javax.swing.JButton removeAllButton; private javax.swing.JButton removeClassButton; private javax.swing.JButton revertButton; // End of variables declaration//GEN-END:variables // from http://forum.java.sun.com/thread.jspa?forumID=57&threadID=626866 private static final KeyStroke ENTER = KeyStroke.getKeyStroke(KeyEvent.VK_ENTER, 0); public static void addAction(JList source, Action action) { // Handle enter key InputMap im = source.getInputMap(); im.put(ENTER, ENTER); source.getActionMap().put(ENTER, action); // Handle mouse double click source.addMouseListener(new ActionMouseListener()); } // Implement Mouse Listener static class ActionMouseListener extends MouseAdapter { @Override public void mouseClicked(MouseEvent e) { if (e.getClickCount() == 2) { JList list = (JList) e.getSource(); Action action = list.getActionMap().get(ENTER); if (action != null) { ActionEvent event = new ActionEvent( list, ActionEvent.ACTION_PERFORMED, ""); action.actionPerformed(event); } } } } }
src/net/sf/jaer/util/ClassChooserPanel.java
/* ClassChooserPanel2.java * * Created on May 13, 2007, 3:46 PM */ package net.sf.jaer.util; import java.awt.Color; import java.awt.Component; import java.awt.Cursor; import java.awt.Desktop; import java.awt.event.ActionEvent; import java.awt.event.KeyEvent; import java.awt.event.MouseAdapter; import java.awt.event.MouseEvent; import java.beans.PropertyChangeEvent; import java.beans.PropertyChangeListener; import java.io.IOException; import java.net.URI; import java.util.ArrayList; import java.util.Collections; import java.util.Comparator; import java.util.Enumeration; import java.util.HashMap; import java.util.List; import java.util.Vector; import java.util.logging.Level; import java.util.logging.Logger; import javax.swing.AbstractAction; import javax.swing.Action; import javax.swing.DefaultListModel; import javax.swing.InputMap; import javax.swing.JLabel; import javax.swing.JList; import javax.swing.JOptionPane; import javax.swing.KeyStroke; import javax.swing.ListCellRenderer; import javax.swing.ProgressMonitor; import javax.swing.SwingWorker; import javax.swing.event.HyperlinkEvent; import javax.swing.event.HyperlinkListener; import javax.swing.event.ListDataEvent; import javax.swing.event.ListDataListener; import net.sf.jaer.Description; import net.sf.jaer.DevelopmentStatus; /** * A panel that finds subclasses of a class, displays them in a left list, * displays another list given as a parameter in the right panel, and accepts a * list of default class names. The user can choose which classes and these are * returned by a call to getList. The list of available classes is built in the * background. * * @author tobi */ public class ClassChooserPanel extends javax.swing.JPanel { private static final Logger log = Logger.getLogger("net.sf.jaer.util"); private static final String MISSING_DESCRIPTION_MESSAGE = "<html>No description available - provide one using @Description annotation, as in <pre>@Description(\"Example class\") \n public class MyClass</pre></html>"; private FilterableListModel chosenClassesListModel, availClassesListModel; private ArrayList<ClassNameWithDescriptionAndDevelopmentStatus> availAllList; private ArrayList<String> revertCopy, defaultClassNames; private DescriptionMap descriptionMap = new DescriptionMap(); private Class superClass = null; // the classes available will be subclasses of this class private class ClassDescription { String description = null; DevelopmentStatus.Status developmentStatus = null; public ClassDescription(String description, DevelopmentStatus.Status developmentStatus) { this.description = description; this.developmentStatus = developmentStatus; } } class DescriptionMap extends HashMap<String, ClassDescription> { ClassDescription get(String name) { if (name == null) { return null; } if (super.get(name) == null) { put(name); } return super.get(name); } void put(String name) { if (name == null) { return; } if (containsKey(name)) { return; } try { Class c = Class.forName(name); if (c == null) { log.warning("tried to put class " + name + " but there is no such class"); return; } String descriptionString = null; if (c.isAnnotationPresent(Description.class)) { Description des = (Description) c.getAnnotation(Description.class); descriptionString = des.value(); } DevelopmentStatus.Status devStatus = null; if (c.isAnnotationPresent(DevelopmentStatus.class)) { DevelopmentStatus des = (DevelopmentStatus) c.getAnnotation(DevelopmentStatus.class); devStatus = des.value(); } ClassDescription des = new ClassDescription(descriptionString, devStatus); put(name, des); } catch (Exception e) { log.warning("trying to put class named " + name + " caught " + e.toString()); } } } private class AddAction extends AbstractAction { @Override public void actionPerformed(ActionEvent e) { Object o = availClassJList.getSelectedValue(); if (o == null) { return; } if (containsClass(chosenClassesListModel, o)) { boolean addIt = checkIfAddDuplicate(o); if (!addIt) { return; } } int last = chosenClassesListModel.getSize() - 1; chosenClassesListModel.add(last + 1, o); classJList.setSelectedIndex(last + 1); } }; /** * Creates new form ClassChooserPanel * * @param superClass a Class that will be used to search the classpath for * subclasses of subClassOf. * @param classNames a list of names, which is filled in by the actions of * the user with the chosen classes * @param defaultClassNames the list on the right is replaced by this list * if the user pushes the Defaults button. */ public ClassChooserPanel(final Class superClass, ArrayList<String> classNames, ArrayList<String> defaultClassNames) { initComponents(); this.superClass = superClass; includeExperimentalCB.setEnabled(onlyStableCB.isSelected()); availFilterTextField.requestFocusInWindow(); this.defaultClassNames = defaultClassNames; final DefaultListModel tmpList = new DefaultListModel(); tmpList.addElement("scanning..."); availClassJList.setModel(tmpList); try { availAllList = new ArrayList<ClassNameWithDescriptionAndDevelopmentStatus>(); availClassesListModel = new FilterableListModel(availAllList); availClassJList.setModel(availClassesListModel); availClassJList.setCellRenderer(new MyCellRenderer()); addAction(availClassJList, new AddAction()); filterAvailable(); // user typed while list is populated availClassesListModel.addListDataListener(new ListDataListener() { @Override public void intervalAdded(ListDataEvent lde) { filterAvailable(); } @Override public void intervalRemoved(ListDataEvent lde) { } @Override public void contentsChanged(ListDataEvent lde) { } }); } catch (Exception ex) { Logger.getLogger(ClassChooserPanel.class.getName()).log(Level.SEVERE, null, ex); } finally { setCursor(Cursor.getDefaultCursor()); } Action removeAction = new AbstractAction() { @Override public void actionPerformed(final ActionEvent e) { int index = classJList.getSelectedIndex(); chosenClassesListModel.removeElementAt(index); int size = chosenClassesListModel.getSize(); if (size == 0) { //Nobody's left, disable firing. removeClassButton.setEnabled(false); } else { //Select an index. if (index == chosenClassesListModel.getSize()) { //removed item in last position index--; } classJList.setSelectedIndex(index); classJList.ensureIndexIsVisible(index); } } }; addAction(classJList, removeAction); populateAvailableClassesListModel(superClass, true); revertCopy = new ArrayList<>(classNames); chosenClassesListModel = new FilterableListModel(classNames); classJList.setModel(chosenClassesListModel); classJList.setCellRenderer(new MyCellRenderer()); descPane.addHyperlinkListener(new HyperlinkListener() { @Override public void hyperlinkUpdate(HyperlinkEvent event) { if (event.getEventType() == HyperlinkEvent.EventType.ACTIVATED) { String url = event.getURL().toString(); try { Desktop.getDesktop().browse(URI.create(url)); } catch (IOException ex) { Logger.getLogger(ClassChooserPanel.class.getName()).log(Level.SEVERE, null, ex); } } } }); } private void populateAvailableClassesListModel(final Class subclassOf, boolean useCache) { final ProgressMonitor progressMonitor = new ProgressMonitor(this, "Finding classes", "", 0, 100); progressMonitor.setMillisToPopup(10); final SubclassFinder.SubclassFinderWorker worker = new SubclassFinder.SubclassFinderWorker(subclassOf, availClassesListModel, useCache); worker.addPropertyChangeListener(new PropertyChangeListener() { @Override public void propertyChange(PropertyChangeEvent evt) { // System.out.println(evt.getPropertyName() + " " + evt.getNewValue()); if ("progress" == evt.getPropertyName()) { int progress = (Integer) evt.getNewValue(); progressMonitor.setProgress(progress); String message = String.format("Completed %d%%.\n", progress); progressMonitor.setNote(message); if (progressMonitor.isCanceled() || worker.isDone()) { if (progressMonitor.isCanceled()) { worker.cancel(true); } } } if ((evt != null) && evt.getNewValue().equals(SwingWorker.StateValue.DONE)) { try { availAllList = worker.get(); if (availAllList == null) { log.warning("got empty list of classes - something wrong here, aborting dialog"); return; } Collections.sort(availAllList, new ClassNameSorter()); availClassesListModel = new FilterableListModel(availAllList); availClassJList.setModel(availClassesListModel); availClassJList.setCellRenderer(new MyCellRenderer()); addAction(availClassJList, new AddAction()); filterAvailable(); } catch (Exception ex) { Logger.getLogger(ClassChooserPanel.class.getName()).log(Level.SEVERE, null, ex); } finally { setCursor(Cursor.getDefaultCursor()); } } } }); setCursor(Cursor.getPredefinedCursor(Cursor.WAIT_CURSOR)); worker.execute(); } private boolean containsClass(FilterableListModel model, Object obj) { for (Object o : model.toArray()) { if (o instanceof String && ((String) o) .equals(((ClassNameWithDescriptionAndDevelopmentStatus) obj).getClassName())) { return true; } else if (o instanceof ClassNameWithDescriptionAndDevelopmentStatus && ((ClassNameWithDescriptionAndDevelopmentStatus) o).getClassName() .equals(((ClassNameWithDescriptionAndDevelopmentStatus) obj).getClassName())) { return true; } } return false; } private class ClassNameSorter implements Comparator { @Override public int compare(Object o1, Object o2) { if ((o1 instanceof ClassNameWithDescriptionAndDevelopmentStatus) && (o2 instanceof ClassNameWithDescriptionAndDevelopmentStatus)) { ClassNameWithDescriptionAndDevelopmentStatus c1 = (ClassNameWithDescriptionAndDevelopmentStatus) o1; ClassNameWithDescriptionAndDevelopmentStatus c2 = (ClassNameWithDescriptionAndDevelopmentStatus) o2; return shortName(c1.getClassName()).compareTo(shortName(c2.getClassName())); } else { return -1; } } } private DevelopmentStatus.Status getClassDevelopmentStatus(String className) { ClassDescription des = descriptionMap.get(className); if (des == null) { return null; } return des.developmentStatus; } private String getClassDescription(String className) { ClassDescription des = descriptionMap.get(className); if (des == null) { return null; } return des.description; } private class MyCellRenderer extends JLabel implements ListCellRenderer { // This is the only method defined by ListCellRenderer. // We just reconfigure the JLabel each time we're called. /** * @param list The JList we're painting. * @param value The value returned by * list.getModel().getElementAt(index). * @param index The cells index. * @param isSelected True if the specified cell was selected. * @param cellHasFocus True if the specified cell has the focus. */ @Override public Component getListCellRendererComponent(JList list, Object obj, int index, boolean isSelected, boolean cellHasFocus) { String fullclassname = obj.toString(); String shortname = shortName(fullclassname);//.substring(fullclassname.lastIndexOf('.') + 1); setText(shortname); Color foreground, background; if (isSelected) { background = list.getSelectionBackground(); DevelopmentStatus.Status develStatus = getClassDevelopmentStatus(fullclassname); String des = getClassDescription(fullclassname); ClassNameTF.setText(fullclassname); if (develStatus == DevelopmentStatus.Status.Experimental) { foreground = Color.BLACK; develStatusTF.setText(develStatus.toString()); } else if (develStatus == DevelopmentStatus.Status.InDevelopment) { foreground = Color.BLACK; develStatusTF.setText(develStatus.toString()); } else if (develStatus == DevelopmentStatus.Status.Stable) { foreground = Color. BLACK; develStatusTF.setText(develStatus.toString()); } else { foreground = Color.BLACK; develStatusTF.setText("unknown"); } if (des != null) { if (des.startsWith("<html>")) { setToolTipText(des); } else { setToolTipText(fullclassname + ": " + des); } descPane.setContentType("text/html"); descPane.setText("<html>" + shortname + ": " + des); } else { foreground = Color.GRAY; setToolTipText(fullclassname); descPane.setText(MISSING_DESCRIPTION_MESSAGE); } } else { background = list.getBackground(); DevelopmentStatus.Status develStatus = getClassDevelopmentStatus(fullclassname); if (develStatus == DevelopmentStatus.Status.Experimental) { foreground = Color.ORANGE.darker(); } else if (develStatus == DevelopmentStatus.Status.InDevelopment) { foreground = Color.DARK_GRAY; } else if (develStatus == DevelopmentStatus.Status.Stable) { foreground = Color.BLUE; } else { foreground = Color.GRAY; } if (getClassDescription(fullclassname) == null) { foreground = Color.LIGHT_GRAY; } } setEnabled(list.isEnabled()); setOpaque(true); setForeground(foreground); setBackground(background); return this; } } private String shortName(String s) { if (s == null) { return "null"; } int i = s.lastIndexOf('.'); if ((i < 0) || (i == (s.length() - 1))) { return s; } return s.substring(i + 1); } // extends DefaultListModel to add a text filter public class FilterableListModel<ClassNameWithDescriptionAndDevelopmentStatus> extends DefaultListModel<ClassNameWithDescriptionAndDevelopmentStatus> { Vector<ClassNameWithDescriptionAndDevelopmentStatus> origList = new Vector(); String filterString = null; FilterableListModel(List<ClassNameWithDescriptionAndDevelopmentStatus> list) { super(); for (ClassNameWithDescriptionAndDevelopmentStatus s : list) { this.addElement(s); } origList.addAll(list); } synchronized void resetList() { clear(); for (ClassNameWithDescriptionAndDevelopmentStatus o : origList) { addElement(o); } } synchronized void filter(String s) { boolean onlyStable = onlyStableCB.isSelected(); if (((s == null) || s.equals("")) && !onlyStable) { resetList(); return; } boolean passAllStable = false; if (onlyStable && ((s == null) || s.equals(""))) { passAllStable = true; // pass all stable filters } boolean includeExperimental = includeExperimentalCB.isSelected(); filterString = s.toLowerCase(); resetList(); Vector v = new Vector(); // list to prune out // must build a list of stuff to prune, then prune Enumeration en = elements(); while (en.hasMoreElements()) { // add all elements that should be filtered out Object o = en.nextElement(); net.sf.jaer.util.ClassNameWithDescriptionAndDevelopmentStatus cn; cn = (net.sf.jaer.util.ClassNameWithDescriptionAndDevelopmentStatus) o; String str = null; boolean isStable = false; DevelopmentStatus ds = cn.getDevelopmentStatus(); if (ds != null && (ds.value().equals(DevelopmentStatus.Status.Stable) || (includeExperimental && ds.value().equals(DevelopmentStatus.Status.Experimental)))) { isStable = true; // this class is stable } if (passAllStable) { if (!isStable) { v.add(o); // filter out this class because it not stable and we are passing all stable filters only } } else { // add (filter out) depending on if strings don't match or if !isStable and onlyStable is true if (onlyStable && !isStable) { v.add(o); continue; } if (includeDescriptionCB.isSelected()) { str = (cn.toString() + cn.getDescription()).toLowerCase(); } else { str = cn.toString(); } int ind = str.indexOf(filterString); if (ind == -1 || (!isStable && onlyStable)) { v.add(o); } } } // prune list for (Object o : v) { removeElement(o); } } synchronized void clearFilter() { filter(null); } } public FilterableListModel getChosenClassesListModel() { return chosenClassesListModel; } /** * This method is called from within the constructor to initialize the form. * WARNING: Do NOT modify this code. The content of this method is always * regenerated by the Form Editor. */ // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents private void initComponents() { availClassPanel = new javax.swing.JPanel(); availClassDesciptionPanel = new javax.swing.JScrollPane(); availClassJList = new javax.swing.JList(); onlyStableCB = new javax.swing.JCheckBox(); includeExperimentalCB = new javax.swing.JCheckBox(); filterLabel = new javax.swing.JLabel(); availFilterTextField = new javax.swing.JTextField(); clearFilterBut = new javax.swing.JButton(); includeDescriptionCB = new javax.swing.JCheckBox(); refrreshButton = new javax.swing.JButton(); chosenClassPanel = new javax.swing.JPanel(); jScrollPane3 = new javax.swing.JScrollPane(); classJList = new javax.swing.JList(); descPanel = new javax.swing.JPanel(); ClassDescSP = new javax.swing.JScrollPane(); descPane = new javax.swing.JTextPane(); devlStatusLbl = new javax.swing.JLabel(); develStatusTF = new javax.swing.JTextField(); ClassNameLbl = new javax.swing.JLabel(); ClassNameTF = new javax.swing.JTextField(); jPanel1 = new javax.swing.JPanel(); addClassButton = new javax.swing.JButton(); removeClassButton = new javax.swing.JButton(); removeAllButton = new javax.swing.JButton(); moveUpButton = new javax.swing.JButton(); moveDownButton = new javax.swing.JButton(); revertButton = new javax.swing.JButton(); defaultsButton = new javax.swing.JButton(); setPreferredSize(new java.awt.Dimension(580, 686)); availClassPanel.setBorder(javax.swing.BorderFactory.createTitledBorder("Available classes")); availClassPanel.setToolTipText("<html>If your class doesn't show up here, rebuild the project to get it into jAER.jar (or some other jar on the classpath). <p> Yyour class must be concrete (not abstract). <p> Finally, if your class lives in a separate JAR archive, make sure your archive classpath is not on the excluded list in the class ListClasses."); availClassPanel.setPreferredSize(new java.awt.Dimension(400, 300)); availClassDesciptionPanel.setBorder(null); availClassJList.setToolTipText("If your class doesn't show up here, rebuild the project to get it into jAER.jar (or some other jar on the classpath) and hit the Refresh button to rescan classpath."); availClassDesciptionPanel.setViewportView(availClassJList); availClassJList.getAccessibleContext().setAccessibleDescription(""); onlyStableCB.setText("Only Stable"); onlyStableCB.setToolTipText("Show only items with DevelopmentStatus.Stable"); onlyStableCB.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { onlyStableCBActionPerformed(evt); } }); includeExperimentalCB.setText("Include Experimental"); includeExperimentalCB.setToolTipText("Include Experimental classes in search results"); includeExperimentalCB.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { includeExperimentalCBActionPerformed(evt); } }); filterLabel.setText("Filter"); availFilterTextField.setToolTipText("type any part of your filter name or description here to filter list"); availFilterTextField.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { availFilterTextFieldActionPerformed(evt); } }); availFilterTextField.addKeyListener(new java.awt.event.KeyAdapter() { public void keyTyped(java.awt.event.KeyEvent evt) { availFilterTextFieldKeyTyped(evt); } }); clearFilterBut.setText("X"); clearFilterBut.setIconTextGap(0); clearFilterBut.setMargin(new java.awt.Insets(2, 1, 1, 2)); clearFilterBut.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { clearFilterButActionPerformed(evt); } }); includeDescriptionCB.setSelected(true); includeDescriptionCB.setText("Include descriptions"); includeDescriptionCB.setToolTipText("Include class Descriptions in filter results"); includeDescriptionCB.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { includeDescriptionCBActionPerformed(evt); } }); refrreshButton.setText("Refresh list"); refrreshButton.setToolTipText("<html> <p>Scans entire classpath for possible classes</p><p>(needs to be refreshed if new classes are added)</p>"); refrreshButton.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { refrreshButtonActionPerformed(evt); } }); javax.swing.GroupLayout availClassPanelLayout = new javax.swing.GroupLayout(availClassPanel); availClassPanel.setLayout(availClassPanelLayout); availClassPanelLayout.setHorizontalGroup( availClassPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(availClassPanelLayout.createSequentialGroup() .addContainerGap() .addGroup(availClassPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addComponent(availClassDesciptionPanel, javax.swing.GroupLayout.PREFERRED_SIZE, 222, javax.swing.GroupLayout.PREFERRED_SIZE) .addComponent(includeExperimentalCB) .addGroup(availClassPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING, false) .addGroup(availClassPanelLayout.createSequentialGroup() .addComponent(onlyStableCB) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE) .addComponent(includeDescriptionCB)) .addGroup(availClassPanelLayout.createSequentialGroup() .addComponent(filterLabel) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addComponent(availFilterTextField, javax.swing.GroupLayout.PREFERRED_SIZE, 116, javax.swing.GroupLayout.PREFERRED_SIZE) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addComponent(clearFilterBut) .addGap(44, 44, 44))))) .addComponent(refrreshButton) ); availClassPanelLayout.setVerticalGroup( availClassPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, availClassPanelLayout.createSequentialGroup() .addComponent(refrreshButton) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addGroup(availClassPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE) .addComponent(filterLabel) .addComponent(availFilterTextField, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE) .addComponent(clearFilterBut)) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED) .addGroup(availClassPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE) .addComponent(onlyStableCB) .addComponent(includeDescriptionCB)) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addComponent(includeExperimentalCB) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED) .addComponent(availClassDesciptionPanel) .addContainerGap()) ); chosenClassPanel.setBorder(javax.swing.BorderFactory.createTitledBorder("Selected classes")); chosenClassPanel.setToolTipText("These classes will be available to choose."); chosenClassPanel.setPreferredSize(new java.awt.Dimension(400, 300)); jScrollPane3.setBorder(null); classJList.setSelectionMode(javax.swing.ListSelectionModel.SINGLE_SELECTION); classJList.setToolTipText("These classes will be available to choose."); classJList.addMouseListener(new java.awt.event.MouseAdapter() { public void mouseClicked(java.awt.event.MouseEvent evt) { classJListMouseClicked(evt); } }); jScrollPane3.setViewportView(classJList); classJList.getAccessibleContext().setAccessibleDescription(""); javax.swing.GroupLayout chosenClassPanelLayout = new javax.swing.GroupLayout(chosenClassPanel); chosenClassPanel.setLayout(chosenClassPanelLayout); chosenClassPanelLayout.setHorizontalGroup( chosenClassPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addComponent(jScrollPane3, javax.swing.GroupLayout.PREFERRED_SIZE, 0, Short.MAX_VALUE) ); chosenClassPanelLayout.setVerticalGroup( chosenClassPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addComponent(jScrollPane3) ); descPanel.setBorder(javax.swing.BorderFactory.createTitledBorder("Class description")); ClassDescSP.setBorder(null); descPane.setEditable(false); descPane.setBorder(null); ClassDescSP.setViewportView(descPane); devlStatusLbl.setHorizontalAlignment(javax.swing.SwingConstants.RIGHT); devlStatusLbl.setText("Development status:"); develStatusTF.setEditable(false); develStatusTF.setBackground(new java.awt.Color(255, 255, 255)); develStatusTF.setToolTipText("Shows DevelopmentStatus of class as annotated with DevelopmentStatus"); develStatusTF.setBorder(null); ClassNameLbl.setHorizontalAlignment(javax.swing.SwingConstants.RIGHT); ClassNameLbl.setText("Full class name:"); ClassNameTF.setEditable(false); ClassNameTF.setBackground(new java.awt.Color(255, 255, 255)); ClassNameTF.setToolTipText("Shows the full classname of a class and hence its location in the jAER project"); ClassNameTF.setBorder(null); javax.swing.GroupLayout descPanelLayout = new javax.swing.GroupLayout(descPanel); descPanel.setLayout(descPanelLayout); descPanelLayout.setHorizontalGroup( descPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(descPanelLayout.createSequentialGroup() .addGap(2, 2, 2) .addGroup(descPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(descPanelLayout.createSequentialGroup() .addComponent(ClassDescSP, javax.swing.GroupLayout.DEFAULT_SIZE, 642, Short.MAX_VALUE) .addGap(2, 2, 2)) .addGroup(descPanelLayout.createSequentialGroup() .addGroup(descPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addComponent(devlStatusLbl) .addComponent(ClassNameLbl, javax.swing.GroupLayout.PREFERRED_SIZE, 100, javax.swing.GroupLayout.PREFERRED_SIZE)) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addGroup(descPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addComponent(ClassNameTF, javax.swing.GroupLayout.DEFAULT_SIZE, 442, Short.MAX_VALUE) .addComponent(develStatusTF, javax.swing.GroupLayout.DEFAULT_SIZE, 442, Short.MAX_VALUE)) .addContainerGap()))) ); descPanelLayout.setVerticalGroup( descPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(descPanelLayout.createSequentialGroup() .addComponent(ClassDescSP, javax.swing.GroupLayout.PREFERRED_SIZE, 34, javax.swing.GroupLayout.PREFERRED_SIZE) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED) .addGroup(descPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE) .addComponent(devlStatusLbl) .addComponent(develStatusTF, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)) .addGap(5, 5, 5) .addGroup(descPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE) .addComponent(ClassNameLbl) .addComponent(ClassNameTF, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))) ); addClassButton.setMnemonic('a'); addClassButton.setText(">"); addClassButton.setToolTipText("Add the filter to the list of available filters"); addClassButton.setMargin(new java.awt.Insets(2, 5, 2, 5)); addClassButton.setMaximumSize(null); addClassButton.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { addClassButtonActionPerformed(evt); } }); removeClassButton.setMnemonic('r'); removeClassButton.setText("<"); removeClassButton.setToolTipText("Remove the filter from the list of selected filters"); removeClassButton.setMargin(new java.awt.Insets(2, 5, 2, 5)); removeClassButton.setMaximumSize(null); removeClassButton.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { removeClassButtonActionPerformed(evt); } }); removeAllButton.setText("<<"); removeAllButton.setToolTipText("Remove all filters from the list of selected filters"); removeAllButton.setMargin(new java.awt.Insets(2, 5, 2, 5)); removeAllButton.setMaximumSize(null); removeAllButton.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { removeAllButtonActionPerformed(evt); } }); moveUpButton.setMnemonic('u'); moveUpButton.setText("Move up"); moveUpButton.setMargin(new java.awt.Insets(2, 5, 2, 5)); moveUpButton.setMaximumSize(null); moveUpButton.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { moveUpButtonActionPerformed(evt); } }); moveDownButton.setMnemonic('d'); moveDownButton.setText("Move down"); moveDownButton.setMargin(new java.awt.Insets(2, 5, 2, 5)); moveDownButton.setMaximumSize(null); moveDownButton.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { moveDownButtonActionPerformed(evt); } }); revertButton.setMnemonic('e'); revertButton.setText("Revert"); revertButton.setToolTipText("Revert changes to the list"); revertButton.setMargin(new java.awt.Insets(2, 5, 2, 5)); revertButton.setMaximumSize(null); revertButton.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { revertButtonActionPerformed(evt); } }); defaultsButton.setMnemonic('d'); defaultsButton.setText("Add Defaults"); defaultsButton.setToolTipText("Adds the defaults to the end of the selected classes list"); defaultsButton.setMargin(new java.awt.Insets(2, 5, 2, 5)); defaultsButton.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { defaultsButtonActionPerformed(evt); } }); javax.swing.GroupLayout jPanel1Layout = new javax.swing.GroupLayout(jPanel1); jPanel1.setLayout(jPanel1Layout); jPanel1Layout.setHorizontalGroup( jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, jPanel1Layout.createSequentialGroup() .addContainerGap() .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addComponent(defaultsButton, javax.swing.GroupLayout.DEFAULT_SIZE, 116, Short.MAX_VALUE) .addComponent(removeClassButton, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE) .addComponent(removeAllButton, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE) .addComponent(moveUpButton, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE) .addComponent(revertButton, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE) .addComponent(moveDownButton, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE) .addComponent(addClassButton, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)) .addContainerGap()) ); jPanel1Layout.setVerticalGroup( jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(jPanel1Layout.createSequentialGroup() .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE) .addComponent(addClassButton, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addComponent(removeClassButton, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addComponent(removeAllButton, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE) .addGap(18, 18, 18) .addComponent(moveUpButton, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addComponent(moveDownButton, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE) .addGap(18, 18, 18) .addComponent(revertButton, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addComponent(defaultsButton)) ); javax.swing.GroupLayout layout = new javax.swing.GroupLayout(this); this.setLayout(layout); layout.setHorizontalGroup( layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup() .addContainerGap() .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING) .addComponent(descPanel, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE) .addGroup(layout.createSequentialGroup() .addComponent(availClassPanel, javax.swing.GroupLayout.PREFERRED_SIZE, 240, javax.swing.GroupLayout.PREFERRED_SIZE) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED) .addComponent(jPanel1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addComponent(chosenClassPanel, javax.swing.GroupLayout.DEFAULT_SIZE, 178, Short.MAX_VALUE)))) ); layout.setVerticalGroup( layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(layout.createSequentialGroup() .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(layout.createSequentialGroup() .addContainerGap() .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addComponent(chosenClassPanel, javax.swing.GroupLayout.DEFAULT_SIZE, 563, Short.MAX_VALUE) .addComponent(availClassPanel, javax.swing.GroupLayout.Alignment.TRAILING, javax.swing.GroupLayout.DEFAULT_SIZE, 563, Short.MAX_VALUE))) .addGroup(layout.createSequentialGroup() .addGap(40, 40, 40) .addComponent(jPanel1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, 135, Short.MAX_VALUE))) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED) .addComponent(descPanel, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE) .addContainerGap()) ); }// </editor-fold>//GEN-END:initComponents private void classJListMouseClicked(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_classJListMouseClicked moveDownButton.setEnabled(true); moveUpButton.setEnabled(true); }//GEN-LAST:event_classJListMouseClicked private void clearFilterButActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_clearFilterButActionPerformed availFilterTextField.setText(""); availClassesListModel.clearFilter(); }//GEN-LAST:event_clearFilterButActionPerformed private void availFilterTextFieldKeyTyped(java.awt.event.KeyEvent evt) {//GEN-FIRST:event_availFilterTextFieldKeyTyped filterAvailable(); }//GEN-LAST:event_availFilterTextFieldKeyTyped private void availFilterTextFieldActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_availFilterTextFieldActionPerformed filterAvailable(); }//GEN-LAST:event_availFilterTextFieldActionPerformed private void filterAvailable() { if (availClassesListModel == null) { return; } String s = availFilterTextField.getText(); availClassesListModel.filter(s); } private void includeDescriptionCBActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_includeDescriptionCBActionPerformed String s = availFilterTextField.getText(); availClassesListModel.filter(s); }//GEN-LAST:event_includeDescriptionCBActionPerformed private void onlyStableCBActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_onlyStableCBActionPerformed if (availClassesListModel == null) { return; // not ready yet } includeExperimentalCB.setEnabled(onlyStableCB.isSelected()); String s = availFilterTextField.getText(); availClassesListModel.filter(s); }//GEN-LAST:event_onlyStableCBActionPerformed private void includeExperimentalCBActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_includeExperimentalCBActionPerformed String s = availFilterTextField.getText(); availClassesListModel.filter(s); }//GEN-LAST:event_includeExperimentalCBActionPerformed private void defaultsButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_defaultsButtonActionPerformed // chosenClassesListModel.clear(); int i = 0; if (defaultClassNames == null) { log.warning("No default classes to add"); return; } for (String s : defaultClassNames) { // add them in reverse order because they were added to the list chosenClassesListModel.insertElementAt(s, i++); // chosenClassesListModel.addElement(s); } }//GEN-LAST:event_defaultsButtonActionPerformed private void revertButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_revertButtonActionPerformed chosenClassesListModel.clear(); for (String s : revertCopy) { chosenClassesListModel.addElement(s); } }//GEN-LAST:event_revertButtonActionPerformed private void moveDownButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_moveDownButtonActionPerformed int last = chosenClassesListModel.getSize() - 1; int index = classJList.getSelectedIndex(); if (index == last) { return; } Object o = chosenClassesListModel.getElementAt(index); chosenClassesListModel.removeElementAt(index); chosenClassesListModel.insertElementAt(o, index + 1); classJList.setSelectedIndex(index + 1); }//GEN-LAST:event_moveDownButtonActionPerformed private void moveUpButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_moveUpButtonActionPerformed int index = classJList.getSelectedIndex(); if (index == 0) { return; } Object o = chosenClassesListModel.getElementAt(index); chosenClassesListModel.removeElementAt(index); chosenClassesListModel.insertElementAt(o, index - 1); classJList.setSelectedIndex(index - 1); }//GEN-LAST:event_moveUpButtonActionPerformed private void removeAllButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_removeAllButtonActionPerformed chosenClassesListModel.clear(); }//GEN-LAST:event_removeAllButtonActionPerformed private void removeClassButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_removeClassButtonActionPerformed int index = classJList.getSelectedIndex(); chosenClassesListModel.removeElementAt(index); int size = chosenClassesListModel.getSize(); if (size == 0) { //Nobody's left, disable firing. removeClassButton.setEnabled(false); } else { //Select an index. if (index == chosenClassesListModel.getSize()) { //removed item in last position index--; } classJList.setSelectedIndex(index); classJList.ensureIndexIsVisible(index); } }//GEN-LAST:event_removeClassButtonActionPerformed private void addClassButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_addClassButtonActionPerformed Object o = availClassJList.getSelectedValue(); if (o == null) { return; } if (containsClass(chosenClassesListModel, o)) { boolean addIt = checkIfAddDuplicate(o); if (!addIt) { return; } } int last = chosenClassesListModel.getSize() - 1; chosenClassesListModel.add(last + 1, o); classJList.setSelectedIndex(last + 1); }//GEN-LAST:event_addClassButtonActionPerformed private void refrreshButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_refrreshButtonActionPerformed populateAvailableClassesListModel(superClass, false); }//GEN-LAST:event_refrreshButtonActionPerformed private boolean checkIfAddDuplicate(Object o) { int retVal = JOptionPane.showOptionDialog(this, "List already contains " + o.toString() + "; add it anyway?", "Confirm addition", JOptionPane.YES_NO_OPTION, JOptionPane.QUESTION_MESSAGE, null, new String[]{"Yes", "No"}, "Yes"); return retVal == JOptionPane.YES_OPTION; } // Variables declaration - do not modify//GEN-BEGIN:variables private javax.swing.JScrollPane ClassDescSP; private javax.swing.JLabel ClassNameLbl; private javax.swing.JTextField ClassNameTF; private javax.swing.JButton addClassButton; private javax.swing.JScrollPane availClassDesciptionPanel; private javax.swing.JList availClassJList; private javax.swing.JPanel availClassPanel; private javax.swing.JTextField availFilterTextField; private javax.swing.JPanel chosenClassPanel; private javax.swing.JList classJList; private javax.swing.JButton clearFilterBut; private javax.swing.JButton defaultsButton; private javax.swing.JTextPane descPane; private javax.swing.JPanel descPanel; private javax.swing.JTextField develStatusTF; private javax.swing.JLabel devlStatusLbl; private javax.swing.JLabel filterLabel; private javax.swing.JCheckBox includeDescriptionCB; private javax.swing.JCheckBox includeExperimentalCB; private javax.swing.JPanel jPanel1; private javax.swing.JScrollPane jScrollPane3; private javax.swing.JButton moveDownButton; private javax.swing.JButton moveUpButton; private javax.swing.JCheckBox onlyStableCB; private javax.swing.JButton refrreshButton; private javax.swing.JButton removeAllButton; private javax.swing.JButton removeClassButton; private javax.swing.JButton revertButton; // End of variables declaration//GEN-END:variables // from http://forum.java.sun.com/thread.jspa?forumID=57&threadID=626866 private static final KeyStroke ENTER = KeyStroke.getKeyStroke(KeyEvent.VK_ENTER, 0); public static void addAction(JList source, Action action) { // Handle enter key InputMap im = source.getInputMap(); im.put(ENTER, ENTER); source.getActionMap().put(ENTER, action); // Handle mouse double click source.addMouseListener(new ActionMouseListener()); } // Implement Mouse Listener static class ActionMouseListener extends MouseAdapter { @Override public void mouseClicked(MouseEvent e) { if (e.getClickCount() == 2) { JList list = (JList) e.getSource(); Action action = list.getActionMap().get(ENTER); if (action != null) { ActionEvent event = new ActionEvent( list, ActionEvent.ACTION_PERFORMED, ""); action.actionPerformed(event); } } } } }
fixed annoying bug where double clicking selected items adds it twice, triggering the warning. Now if you use arrow the item is added after a particular selected class too.
src/net/sf/jaer/util/ClassChooserPanel.java
fixed annoying bug where double clicking selected items adds it twice, triggering the warning. Now if you use arrow the item is added after a particular selected class too.
<ide><path>rc/net/sf/jaer/util/ClassChooserPanel.java <ide> availClassJList.setModel(availClassesListModel); <ide> availClassJList.setCellRenderer(new MyCellRenderer()); <ide> <del> addAction(availClassJList, new AddAction()); <add>// addAction(availClassJList, new AddAction()); <ide> filterAvailable(); // user typed while list is populated <ide> availClassesListModel.addListDataListener(new ListDataListener() { <ide> @Override <ide> } <ide> } <ide> int last = chosenClassesListModel.getSize() - 1; <add> int selectedIdx=classJList.getSelectedIndex(); <add> if(selectedIdx>0) last=selectedIdx; <ide> chosenClassesListModel.add(last + 1, o); <ide> classJList.setSelectedIndex(last + 1); <ide> }//GEN-LAST:event_addClassButtonActionPerformed
Java
mit
508158fd89c6e574b8b10ea9b09aaa30f2e0755e
0
JCThePants/ArborianQuests,JCThePants/ArborianQuests
/* * This file is part of ArborianQuests for Bukkit, licensed under the MIT License (MIT). * * Copyright (c) JCThePants (www.jcwhatever.com) * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ package com.jcwhatever.arborianquests.commands.admin.items; import com.jcwhatever.arborianquests.ArborianQuests; import com.jcwhatever.arborianquests.Lang; import com.jcwhatever.arborianquests.items.ScriptItem; import com.jcwhatever.nucleus.commands.AbstractCommand; import com.jcwhatever.nucleus.commands.CommandInfo; import com.jcwhatever.nucleus.commands.arguments.CommandArguments; import com.jcwhatever.nucleus.commands.exceptions.InvalidArgumentException; import com.jcwhatever.nucleus.messaging.ChatPaginator; import com.jcwhatever.nucleus.utils.items.ItemStackUtils; import com.jcwhatever.nucleus.utils.items.serializer.ItemStackSerializer.SerializerOutputType; import com.jcwhatever.nucleus.utils.language.Localizable; import com.jcwhatever.nucleus.utils.text.TextUtils.FormatTemplate; import org.bukkit.command.CommandSender; import java.util.Collection; @CommandInfo( parent="items", command = "list", staticParams = { "page=1" }, floatingParams = { "search="}, description = "List all quest items.", paramDescriptions = { "page= {PAGE}", "search= Optional. Use to show items that contain the specified search text." }) public class ListSubCommand extends AbstractCommand { @Localizable static final String _PAGINATOR_TITLE = "Quest Items"; @Override public void execute (CommandSender sender, CommandArguments args) throws InvalidArgumentException { int page = args.getInteger("page"); ChatPaginator pagin = createPagin(Lang.get(_PAGINATOR_TITLE)); Collection<ScriptItem> items = ArborianQuests.getScriptItemManager().getAll(); for (ScriptItem item : items) { pagin.add(item.getName(), ItemStackUtils.serialize(item.getItem(), SerializerOutputType.COLOR)); } if (!args.isDefaultValue("search")) pagin.setSearchTerm(args.getString("search")); pagin.show(sender, page, FormatTemplate.LIST_ITEM_DESCRIPTION); } }
src/com/jcwhatever/arborianquests/commands/admin/items/ListSubCommand.java
/* * This file is part of ArborianQuests for Bukkit, licensed under the MIT License (MIT). * * Copyright (c) JCThePants (www.jcwhatever.com) * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ package com.jcwhatever.arborianquests.commands.admin.items; import com.jcwhatever.arborianquests.ArborianQuests; import com.jcwhatever.arborianquests.Lang; import com.jcwhatever.arborianquests.items.ScriptItem; import com.jcwhatever.nucleus.commands.AbstractCommand; import com.jcwhatever.nucleus.commands.CommandInfo; import com.jcwhatever.nucleus.commands.arguments.CommandArguments; import com.jcwhatever.nucleus.commands.exceptions.InvalidArgumentException; import com.jcwhatever.nucleus.messaging.ChatPaginator; import com.jcwhatever.nucleus.utils.items.ItemStackUtils; import com.jcwhatever.nucleus.utils.items.serializer.ItemStackSerializer.SerializerOutputType; import com.jcwhatever.nucleus.utils.language.Localizable; import com.jcwhatever.nucleus.utils.text.TextUtils.FormatTemplate; import org.bukkit.command.CommandSender; import java.util.Collection; @CommandInfo( parent="items", command = "list", staticParams = { "page=1" }, floatingParams = { "search="}, description = "List all quest items.", paramDescriptions = { "page= {PAGE}", "search= Optional. Use to show items that contain the specified search text." }) public class ListSubCommand extends AbstractCommand { @Localizable static final String _PAGINATOR_TITLE = "Quest Items"; @Override public void execute (CommandSender sender, CommandArguments args) throws InvalidArgumentException { int page = args.getInteger("page"); ChatPaginator pagin = createPagin(Lang.get(_PAGINATOR_TITLE)); Collection<ScriptItem> items = ArborianQuests.getScriptItemManager().getAll(); for (ScriptItem item : items) { pagin.add(item.getName(), ItemStackUtils.serializeToString(item.getItem(), SerializerOutputType.COLOR)); } if (!args.isDefaultValue("search")) pagin.setSearchTerm(args.getString("search")); pagin.show(sender, page, FormatTemplate.LIST_ITEM_DESCRIPTION); } }
refactoring, comment fixes in ItemStackUtils
src/com/jcwhatever/arborianquests/commands/admin/items/ListSubCommand.java
refactoring, comment fixes in ItemStackUtils
<ide><path>rc/com/jcwhatever/arborianquests/commands/admin/items/ListSubCommand.java <ide> Collection<ScriptItem> items = ArborianQuests.getScriptItemManager().getAll(); <ide> <ide> for (ScriptItem item : items) { <del> pagin.add(item.getName(), ItemStackUtils.serializeToString(item.getItem(), SerializerOutputType.COLOR)); <add> pagin.add(item.getName(), ItemStackUtils.serialize(item.getItem(), SerializerOutputType.COLOR)); <ide> } <ide> <ide> if (!args.isDefaultValue("search"))
Java
mit
b4b483575ff6c9b9ef1c91c56978974b74a3eb1c
0
erogenousbeef/BigReactors,28Smiles/BigReactors
package erogenousbeef.bigreactors.common.multiblock; import io.netty.buffer.ByteBuf; import java.util.HashSet; import java.util.Iterator; import java.util.Set; import net.minecraft.block.Block; import net.minecraft.block.material.Material; import net.minecraft.entity.player.EntityPlayer; import net.minecraft.entity.player.EntityPlayerMP; import net.minecraft.init.Blocks; import net.minecraft.item.ItemStack; import net.minecraft.nbt.NBTTagCompound; import net.minecraft.tileentity.TileEntity; import net.minecraft.world.World; import net.minecraftforge.common.util.ForgeDirection; import net.minecraftforge.fluids.Fluid; import net.minecraftforge.fluids.FluidRegistry; import net.minecraftforge.fluids.FluidStack; import net.minecraftforge.fluids.FluidTankInfo; import net.minecraftforge.fluids.IFluidBlock; import cofh.api.energy.IEnergyHandler; import cofh.lib.util.helpers.ItemHelper; import cpw.mods.fml.common.network.simpleimpl.IMessage; import erogenousbeef.bigreactors.api.IHeatEntity; import erogenousbeef.bigreactors.api.registry.Reactants; import erogenousbeef.bigreactors.api.registry.ReactorInterior; import erogenousbeef.bigreactors.common.BRLog; import erogenousbeef.bigreactors.common.BigReactors; import erogenousbeef.bigreactors.common.data.RadiationData; import erogenousbeef.bigreactors.common.interfaces.IMultipleFluidHandler; import erogenousbeef.bigreactors.common.interfaces.IReactorFuelInfo; import erogenousbeef.bigreactors.common.multiblock.block.BlockReactorPart; import erogenousbeef.bigreactors.common.multiblock.helpers.CoolantContainer; import erogenousbeef.bigreactors.common.multiblock.helpers.FuelContainer; import erogenousbeef.bigreactors.common.multiblock.helpers.RadiationHelper; import erogenousbeef.bigreactors.common.multiblock.interfaces.IActivateable; import erogenousbeef.bigreactors.common.multiblock.interfaces.ITickableMultiblockPart; import erogenousbeef.bigreactors.common.multiblock.tileentity.TileEntityReactorAccessPort; import erogenousbeef.bigreactors.common.multiblock.tileentity.TileEntityReactorControlRod; import erogenousbeef.bigreactors.common.multiblock.tileentity.TileEntityReactorCoolantPort; import erogenousbeef.bigreactors.common.multiblock.tileentity.TileEntityReactorFuelRod; import erogenousbeef.bigreactors.common.multiblock.tileentity.TileEntityReactorGlass; import erogenousbeef.bigreactors.common.multiblock.tileentity.TileEntityReactorPart; import erogenousbeef.bigreactors.common.multiblock.tileentity.TileEntityReactorPowerTap; import erogenousbeef.bigreactors.net.CommonPacketHandler; import erogenousbeef.bigreactors.net.message.multiblock.ReactorUpdateMessage; import erogenousbeef.bigreactors.net.message.multiblock.ReactorUpdateWasteEjectionMessage; import erogenousbeef.bigreactors.utils.StaticUtils; import erogenousbeef.core.common.CoordTriplet; import erogenousbeef.core.multiblock.IMultiblockPart; import erogenousbeef.core.multiblock.MultiblockControllerBase; import erogenousbeef.core.multiblock.MultiblockValidationException; import erogenousbeef.core.multiblock.rectangular.RectangularMultiblockControllerBase; public class MultiblockReactor extends RectangularMultiblockControllerBase implements IEnergyHandler, IReactorFuelInfo, IMultipleFluidHandler, IActivateable { public static final int FuelCapacityPerFuelRod = 4 * Reactants.standardSolidReactantAmount; // 4 ingots per rod public static final int FLUID_SUPERHEATED = CoolantContainer.HOT; public static final int FLUID_COOLANT = CoolantContainer.COLD; private static final float passiveCoolingPowerEfficiency = 0.5f; // 50% power penalty, so this comes out as about 1/3 a basic water-cooled reactor private static final float passiveCoolingTransferEfficiency = 0.2f; // 20% of available heat transferred per tick when passively cooled private static final float reactorHeatLossConductivity = 0.001f; // circa 1RF per tick per external surface block // Game stuff - stored protected boolean active; private float reactorHeat; private float fuelHeat; private WasteEjectionSetting wasteEjection; private float energyStored; protected FuelContainer fuelContainer; protected RadiationHelper radiationHelper; protected CoolantContainer coolantContainer; // Game stuff - derived at runtime protected float fuelToReactorHeatTransferCoefficient; protected float reactorToCoolantSystemHeatTransferCoefficient; protected float reactorHeatLossCoefficient; protected Iterator<TileEntityReactorFuelRod> currentFuelRod; int reactorVolume; // UI stuff private float energyGeneratedLastTick; private float fuelConsumedLastTick; public enum WasteEjectionSetting { kAutomatic, // Full auto, always remove waste kManual, // Manual, only on button press } public static final WasteEjectionSetting[] s_EjectionSettings = WasteEjectionSetting.values(); // Lists of connected parts private Set<TileEntityReactorPowerTap> attachedPowerTaps; private Set<ITickableMultiblockPart> attachedTickables; private Set<TileEntityReactorControlRod> attachedControlRods; // Highest internal Y-coordinate in the fuel column private Set<TileEntityReactorAccessPort> attachedAccessPorts; private Set<TileEntityReactorPart> attachedControllers; private Set<TileEntityReactorFuelRod> attachedFuelRods; private Set<TileEntityReactorCoolantPort> attachedCoolantPorts; private Set<TileEntityReactorGlass> attachedGlass; // Updates private Set<EntityPlayer> updatePlayers; private int ticksSinceLastUpdate; private static final int ticksBetweenUpdates = 3; private static final int maxEnergyStored = 10000000; public MultiblockReactor(World world) { super(world); // Game stuff active = false; reactorHeat = 0f; fuelHeat = 0f; energyStored = 0f; wasteEjection = WasteEjectionSetting.kAutomatic; // Derived stats fuelToReactorHeatTransferCoefficient = 0f; reactorToCoolantSystemHeatTransferCoefficient = 0f; reactorHeatLossCoefficient = 0f; // UI and stats energyGeneratedLastTick = 0f; fuelConsumedLastTick = 0f; attachedPowerTaps = new HashSet<TileEntityReactorPowerTap>(); attachedTickables = new HashSet<ITickableMultiblockPart>(); attachedControlRods = new HashSet<TileEntityReactorControlRod>(); attachedAccessPorts = new HashSet<TileEntityReactorAccessPort>(); attachedControllers = new HashSet<TileEntityReactorPart>(); attachedFuelRods = new HashSet<TileEntityReactorFuelRod>(); attachedCoolantPorts = new HashSet<TileEntityReactorCoolantPort>(); attachedGlass = new HashSet<TileEntityReactorGlass>(); currentFuelRod = null; updatePlayers = new HashSet<EntityPlayer>(); ticksSinceLastUpdate = 0; fuelContainer = new FuelContainer(); radiationHelper = new RadiationHelper(); coolantContainer = new CoolantContainer(); reactorVolume = 0; } public void beginUpdatingPlayer(EntityPlayer playerToUpdate) { updatePlayers.add(playerToUpdate); sendIndividualUpdate(playerToUpdate); } public void stopUpdatingPlayer(EntityPlayer playerToRemove) { updatePlayers.remove(playerToRemove); } @Override protected void onBlockAdded(IMultiblockPart part) { if(part instanceof TileEntityReactorAccessPort) { attachedAccessPorts.add((TileEntityReactorAccessPort)part); } if(part instanceof TileEntityReactorControlRod) { TileEntityReactorControlRod controlRod = (TileEntityReactorControlRod)part; attachedControlRods.add(controlRod); } if(part instanceof TileEntityReactorPowerTap) { attachedPowerTaps.add((TileEntityReactorPowerTap)part); } if(part instanceof TileEntityReactorPart) { TileEntityReactorPart reactorPart = (TileEntityReactorPart)part; if(BlockReactorPart.isController(reactorPart.getBlockMetadata())) { attachedControllers.add(reactorPart); } } if(part instanceof ITickableMultiblockPart) { attachedTickables.add((ITickableMultiblockPart)part); } if(part instanceof TileEntityReactorFuelRod) { TileEntityReactorFuelRod fuelRod = (TileEntityReactorFuelRod)part; attachedFuelRods.add(fuelRod); // Reset iterator currentFuelRod = attachedFuelRods.iterator(); if(worldObj.isRemote) { worldObj.markBlockForUpdate(fuelRod.xCoord, fuelRod.yCoord, fuelRod.zCoord); } } if(part instanceof TileEntityReactorCoolantPort) { attachedCoolantPorts.add((TileEntityReactorCoolantPort) part); } if(part instanceof TileEntityReactorGlass) { attachedGlass.add((TileEntityReactorGlass)part); } } @Override protected void onBlockRemoved(IMultiblockPart part) { if(part instanceof TileEntityReactorAccessPort) { attachedAccessPorts.remove((TileEntityReactorAccessPort)part); } if(part instanceof TileEntityReactorControlRod) { attachedControlRods.remove((TileEntityReactorControlRod)part); } if(part instanceof TileEntityReactorPowerTap) { attachedPowerTaps.remove((TileEntityReactorPowerTap)part); } if(part instanceof TileEntityReactorPart) { TileEntityReactorPart reactorPart = (TileEntityReactorPart)part; if(BlockReactorPart.isController(reactorPart.getBlockMetadata())) { attachedControllers.remove(reactorPart); } } if(part instanceof ITickableMultiblockPart) { attachedTickables.remove((ITickableMultiblockPart)part); } if(part instanceof TileEntityReactorFuelRod) { attachedFuelRods.remove(part); currentFuelRod = attachedFuelRods.iterator(); } if(part instanceof TileEntityReactorCoolantPort) { attachedCoolantPorts.remove((TileEntityReactorCoolantPort)part); } if(part instanceof TileEntityReactorGlass) { attachedGlass.remove((TileEntityReactorGlass)part); } } @Override protected void isMachineWhole() throws MultiblockValidationException { // Ensure that there is at least one controller and control rod attached. if(attachedControlRods.size() < 1) { throw new MultiblockValidationException("Not enough control rods. Reactors require at least 1."); } if(attachedControllers.size() < 1) { throw new MultiblockValidationException("Not enough controllers. Reactors require at least 1."); } super.isMachineWhole(); } @Override public void updateClient() {} // Update loop. Only called when the machine is assembled. @Override public boolean updateServer() { if(Float.isNaN(this.getReactorHeat())) { this.setReactorHeat(0.0f); } float oldHeat = this.getReactorHeat(); float oldEnergy = this.getEnergyStored(); energyGeneratedLastTick = 0f; fuelConsumedLastTick = 0f; float newHeat = 0f; if(getActive()) { // Select a control rod to radiate from. Reset the iterator and select a new Y-level if needed. if(!currentFuelRod.hasNext()) { currentFuelRod = attachedFuelRods.iterator(); } // Radiate from that control rod TileEntityReactorFuelRod source = currentFuelRod.next(); TileEntityReactorControlRod sourceControlRod = (TileEntityReactorControlRod)worldObj.getTileEntity(source.xCoord, getMaximumCoord().y, source.zCoord); if(source != null && sourceControlRod != null) { RadiationData radData = radiationHelper.radiate(worldObj, fuelContainer, source, sourceControlRod, getFuelHeat(), getReactorHeat(), attachedControlRods.size()); // Assimilate results of radiation if(radData != null) { addFuelHeat(radData.getFuelHeatChange(attachedFuelRods.size())); addReactorHeat(radData.getEnvironmentHeatChange(getReactorVolume())); fuelConsumedLastTick += radData.fuelUsage; } } } // Allow radiation to decay even when reactor is off. radiationHelper.tick(getActive()); // If we can, poop out waste and inject new fuel. if(wasteEjection == WasteEjectionSetting.kAutomatic) { ejectWaste(false, null); } refuel(); // Heat Transfer: Fuel Pool <> Reactor Environment float tempDiff = fuelHeat - reactorHeat; if(tempDiff > 0.01f) { float rfTransferred = tempDiff * fuelToReactorHeatTransferCoefficient; float fuelRf = StaticUtils.Energy.getRFFromVolumeAndTemp(attachedFuelRods.size(), fuelHeat); fuelRf -= rfTransferred; setFuelHeat(StaticUtils.Energy.getTempFromVolumeAndRF(attachedFuelRods.size(), fuelRf)); // Now see how much the reactor's temp has increased float reactorRf = StaticUtils.Energy.getRFFromVolumeAndTemp(getReactorVolume(), getReactorHeat()); reactorRf += rfTransferred; setReactorHeat(StaticUtils.Energy.getTempFromVolumeAndRF(getReactorVolume(), reactorRf)); } // If we have a temperature differential between environment and coolant system, move heat between them. tempDiff = getReactorHeat() - getCoolantTemperature(); if(tempDiff > 0.01f) { float rfTransferred = tempDiff * reactorToCoolantSystemHeatTransferCoefficient; float reactorRf = StaticUtils.Energy.getRFFromVolumeAndTemp(getReactorVolume(), getReactorHeat()); if(isPassivelyCooled()) { rfTransferred *= passiveCoolingTransferEfficiency; generateEnergy(rfTransferred * passiveCoolingPowerEfficiency); } else { rfTransferred -= coolantContainer.onAbsorbHeat(rfTransferred); energyGeneratedLastTick = coolantContainer.getFluidVaporizedLastTick(); // Piggyback so we don't have useless stuff in the update packet } reactorRf -= rfTransferred; setReactorHeat(StaticUtils.Energy.getTempFromVolumeAndRF(getReactorVolume(), reactorRf)); } // Do passive heat loss - this is always versus external environment tempDiff = getReactorHeat() - getPassiveCoolantTemperature(); if(tempDiff > 0.000001f) { float rfLost = Math.max(1f, tempDiff * reactorHeatLossCoefficient); // Lose at least 1RF/t float reactorNewRf = Math.max(0f, StaticUtils.Energy.getRFFromVolumeAndTemp(getReactorVolume(), getReactorHeat()) - rfLost); setReactorHeat(StaticUtils.Energy.getTempFromVolumeAndRF(getReactorVolume(), reactorNewRf)); } // Prevent cryogenics if(reactorHeat < 0f) { setReactorHeat(0f); } if(fuelHeat < 0f) { setFuelHeat(0f); } // Distribute available power int energyAvailable = (int)getEnergyStored(); int energyRemaining = energyAvailable; if(attachedPowerTaps.size() > 0 && energyRemaining > 0) { // First, try to distribute fairly int splitEnergy = energyRemaining / attachedPowerTaps.size(); for(TileEntityReactorPowerTap powerTap : attachedPowerTaps) { if(energyRemaining <= 0) { break; } if(powerTap == null || !powerTap.isConnected()) { continue; } energyRemaining -= splitEnergy - powerTap.onProvidePower(splitEnergy); } // Next, just hose out whatever we can, if we have any left if(energyRemaining > 0) { for(TileEntityReactorPowerTap powerTap : attachedPowerTaps) { if(energyRemaining <= 0) { break; } if(powerTap == null || !powerTap.isConnected()) { continue; } energyRemaining = powerTap.onProvidePower(energyRemaining); } } } if(energyAvailable != energyRemaining) { reduceStoredEnergy((energyAvailable - energyRemaining)); } // Send updates periodically ticksSinceLastUpdate++; if(ticksSinceLastUpdate >= ticksBetweenUpdates) { ticksSinceLastUpdate = 0; sendTickUpdate(); } // TODO: Overload/overheat // Update any connected tickables for(ITickableMultiblockPart tickable : attachedTickables) { if(tickable == null) { continue; } tickable.onMultiblockServerTick(); } if(attachedGlass.size() > 0 && fuelContainer.shouldUpdate()) { markReferenceCoordForUpdate(); } return (oldHeat != this.getReactorHeat() || oldEnergy != this.getEnergyStored()); } public void setEnergyStored(float oldEnergy) { energyStored = oldEnergy; if(energyStored < 0.0 || Float.isNaN(energyStored)) { energyStored = 0.0f; } else if(energyStored > maxEnergyStored) { energyStored = maxEnergyStored; } } /** * Generate energy, internally. Will be multiplied by the BR Setting powerProductionMultiplier * @param newEnergy Base, unmultiplied energy to generate */ protected void generateEnergy(float newEnergy) { this.energyGeneratedLastTick += newEnergy * BigReactors.powerProductionMultiplier; this.addStoredEnergy(newEnergy * BigReactors.powerProductionMultiplier); } /** * Add some energy to the internal storage buffer. * Will not increase the buffer above the maximum or reduce it below 0. * @param newEnergy */ protected void addStoredEnergy(float newEnergy) { if(Float.isNaN(newEnergy)) { return; } energyStored += newEnergy; if(energyStored > maxEnergyStored) { energyStored = maxEnergyStored; } if(-0.00001f < energyStored && energyStored < 0.00001f) { // Clamp to zero energyStored = 0f; } } /** * Remove some energy from the internal storage buffer. * Will not reduce the buffer below 0. * @param energy Amount by which the buffer should be reduced. */ protected void reduceStoredEnergy(float energy) { this.addStoredEnergy(-1f * energy); } public void setActive(boolean act) { if(act == this.active) { return; } this.active = act; for(IMultiblockPart part : connectedParts) { if(this.active) { part.onMachineActivated(); } else { part.onMachineDeactivated(); } } if(worldObj.isRemote) { // Force controllers to re-render on client for(IMultiblockPart part : attachedControllers) { worldObj.markBlockForUpdate(part.xCoord, part.yCoord, part.zCoord); } } else { this.markReferenceCoordForUpdate(); } } protected void addReactorHeat(float newCasingHeat) { if(Float.isNaN(newCasingHeat)) { return; } reactorHeat += newCasingHeat; // Clamp to zero to prevent floating point issues if(-0.00001f < reactorHeat && reactorHeat < 0.00001f) { reactorHeat = 0.0f; } } public float getReactorHeat() { return reactorHeat; } public void setReactorHeat(float newHeat) { if(Float.isNaN(newHeat)) { reactorHeat = 0.0f; } else { reactorHeat = newHeat; } } protected void addFuelHeat(float additionalHeat) { if(Float.isNaN(additionalHeat)) { return; } fuelHeat += additionalHeat; if(-0.00001f < fuelHeat & fuelHeat < 0.00001f) { fuelHeat = 0f; } } public float getFuelHeat() { return fuelHeat; } public void setFuelHeat(float newFuelHeat) { if(Float.isNaN(newFuelHeat)) { fuelHeat = 0f; } else { fuelHeat = newFuelHeat; } } public int getFuelRodCount() { return attachedControlRods.size(); } // Static validation helpers // Water, air, and metal blocks @Override protected void isBlockGoodForInterior(World world, int x, int y, int z) throws MultiblockValidationException { if(world.isAirBlock(x, y, z)) { return; } // Air is OK Material material = world.getBlock(x, y, z).getMaterial(); if(material == net.minecraft.block.material.MaterialLiquid.water) { return; } Block block = world.getBlock(x, y, z); if(block == Blocks.iron_block || block == Blocks.gold_block || block == Blocks.diamond_block || block == Blocks.emerald_block) { return; } // Permit registered moderator blocks int metadata = world.getBlockMetadata(x, y, z); if(ReactorInterior.getBlockData(ItemHelper.oreProxy.getOreName(new ItemStack(block, 1, metadata))) != null) { return; } // Permit TE fluids if(block != null) { if(block instanceof IFluidBlock) { Fluid fluid = ((IFluidBlock)block).getFluid(); String fluidName = fluid.getName(); if(ReactorInterior.getFluidData(fluidName) != null) { return; } throw new MultiblockValidationException(String.format("%d, %d, %d - The fluid %s is not valid for the reactor's interior", x, y, z, fluidName)); } else { throw new MultiblockValidationException(String.format("%d, %d, %d - %s is not valid for the reactor's interior", x, y, z, block.getLocalizedName())); } } else { throw new MultiblockValidationException(String.format("%d, %d, %d - Null block found, not valid for the reactor's interior", x, y, z)); } } @Override public void writeToNBT(NBTTagCompound data) { data.setBoolean("reactorActive", this.active); data.setFloat("heat", this.reactorHeat); data.setFloat("fuelHeat", fuelHeat); data.setFloat("storedEnergy", this.energyStored); data.setInteger("wasteEjection2", this.wasteEjection.ordinal()); data.setTag("fuelContainer", fuelContainer.writeToNBT(new NBTTagCompound())); data.setTag("radiation", radiationHelper.writeToNBT(new NBTTagCompound())); data.setTag("coolantContainer", coolantContainer.writeToNBT(new NBTTagCompound())); } @Override public void readFromNBT(NBTTagCompound data) { if(data.hasKey("reactorActive")) { setActive(data.getBoolean("reactorActive")); } if(data.hasKey("heat")) { setReactorHeat(Math.max(getReactorHeat(), data.getFloat("heat"))); } if(data.hasKey("storedEnergy")) { setEnergyStored(Math.max(getEnergyStored(), data.getFloat("storedEnergy"))); } if(data.hasKey("wasteEjection")) { this.wasteEjection = s_EjectionSettings[data.getInteger("wasteEjection")]; } if(data.hasKey("fuelHeat")) { setFuelHeat(data.getFloat("fuelHeat")); } if(data.hasKey("fuelContainer")) { fuelContainer.readFromNBT(data.getCompoundTag("fuelContainer")); } if(data.hasKey("radiation")) { radiationHelper.readFromNBT(data.getCompoundTag("radiation")); } if(data.hasKey("coolantContainer")) { coolantContainer.readFromNBT(data.getCompoundTag("coolantContainer")); } } @Override protected int getMinimumNumberOfBlocksForAssembledMachine() { // Hollow cube. return 26; } @Override public void formatDescriptionPacket(NBTTagCompound data) { writeToNBT(data); } @Override public void decodeDescriptionPacket(NBTTagCompound data) { readFromNBT(data); onFuelStatusChanged(); } // Network & Storage methods /* * Serialize a reactor into a given Byte buffer * @param buf The byte buffer to serialize into */ public void serialize(ByteBuf buf) { int fuelTypeID, wasteTypeID, coolantTypeID, vaporTypeID; // Marshal fluid types into integers { Fluid coolantType, vaporType; coolantType = coolantContainer.getCoolantType(); vaporType = coolantContainer.getVaporType(); coolantTypeID = coolantType == null ? -1 : coolantType.getID(); vaporTypeID = vaporType == null ? -1 : vaporType.getID(); } // Basic data buf.writeBoolean(active); buf.writeFloat(reactorHeat); buf.writeFloat(fuelHeat); buf.writeFloat(energyStored); buf.writeFloat(radiationHelper.getFertility()); // Statistics buf.writeFloat(energyGeneratedLastTick); buf.writeFloat(fuelConsumedLastTick); // Coolant data buf.writeInt(coolantTypeID); buf.writeInt(coolantContainer.getCoolantAmount()); buf.writeInt(vaporTypeID); buf.writeInt(coolantContainer.getVaporAmount()); fuelContainer.serialize(buf); } /* * Deserialize a reactor's data from a given Byte buffer * @param buf The byte buffer containing reactor data */ public void deserialize(ByteBuf buf) { // Basic data setActive(buf.readBoolean()); setReactorHeat(buf.readFloat()); setFuelHeat(buf.readFloat()); setEnergyStored(buf.readFloat()); radiationHelper.setFertility(buf.readFloat()); // Statistics setEnergyGeneratedLastTick(buf.readFloat()); setFuelConsumedLastTick(buf.readFloat()); // Coolant data int coolantTypeID = buf.readInt(); int coolantAmt = buf.readInt(); int vaporTypeID = buf.readInt(); int vaporAmt = buf.readInt(); // Fuel & waste data fuelContainer.deserialize(buf); if(coolantTypeID == -1) { coolantContainer.emptyCoolant(); } else { coolantContainer.setCoolant(new FluidStack(FluidRegistry.getFluid(coolantTypeID), coolantAmt)); } if(vaporTypeID == -1) { coolantContainer.emptyVapor(); } else { coolantContainer.setVapor(new FluidStack(FluidRegistry.getFluid(vaporTypeID), vaporAmt)); } } protected IMessage getUpdatePacket() { return new ReactorUpdateMessage(this); } /** * Sends a full state update to a player. */ protected void sendIndividualUpdate(EntityPlayer player) { if(this.worldObj.isRemote) { return; } CommonPacketHandler.INSTANCE.sendTo(getUpdatePacket(), (EntityPlayerMP)player); } /** * Send an update to any clients with GUIs open */ protected void sendTickUpdate() { if(this.worldObj.isRemote) { return; } if(this.updatePlayers.size() <= 0) { return; } for(EntityPlayer player : updatePlayers) { CommonPacketHandler.INSTANCE.sendTo(getUpdatePacket(), (EntityPlayerMP)player); } } /** * Attempt to distribute a stack of ingots to a given access port, sensitive to the amount and type of ingots already in it. * @param port The port to which we're distributing ingots. * @param itemsToDistribute The stack of ingots to distribute. Will be modified during the operation and may be returned with stack size 0. * @param distributeToInputs Should we try to send ingots to input ports? * @return The number of waste items distributed, i.e. the differential in stack size for wasteToDistribute. */ private int tryDistributeItems(TileEntityReactorAccessPort port, ItemStack itemsToDistribute, boolean distributeToInputs) { ItemStack existingStack = port.getStackInSlot(TileEntityReactorAccessPort.SLOT_OUTLET); int initialWasteAmount = itemsToDistribute.stackSize; if(!port.isInlet() || (distributeToInputs || attachedAccessPorts.size() < 2)) { // Dump waste preferentially to outlets, unless we only have one access port if(existingStack == null) { if(itemsToDistribute.stackSize > port.getInventoryStackLimit()) { ItemStack newStack = itemsToDistribute.splitStack(port.getInventoryStackLimit()); port.setInventorySlotContents(TileEntityReactorAccessPort.SLOT_OUTLET, newStack); } else { port.setInventorySlotContents(TileEntityReactorAccessPort.SLOT_OUTLET, itemsToDistribute.copy()); itemsToDistribute.stackSize = 0; } } else if(existingStack.isItemEqual(itemsToDistribute)) { if(existingStack.stackSize + itemsToDistribute.stackSize <= existingStack.getMaxStackSize()) { existingStack.stackSize += itemsToDistribute.stackSize; itemsToDistribute.stackSize = 0; } else { int amt = existingStack.getMaxStackSize() - existingStack.stackSize; itemsToDistribute.stackSize -= existingStack.getMaxStackSize() - existingStack.stackSize; existingStack.stackSize += amt; } } port.onItemsReceived(); } return initialWasteAmount - itemsToDistribute.stackSize; } @Override protected void onAssimilated(MultiblockControllerBase otherMachine) { this.attachedPowerTaps.clear(); this.attachedTickables.clear(); this.attachedAccessPorts.clear(); this.attachedControllers.clear(); this.attachedControlRods.clear(); currentFuelRod = null; } @Override protected void onAssimilate(MultiblockControllerBase otherMachine) { if(!(otherMachine instanceof MultiblockReactor)) { BRLog.warning("[%s] Reactor @ %s is attempting to assimilate a non-Reactor machine! That machine's data will be lost!", worldObj.isRemote?"CLIENT":"SERVER", getReferenceCoord()); return; } MultiblockReactor otherReactor = (MultiblockReactor)otherMachine; if(otherReactor.reactorHeat > this.reactorHeat) { setReactorHeat(otherReactor.reactorHeat); } if(otherReactor.fuelHeat > this.fuelHeat) { setFuelHeat(otherReactor.fuelHeat); } if(otherReactor.getEnergyStored() > this.getEnergyStored()) { this.setEnergyStored(otherReactor.getEnergyStored()); } fuelContainer.merge(otherReactor.fuelContainer); radiationHelper.merge(otherReactor.radiationHelper); coolantContainer.merge(otherReactor.coolantContainer); } @Override public void onAttachedPartWithMultiblockData(IMultiblockPart part, NBTTagCompound data) { this.readFromNBT(data); } public float getEnergyStored() { return energyStored; } /** * Directly set the waste ejection setting. Will dispatch network updates * from server to interested clients. * @param newSetting The new waste ejection setting. */ public void setWasteEjection(WasteEjectionSetting newSetting) { if(this.wasteEjection != newSetting) { this.wasteEjection = newSetting; if(!this.worldObj.isRemote) { if(this.updatePlayers.size() > 0) { CoordTriplet coord = getReferenceCoord(); for(EntityPlayer player : updatePlayers) { CommonPacketHandler.INSTANCE.sendTo(new ReactorUpdateWasteEjectionMessage(this), (EntityPlayerMP)player); } } } } } public WasteEjectionSetting getWasteEjection() { return this.wasteEjection; } protected void refuel() { // For now, we only need to check fuel ports when we have more space than can accomodate 1 ingot if(fuelContainer.getRemainingSpace() < Reactants.standardSolidReactantAmount) { return; } int amtAdded = 0; // Loop: Consume input reactants from all ports for(TileEntityReactorAccessPort port : attachedAccessPorts) { if(fuelContainer.getRemainingSpace() <= 0) { break; } if(port == null || !port.isConnected()) { continue; } // See what type of reactant the port contains; if none, skip it. String portReactantType = port.getInputReactantType(); int portReactantAmount = port.getInputReactantAmount(); if(portReactantType == null || portReactantAmount <= 0) { continue; } if(!Reactants.isFuel(portReactantType)) { continue; } // Skip nonfuels // How much fuel can we actually add from this type of reactant? int amountToAdd = fuelContainer.addFuel(portReactantType, portReactantAmount, false); if(amountToAdd <= 0) { continue; } int portCanAdd = port.consumeReactantItem(amountToAdd); if(portCanAdd <= 0) { continue; } amtAdded = fuelContainer.addFuel(portReactantType, portReactantAmount, true); } if(amtAdded > 0) { markReferenceCoordForUpdate(); markReferenceCoordDirty(); } } /** * Attempt to eject waste contained in the reactor * @param dumpAll If true, any waste remaining after ejection will be discarded. * @param destination If set, waste will only be ejected to ports with coordinates matching this one. */ public void ejectWaste(boolean dumpAll, CoordTriplet destination) { // For now, we can optimize by only running this when we have enough waste to product an ingot int amtEjected = 0; String wasteReactantType = fuelContainer.getWasteType(); if(wasteReactantType == null) { return; } int minimumReactantAmount = Reactants.getMinimumReactantToProduceSolid(wasteReactantType); if(fuelContainer.getWasteAmount() >= minimumReactantAmount) { for(TileEntityReactorAccessPort port : attachedAccessPorts) { if(fuelContainer.getWasteAmount() < minimumReactantAmount) { continue; } if(port == null || !port.isConnected()) { continue; } if(destination != null && !destination.equals(port.xCoord, port.yCoord, port.zCoord)) { continue; } // First time through, we eject only to outlet ports if(destination == null && !port.isInlet()) { int reactantEjected = port.emitReactant(wasteReactantType, fuelContainer.getWasteAmount()); fuelContainer.dumpWaste(reactantEjected); amtEjected += reactantEjected; } } if(destination == null && fuelContainer.getWasteAmount() > minimumReactantAmount) { // Loop a second time when destination is null and we still have waste for(TileEntityReactorAccessPort port : attachedAccessPorts) { if(fuelContainer.getWasteAmount() < minimumReactantAmount) { continue; } if(port == null || !port.isConnected()) { continue; } int reactantEjected = port.emitReactant(wasteReactantType, fuelContainer.getWasteAmount()); fuelContainer.dumpWaste(reactantEjected); amtEjected += reactantEjected; } } } if(dumpAll) { amtEjected += fuelContainer.getWasteAmount(); fuelContainer.setWaste(null); } if(amtEjected > 0) { markReferenceCoordForUpdate(); markReferenceCoordDirty(); } } /** * Eject fuel contained in the reactor. * @param dumpAll If true, any remaining fuel will simply be lost. * @param destination If not null, then fuel will only be distributed to a port matching these coordinates. */ public void ejectFuel(boolean dumpAll, CoordTriplet destination) { // For now, we can optimize by only running this when we have enough waste to product an ingot int amtEjected = 0; String fuelReactantType = fuelContainer.getFuelType(); if(fuelReactantType == null) { return; } int minimumReactantAmount = Reactants.getMinimumReactantToProduceSolid(fuelReactantType); if(fuelContainer.getFuelAmount() >= minimumReactantAmount) { for(TileEntityReactorAccessPort port : attachedAccessPorts) { if(fuelContainer.getFuelAmount() < minimumReactantAmount) { continue; } if(port == null || !port.isConnected()) { continue; } if(destination != null && !destination.equals(port.xCoord, port.yCoord, port.zCoord)) { continue; } int reactantEjected = port.emitReactant(fuelReactantType, fuelContainer.getFuelAmount()); fuelContainer.dumpFuel(reactantEjected); amtEjected += reactantEjected; } } if(dumpAll) { amtEjected += fuelContainer.getFuelAmount(); fuelContainer.setFuel(null); } if(amtEjected > 0) { markReferenceCoordForUpdate(); markReferenceCoordDirty(); } } @Override protected void onMachineAssembled() { recalculateDerivedValues(); } @Override protected void onMachineRestored() { recalculateDerivedValues(); } @Override protected void onMachinePaused() { } @Override protected void onMachineDisassembled() { this.active = false; } private void recalculateDerivedValues() { // Recalculate size of fuel/waste tank via fuel rods CoordTriplet minCoord, maxCoord; minCoord = getMinimumCoord(); maxCoord = getMaximumCoord(); fuelContainer.setCapacity(attachedFuelRods.size() * FuelCapacityPerFuelRod); // Calculate derived stats // Calculate heat transfer based on fuel rod environment fuelToReactorHeatTransferCoefficient = 0f; for(TileEntityReactorFuelRod fuelRod : attachedFuelRods) { fuelToReactorHeatTransferCoefficient += fuelRod.getHeatTransferRate(); } // Pick a random fuel rod Y as a starting point int maxFuelRodY = maxCoord.y - 1; int minFuelRodY = minCoord.y + 1; currentFuelRod = attachedFuelRods.iterator(); // Calculate heat transfer to coolant system based on reactor interior surface area. // This is pretty simple to start with - surface area of the rectangular prism defining the interior. int xSize = maxCoord.x - minCoord.x - 1; int ySize = maxCoord.y - minCoord.y - 1; int zSize = maxCoord.z - minCoord.z - 1; int surfaceArea = 2 * (xSize * ySize + xSize * zSize + ySize * zSize); reactorToCoolantSystemHeatTransferCoefficient = IHeatEntity.conductivityIron * surfaceArea; // Calculate passive heat loss. // Get external surface area xSize += 2; ySize += 2; zSize += 2; surfaceArea = 2 * (xSize * ySize + xSize * zSize + ySize * zSize); reactorHeatLossCoefficient = reactorHeatLossConductivity * surfaceArea; if(worldObj.isRemote) { // Make sure our fuel rods re-render this.onFuelStatusChanged(); } else { // Force an update of the client's multiblock information markReferenceCoordForUpdate(); } calculateReactorVolume(); if(attachedCoolantPorts.size() > 0) { int outerVolume = StaticUtils.ExtraMath.Volume(minCoord, maxCoord) - reactorVolume; coolantContainer.setCapacity(Math.max(0, Math.min(50000, outerVolume * 100))); } else { coolantContainer.setCapacity(0); } } @Override protected int getMaximumXSize() { return BigReactors.maximumReactorSize; } @Override protected int getMaximumZSize() { return BigReactors.maximumReactorSize; } @Override protected int getMaximumYSize() { return BigReactors.maximumReactorHeight; } /** * Used to update the UI */ public void setEnergyGeneratedLastTick(float energyGeneratedLastTick) { this.energyGeneratedLastTick = energyGeneratedLastTick; } /** * UI Helper */ public float getEnergyGeneratedLastTick() { return this.energyGeneratedLastTick; } /** * Used to update the UI */ public void setFuelConsumedLastTick(float fuelConsumed) { fuelConsumedLastTick = fuelConsumed; } /** * UI Helper */ public float getFuelConsumedLastTick() { return fuelConsumedLastTick; } /** * UI Helper * @return Percentile fuel richness (fuel/fuel+waste), or 0 if all control rods are empty */ public float getFuelRichness() { int amtFuel, amtWaste; amtFuel = fuelContainer.getFuelAmount(); amtWaste = fuelContainer.getWasteAmount(); if(amtFuel + amtWaste <= 0f) { return 0f; } else { return (float)amtFuel / (float)(amtFuel+amtWaste); } } /** DO NOT USE **/ @Override public int receiveEnergy(ForgeDirection from, int maxReceive, boolean simulate) { int amtReceived = (int)Math.min(maxReceive, Math.floor(this.maxEnergyStored - this.energyStored)); if(!simulate) { this.addStoredEnergy(amtReceived); } return amtReceived; } @Override public int extractEnergy(ForgeDirection from, int maxExtract, boolean simulate) { int amtRemoved = (int)Math.min(maxExtract, this.energyStored); if(!simulate) { this.reduceStoredEnergy(amtRemoved); } return amtRemoved; } @Override public boolean canConnectEnergy(ForgeDirection from) { return false; } @Override public int getEnergyStored(ForgeDirection from) { return (int)energyStored; } @Override public int getMaxEnergyStored(ForgeDirection from) { return maxEnergyStored; } // Redstone helper public void setAllControlRodInsertionValues(int newValue) { if(this.assemblyState != AssemblyState.Assembled) { return; } for(TileEntityReactorControlRod cr : attachedControlRods) { if(cr != null && cr.isConnected()) { cr.setControlRodInsertion((short)newValue); } } } public void changeAllControlRodInsertionValues(short delta) { if(this.assemblyState != AssemblyState.Assembled) { return; } for(TileEntityReactorControlRod cr : attachedControlRods) { if(cr != null && cr.isConnected()) { cr.setControlRodInsertion( (short) (cr.getControlRodInsertion() + delta) ); } } } public CoordTriplet[] getControlRodLocations() { CoordTriplet[] coords = new CoordTriplet[this.attachedControlRods.size()]; int i = 0; for(TileEntityReactorControlRod cr : attachedControlRods) { coords[i++] = cr.getWorldLocation(); } return coords; } public int getFuelAmount() { return fuelContainer.getFuelAmount(); } public int getWasteAmount() { return fuelContainer.getWasteAmount(); } public String getFuelType() { return fuelContainer.getFuelType(); } public String getWasteType() { return fuelContainer.getWasteType(); } public int getEnergyStoredPercentage() { return (int)(this.energyStored / (float)this.maxEnergyStored * 100f); } @Override public int getCapacity() { if(worldObj.isRemote && assemblyState != AssemblyState.Assembled) { // Estimate capacity return attachedFuelRods.size() * FuelCapacityPerFuelRod; } return fuelContainer.getCapacity(); } public float getFuelFertility() { return radiationHelper.getFertilityModifier(); } // Coolant subsystem public CoolantContainer getCoolantContainer() { return coolantContainer; } protected float getPassiveCoolantTemperature() { return IHeatEntity.ambientHeat; } protected float getCoolantTemperature() { if(isPassivelyCooled()) { return getPassiveCoolantTemperature(); } else { return coolantContainer.getCoolantTemperature(getReactorHeat()); } } public boolean isPassivelyCooled() { if(coolantContainer == null || coolantContainer.getCapacity() <= 0) { return true; } else { return false; } } protected int getReactorVolume() { return reactorVolume; } protected void calculateReactorVolume() { CoordTriplet minInteriorCoord = getMinimumCoord(); minInteriorCoord.x += 1; minInteriorCoord.y += 1; minInteriorCoord.z += 1; CoordTriplet maxInteriorCoord = getMaximumCoord(); maxInteriorCoord.x -= 1; maxInteriorCoord.y -= 1; maxInteriorCoord.z -= 1; reactorVolume = StaticUtils.ExtraMath.Volume(minInteriorCoord, maxInteriorCoord); } // Client-only protected void onFuelStatusChanged() { if(worldObj.isRemote) { // On the client, re-render all the fuel rod blocks when the fuel status changes for(TileEntityReactorFuelRod fuelRod : attachedFuelRods) { worldObj.markBlockForUpdate(fuelRod.xCoord, fuelRod.yCoord, fuelRod.zCoord); } } } private static final FluidTankInfo[] emptyTankInfo = new FluidTankInfo[0]; @Override public FluidTankInfo[] getTankInfo() { if(isPassivelyCooled()) { return emptyTankInfo; } return coolantContainer.getTankInfo(-1); } protected void markReferenceCoordForUpdate() { CoordTriplet rc = getReferenceCoord(); if(worldObj != null && rc != null) { worldObj.markBlockForUpdate(rc.x, rc.y, rc.z); } } protected void markReferenceCoordDirty() { if(worldObj == null || worldObj.isRemote) { return; } CoordTriplet referenceCoord = getReferenceCoord(); if(referenceCoord == null) { return; } TileEntity saveTe = worldObj.getTileEntity(referenceCoord.x, referenceCoord.y, referenceCoord.z); worldObj.markTileEntityChunkModified(referenceCoord.x, referenceCoord.y, referenceCoord.z, saveTe); } @Override public boolean getActive() { return this.active; } public String getDebugInfo() { StringBuilder sb = new StringBuilder(); sb.append("Assembled: ").append(Boolean.toString(isAssembled())).append("\n"); sb.append("Attached Blocks: ").append(Integer.toString(connectedParts.size())).append("\n"); if(getLastValidationException() != null) { sb.append("Validation Exception:\n").append(getLastValidationException().getMessage()).append("\n"); } if(isAssembled()) { sb.append("\nActive: ").append(Boolean.toString(getActive())); sb.append("\nStored Energy: ").append(Float.toString(getEnergyStored())); sb.append("\nCasing Heat: ").append(Float.toString(getReactorHeat())); sb.append("\nFuel Heat: ").append(Float.toString(getFuelHeat())); sb.append("\n\nReactant Tanks:\n"); sb.append( fuelContainer.getDebugInfo() ); sb.append("\n\nActively Cooled: ").append(Boolean.toString(!isPassivelyCooled())); if(!isPassivelyCooled()) { sb.append("\n\nCoolant Tanks:\n"); sb.append( coolantContainer.getDebugInfo() ); } } return sb.toString(); } }
src/main/java/erogenousbeef/bigreactors/common/multiblock/MultiblockReactor.java
package erogenousbeef.bigreactors.common.multiblock; import io.netty.buffer.ByteBuf; import java.util.HashSet; import java.util.Iterator; import java.util.Set; import net.minecraft.block.Block; import net.minecraft.block.material.Material; import net.minecraft.entity.player.EntityPlayer; import net.minecraft.entity.player.EntityPlayerMP; import net.minecraft.init.Blocks; import net.minecraft.item.ItemStack; import net.minecraft.nbt.NBTTagCompound; import net.minecraft.tileentity.TileEntity; import net.minecraft.world.World; import net.minecraftforge.common.util.ForgeDirection; import net.minecraftforge.fluids.Fluid; import net.minecraftforge.fluids.FluidRegistry; import net.minecraftforge.fluids.FluidStack; import net.minecraftforge.fluids.FluidTankInfo; import net.minecraftforge.fluids.IFluidBlock; import cofh.api.energy.IEnergyHandler; import cofh.lib.util.helpers.ItemHelper; import cpw.mods.fml.common.network.simpleimpl.IMessage; import erogenousbeef.bigreactors.api.IHeatEntity; import erogenousbeef.bigreactors.api.registry.Reactants; import erogenousbeef.bigreactors.api.registry.ReactorInterior; import erogenousbeef.bigreactors.common.BRLog; import erogenousbeef.bigreactors.common.BigReactors; import erogenousbeef.bigreactors.common.data.RadiationData; import erogenousbeef.bigreactors.common.interfaces.IMultipleFluidHandler; import erogenousbeef.bigreactors.common.interfaces.IReactorFuelInfo; import erogenousbeef.bigreactors.common.multiblock.block.BlockReactorPart; import erogenousbeef.bigreactors.common.multiblock.helpers.CoolantContainer; import erogenousbeef.bigreactors.common.multiblock.helpers.FuelContainer; import erogenousbeef.bigreactors.common.multiblock.helpers.RadiationHelper; import erogenousbeef.bigreactors.common.multiblock.interfaces.IActivateable; import erogenousbeef.bigreactors.common.multiblock.interfaces.ITickableMultiblockPart; import erogenousbeef.bigreactors.common.multiblock.tileentity.TileEntityReactorAccessPort; import erogenousbeef.bigreactors.common.multiblock.tileentity.TileEntityReactorControlRod; import erogenousbeef.bigreactors.common.multiblock.tileentity.TileEntityReactorCoolantPort; import erogenousbeef.bigreactors.common.multiblock.tileentity.TileEntityReactorFuelRod; import erogenousbeef.bigreactors.common.multiblock.tileentity.TileEntityReactorGlass; import erogenousbeef.bigreactors.common.multiblock.tileentity.TileEntityReactorPart; import erogenousbeef.bigreactors.common.multiblock.tileentity.TileEntityReactorPowerTap; import erogenousbeef.bigreactors.net.CommonPacketHandler; import erogenousbeef.bigreactors.net.message.multiblock.ReactorUpdateMessage; import erogenousbeef.bigreactors.net.message.multiblock.ReactorUpdateWasteEjectionMessage; import erogenousbeef.bigreactors.utils.StaticUtils; import erogenousbeef.core.common.CoordTriplet; import erogenousbeef.core.multiblock.IMultiblockPart; import erogenousbeef.core.multiblock.MultiblockControllerBase; import erogenousbeef.core.multiblock.MultiblockValidationException; import erogenousbeef.core.multiblock.rectangular.RectangularMultiblockControllerBase; public class MultiblockReactor extends RectangularMultiblockControllerBase implements IEnergyHandler, IReactorFuelInfo, IMultipleFluidHandler, IActivateable { public static final int FuelCapacityPerFuelRod = 4 * Reactants.standardSolidReactantAmount; // 4 ingots per rod public static final int FLUID_SUPERHEATED = CoolantContainer.HOT; public static final int FLUID_COOLANT = CoolantContainer.COLD; private static final float passiveCoolingPowerEfficiency = 0.5f; // 50% power penalty, so this comes out as about 1/3 a basic water-cooled reactor private static final float passiveCoolingTransferEfficiency = 0.2f; // 20% of available heat transferred per tick when passively cooled private static final float reactorHeatLossConductivity = 0.001f; // circa 1RF per tick per external surface block // Game stuff - stored protected boolean active; private float reactorHeat; private float fuelHeat; private WasteEjectionSetting wasteEjection; private float energyStored; protected FuelContainer fuelContainer; protected RadiationHelper radiationHelper; protected CoolantContainer coolantContainer; // Game stuff - derived at runtime protected float fuelToReactorHeatTransferCoefficient; protected float reactorToCoolantSystemHeatTransferCoefficient; protected float reactorHeatLossCoefficient; protected Iterator<TileEntityReactorFuelRod> currentFuelRod; int reactorVolume; // UI stuff private float energyGeneratedLastTick; private float fuelConsumedLastTick; public enum WasteEjectionSetting { kAutomatic, // Full auto, always remove waste kManual, // Manual, only on button press } public static final WasteEjectionSetting[] s_EjectionSettings = WasteEjectionSetting.values(); // Lists of connected parts private Set<TileEntityReactorPowerTap> attachedPowerTaps; private Set<ITickableMultiblockPart> attachedTickables; private Set<TileEntityReactorControlRod> attachedControlRods; // Highest internal Y-coordinate in the fuel column private Set<TileEntityReactorAccessPort> attachedAccessPorts; private Set<TileEntityReactorPart> attachedControllers; private Set<TileEntityReactorFuelRod> attachedFuelRods; private Set<TileEntityReactorCoolantPort> attachedCoolantPorts; private Set<TileEntityReactorGlass> attachedGlass; // Updates private Set<EntityPlayer> updatePlayers; private int ticksSinceLastUpdate; private static final int ticksBetweenUpdates = 3; private static final int maxEnergyStored = 10000000; public MultiblockReactor(World world) { super(world); // Game stuff active = false; reactorHeat = 0f; fuelHeat = 0f; energyStored = 0f; wasteEjection = WasteEjectionSetting.kAutomatic; // Derived stats fuelToReactorHeatTransferCoefficient = 0f; reactorToCoolantSystemHeatTransferCoefficient = 0f; reactorHeatLossCoefficient = 0f; // UI and stats energyGeneratedLastTick = 0f; fuelConsumedLastTick = 0f; attachedPowerTaps = new HashSet<TileEntityReactorPowerTap>(); attachedTickables = new HashSet<ITickableMultiblockPart>(); attachedControlRods = new HashSet<TileEntityReactorControlRod>(); attachedAccessPorts = new HashSet<TileEntityReactorAccessPort>(); attachedControllers = new HashSet<TileEntityReactorPart>(); attachedFuelRods = new HashSet<TileEntityReactorFuelRod>(); attachedCoolantPorts = new HashSet<TileEntityReactorCoolantPort>(); attachedGlass = new HashSet<TileEntityReactorGlass>(); currentFuelRod = null; updatePlayers = new HashSet<EntityPlayer>(); ticksSinceLastUpdate = 0; fuelContainer = new FuelContainer(); radiationHelper = new RadiationHelper(); coolantContainer = new CoolantContainer(); reactorVolume = 0; } public void beginUpdatingPlayer(EntityPlayer playerToUpdate) { updatePlayers.add(playerToUpdate); sendIndividualUpdate(playerToUpdate); } public void stopUpdatingPlayer(EntityPlayer playerToRemove) { updatePlayers.remove(playerToRemove); } @Override protected void onBlockAdded(IMultiblockPart part) { if(part instanceof TileEntityReactorAccessPort) { attachedAccessPorts.add((TileEntityReactorAccessPort)part); } if(part instanceof TileEntityReactorControlRod) { TileEntityReactorControlRod controlRod = (TileEntityReactorControlRod)part; attachedControlRods.add(controlRod); } if(part instanceof TileEntityReactorPowerTap) { attachedPowerTaps.add((TileEntityReactorPowerTap)part); } if(part instanceof TileEntityReactorPart) { TileEntityReactorPart reactorPart = (TileEntityReactorPart)part; if(BlockReactorPart.isController(reactorPart.getBlockMetadata())) { attachedControllers.add(reactorPart); } } if(part instanceof ITickableMultiblockPart) { attachedTickables.add((ITickableMultiblockPart)part); } if(part instanceof TileEntityReactorFuelRod) { TileEntityReactorFuelRod fuelRod = (TileEntityReactorFuelRod)part; attachedFuelRods.add(fuelRod); // Reset iterator currentFuelRod = attachedFuelRods.iterator(); if(worldObj.isRemote) { worldObj.markBlockForUpdate(fuelRod.xCoord, fuelRod.yCoord, fuelRod.zCoord); } } if(part instanceof TileEntityReactorCoolantPort) { attachedCoolantPorts.add((TileEntityReactorCoolantPort) part); } if(part instanceof TileEntityReactorGlass) { attachedGlass.add((TileEntityReactorGlass)part); } } @Override protected void onBlockRemoved(IMultiblockPart part) { if(part instanceof TileEntityReactorAccessPort) { attachedAccessPorts.remove((TileEntityReactorAccessPort)part); } if(part instanceof TileEntityReactorControlRod) { attachedControlRods.remove((TileEntityReactorControlRod)part); } if(part instanceof TileEntityReactorPowerTap) { attachedPowerTaps.remove((TileEntityReactorPowerTap)part); } if(part instanceof TileEntityReactorPart) { TileEntityReactorPart reactorPart = (TileEntityReactorPart)part; if(BlockReactorPart.isController(reactorPart.getBlockMetadata())) { attachedControllers.remove(reactorPart); } } if(part instanceof ITickableMultiblockPart) { attachedTickables.remove((ITickableMultiblockPart)part); } if(part instanceof TileEntityReactorFuelRod) { attachedFuelRods.remove(part); currentFuelRod = attachedFuelRods.iterator(); } if(part instanceof TileEntityReactorCoolantPort) { attachedCoolantPorts.remove((TileEntityReactorCoolantPort)part); } if(part instanceof TileEntityReactorGlass) { attachedGlass.remove((TileEntityReactorGlass)part); } } @Override protected void isMachineWhole() throws MultiblockValidationException { // Ensure that there is at least one controller and control rod attached. if(attachedControlRods.size() < 1) { throw new MultiblockValidationException("Not enough control rods. Reactors require at least 1."); } if(attachedControllers.size() < 1) { throw new MultiblockValidationException("Not enough controllers. Reactors require at least 1."); } super.isMachineWhole(); } @Override public void updateClient() {} // Update loop. Only called when the machine is assembled. @Override public boolean updateServer() { if(Float.isNaN(this.getReactorHeat())) { this.setReactorHeat(0.0f); } float oldHeat = this.getReactorHeat(); float oldEnergy = this.getEnergyStored(); energyGeneratedLastTick = 0f; fuelConsumedLastTick = 0f; float newHeat = 0f; if(getActive()) { // Select a control rod to radiate from. Reset the iterator and select a new Y-level if needed. if(!currentFuelRod.hasNext()) { currentFuelRod = attachedFuelRods.iterator(); } // Radiate from that control rod TileEntityReactorFuelRod source = currentFuelRod.next(); TileEntityReactorControlRod sourceControlRod = (TileEntityReactorControlRod)worldObj.getTileEntity(source.xCoord, getMaximumCoord().y, source.zCoord); if(source != null && sourceControlRod != null) { RadiationData radData = radiationHelper.radiate(worldObj, fuelContainer, source, sourceControlRod, getFuelHeat(), getReactorHeat(), attachedControlRods.size()); // Assimilate results of radiation if(radData != null) { addFuelHeat(radData.getFuelHeatChange(attachedFuelRods.size())); addReactorHeat(radData.getEnvironmentHeatChange(getReactorVolume())); fuelConsumedLastTick += radData.fuelUsage; } } } // Allow radiation to decay even when reactor is off. radiationHelper.tick(getActive()); // If we can, poop out waste and inject new fuel. if(wasteEjection == WasteEjectionSetting.kAutomatic) { ejectWaste(false, null); } refuel(); // Heat Transfer: Fuel Pool <> Reactor Environment float tempDiff = fuelHeat - reactorHeat; if(tempDiff > 0.01f) { float rfTransferred = tempDiff * fuelToReactorHeatTransferCoefficient; float fuelRf = StaticUtils.Energy.getRFFromVolumeAndTemp(attachedFuelRods.size(), fuelHeat); fuelRf -= rfTransferred; setFuelHeat(StaticUtils.Energy.getTempFromVolumeAndRF(attachedFuelRods.size(), fuelRf)); // Now see how much the reactor's temp has increased float reactorRf = StaticUtils.Energy.getRFFromVolumeAndTemp(getReactorVolume(), getReactorHeat()); reactorRf += rfTransferred; setReactorHeat(StaticUtils.Energy.getTempFromVolumeAndRF(getReactorVolume(), reactorRf)); } // If we have a temperature differential between environment and coolant system, move heat between them. tempDiff = getReactorHeat() - getCoolantTemperature(); if(tempDiff > 0.01f) { float rfTransferred = tempDiff * reactorToCoolantSystemHeatTransferCoefficient; float reactorRf = StaticUtils.Energy.getRFFromVolumeAndTemp(getReactorVolume(), getReactorHeat()); if(isPassivelyCooled()) { rfTransferred *= passiveCoolingTransferEfficiency; generateEnergy(rfTransferred * passiveCoolingPowerEfficiency); } else { rfTransferred -= coolantContainer.onAbsorbHeat(rfTransferred); energyGeneratedLastTick = coolantContainer.getFluidVaporizedLastTick(); // Piggyback so we don't have useless stuff in the update packet } reactorRf -= rfTransferred; setReactorHeat(StaticUtils.Energy.getTempFromVolumeAndRF(getReactorVolume(), reactorRf)); } // Do passive heat loss - this is always versus external environment tempDiff = getReactorHeat() - getPassiveCoolantTemperature(); if(tempDiff > 0.000001f) { float rfLost = Math.max(1f, tempDiff * reactorHeatLossCoefficient); // Lose at least 1RF/t float reactorNewRf = Math.max(0f, StaticUtils.Energy.getRFFromVolumeAndTemp(getReactorVolume(), getReactorHeat()) - rfLost); setReactorHeat(StaticUtils.Energy.getTempFromVolumeAndRF(getReactorVolume(), reactorNewRf)); } // Prevent cryogenics if(reactorHeat < 0f) { setReactorHeat(0f); } if(fuelHeat < 0f) { setFuelHeat(0f); } // Distribute available power int energyAvailable = (int)getEnergyStored(); int energyRemaining = energyAvailable; if(attachedPowerTaps.size() > 0 && energyRemaining > 0) { // First, try to distribute fairly int splitEnergy = energyRemaining / attachedPowerTaps.size(); for(TileEntityReactorPowerTap powerTap : attachedPowerTaps) { if(energyRemaining <= 0) { break; } if(powerTap == null || !powerTap.isConnected()) { continue; } energyRemaining -= splitEnergy - powerTap.onProvidePower(splitEnergy); } // Next, just hose out whatever we can, if we have any left if(energyRemaining > 0) { for(TileEntityReactorPowerTap powerTap : attachedPowerTaps) { if(energyRemaining <= 0) { break; } if(powerTap == null || !powerTap.isConnected()) { continue; } energyRemaining = powerTap.onProvidePower(energyRemaining); } } } if(energyAvailable != energyRemaining) { reduceStoredEnergy((energyAvailable - energyRemaining)); } // Send updates periodically ticksSinceLastUpdate++; if(ticksSinceLastUpdate >= ticksBetweenUpdates) { ticksSinceLastUpdate = 0; sendTickUpdate(); } // TODO: Overload/overheat // Update any connected tickables for(ITickableMultiblockPart tickable : attachedTickables) { if(tickable == null) { continue; } tickable.onMultiblockServerTick(); } if(attachedGlass.size() > 0 && fuelContainer.shouldUpdate()) { markReferenceCoordForUpdate(); } return (oldHeat != this.getReactorHeat() || oldEnergy != this.getEnergyStored()); } public void setEnergyStored(float oldEnergy) { energyStored = oldEnergy; if(energyStored < 0.0 || Float.isNaN(energyStored)) { energyStored = 0.0f; } else if(energyStored > maxEnergyStored) { energyStored = maxEnergyStored; } } /** * Generate energy, internally. Will be multiplied by the BR Setting powerProductionMultiplier * @param newEnergy Base, unmultiplied energy to generate */ protected void generateEnergy(float newEnergy) { this.energyGeneratedLastTick += newEnergy * BigReactors.powerProductionMultiplier; this.addStoredEnergy(newEnergy * BigReactors.powerProductionMultiplier); } /** * Add some energy to the internal storage buffer. * Will not increase the buffer above the maximum or reduce it below 0. * @param newEnergy */ protected void addStoredEnergy(float newEnergy) { if(Float.isNaN(newEnergy)) { return; } energyStored += newEnergy; if(energyStored > maxEnergyStored) { energyStored = maxEnergyStored; } if(-0.00001f < energyStored && energyStored < 0.00001f) { // Clamp to zero energyStored = 0f; } } /** * Remove some energy from the internal storage buffer. * Will not reduce the buffer below 0. * @param energy Amount by which the buffer should be reduced. */ protected void reduceStoredEnergy(float energy) { this.addStoredEnergy(-1f * energy); } public void setActive(boolean act) { if(act == this.active) { return; } this.active = act; for(IMultiblockPart part : connectedParts) { if(this.active) { part.onMachineActivated(); } else { part.onMachineDeactivated(); } } if(worldObj.isRemote) { // Force controllers to re-render on client for(IMultiblockPart part : attachedControllers) { worldObj.markBlockForUpdate(part.xCoord, part.yCoord, part.zCoord); } } else { this.markReferenceCoordForUpdate(); } } protected void addReactorHeat(float newCasingHeat) { if(Float.isNaN(newCasingHeat)) { return; } reactorHeat += newCasingHeat; // Clamp to zero to prevent floating point issues if(-0.00001f < reactorHeat && reactorHeat < 0.00001f) { reactorHeat = 0.0f; } } public float getReactorHeat() { return reactorHeat; } public void setReactorHeat(float newHeat) { if(Float.isNaN(newHeat)) { reactorHeat = 0.0f; } else { reactorHeat = newHeat; } } protected void addFuelHeat(float additionalHeat) { if(Float.isNaN(additionalHeat)) { return; } fuelHeat += additionalHeat; if(-0.00001f < fuelHeat & fuelHeat < 0.00001f) { fuelHeat = 0f; } } public float getFuelHeat() { return fuelHeat; } public void setFuelHeat(float newFuelHeat) { if(Float.isNaN(newFuelHeat)) { fuelHeat = 0f; } else { fuelHeat = newFuelHeat; } } public int getFuelRodCount() { return attachedControlRods.size(); } // Static validation helpers // Water, air, and metal blocks @Override protected void isBlockGoodForInterior(World world, int x, int y, int z) throws MultiblockValidationException { if(world.isAirBlock(x, y, z)) { return; } // Air is OK Material material = world.getBlock(x, y, z).getMaterial(); if(material == net.minecraft.block.material.MaterialLiquid.water) { return; } Block block = world.getBlock(x, y, z); if(block == Blocks.iron_block || block == Blocks.gold_block || block == Blocks.diamond_block || block == Blocks.emerald_block) { return; } // Permit registered moderator blocks int metadata = world.getBlockMetadata(x, y, z); if(ReactorInterior.getBlockData(ItemHelper.oreProxy.getOreName(new ItemStack(block, 1, metadata))) != null) { return; } // Permit TE fluids if(block != null) { if(block instanceof IFluidBlock) { Fluid fluid = ((IFluidBlock)block).getFluid(); String fluidName = fluid.getName(); if(ReactorInterior.getFluidData(fluidName) != null) { return; } throw new MultiblockValidationException(String.format("%d, %d, %d - The fluid %s is not valid for the reactor's interior", x, y, z, fluidName)); } else { throw new MultiblockValidationException(String.format("%d, %d, %d - %s is not valid for the reactor's interior", x, y, z, block.getLocalizedName())); } } else { throw new MultiblockValidationException(String.format("%d, %d, %d - Null block found, not valid for the reactor's interior", x, y, z)); } } @Override public void writeToNBT(NBTTagCompound data) { data.setBoolean("reactorActive", this.active); data.setFloat("heat", this.reactorHeat); data.setFloat("fuelHeat", fuelHeat); data.setFloat("storedEnergy", this.energyStored); data.setInteger("wasteEjection2", this.wasteEjection.ordinal()); data.setTag("fuelContainer", fuelContainer.writeToNBT(new NBTTagCompound())); data.setTag("radiation", radiationHelper.writeToNBT(new NBTTagCompound())); data.setTag("coolantContainer", coolantContainer.writeToNBT(new NBTTagCompound())); } @Override public void readFromNBT(NBTTagCompound data) { if(data.hasKey("reactorActive")) { setActive(data.getBoolean("reactorActive")); } if(data.hasKey("heat")) { setReactorHeat(Math.max(getReactorHeat(), data.getFloat("heat"))); } if(data.hasKey("storedEnergy")) { setEnergyStored(Math.max(getEnergyStored(), data.getFloat("storedEnergy"))); } if(data.hasKey("wasteEjection")) { this.wasteEjection = s_EjectionSettings[data.getInteger("wasteEjection")]; } if(data.hasKey("fuelHeat")) { setFuelHeat(data.getFloat("fuelHeat")); } if(data.hasKey("fuelContainer")) { fuelContainer.readFromNBT(data.getCompoundTag("fuelContainer")); } if(data.hasKey("radiation")) { radiationHelper.readFromNBT(data.getCompoundTag("radiation")); } if(data.hasKey("coolantContainer")) { coolantContainer.readFromNBT(data.getCompoundTag("coolantContainer")); } } @Override protected int getMinimumNumberOfBlocksForAssembledMachine() { // Hollow cube. return 26; } @Override public void formatDescriptionPacket(NBTTagCompound data) { writeToNBT(data); } @Override public void decodeDescriptionPacket(NBTTagCompound data) { readFromNBT(data); onFuelStatusChanged(); } // Network & Storage methods /* * Serialize a reactor into a given Byte buffer * @param buf The byte buffer to serialize into */ public void serialize(ByteBuf buf) { int fuelTypeID, wasteTypeID, coolantTypeID, vaporTypeID; // Marshal fluid types into integers { Fluid coolantType, vaporType; coolantType = coolantContainer.getCoolantType(); vaporType = coolantContainer.getVaporType(); coolantTypeID = coolantType == null ? -1 : coolantType.getID(); vaporTypeID = vaporType == null ? -1 : vaporType.getID(); } // Basic data buf.writeBoolean(active); buf.writeFloat(reactorHeat); buf.writeFloat(fuelHeat); buf.writeFloat(energyStored); buf.writeFloat(radiationHelper.getFertility()); // Statistics buf.writeFloat(energyGeneratedLastTick); buf.writeFloat(fuelConsumedLastTick); // Coolant data buf.writeInt(coolantTypeID); buf.writeInt(coolantContainer.getCoolantAmount()); buf.writeInt(vaporTypeID); buf.writeInt(coolantContainer.getVaporAmount()); fuelContainer.serialize(buf); } /* * Deserialize a reactor's data from a given Byte buffer * @param buf The byte buffer containing reactor data */ public void deserialize(ByteBuf buf) { // Basic data setActive(buf.readBoolean()); setReactorHeat(buf.readFloat()); setFuelHeat(buf.readFloat()); setEnergyStored(buf.readFloat()); radiationHelper.setFertility(buf.readFloat()); // Statistics setEnergyGeneratedLastTick(buf.readFloat()); setFuelConsumedLastTick(buf.readFloat()); // Coolant data int coolantTypeID = buf.readInt(); int coolantAmt = buf.readInt(); int vaporTypeID = buf.readInt(); int vaporAmt = buf.readInt(); // Fuel & waste data fuelContainer.deserialize(buf); if(coolantTypeID == -1) { coolantContainer.emptyCoolant(); } else { coolantContainer.setCoolant(new FluidStack(FluidRegistry.getFluid(coolantTypeID), coolantAmt)); } if(vaporTypeID == -1) { coolantContainer.emptyVapor(); } else { coolantContainer.setVapor(new FluidStack(FluidRegistry.getFluid(vaporTypeID), vaporAmt)); } } protected IMessage getUpdatePacket() { return new ReactorUpdateMessage(this); } /** * Sends a full state update to a player. */ protected void sendIndividualUpdate(EntityPlayer player) { if(this.worldObj.isRemote) { return; } CommonPacketHandler.INSTANCE.sendTo(getUpdatePacket(), (EntityPlayerMP)player); } /** * Send an update to any clients with GUIs open */ protected void sendTickUpdate() { if(this.worldObj.isRemote) { return; } if(this.updatePlayers.size() <= 0) { return; } for(EntityPlayer player : updatePlayers) { CommonPacketHandler.INSTANCE.sendTo(getUpdatePacket(), (EntityPlayerMP)player); } } /** * Attempt to distribute a stack of ingots to a given access port, sensitive to the amount and type of ingots already in it. * @param port The port to which we're distributing ingots. * @param itemsToDistribute The stack of ingots to distribute. Will be modified during the operation and may be returned with stack size 0. * @param distributeToInputs Should we try to send ingots to input ports? * @return The number of waste items distributed, i.e. the differential in stack size for wasteToDistribute. */ private int tryDistributeItems(TileEntityReactorAccessPort port, ItemStack itemsToDistribute, boolean distributeToInputs) { ItemStack existingStack = port.getStackInSlot(TileEntityReactorAccessPort.SLOT_OUTLET); int initialWasteAmount = itemsToDistribute.stackSize; if(!port.isInlet() || (distributeToInputs || attachedAccessPorts.size() < 2)) { // Dump waste preferentially to outlets, unless we only have one access port if(existingStack == null) { if(itemsToDistribute.stackSize > port.getInventoryStackLimit()) { ItemStack newStack = itemsToDistribute.splitStack(port.getInventoryStackLimit()); port.setInventorySlotContents(TileEntityReactorAccessPort.SLOT_OUTLET, newStack); } else { port.setInventorySlotContents(TileEntityReactorAccessPort.SLOT_OUTLET, itemsToDistribute.copy()); itemsToDistribute.stackSize = 0; } } else if(existingStack.isItemEqual(itemsToDistribute)) { if(existingStack.stackSize + itemsToDistribute.stackSize <= existingStack.getMaxStackSize()) { existingStack.stackSize += itemsToDistribute.stackSize; itemsToDistribute.stackSize = 0; } else { int amt = existingStack.getMaxStackSize() - existingStack.stackSize; itemsToDistribute.stackSize -= existingStack.getMaxStackSize() - existingStack.stackSize; existingStack.stackSize += amt; } } port.onItemsReceived(); } return initialWasteAmount - itemsToDistribute.stackSize; } @Override protected void onAssimilated(MultiblockControllerBase otherMachine) { this.attachedPowerTaps.clear(); this.attachedTickables.clear(); this.attachedAccessPorts.clear(); this.attachedControllers.clear(); this.attachedControlRods.clear(); currentFuelRod = null; } @Override protected void onAssimilate(MultiblockControllerBase otherMachine) { if(!(otherMachine instanceof MultiblockReactor)) { BRLog.warning("[%s] Reactor @ %s is attempting to assimilate a non-Reactor machine! That machine's data will be lost!", worldObj.isRemote?"CLIENT":"SERVER", getReferenceCoord()); return; } MultiblockReactor otherReactor = (MultiblockReactor)otherMachine; if(otherReactor.reactorHeat > this.reactorHeat) { setReactorHeat(otherReactor.reactorHeat); } if(otherReactor.fuelHeat > this.fuelHeat) { setFuelHeat(otherReactor.fuelHeat); } if(otherReactor.getEnergyStored() > this.getEnergyStored()) { this.setEnergyStored(otherReactor.getEnergyStored()); } fuelContainer.merge(otherReactor.fuelContainer); radiationHelper.merge(otherReactor.radiationHelper); coolantContainer.merge(otherReactor.coolantContainer); } @Override public void onAttachedPartWithMultiblockData(IMultiblockPart part, NBTTagCompound data) { this.readFromNBT(data); } public float getEnergyStored() { return energyStored; } /** * Directly set the waste ejection setting. Will dispatch network updates * from server to interested clients. * @param newSetting The new waste ejection setting. */ public void setWasteEjection(WasteEjectionSetting newSetting) { if(this.wasteEjection != newSetting) { this.wasteEjection = newSetting; if(!this.worldObj.isRemote) { if(this.updatePlayers.size() > 0) { CoordTriplet coord = getReferenceCoord(); for(EntityPlayer player : updatePlayers) { CommonPacketHandler.INSTANCE.sendTo(new ReactorUpdateWasteEjectionMessage(this), (EntityPlayerMP)player); } } } } } public WasteEjectionSetting getWasteEjection() { return this.wasteEjection; } protected void refuel() { // For now, we only need to check fuel ports when we have more space than can accomodate 1 ingot if(fuelContainer.getRemainingSpace() < Reactants.standardSolidReactantAmount) { return; } int amtAdded = 0; // Loop: Consume input reactants from all ports for(TileEntityReactorAccessPort port : attachedAccessPorts) { if(fuelContainer.getRemainingSpace() <= 0) { break; } if(port == null || !port.isConnected()) { continue; } // See what type of reactant the port contains; if none, skip it. String portReactantType = port.getInputReactantType(); int portReactantAmount = port.getInputReactantAmount(); if(portReactantType == null || portReactantAmount <= 0) { continue; } if(!Reactants.isFuel(portReactantType)) { continue; } // Skip nonfuels // How much fuel can we actually add from this type of reactant? int amountToAdd = fuelContainer.addFuel(portReactantType, portReactantAmount, false); if(amountToAdd <= 0) { continue; } int portCanAdd = port.consumeReactantItem(amountToAdd); if(portCanAdd <= 0) { continue; } amtAdded = fuelContainer.addFuel(portReactantType, portReactantAmount, true); } if(amtAdded > 0) { markReferenceCoordForUpdate(); markReferenceCoordDirty(); } } /** * Attempt to eject waste contained in the reactor * @param dumpAll If true, any waste remaining after ejection will be discarded. * @param destination If set, waste will only be ejected to ports with coordinates matching this one. */ public void ejectWaste(boolean dumpAll, CoordTriplet destination) { // For now, we can optimize by only running this when we have enough waste to product an ingot int amtEjected = 0; String wasteReactantType = fuelContainer.getWasteType(); if(wasteReactantType == null) { return; } int minimumReactantAmount = Reactants.getMinimumReactantToProduceSolid(wasteReactantType); if(fuelContainer.getWasteAmount() >= minimumReactantAmount) { for(TileEntityReactorAccessPort port : attachedAccessPorts) { if(fuelContainer.getWasteAmount() < minimumReactantAmount) { continue; } if(port == null || !port.isConnected()) { continue; } if(destination != null && !destination.equals(port.xCoord, port.yCoord, port.zCoord)) { continue; } // First time through, we eject only to outlet ports if(destination == null && !port.isInlet()) { int reactantEjected = port.emitReactant(wasteReactantType, fuelContainer.getWasteAmount()); fuelContainer.dumpWaste(reactantEjected); amtEjected += reactantEjected; } } if(destination == null && fuelContainer.getWasteAmount() > minimumReactantAmount) { // Loop a second time when destination is null and we still have waste for(TileEntityReactorAccessPort port : attachedAccessPorts) { if(fuelContainer.getWasteAmount() < minimumReactantAmount) { continue; } if(port == null || !port.isConnected()) { continue; } int reactantEjected = port.emitReactant(wasteReactantType, fuelContainer.getWasteAmount()); fuelContainer.dumpWaste(reactantEjected); amtEjected += reactantEjected; } } } if(dumpAll) { amtEjected += fuelContainer.getWasteAmount(); fuelContainer.setWaste(null); } else { fuelContainer.dumpWaste(amtEjected); } if(amtEjected > 0) { markReferenceCoordForUpdate(); markReferenceCoordDirty(); } } /** * Eject fuel contained in the reactor. * @param dumpAll If true, any remaining fuel will simply be lost. * @param destination If not null, then fuel will only be distributed to a port matching these coordinates. */ public void ejectFuel(boolean dumpAll, CoordTriplet destination) { // For now, we can optimize by only running this when we have enough waste to product an ingot int amtEjected = 0; String fuelReactantType = fuelContainer.getFuelType(); if(fuelReactantType == null) { return; } int minimumReactantAmount = Reactants.getMinimumReactantToProduceSolid(fuelReactantType); if(fuelContainer.getFuelAmount() >= minimumReactantAmount) { for(TileEntityReactorAccessPort port : attachedAccessPorts) { if(fuelContainer.getFuelAmount() < minimumReactantAmount) { continue; } if(port == null || !port.isConnected()) { continue; } if(destination != null && !destination.equals(port.xCoord, port.yCoord, port.zCoord)) { continue; } int reactantEjected = port.emitReactant(fuelReactantType, fuelContainer.getFuelAmount()); fuelContainer.dumpFuel(reactantEjected); amtEjected += reactantEjected; } } if(dumpAll) { amtEjected += fuelContainer.getFuelAmount(); fuelContainer.setFuel(null); } else { fuelContainer.dumpFuel(amtEjected); } if(amtEjected > 0) { markReferenceCoordForUpdate(); markReferenceCoordDirty(); } } @Override protected void onMachineAssembled() { recalculateDerivedValues(); } @Override protected void onMachineRestored() { recalculateDerivedValues(); } @Override protected void onMachinePaused() { } @Override protected void onMachineDisassembled() { this.active = false; } private void recalculateDerivedValues() { // Recalculate size of fuel/waste tank via fuel rods CoordTriplet minCoord, maxCoord; minCoord = getMinimumCoord(); maxCoord = getMaximumCoord(); fuelContainer.setCapacity(attachedFuelRods.size() * FuelCapacityPerFuelRod); // Calculate derived stats // Calculate heat transfer based on fuel rod environment fuelToReactorHeatTransferCoefficient = 0f; for(TileEntityReactorFuelRod fuelRod : attachedFuelRods) { fuelToReactorHeatTransferCoefficient += fuelRod.getHeatTransferRate(); } // Pick a random fuel rod Y as a starting point int maxFuelRodY = maxCoord.y - 1; int minFuelRodY = minCoord.y + 1; currentFuelRod = attachedFuelRods.iterator(); // Calculate heat transfer to coolant system based on reactor interior surface area. // This is pretty simple to start with - surface area of the rectangular prism defining the interior. int xSize = maxCoord.x - minCoord.x - 1; int ySize = maxCoord.y - minCoord.y - 1; int zSize = maxCoord.z - minCoord.z - 1; int surfaceArea = 2 * (xSize * ySize + xSize * zSize + ySize * zSize); reactorToCoolantSystemHeatTransferCoefficient = IHeatEntity.conductivityIron * surfaceArea; // Calculate passive heat loss. // Get external surface area xSize += 2; ySize += 2; zSize += 2; surfaceArea = 2 * (xSize * ySize + xSize * zSize + ySize * zSize); reactorHeatLossCoefficient = reactorHeatLossConductivity * surfaceArea; if(worldObj.isRemote) { // Make sure our fuel rods re-render this.onFuelStatusChanged(); } else { // Force an update of the client's multiblock information markReferenceCoordForUpdate(); } calculateReactorVolume(); if(attachedCoolantPorts.size() > 0) { int outerVolume = StaticUtils.ExtraMath.Volume(minCoord, maxCoord) - reactorVolume; coolantContainer.setCapacity(Math.max(0, Math.min(50000, outerVolume * 100))); } else { coolantContainer.setCapacity(0); } } @Override protected int getMaximumXSize() { return BigReactors.maximumReactorSize; } @Override protected int getMaximumZSize() { return BigReactors.maximumReactorSize; } @Override protected int getMaximumYSize() { return BigReactors.maximumReactorHeight; } /** * Used to update the UI */ public void setEnergyGeneratedLastTick(float energyGeneratedLastTick) { this.energyGeneratedLastTick = energyGeneratedLastTick; } /** * UI Helper */ public float getEnergyGeneratedLastTick() { return this.energyGeneratedLastTick; } /** * Used to update the UI */ public void setFuelConsumedLastTick(float fuelConsumed) { fuelConsumedLastTick = fuelConsumed; } /** * UI Helper */ public float getFuelConsumedLastTick() { return fuelConsumedLastTick; } /** * UI Helper * @return Percentile fuel richness (fuel/fuel+waste), or 0 if all control rods are empty */ public float getFuelRichness() { int amtFuel, amtWaste; amtFuel = fuelContainer.getFuelAmount(); amtWaste = fuelContainer.getWasteAmount(); if(amtFuel + amtWaste <= 0f) { return 0f; } else { return (float)amtFuel / (float)(amtFuel+amtWaste); } } /** DO NOT USE **/ @Override public int receiveEnergy(ForgeDirection from, int maxReceive, boolean simulate) { int amtReceived = (int)Math.min(maxReceive, Math.floor(this.maxEnergyStored - this.energyStored)); if(!simulate) { this.addStoredEnergy(amtReceived); } return amtReceived; } @Override public int extractEnergy(ForgeDirection from, int maxExtract, boolean simulate) { int amtRemoved = (int)Math.min(maxExtract, this.energyStored); if(!simulate) { this.reduceStoredEnergy(amtRemoved); } return amtRemoved; } @Override public boolean canConnectEnergy(ForgeDirection from) { return false; } @Override public int getEnergyStored(ForgeDirection from) { return (int)energyStored; } @Override public int getMaxEnergyStored(ForgeDirection from) { return maxEnergyStored; } // Redstone helper public void setAllControlRodInsertionValues(int newValue) { if(this.assemblyState != AssemblyState.Assembled) { return; } for(TileEntityReactorControlRod cr : attachedControlRods) { if(cr != null && cr.isConnected()) { cr.setControlRodInsertion((short)newValue); } } } public void changeAllControlRodInsertionValues(short delta) { if(this.assemblyState != AssemblyState.Assembled) { return; } for(TileEntityReactorControlRod cr : attachedControlRods) { if(cr != null && cr.isConnected()) { cr.setControlRodInsertion( (short) (cr.getControlRodInsertion() + delta) ); } } } public CoordTriplet[] getControlRodLocations() { CoordTriplet[] coords = new CoordTriplet[this.attachedControlRods.size()]; int i = 0; for(TileEntityReactorControlRod cr : attachedControlRods) { coords[i++] = cr.getWorldLocation(); } return coords; } public int getFuelAmount() { return fuelContainer.getFuelAmount(); } public int getWasteAmount() { return fuelContainer.getWasteAmount(); } public String getFuelType() { return fuelContainer.getFuelType(); } public String getWasteType() { return fuelContainer.getWasteType(); } public int getEnergyStoredPercentage() { return (int)(this.energyStored / (float)this.maxEnergyStored * 100f); } @Override public int getCapacity() { if(worldObj.isRemote && assemblyState != AssemblyState.Assembled) { // Estimate capacity return attachedFuelRods.size() * FuelCapacityPerFuelRod; } return fuelContainer.getCapacity(); } public float getFuelFertility() { return radiationHelper.getFertilityModifier(); } // Coolant subsystem public CoolantContainer getCoolantContainer() { return coolantContainer; } protected float getPassiveCoolantTemperature() { return IHeatEntity.ambientHeat; } protected float getCoolantTemperature() { if(isPassivelyCooled()) { return getPassiveCoolantTemperature(); } else { return coolantContainer.getCoolantTemperature(getReactorHeat()); } } public boolean isPassivelyCooled() { if(coolantContainer == null || coolantContainer.getCapacity() <= 0) { return true; } else { return false; } } protected int getReactorVolume() { return reactorVolume; } protected void calculateReactorVolume() { CoordTriplet minInteriorCoord = getMinimumCoord(); minInteriorCoord.x += 1; minInteriorCoord.y += 1; minInteriorCoord.z += 1; CoordTriplet maxInteriorCoord = getMaximumCoord(); maxInteriorCoord.x -= 1; maxInteriorCoord.y -= 1; maxInteriorCoord.z -= 1; reactorVolume = StaticUtils.ExtraMath.Volume(minInteriorCoord, maxInteriorCoord); } // Client-only protected void onFuelStatusChanged() { if(worldObj.isRemote) { // On the client, re-render all the fuel rod blocks when the fuel status changes for(TileEntityReactorFuelRod fuelRod : attachedFuelRods) { worldObj.markBlockForUpdate(fuelRod.xCoord, fuelRod.yCoord, fuelRod.zCoord); } } } private static final FluidTankInfo[] emptyTankInfo = new FluidTankInfo[0]; @Override public FluidTankInfo[] getTankInfo() { if(isPassivelyCooled()) { return emptyTankInfo; } return coolantContainer.getTankInfo(-1); } protected void markReferenceCoordForUpdate() { CoordTriplet rc = getReferenceCoord(); if(worldObj != null && rc != null) { worldObj.markBlockForUpdate(rc.x, rc.y, rc.z); } } protected void markReferenceCoordDirty() { if(worldObj == null || worldObj.isRemote) { return; } CoordTriplet referenceCoord = getReferenceCoord(); if(referenceCoord == null) { return; } TileEntity saveTe = worldObj.getTileEntity(referenceCoord.x, referenceCoord.y, referenceCoord.z); worldObj.markTileEntityChunkModified(referenceCoord.x, referenceCoord.y, referenceCoord.z, saveTe); } @Override public boolean getActive() { return this.active; } public String getDebugInfo() { StringBuilder sb = new StringBuilder(); sb.append("Assembled: ").append(Boolean.toString(isAssembled())).append("\n"); sb.append("Attached Blocks: ").append(Integer.toString(connectedParts.size())).append("\n"); if(getLastValidationException() != null) { sb.append("Validation Exception:\n").append(getLastValidationException().getMessage()).append("\n"); } if(isAssembled()) { sb.append("\nActive: ").append(Boolean.toString(getActive())); sb.append("\nStored Energy: ").append(Float.toString(getEnergyStored())); sb.append("\nCasing Heat: ").append(Float.toString(getReactorHeat())); sb.append("\nFuel Heat: ").append(Float.toString(getFuelHeat())); sb.append("\n\nReactant Tanks:\n"); sb.append( fuelContainer.getDebugInfo() ); sb.append("\n\nActively Cooled: ").append(Boolean.toString(!isPassivelyCooled())); if(!isPassivelyCooled()) { sb.append("\n\nCoolant Tanks:\n"); sb.append( coolantContainer.getDebugInfo() ); } } return sb.toString(); } }
Reactor is erroneously dumping extra fuel/waste when commanded to. May be related to #332
src/main/java/erogenousbeef/bigreactors/common/multiblock/MultiblockReactor.java
Reactor is erroneously dumping extra fuel/waste when commanded to. May be related to #332
<ide><path>rc/main/java/erogenousbeef/bigreactors/common/multiblock/MultiblockReactor.java <ide> amtEjected += fuelContainer.getWasteAmount(); <ide> fuelContainer.setWaste(null); <ide> } <del> else { <del> fuelContainer.dumpWaste(amtEjected); <del> } <ide> <ide> if(amtEjected > 0) { <ide> markReferenceCoordForUpdate(); <ide> amtEjected += fuelContainer.getFuelAmount(); <ide> fuelContainer.setFuel(null); <ide> } <del> else { <del> fuelContainer.dumpFuel(amtEjected); <del> } <ide> <ide> if(amtEjected > 0) { <ide> markReferenceCoordForUpdate();
Java
apache-2.0
25407088d363fa863fa09b93b38c8285ac3e98ac
0
Nevnin/Magazyn
import javax.swing.JPanel; import javax.swing.JSplitPane; import javax.swing.ListSelectionModel; import javax.swing.event.ListSelectionEvent; import javax.swing.event.ListSelectionListener; import java.awt.Dimension; import java.sql.Connection; import java.sql.DriverManager; import java.sql.PreparedStatement; import java.sql.ResultSet; import java.sql.SQLException; import java.sql.Statement; import java.util.Date; import javax.swing.JButton; import javax.swing.JList; import java.awt.GridLayout; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import java.awt.Color; import javax.swing.border.LineBorder; public class Zamowienie extends JPanel implements ActionListener { String serverName = "localhost"; String mydatabase = "magazyn"; String url = "jdbc:mysql://" + serverName + "/" + mydatabase; String username = "root"; String password = ""; Polaczenie poloczenie; public JList list_1,list_2; private JList list_1_2; private JList list_1_1; String[] tablica; String[] tablica1; JButton zamow ; JSplitPane splitPane; PanelDoZam p; public Zamowienie() { setBorder(new LineBorder(new Color(0, 0, 0))); setPreferredSize(new Dimension(400,300)); GridLayout g= new GridLayout(2,1); setLayout(g); try { poloczenie = new Polaczenie(); } catch (SQLException e) { // TODO Auto-generated catch block e.printStackTrace(); } try { String query1 = "SELECT * FROM `towar` WHERE StanMagazynowyDysponowany < MinStanMagazynowy"; ResultSet rs = poloczenie.sqlSelect(query1); rs.last(); int rozmiar = rs.getRow(); rs.beforeFirst(); int i =0; tablica= new String[rozmiar]; while(rs.next()) { tablica[i]=rs.getString(2); i++; } } catch (SQLException e) { // TODO Auto-generated catch block e.printStackTrace(); } // SimpleDateFormat dt= new SimpleDateFormat("yyyy-MM-dd"); // Date data = new Date(); // System.out.println(dt.format(data)); splitPane = new JSplitPane(); splitPane.setBounds(85, 5, 207, 202); // splitPane.setPreferredSize(new Dimension(400, 400)); // splitPane.setMinimumSize(new Dimension(400, 200)); add(splitPane,g); list_2 = new JList(); list_2.setPreferredSize(new Dimension(200,200)); list_2.setSelectionMode(ListSelectionModel.SINGLE_SELECTION); splitPane.setRightComponent(list_2); list_1_2 = new JList(tablica); list_1_2.setSize(new Dimension(200,200)); // list_1.setPreferredSize(new Dimension(200, 10)); list_1_2.setSelectionMode(ListSelectionModel.SINGLE_SELECTION); list_1_2.addListSelectionListener(new ListSelectionListener(){ @Override public void valueChanged(ListSelectionEvent e) { if(e.getValueIsAdjusting()==true) { String query = "SELECT dostawca.NazwaSkrocona FROM `towar` INNER JOIN dostawcatowar ON dostawcatowar.IdTowar=towar.IdTowar INNER JOIN dostawca ON dostawca.IdDostawca= dostawcatowar.IdDostawca WHERE towar.NazwaTowaru ='"+list_1_2.getSelectedValue()+"'GROUP BY dostawca.NazwaSkrocona"; try { ResultSet rs = poloczenie.sqlSelect(query); rs.last(); int rozmiar = rs.getRow(); rs.beforeFirst(); tablica1 = new String[rozmiar]; int i =0; while(rs.next()) { tablica1[i]=rs.getString(1); i++; } list_2 = new JList(tablica1); list_2.setPreferredSize(new Dimension(200,200)); list_2.setSelectionMode(ListSelectionModel.SINGLE_SELECTION); list_2.addListSelectionListener(new ListSelectionListener(){ @Override public void valueChanged(ListSelectionEvent e) { if(e.getValueIsAdjusting()==true) { p = new PanelDoZam(0); add(p,g); ustawNasluchZdarzen(); validate(); repaint(); } }}); splitPane.setRightComponent(list_2); list_2.setAlignmentX(CENTER_ALIGNMENT); validate(); repaint(); } catch (SQLException e1) { // TODO Auto-generated catch block e1.printStackTrace(); } } }}); splitPane.setLeftComponent(list_1_2); } private void ustawNasluchZdarzen() { p.zamow.addActionListener(this); } public void Zamowienie(Date TerminRealizacji, Date DataRealizacji,float KosztZamowienia , int IdDostawcy , String NumerZamowienia, String SposobDostawy , float KosztDostawy) throws SQLException { Connection connection = DriverManager.getConnection(url, username, password); String query = "INSERT INTO zamowienie " + "(TerminReallizacji,DataRealizacji,KosztZamowienia,IdDostawcy,DataWystawienia,NumerZamowienia,SposobDostawy,KosztDostawy,WartoscTowarow)" + " values (?, ?, ?, ?, ?, ?,?,?,?)"; PreparedStatement preparedStmt = connection.prepareStatement(query,Statement.RETURN_GENERATED_KEYS); preparedStmt.setDate (1,(java.sql.Date) TerminRealizacji); preparedStmt.setDate (2,(java.sql.Date) DataRealizacji); preparedStmt.setFloat (3,KosztZamowienia); preparedStmt.setInt (4,IdDostawcy); Date dzis = new Date(); preparedStmt.setDate (5,(java.sql.Date) dzis); preparedStmt.setString (6,NumerZamowienia); preparedStmt.setString (7,SposobDostawy); preparedStmt.setFloat (8,KosztDostawy); float WartoscDostawy = KosztDostawy+KosztZamowienia; preparedStmt.setFloat (9,WartoscDostawy); preparedStmt.execute(); connection.close(); } public void dodanieTowaruDoZamowienia(int idZam, int idTow,int ilosc, double cena) throws SQLException { Connection connection = DriverManager.getConnection(url, username, password); String query = "INSERT INTO zamowienietowar " + "(LP,IdTowar,Cena,Ilosc,WartoscNetto,IdZamowienie)" + " values (?, ?, ?, ?, ?, ?)"; int LP = LP(idZam)+1; PreparedStatement preparedStmt = connection.prepareStatement(query,Statement.RETURN_GENERATED_KEYS); preparedStmt.setInt (1,LP); preparedStmt.setInt (2, idTow); preparedStmt.setDouble (3, cena); preparedStmt.setInt (4, ilosc); double wartosc= cena * ilosc; preparedStmt.setDouble (5,wartosc); preparedStmt.setInt (6,idZam); preparedStmt.execute(); String query2= "UPDATE zamowienie set KosztZamowienia =KosztZamowienia + ? WHERE IdZamowienie=?"; PreparedStatement preparedStmt2 = connection.prepareStatement(query2); preparedStmt2.setDouble(1,wartosc); preparedStmt2.setInt(2,idZam); preparedStmt.execute(); connection.close(); } public int LP(int idZam) { String query = "Select LP from zamowienietowar INNER JOIN zamowienie WHERE IdZamowienie="+idZam; ResultSet rs; int LP=0; try { rs = poloczenie.sqlSelect(query); while(rs.next()) { if(LP<rs.getInt(1)) { LP=rs.getInt(1); } } } catch (SQLException e) { // TODO Auto-generated catch block e.printStackTrace(); } return LP; } @Override public void actionPerformed(ActionEvent e) { Object z= e.getSource(); if(z==p.zamow) { } } }
src/Zamowienie.java
import javax.swing.JPanel; import javax.swing.JScrollPane; import javax.swing.JSplitPane; import javax.swing.JTextField; import javax.swing.ListModel; import javax.swing.ListSelectionModel; import javax.swing.border.Border; import javax.swing.event.ListSelectionEvent; import javax.swing.event.ListSelectionListener; import java.awt.Dimension; import java.sql.Connection; import java.sql.DriverManager; import java.sql.PreparedStatement; import java.sql.ResultSet; import java.sql.SQLException; import java.sql.Statement; import java.text.SimpleDateFormat; import java.util.Calendar; import java.util.Date; import java.util.Properties; import javax.swing.JButton; import javax.swing.JDesktopPane; import javax.swing.JLabel; import javax.swing.JList; import java.awt.FlowLayout; import java.awt.GridBagConstraints; import java.awt.GridBagLayout; import java.awt.GridLayout; import java.awt.Label; import java.awt.TextField; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import org.eclipse.wb.swing.FocusTraversalOnArray; import org.jdatepicker.impl.JDatePanelImpl; import org.jdatepicker.impl.JDatePickerImpl; import org.jdatepicker.impl.UtilDateModel; import javafx.scene.Scene; import javafx.scene.control.DatePicker; import javafx.scene.layout.VBox; import java.awt.Button; import java.awt.Color; import java.awt.Component; import javax.swing.border.LineBorder; public class Zamowienie extends JPanel implements ActionListener { String serverName = "localhost"; String mydatabase = "magazyn"; String url = "jdbc:mysql://" + serverName + "/" + mydatabase; String username = "root"; String password = ""; Polaczenie poloczenie; public JList list_1,list_2; private JList list_1_2; private JList list_1_1; String[] tablica; String[] tablica1; JButton zamow ; JSplitPane splitPane; PanelDoZam p; public Zamowienie() { setBorder(new LineBorder(new Color(0, 0, 0))); setPreferredSize(new Dimension(400,300)); GridLayout g= new GridLayout(2,1); setLayout(g); try { poloczenie = new Polaczenie(); } catch (SQLException e) { // TODO Auto-generated catch block e.printStackTrace(); } try { String query1 = "SELECT * FROM `towar` WHERE StanMagazynowyDysponowany < MinStanMagazynowy"; ResultSet rs = poloczenie.sqlSelect(query1); rs.last(); int rozmiar = rs.getRow(); rs.beforeFirst(); int i =0; tablica= new String[rozmiar]; while(rs.next()) { tablica[i]=rs.getString(2); i++; } } catch (SQLException e) { // TODO Auto-generated catch block e.printStackTrace(); } // SimpleDateFormat dt= new SimpleDateFormat("yyyy-MM-dd"); // Date data = new Date(); // System.out.println(dt.format(data)); splitPane = new JSplitPane(); splitPane.setBounds(85, 5, 207, 202); // splitPane.setPreferredSize(new Dimension(400, 400)); // splitPane.setMinimumSize(new Dimension(400, 200)); add(splitPane,g); list_2 = new JList(); list_2.setPreferredSize(new Dimension(200,200)); list_2.setSelectionMode(ListSelectionModel.SINGLE_SELECTION); splitPane.setRightComponent(list_2); list_1_2 = new JList(tablica); list_1_2.setSize(new Dimension(200,200)); // list_1.setPreferredSize(new Dimension(200, 10)); list_1_2.setSelectionMode(ListSelectionModel.SINGLE_SELECTION); list_1_2.addListSelectionListener(new ListSelectionListener(){ @Override public void valueChanged(ListSelectionEvent e) { if(e.getValueIsAdjusting()==true) { String query = "SELECT dostawca.NazwaSkrocona FROM `towar` INNER JOIN dostawcatowar ON dostawcatowar.IdTowar=towar.IdTowar INNER JOIN dostawca ON dostawca.IdDostawca= dostawcatowar.IdDostawca WHERE towar.NazwaTowaru ='"+list_1_2.getSelectedValue()+"'GROUP BY dostawca.NazwaSkrocona"; try { ResultSet rs = poloczenie.sqlSelect(query); rs.last(); int rozmiar = rs.getRow(); rs.beforeFirst(); tablica1 = new String[rozmiar]; int i =0; while(rs.next()) { tablica1[i]=rs.getString(1); i++; } list_2 = new JList(tablica1); list_2.setPreferredSize(new Dimension(200,200)); list_2.setSelectionMode(ListSelectionModel.SINGLE_SELECTION); list_2.addListSelectionListener(new ListSelectionListener(){ @Override public void valueChanged(ListSelectionEvent e) { if(e.getValueIsAdjusting()==true) { p = new PanelDoZam(0); add(p,g); ustawNasluchZdarzen(); validate(); repaint(); } }}); splitPane.setRightComponent(list_2); list_2.setAlignmentX(CENTER_ALIGNMENT); validate(); repaint(); } catch (SQLException e1) { // TODO Auto-generated catch block e1.printStackTrace(); } } }}); splitPane.setLeftComponent(list_1_2); } private void ustawNasluchZdarzen() { p.zamow.addActionListener(this); } public void Zamowienie(Date TerminRealizacji, Date DataRealizacji,float KosztZamowienia , int IdDostawcy , String NumerZamowienia, String SposobDostawy , float KosztDostawy) throws SQLException { Connection connection = DriverManager.getConnection(url, username, password); String query = "INSERT INTO zamowienie " + "(TerminReallizacji,DataRealizacji,KosztZamowienia,IdDostawcy,DataWystawienia,NumerZamowienia,SposobDostawy,KosztDostawy,WartoscTowarow)" + " values (?, ?, ?, ?, ?, ?,?,?,?)"; PreparedStatement preparedStmt = connection.prepareStatement(query,Statement.RETURN_GENERATED_KEYS); preparedStmt.setDate (1,(java.sql.Date) TerminRealizacji); preparedStmt.setDate (2,(java.sql.Date) DataRealizacji); preparedStmt.setFloat (3,KosztZamowienia); preparedStmt.setInt (4,IdDostawcy); Date dzis = new Date(); preparedStmt.setDate (5,(java.sql.Date) dzis); preparedStmt.setString (6,NumerZamowienia); preparedStmt.setString (7,SposobDostawy); preparedStmt.setFloat (8,KosztDostawy); float WartoscDostawy = KosztDostawy+KosztZamowienia; preparedStmt.setFloat (9,WartoscDostawy); preparedStmt.execute(); connection.close(); } public void dodanieTowaruDoZamowienia(int idZam, int idTow,int ilosc, double cena) throws SQLException { Connection connection = DriverManager.getConnection(url, username, password); String query = "INSERT INTO zamowienietowar " + "(LP,IdTowar,Cena,Ilosc,WartoscNetto,IdZamowienie)" + " values (?, ?, ?, ?, ?, ?)"; int LP = LP(idZam)+1; PreparedStatement preparedStmt = connection.prepareStatement(query,Statement.RETURN_GENERATED_KEYS); preparedStmt.setInt (1,LP); preparedStmt.setInt (2, idTow); preparedStmt.setDouble (3, cena); preparedStmt.setInt (4, ilosc); double wartosc= cena * ilosc; preparedStmt.setDouble (5,wartosc); preparedStmt.setInt (6,idZam); preparedStmt.execute(); String query2= "UPDATE zamowienie set KosztZamowienia =KosztZamowienia + ? WHERE IdZamowienie=?"; PreparedStatement preparedStmt2 = connection.prepareStatement(query2); preparedStmt2.setDouble(1,wartosc); preparedStmt2.setInt(2,idZam); preparedStmt.execute(); connection.close(); } public int LP(int idZam) { String query = "Select LP from zamowienietowar INNER JOIN zamowienie WHERE IdZamowienie="+idZam; ResultSet rs; int LP=0; try { rs = poloczenie.sqlSelect(query); while(rs.next()) { if(LP<rs.getInt(1)) { LP=rs.getInt(1); } } } catch (SQLException e) { // TODO Auto-generated catch block e.printStackTrace(); } return LP; } @Override public void actionPerformed(ActionEvent e) { Object z= e.getSource(); if(z==p.zamow) { } } }
usuwanie importow
src/Zamowienie.java
usuwanie importow
<ide><path>rc/Zamowienie.java <ide> import javax.swing.JPanel; <del>import javax.swing.JScrollPane; <ide> import javax.swing.JSplitPane; <del>import javax.swing.JTextField; <del>import javax.swing.ListModel; <ide> import javax.swing.ListSelectionModel; <del>import javax.swing.border.Border; <ide> import javax.swing.event.ListSelectionEvent; <ide> import javax.swing.event.ListSelectionListener; <ide> <ide> import java.sql.ResultSet; <ide> import java.sql.SQLException; <ide> import java.sql.Statement; <del>import java.text.SimpleDateFormat; <del>import java.util.Calendar; <ide> import java.util.Date; <del>import java.util.Properties; <ide> <ide> import javax.swing.JButton; <del>import javax.swing.JDesktopPane; <del>import javax.swing.JLabel; <ide> import javax.swing.JList; <del>import java.awt.FlowLayout; <del>import java.awt.GridBagConstraints; <del>import java.awt.GridBagLayout; <ide> import java.awt.GridLayout; <del>import java.awt.Label; <del>import java.awt.TextField; <ide> import java.awt.event.ActionEvent; <ide> import java.awt.event.ActionListener; <ide> <del>import org.eclipse.wb.swing.FocusTraversalOnArray; <del>import org.jdatepicker.impl.JDatePanelImpl; <del>import org.jdatepicker.impl.JDatePickerImpl; <del>import org.jdatepicker.impl.UtilDateModel; <del> <del>import javafx.scene.Scene; <del>import javafx.scene.control.DatePicker; <del>import javafx.scene.layout.VBox; <del> <del>import java.awt.Button; <ide> import java.awt.Color; <del>import java.awt.Component; <ide> import javax.swing.border.LineBorder; <ide> <ide> public class Zamowienie extends JPanel implements ActionListener {
Java
apache-2.0
53bb2d9185c615109a1134b75a98b783cbdd0eec
0
MyersResearchGroup/iBioSim,MyersResearchGroup/iBioSim,MyersResearchGroup/iBioSim
package biomodel.util; public class GlobalConstants { public static final String ACTIVATED_RNAP_BINDING_STRING = "Kao"; public static final String FORWARD_ACTIVATED_RNAP_BINDING_STRING = "kao_f"; public static final String REVERSE_ACTIVATED_RNAP_BINDING_STRING = "kao_r"; public static final String RNAP_BINDING_STRING = "Ko"; public static final String FORWARD_RNAP_BINDING_STRING = "ko_f"; public static final String REVERSE_RNAP_BINDING_STRING = "ko_r"; public static final String KREP_STRING = "Kr"; public static final String FORWARD_KREP_STRING = "kr_f"; public static final String REVERSE_KREP_STRING = "kr_r"; public static final String KACT_STRING = "Ka"; public static final String FORWARD_KACT_STRING = "ka_f"; public static final String REVERSE_KACT_STRING = "ka_r"; public static final String KCOMPLEX_STRING = "Kc"; public static final String FORWARD_KCOMPLEX_STRING = "kc_f"; public static final String REVERSE_KCOMPLEX_STRING = "kc_r"; public static final String MEMDIFF_STRING = "kmdiff"; public static final String FORWARD_MEMDIFF_STRING = "kmdiff_f"; public static final String REVERSE_MEMDIFF_STRING = "kmdiff_r"; // public static final String KBIO_STRING = "Kbio"; public static final String OCR_STRING = "ko"; public static final String KBASAL_STRING = "kb"; public static final String ACTIVATED_STRING = "ka"; public static final String KDECAY_STRING = "kd"; public static final String KECDIFF_STRING = "kecdiff"; public static final String KECDECAY_STRING = "kecd"; public static final String PROMOTER_COUNT_STRING = "ng"; public static final String RNAP_STRING = "nr"; public static final String STOICHIOMETRY_STRING = "np"; public static final String COOPERATIVITY_STRING = "nc"; public static final String COMPLEX = "complex"; public static final String DIFFUSIBLE = "diffusible"; public static final String KASSOCIATION_STRING = "Kassociation"; // Dimerization value public static final String GENE_PRODUCT = "gene product"; public static final String TRANSCRIPTION_FACTOR = "transcription factor"; // public static final String KREP_VALUE = ".5"; // public static final String KACT_VALUE = ".0033"; // public static final String KBIO_VALUE = ".05"; // public static final String PROMOTER_COUNT_VALUE = "2"; // public static final String KASSOCIATION_VALUE = ".05"; // public static final String KBASAL_VALUE = ".0001"; // public static final String OCR_VALUE = ".05"; // public static final String KDECAY_VALUE = ".0075"; // public static final String RNAP_VALUE = "30"; // public static final String RNAP_BINDING_VALUE = ".033"; // public static final String STOICHIOMETRY_VALUE = "10"; // public static final String COOPERATIVITY_VALUE = "2"; // public static final String ACTIVED_VALUE = ".25"; public static final String ID = "ID"; public static final String COMPONENT = "Component"; public static final String SPECIES = "Species"; public static final String INFLUENCE = "Influence"; public static final String COMPONENT_CONNECTION = "Component Connection"; public static final String PRODUCTION = "Production"; public static final String REACTION = "Reaction"; public static final String MODIFIER = "Modifier"; public static final String REACTION_EDGE = "Reaction_Edge"; public static final String RULE_EDGE = "Rule_Edge"; public static final String CONSTRAINT_EDGE = "Constraint_Edge"; public static final String EVENT_EDGE = "Event_Edge"; public static final String PETRI_NET_EDGE = "Petri_Net_Edge"; public static final String GRID_RECTANGLE = "Grid Rectangle"; public static final String PORTMAP = "Port Map"; public static final String PORT = "port"; public static final String NAME = "Name"; public static final String CONSTANT = "boundary"; public static final String SPASTIC = "constitutive"; public static final String DEGRADES = "degrades"; public static final String NORMAL = "normal"; public static final String INPUT = "input"; public static final String OUTPUT = "output"; public static final String INTERNAL = "internal"; public static final String TYPE = "Port Type"; public static final String MAX_DIMER_STRING = "N-mer as trascription factor"; public static final String INITIAL_STRING = "ns"; public static final String PROMOTER = "Promoter"; public static final String VARIABLE = "Variable"; public static final String PLACE = "Place"; public static final String BOOLEAN = "Boolean"; public static final String MRNA = "mRNA"; public static final String EXPLICIT_PROMOTER = "ExplicitPromoter"; public static final String SBMLFILE = "SBML file"; public static final String BIOABS = "Biochemical abstraction"; public static final String DIMABS = "Dimerization abstraction"; public static final String COMPARTMENT = "compartment"; public static final String PARAMETER = "parameter"; public static final String LOCALPARAMETER = "localParameter"; public static final String SBMLSPECIES = "species"; public static final String SBMLREACTION = "reaction"; public static final String EVENT = "event"; public static final String TRANSITION = "transition"; public static final String CONSTRAINT = "constraint"; public static final String FUNCTION = "functionDefinition"; public static final String UNIT = "unitDefinition"; public static final String RULE = "rule"; public static final String ASSIGNMENT_RULE = "assignmentRule"; public static final String INITIAL_ASSIGNMENT = "initialAssignment"; public static final String RATE_RULE = "rateRule"; public static final String ALGEBRAIC_RULE = "algebraicRule"; public static final String GLYPH = "Glyph"; public static final String REACTANT_GLYPH = "ReactantGlyph"; public static final String PRODUCT_GLYPH = "ProductGlyph"; public static final String MODIFIER_GLYPH = "ModifierGlyph"; public static final String TEXT_GLYPH = "TextGlyph"; public static final String ENCLOSING_COMPARTMENT = "enclosingCompartment"; public static final String DEFAULT_COMPARTMENT = "defaultCompartment"; public static final String FAIL = "fail"; public static final String FAIL_TRANSITION = "failTransition"; public static final String RATE = "rate"; public static final String TRIGGER = "trigger"; public static final String SBOL_PROMOTER = "sbolPromoter"; public static final String SBOL_TERMINATOR = "sbolTerminator"; public static final String SBOL_RBS = "sbolRBS"; public static final String SBOL_CDS = "sbolCDS"; public static final String SO_PROMOTER = "SO_0000167"; public static final String SO_TERMINATOR = "SO_0000141"; public static final String SO_RBS = "SO_0000139"; public static final String SO_CDS = "SO_0000316"; public static final String SO_AUTHORITY = "purl.obolibrary.org"; public static final String SBOL_DNA_COMPONENT = "sbolDnaComponent"; public static final String GENETIC_CONSTRUCT_REGEX_DEFAULT = SO_PROMOTER + "(" + SO_RBS + "," + SO_CDS + ")+" + SO_TERMINATOR + "+"; public static final String GENETIC_CONSTRUCT_REGEX_PREFERENCE = "biosim.assembly.regex"; public static final String SBOL_AUTHORITY_PREFERENCE = "biosim.assembly.authority"; public static final String SBOL_AUTHORITY_DEFAULT = "http://www.async.ece.utah.edu"; public static final String CONSTRUCT_VALIDATION_DEFAULT = "True"; public static final String CONSTRUCT_VALIDATION_PREFERENCE = "biosim.assembly.validation"; public static final String CONSTRUCT_VALIDATION_WARNING_DEFAULT = "False"; public static final String CONSTRUCT_VALIDATION_WARNING_PREFERENCE = "biosim.assembly.warning"; public static final String CONSTRUCT_VALIDATION_FAIL_STATE_ID = "Sf"; public static final String SBOL_ASSEMBLY_PLUS_STRAND = "+"; public static final String SBOL_ASSEMBLY_MINUS_STRAND = "-"; public static final int MEAN_CDS_LENGTH = 695; public static final int SD_CDS_LENGTH = 268; public static final int MEAN_PROMOTER_LENGTH = 62; public static final int SD_PROMOTER_LENGTH = 23; public static final int RBS_LENGTH = 12; public static final int TERMINATOR_LENGTH = 12; public static final int MEAN_GENE_LENGTH = 781; public static final int SD_GENE_LENGTH = 269; public static final String SBOL_FILE_EXTENSION = ".sbol"; public static final String RDF_FILE_EXTENSION = ".rdf"; public static final String SBOL_SYNTH_PROPERTIES_EXTENSION = ".sbolsynth.properties"; public static final String SBOL_SYNTH_SPEC_PROPERTY = "synthesis.spec"; public static final String SBOL_SYNTH_LIBS_PROPERTY = "synthesis.libraries"; public static final String SBOL_SYNTH_LIBS_PREFERENCE = "biosim." + SBOL_SYNTH_LIBS_PROPERTY; public static final String SBOL_SYNTH_LIBS_DEFAULT = ""; public static final String SBOL_SYNTH_METHOD_PROPERTY = "synthesis.method"; public static final String SBOL_SYNTH_METHOD_PREFERENCE = "biosim." + SBOL_SYNTH_METHOD_PROPERTY; public static final String SBOL_SYNTH_EXHAUST_BB = "Exact Branch and Bound"; public static final String SBOL_SYNTH_METHOD_DEFAULT = SBOL_SYNTH_EXHAUST_BB; public static final String SBOL_SYNTH_GREEDY_BB = "Greedy Branch and Bound"; public static final String SBOL_SYNTH_STRUCTURAL_METHODS = SBOL_SYNTH_EXHAUST_BB + "," + SBOL_SYNTH_GREEDY_BB; public static final String SBOL_SYNTH_NUM_SOLNS_PROPERTY = "synthesis.numsolutions"; public static final String SBOL_SYNTH_NUM_SOLNS_PREFERENCE = "biosim." + SBOL_SYNTH_NUM_SOLNS_PROPERTY; public static final String SBOL_SYNTH_NUM_SOLNS_DEFAULT = "1"; public static final String SBOL_SYNTH_COMMAND = "synthesis_project"; public static final String BIO = "biochem"; public static final String ACTIVATION = "activation"; public static final String REPRESSION = "repression"; public static final String REGULATION = "regulation"; public static final String NOINFLUENCE = "no_influence"; public static final int SBO_ACTIVATION = 459; public static final int SBO_REPRESSION = 20; public static final int SBO_DUAL_ACTIVITY = 595; public static final int SBO_NEUTRAL = 594; public static final int SBO_PROMOTER_MODIFIER = 598; public static final int SBO_PROMOTER_BINDING_REGION = 590; public static final int SBO_MRNA = 250; public static final int SBO_PETRI_NET_PLACE = 593; public static final int SBO_LOGICAL = 602; public static final int SBO_PETRI_NET_TRANSITION = 591; public static final int SBO_INPUT_PORT = 600; public static final int SBO_OUTPUT_PORT = 601; public static final int SBO_DEGRADATION = 179; public static final int SBO_DIFFUSION = 185; public static final int SBO_GENETIC_PRODUCTION = 589; public static final int SBO_ASSOCIATION = 177; public static final int SBO_CONSTITUTIVE = 396; // obsolete public static final int SBO_REGULATION = 19; public static final int SBO_OLD_PROMOTER_SPECIES = 369; public static final int SBO_PROMOTER = 535; public static final int SBO_PROMOTER_SPECIES = 354; public static final int SBO_MRNA_OLD = 278; public static final int SBO_BOOLEAN = 547; public static final int SBO_PLACE = 546; public static final int SBO_TRANSITION = 464; public static final int SBO_PRODUCTION = 183; public static final int SBO_COMPLEX = 526; public static final String KISAO_GENERIC = "KISAO:0000000"; public static final String KISAO_MONTE_CARLO = "KISAO:0000319"; public static final String KISAO_GILLESPIE_DIRECT = "KISAO:0000029"; public static final String KISAO_SSA_CR = "KISAO:0000329"; public static final String KISAO_EULER = "KISAO:0000030"; public static final String KISAO_RUNGE_KUTTA_FEHLBERG = "KISAO:0000086"; public static final String KISAO_RUNGE_KUTTA_PRINCE_DORMAND = "KISAO:0000087"; public static final String TRUE = "true"; public static final String FALSE = "false"; public static final String NONE = "none"; public static final String OK = "Ok"; public static final String CANCEL = "Cancel"; // public static final String MAX_DIMER_VALUE = "1"; // public static final String INITIAL_VALUE = "0"; // public static final String DIMER_COUNT_STRING = "label"; // public static final String TYPE_STRING = "label"; public static final int DEFAULT_SPECIES_WIDTH = 100; public static final int DEFAULT_SPECIES_HEIGHT = 30; public static final int DEFAULT_REACTION_WIDTH = 30; public static final int DEFAULT_REACTION_HEIGHT = 30; public static final int DEFAULT_VARIABLE_WIDTH = 30; public static final int DEFAULT_VARIABLE_HEIGHT = 30; public static final int DEFAULT_RULE_WIDTH = 50; public static final int DEFAULT_RULE_HEIGHT = 50; public static final int DEFAULT_CONSTRAINT_WIDTH = 50; public static final int DEFAULT_CONSTRAINT_HEIGHT = 40; public static final int DEFAULT_EVENT_WIDTH = 75; public static final int DEFAULT_EVENT_HEIGHT = 25; public static final int DEFAULT_TRANSITION_WIDTH = 50; public static final int DEFAULT_TRANSITION_HEIGHT = 20; public static final int DEFAULT_COMPONENT_WIDTH = 80; public static final int DEFAULT_COMPONENT_HEIGHT = 40; public static final int DEFAULT_COMPARTMENT_WIDTH = 250; public static final int DEFAULT_COMPARTMENT_HEIGHT = 250; public static final int DEFAULT_TEXT_WIDTH = 40; public static final int DEFAULT_TEXT_HEIGHT = 10; }
gui/src/biomodel/util/GlobalConstants.java
package biomodel.util; public class GlobalConstants { public static final String ACTIVATED_RNAP_BINDING_STRING = "Kao"; public static final String FORWARD_ACTIVATED_RNAP_BINDING_STRING = "kao_f"; public static final String REVERSE_ACTIVATED_RNAP_BINDING_STRING = "kao_r"; public static final String RNAP_BINDING_STRING = "Ko"; public static final String FORWARD_RNAP_BINDING_STRING = "ko_f"; public static final String REVERSE_RNAP_BINDING_STRING = "ko_r"; public static final String KREP_STRING = "Kr"; public static final String FORWARD_KREP_STRING = "kr_f"; public static final String REVERSE_KREP_STRING = "kr_r"; public static final String KACT_STRING = "Ka"; public static final String FORWARD_KACT_STRING = "ka_f"; public static final String REVERSE_KACT_STRING = "ka_r"; public static final String KCOMPLEX_STRING = "Kc"; public static final String FORWARD_KCOMPLEX_STRING = "kc_f"; public static final String REVERSE_KCOMPLEX_STRING = "kc_r"; public static final String MEMDIFF_STRING = "kmdiff"; public static final String FORWARD_MEMDIFF_STRING = "kmdiff_f"; public static final String REVERSE_MEMDIFF_STRING = "kmdiff_r"; // public static final String KBIO_STRING = "Kbio"; public static final String OCR_STRING = "ko"; public static final String KBASAL_STRING = "kb"; public static final String ACTIVATED_STRING = "ka"; public static final String KDECAY_STRING = "kd"; public static final String KECDIFF_STRING = "kecdiff"; public static final String KECDECAY_STRING = "kecd"; public static final String PROMOTER_COUNT_STRING = "ng"; public static final String RNAP_STRING = "nr"; public static final String STOICHIOMETRY_STRING = "np"; public static final String COOPERATIVITY_STRING = "nc"; public static final String COMPLEX = "complex"; public static final String DIFFUSIBLE = "diffusible"; public static final String KASSOCIATION_STRING = "Kassociation"; // Dimerization value public static final String GENE_PRODUCT = "gene product"; public static final String TRANSCRIPTION_FACTOR = "transcription factor"; // public static final String KREP_VALUE = ".5"; // public static final String KACT_VALUE = ".0033"; // public static final String KBIO_VALUE = ".05"; // public static final String PROMOTER_COUNT_VALUE = "2"; // public static final String KASSOCIATION_VALUE = ".05"; // public static final String KBASAL_VALUE = ".0001"; // public static final String OCR_VALUE = ".05"; // public static final String KDECAY_VALUE = ".0075"; // public static final String RNAP_VALUE = "30"; // public static final String RNAP_BINDING_VALUE = ".033"; // public static final String STOICHIOMETRY_VALUE = "10"; // public static final String COOPERATIVITY_VALUE = "2"; // public static final String ACTIVED_VALUE = ".25"; public static final String ID = "ID"; public static final String COMPONENT = "Component"; public static final String SPECIES = "Species"; public static final String INFLUENCE = "Influence"; public static final String COMPONENT_CONNECTION = "Component Connection"; public static final String PRODUCTION = "Production"; public static final String REACTION = "Reaction"; public static final String MODIFIER = "Modifier"; public static final String REACTION_EDGE = "Reaction_Edge"; public static final String RULE_EDGE = "Rule_Edge"; public static final String CONSTRAINT_EDGE = "Constraint_Edge"; public static final String EVENT_EDGE = "Event_Edge"; public static final String PETRI_NET_EDGE = "Petri_Net_Edge"; public static final String GRID_RECTANGLE = "Grid Rectangle"; public static final String PORTMAP = "Port Map"; public static final String PORT = "port"; public static final String NAME = "Name"; public static final String CONSTANT = "boundary"; public static final String SPASTIC = "constitutive"; public static final String DEGRADES = "degrades"; public static final String NORMAL = "normal"; public static final String INPUT = "input"; public static final String OUTPUT = "output"; public static final String INTERNAL = "internal"; public static final String TYPE = "Port Type"; public static final String MAX_DIMER_STRING = "N-mer as trascription factor"; public static final String INITIAL_STRING = "ns"; public static final String PROMOTER = "Promoter"; public static final String VARIABLE = "Variable"; public static final String PLACE = "Place"; public static final String BOOLEAN = "Boolean"; public static final String MRNA = "mRNA"; public static final String EXPLICIT_PROMOTER = "ExplicitPromoter"; public static final String SBMLFILE = "SBML file"; public static final String BIOABS = "Biochemical abstraction"; public static final String DIMABS = "Dimerization abstraction"; public static final String COMPARTMENT = "compartment"; public static final String PARAMETER = "parameter"; public static final String LOCALPARAMETER = "localParameter"; public static final String SBMLSPECIES = "species"; public static final String SBMLREACTION = "reaction"; public static final String EVENT = "event"; public static final String TRANSITION = "transition"; public static final String CONSTRAINT = "constraint"; public static final String FUNCTION = "functionDefinition"; public static final String UNIT = "unitDefinition"; public static final String RULE = "rule"; public static final String ASSIGNMENT_RULE = "assignmentRule"; public static final String INITIAL_ASSIGNMENT = "initialAssignment"; public static final String RATE_RULE = "rateRule"; public static final String ALGEBRAIC_RULE = "algebraicRule"; public static final String GLYPH = "Glyph"; public static final String REACTANT_GLYPH = "ReactantGlyph"; public static final String PRODUCT_GLYPH = "ProductGlyph"; public static final String MODIFIER_GLYPH = "ModifierGlyph"; public static final String TEXT_GLYPH = "TextGlyph"; public static final String ENCLOSING_COMPARTMENT = "enclosingCompartment"; public static final String DEFAULT_COMPARTMENT = "defaultCompartment"; public static final String FAIL = "fail"; public static final String FAIL_TRANSITION = "failTransition"; public static final String RATE = "rate"; public static final String TRIGGER = "trigger"; public static final String SBOL_PROMOTER = "sbolPromoter"; public static final String SBOL_TERMINATOR = "sbolTerminator"; public static final String SBOL_RBS = "sbolRBS"; public static final String SBOL_CDS = "sbolCDS"; public static final String SO_PROMOTER = "SO_0000167"; public static final String SO_TERMINATOR = "SO_0000141"; public static final String SO_RBS = "SO_0000139"; public static final String SO_CDS = "SO_0000316"; public static final String SO_AUTHORITY = "purl.obolibrary.org"; public static final String SBOL_DNA_COMPONENT = "sbolDnaComponent"; public static final String GENETIC_CONSTRUCT_REGEX_DEFAULT = SO_PROMOTER + "(" + SO_RBS + "," + SO_CDS + ")+" + SO_TERMINATOR + "+"; public static final String GENETIC_CONSTRUCT_REGEX_PREFERENCE = "biosim.assembly.regex"; public static final String SBOL_AUTHORITY_PREFERENCE = "biosim.assembly.authority"; public static final String SBOL_AUTHORITY_DEFAULT = "http://www.async.ece.utah.edu"; public static final String CONSTRUCT_VALIDATION_DEFAULT = "True"; public static final String CONSTRUCT_VALIDATION_PREFERENCE = "biosim.assembly.validation"; public static final String CONSTRUCT_VALIDATION_WARNING_DEFAULT = "False"; public static final String CONSTRUCT_VALIDATION_WARNING_PREFERENCE = "biosim.assembly.warning"; public static final String CONSTRUCT_VALIDATION_FAIL_STATE_ID = "Sf"; public static final String SBOL_ASSEMBLY_PLUS_STRAND = "+"; public static final String SBOL_ASSEMBLY_MINUS_STRAND = "-"; public static final int MEAN_CDS_LENGTH = 695; public static final int SD_CDS_LENGTH = 268; public static final int MEAN_PROMOTER_LENGTH = 62; public static final int SD_PROMOTER_LENGTH = 23; public static final int RBS_LENGTH = 12; public static final int TERMINATOR_LENGTH = 12; public static final int MEAN_GENE_LENGTH = 781; public static final int SD_GENE_LENGTH = 269; public static final String SBOL_FILE_EXTENSION = ".sbol"; public static final String RDF_FILE_EXTENSION = ".rdf"; public static final String SBOL_SYNTH_PROPERTIES_EXTENSION = ".sbolsynth.properties"; public static final String SBOL_SYNTH_SPEC_PROPERTY = "synthesis.spec"; public static final String SBOL_SYNTH_LIBS_PROPERTY = "synthesis.libraries"; public static final String SBOL_SYNTH_LIBS_PREFERENCE = "biosim." + SBOL_SYNTH_LIBS_PROPERTY; public static final String SBOL_SYNTH_LIBS_DEFAULT = ""; public static final String SBOL_SYNTH_METHOD_PROPERTY = "synthesis.method"; public static final String SBOL_SYNTH_METHOD_PREFERENCE = "biosim." + SBOL_SYNTH_METHOD_PROPERTY; public static final String SBOL_SYNTH_EXHAUST_BB = "Exhaustive Branch and Bound"; public static final String SBOL_SYNTH_METHOD_DEFAULT = SBOL_SYNTH_EXHAUST_BB; public static final String SBOL_SYNTH_GREEDY_BB = "Greedy Branch and Bound"; public static final String SBOL_SYNTH_STRUCTURAL_METHODS = SBOL_SYNTH_EXHAUST_BB + "," + SBOL_SYNTH_GREEDY_BB; public static final String SBOL_SYNTH_NUM_SOLNS_PROPERTY = "synthesis.numsolutions"; public static final String SBOL_SYNTH_NUM_SOLNS_PREFERENCE = "biosim." + SBOL_SYNTH_NUM_SOLNS_PROPERTY; public static final String SBOL_SYNTH_NUM_SOLNS_DEFAULT = "1"; public static final String SBOL_SYNTH_COMMAND = "synthesis_project"; public static final String BIO = "biochem"; public static final String ACTIVATION = "activation"; public static final String REPRESSION = "repression"; public static final String REGULATION = "regulation"; public static final String NOINFLUENCE = "no_influence"; public static final int SBO_ACTIVATION = 459; public static final int SBO_REPRESSION = 20; public static final int SBO_DUAL_ACTIVITY = 595; public static final int SBO_NEUTRAL = 594; public static final int SBO_PROMOTER_MODIFIER = 598; public static final int SBO_PROMOTER_BINDING_REGION = 590; public static final int SBO_MRNA = 250; public static final int SBO_PETRI_NET_PLACE = 593; public static final int SBO_LOGICAL = 602; public static final int SBO_PETRI_NET_TRANSITION = 591; public static final int SBO_INPUT_PORT = 600; public static final int SBO_OUTPUT_PORT = 601; public static final int SBO_DEGRADATION = 179; public static final int SBO_DIFFUSION = 185; public static final int SBO_GENETIC_PRODUCTION = 589; public static final int SBO_ASSOCIATION = 177; public static final int SBO_CONSTITUTIVE = 396; // obsolete public static final int SBO_REGULATION = 19; public static final int SBO_OLD_PROMOTER_SPECIES = 369; public static final int SBO_PROMOTER = 535; public static final int SBO_PROMOTER_SPECIES = 354; public static final int SBO_MRNA_OLD = 278; public static final int SBO_BOOLEAN = 547; public static final int SBO_PLACE = 546; public static final int SBO_TRANSITION = 464; public static final int SBO_PRODUCTION = 183; public static final int SBO_COMPLEX = 526; public static final String KISAO_GENERIC = "KISAO:0000000"; public static final String KISAO_MONTE_CARLO = "KISAO:0000319"; public static final String KISAO_GILLESPIE_DIRECT = "KISAO:0000029"; public static final String KISAO_SSA_CR = "KISAO:0000329"; public static final String KISAO_EULER = "KISAO:0000030"; public static final String KISAO_RUNGE_KUTTA_FEHLBERG = "KISAO:0000086"; public static final String KISAO_RUNGE_KUTTA_PRINCE_DORMAND = "KISAO:0000087"; public static final String TRUE = "true"; public static final String FALSE = "false"; public static final String NONE = "none"; public static final String OK = "Ok"; public static final String CANCEL = "Cancel"; // public static final String MAX_DIMER_VALUE = "1"; // public static final String INITIAL_VALUE = "0"; // public static final String DIMER_COUNT_STRING = "label"; // public static final String TYPE_STRING = "label"; public static final int DEFAULT_SPECIES_WIDTH = 100; public static final int DEFAULT_SPECIES_HEIGHT = 30; public static final int DEFAULT_REACTION_WIDTH = 30; public static final int DEFAULT_REACTION_HEIGHT = 30; public static final int DEFAULT_VARIABLE_WIDTH = 30; public static final int DEFAULT_VARIABLE_HEIGHT = 30; public static final int DEFAULT_RULE_WIDTH = 50; public static final int DEFAULT_RULE_HEIGHT = 50; public static final int DEFAULT_CONSTRAINT_WIDTH = 50; public static final int DEFAULT_CONSTRAINT_HEIGHT = 40; public static final int DEFAULT_EVENT_WIDTH = 75; public static final int DEFAULT_EVENT_HEIGHT = 25; public static final int DEFAULT_TRANSITION_WIDTH = 50; public static final int DEFAULT_TRANSITION_HEIGHT = 20; public static final int DEFAULT_COMPONENT_WIDTH = 80; public static final int DEFAULT_COMPONENT_HEIGHT = 40; public static final int DEFAULT_COMPARTMENT_WIDTH = 250; public static final int DEFAULT_COMPARTMENT_HEIGHT = 250; public static final int DEFAULT_TEXT_WIDTH = 40; public static final int DEFAULT_TEXT_HEIGHT = 10; }
Changed "Exhaustive Branch and Bound" to "Exact Branch and Bound"
gui/src/biomodel/util/GlobalConstants.java
Changed "Exhaustive Branch and Bound" to "Exact Branch and Bound"
<ide><path>ui/src/biomodel/util/GlobalConstants.java <ide> public static final String SBOL_SYNTH_LIBS_DEFAULT = ""; <ide> public static final String SBOL_SYNTH_METHOD_PROPERTY = "synthesis.method"; <ide> public static final String SBOL_SYNTH_METHOD_PREFERENCE = "biosim." + SBOL_SYNTH_METHOD_PROPERTY; <del> public static final String SBOL_SYNTH_EXHAUST_BB = "Exhaustive Branch and Bound"; <add> public static final String SBOL_SYNTH_EXHAUST_BB = "Exact Branch and Bound"; <ide> public static final String SBOL_SYNTH_METHOD_DEFAULT = SBOL_SYNTH_EXHAUST_BB; <ide> public static final String SBOL_SYNTH_GREEDY_BB = "Greedy Branch and Bound"; <ide> public static final String SBOL_SYNTH_STRUCTURAL_METHODS = SBOL_SYNTH_EXHAUST_BB + "," + SBOL_SYNTH_GREEDY_BB;
JavaScript
apache-2.0
2f7e553f37c47bb99f1b2d07a4c6fd5bd565593f
0
CCI-MOC/GUI-Frontend,CCI-MOC/GUI-Frontend,CCI-MOC/GUI-Frontend,CCI-MOC/GUI-Frontend,CCI-MOC/GUI-Frontend
define(function (require) { var React = require('react/addons'), moment = require('moment'), stores = require('stores'), actions = require('actions'), BootstrapModalMixin = require('components/mixins/BootstrapModalMixin.react'), VersionName = require('../instance/image/components/VersionName.react'), VersionChanges = require('../instance/image/components/VersionChangeLog.react'), EditAvailabilityView = require('./availability/EditAvailabilityView.react'), EditDescriptionView = require('components/images/detail/description/EditDescriptionView.react'), InteractiveDateField = require('components/common/InteractiveDateField.react'), EditMembershipView = require('./membership/EditMembershipView.react'), EditLicensesView = require('./licenses/EditLicensesView.react'), EditScriptsView = require('./scripts/EditScriptsView.react'), ImageSelect = require('components/modals/image_version/ImageSelect.react'); return React.createClass({ displayName: "ImageVersionEditModal", mixins: [BootstrapModalMixin], propTypes: { version: React.PropTypes.object.isRequired, image: React.PropTypes.instanceOf(Backbone.Model).isRequired }, getInitialState: function () { var version = this.props.version, parent_version = version.get('parent'); return { showOptions: false, version: version, versionImage: this.props.image, versionName: version.get('name'), versionChangeLog: (version.get('change_log') == null) ? "" : version.get('change_log'), versionStartDate: (version.get('start_date') == null) ? "" : version.get('start_date'), versionEndDate: (version.get('end_date') == null) ? "" : version.get('end_date'), versionCanImage: version.get('allow_imaging'), versionParentID: (parent_version == null) ? "" : parent_version.id, versionLicenses: null, versionScripts: null, versionMemberships: null, } }, updateState: function () { if (this.isMounted()) this.setState(this.getState()); }, getState: function() { return this.state; }, componentDidMount: function () { stores.ImageStore.addChangeListener(this.updateState); stores.UserStore.addChangeListener(this.updateState); stores.MembershipStore.addChangeListener(this.updateState); stores.ScriptStore.addChangeListener(this.updateState); stores.LicenseStore.addChangeListener(this.updateState); stores.ImageVersionStore.addChangeListener(this.updateState); stores.ImageVersionMembershipStore.addChangeListener(this.updateState); stores.ImageVersionScriptStore.addChangeListener(this.updateState); stores.ImageVersionLicenseStore.addChangeListener(this.updateState); stores.ProviderMachineStore.addChangeListener(this.updateState); }, componentWillUnmount: function () { stores.ImageStore.removeChangeListener(this.updateState); stores.UserStore.removeChangeListener(this.updateState); stores.MembershipStore.removeChangeListener(this.updateState); stores.LicenseStore.removeChangeListener(this.updateState); stores.ScriptStore.removeChangeListener(this.updateState); stores.ImageVersionStore.removeChangeListener(this.updateState); stores.ImageVersionMembershipStore.removeChangeListener(this.updateState); stores.ImageVersionLicenseStore.removeChangeListener(this.updateState); stores.ImageVersionScriptStore.removeChangeListener(this.updateState); stores.ProviderMachineStore.removeChangeListener(this.updateState); }, //TODO: Pull this out to commons valid_date: function (date_stamp) { if (date_stamp === "") return true; var the_date = Date.parse(date_stamp); return !isNaN(the_date); }, isSubmittable: function(){ var hasVersionName = !!this.state.versionName; var hasChangeLog = !!this.state.versionChangeLog; var validEndDate = !!this.valid_date(this.state.versionEndDate); return hasVersionName && hasChangeLog && validEndDate; }, // // Internal Modal Callbacks // ------------------------ // cancel: function(){ this.hide(); }, confirm: function () { this.hide(); this.props.onConfirm( this.props.version, this.state.versionName, this.state.versionChangeLog, this.state.versionEndDate, this.state.versionCanImage, this.state.versionImage ); }, // // Custom Modal Callbacks // ---------------------- // // todo: I don't think there's a reason to update state unless // there's a risk of the component being re-rendered by the parent. // Should probably verify this behavior, but for now, we play it safe. onVersionChange: function (e) { this.setState({versionName: e.target.value}); }, onEndDateChange: function (value) { this.setState({versionEndDate: value}); }, onUncopyableSelected: function (e) { var uncopyable = (e.target.checked); this.setState({versionCanImage: uncopyable}); }, onImageSelected: function (image_id) { var image = stores.ImageStore.get(image_id); this.setState({versionImage: image}); }, onMembershipChanged: function (membership_list) { this.setState({versionMembership: membership_list}); }, // // // Render // ------ // handleNameChange: function(name){ this.setState({versionName: name}); }, handleDescriptionChange: function(description){ this.setState({versionChangeLog: description}); }, onOptionsChange: function() { this.setState({showOptions: !this.state.showOptions}); }, onScriptCreate: function(scriptObj){ actions.ScriptActions.create_AddToImageVersion(this.props.version, { title: scriptObj.title, type: scriptObj.type, text: scriptObj.text }); }, onScriptAdded: function(script){ actions.ImageVersionScriptActions.add({ image_version: this.props.version, script: script }); }, onScriptRemoved: function(script){ actions.ImageVersionScriptActions.remove({ image_version: this.props.version, script: script }); }, onLicenseCreate: function(licenseObj){ actions.LicenseActions.create_AddToImageVersion(this.props.version, { title: licenseObj.title, type: licenseObj.type, text: licenseObj.text }); }, onLicenseAdded: function(license){ actions.ImageVersionLicenseActions.add({ image_version: this.props.version, license: license }); }, onLicenseRemoved: function(license){ actions.ImageVersionLicenseActions.remove({ image_version: this.props.version, license: license }); }, onMembershipAdded: function(membership){ actions.ImageVersionMembershipActions.add({ image_version: this.props.version, group: membership }); }, onMembershipRemoved: function(membership){ actions.ImageVersionMembershipActions.remove({ image_version: this.props.version, group: membership }); }, renderBody: function() { var applicationView, availabilityView, canImageView, nameView, descriptionView, startDateView, endDateView, membershipView, licensesView, scriptsView; var name = this.state.versionName, created = this.state.versionStartDate.format("MMM D, YYYY hh:mm a"), ended, advancedOptions, optionsButtonText = (this.state.showOptions) ? "Hide Advanced Options" : "Advanced Options", membershipsList = stores.MembershipStore.getAll(), licensesList = stores.LicenseStore.getAll(), activeLicensesList = stores.ImageVersionLicenseStore.getLicensesFor(this.props.version), scriptsList = stores.ScriptStore.getAll(), activeScriptsList = stores.ImageVersionScriptStore.getScriptsFor(this.props.version), versionMembers = stores.ImageVersionMembershipStore.getMembershipsFor(this.props.version); if(this.state.versionEndDate && this.state.versionEndDate._isAMomentObject && this.state.versionEndDate.isValid()) { ended = this.state.versionEndDate.format("MMM D, YYYY hh:mm a"); } else { ended = this.state.versionEndDate; } if(!name) { return (<div className="loading"/>); } licensesView = ( <EditLicensesView activeLicenses={activeLicensesList} licenses={licensesList} onLicenseAdded={this.onLicenseAdded} onLicenseRemoved={this.onLicenseRemoved} onCreateNewLicense={this.onLicenseCreate} label={"Licenses Required"} /> ); scriptsView = ( <EditScriptsView activeScripts={activeScriptsList} scripts={scriptsList} onScriptAdded={this.onScriptAdded} onScriptRemoved={this.onScriptRemoved} onCreateNewScript={this.onScriptCreate} label={"Scripts Required"} /> ); nameView = ( <VersionName update={true} value={this.state.versionName} onChange={this.handleNameChange} /> ); descriptionView = ( <VersionChanges value={this.state.versionChangeLog} onChange={this.handleDescriptionChange} /> ); availabilityView = (<EditAvailabilityView image={this.props.image} version={this.props.version} />); if(this.props.image.get('is_public')) { membershipView = (<div> Here lies a pretty view telling users they can add/edit/remove users they shared a specific version with.. ONLY IF that image is private </div>) } else { membershipView = (<EditMembershipView memberships={membershipsList} activeMemberships={versionMembers} onMembershipAdded={this.onMembershipAdded} onMembershipRemoved={this.onMembershipRemoved} label={"Version Shared With:"} />); } applicationView = ( <div className="application-select-container"> <ImageSelect imageId={this.state.versionImage.id} onChange={this.onImageSelected} /> </div> ); //FUTURE_keyTODO: Pull this functionality out if you use it anywhere else.. endDateView = (<InteractiveDateField value={ended} labelText={"Version End-dated On"} onChange={this.onEndDateChange} />); startDateView = (<div className='form-group'> <label htmlFor='version-version'>Version Created On</label> <input type='text' className='form-control' value={created} readOnly={true} editable={false}/> </div> ); canImageView = (<div className='form-group checkbox'> <label htmlFor='version-uncopyable'> <input type='checkbox' className='form-control' checked={this.state.versionCanImage} onChange={this.onUncopyableSelected}/> </label> </div> ); if(this.state.showOptions) { advancedOptions = ( <div className='advanced-options' > {availabilityView} <hr /> {membershipView} <hr /> {licensesView} <hr /> {scriptsView} <hr /> {applicationView} </div> ); } else { advancedOptions = null; } return ( <div role='form'> {nameView} <hr /> {descriptionView} <hr /> { //TODO: implement 'allow Imaging' in the next iteration //canImageView } {startDateView} {endDateView} <div className="form-group clearfix"> <button type="button" className="btn btn-default pull-right" onClick={this.onOptionsChange}> {optionsButtonText} <span className="caret"></span> </button> </div> {advancedOptions} </div> ); }, renderMember: function(member) { return (<li>{member}</li>); }, renderAddMember: function() { return (<li>"Add New Membership"</li>); }, render: function () { var images = stores.ImageStore.getAll(), providers = stores.ProviderStore.getAll(); var version = this.props.version, end_date = version.get('end_date'), versionId = version.id; if (!end_date) { end_date ="" } return ( <div className="modal fade"> <div className="modal-dialog"> <div id="ImageVersionEditModal" className="modal-content"> <div className="modal-header"> {this.renderCloseButton()} <h2>Edit Image Version</h2> </div> <div className="modal-body"> {this.renderBody()} </div> <div className="modal-footer"> <button type="button" className="btn btn-primary" onClick={this.confirm} disabled={!this.isSubmittable()}> Save Changes </button> </div> </div> </div> </div> ); } }); });
troposphere/static/js/components/modals/image_version/ImageVersionEditModal.react.js
define(function (require) { var React = require('react/addons'), moment = require('moment'), stores = require('stores'), actions = require('actions'), BootstrapModalMixin = require('components/mixins/BootstrapModalMixin.react'), VersionName = require('../instance/image/components/VersionName.react'), VersionChanges = require('../instance/image/components/VersionChangeLog.react'), EditAvailabilityView = require('./availability/EditAvailabilityView.react'), EditDescriptionView = require('components/images/detail/description/EditDescriptionView.react'), InteractiveDateField = require('components/common/InteractiveDateField.react'), EditMembershipView = require('./membership/EditMembershipView.react'), EditLicensesView = require('./licenses/EditLicensesView.react'), EditScriptsView = require('./scripts/EditScriptsView.react'), ImageSelect = require('components/modals/image_version/ImageSelect.react'); return React.createClass({ displayName: "ImageVersionEditModal", mixins: [BootstrapModalMixin], propTypes: { version: React.PropTypes.object.isRequired, image: React.PropTypes.instanceOf(Backbone.Model).isRequired }, getInitialState: function () { var version = this.props.version, parent_version = version.get('parent'); return { showOptions: false, version: version, versionImage: this.props.image, versionName: version.get('name'), versionChangeLog: (version.get('change_log') == null) ? "" : version.get('change_log'), versionStartDate: (version.get('start_date') == null) ? "" : version.get('start_date'), versionEndDate: (version.get('end_date') == null) ? "" : version.get('end_date'), versionCanImage: version.get('allow_imaging'), versionParentID: (parent_version == null) ? "" : parent_version.id, versionLicenses: null, versionScripts: null, versionMemberships: null, } }, updateState: function () { if (this.isMounted()) this.setState(this.getState()); }, getState: function() { return this.state; }, componentDidMount: function () { stores.ImageStore.addChangeListener(this.updateState); stores.UserStore.addChangeListener(this.updateState); stores.MembershipStore.addChangeListener(this.updateState); stores.ScriptStore.addChangeListener(this.updateState); stores.LicenseStore.addChangeListener(this.updateState); stores.ImageVersionStore.addChangeListener(this.updateState); stores.ImageVersionMembershipStore.addChangeListener(this.updateState); stores.ImageVersionScriptStore.addChangeListener(this.updateState); stores.ImageVersionLicenseStore.addChangeListener(this.updateState); stores.ProviderMachineStore.addChangeListener(this.updateState); }, componentWillUnmount: function () { stores.ImageStore.removeChangeListener(this.updateState); stores.UserStore.removeChangeListener(this.updateState); stores.MembershipStore.removeChangeListener(this.updateState); stores.LicenseStore.removeChangeListener(this.updateState); stores.ScriptStore.removeChangeListener(this.updateState); stores.ImageVersionStore.removeChangeListener(this.updateState); stores.ImageVersionMembershipStore.removeChangeListener(this.updateState); stores.ImageVersionLicenseStore.removeChangeListener(this.updateState); stores.ImageVersionScriptStore.removeChangeListener(this.updateState); stores.ProviderMachineStore.removeChangeListener(this.updateState); }, //TODO: Pull this out to commons valid_date: function (date_stamp) { if (date_stamp === "") return true; var the_date = Date.parse(date_stamp); return !isNaN(the_date); }, isSubmittable: function(){ var hasVersionName = !!this.state.versionName; var hasChangeLog = !!this.state.versionChangeLog; var validEndDate = !!this.valid_date(this.state.versionEndDate); return hasVersionName && hasChangeLog && validEndDate; }, // // Internal Modal Callbacks // ------------------------ // cancel: function(){ this.hide(); }, confirm: function () { this.hide(); this.props.onConfirm( this.props.version, this.state.versionName, this.state.versionChangeLog, this.state.versionEndDate, this.state.versionCanImage, this.state.versionImage ); }, // // Custom Modal Callbacks // ---------------------- // // todo: I don't think there's a reason to update state unless // there's a risk of the component being re-rendered by the parent. // Should probably verify this behavior, but for now, we play it safe. onVersionChange: function (e) { this.setState({versionName: e.target.value}); }, onEndDateChange: function (value) { this.setState({versionEndDate: value}); }, onUncopyableSelected: function (e) { var uncopyable = (e.target.checked); this.setState({versionCanImage: uncopyable}); }, onImageSelected: function (image_id) { var image = stores.ImageStore.get(image_id); this.setState({versionImage: image}); }, onMembershipChanged: function (membership_list) { this.setState({versionMembership: membership_list}); }, // // // Render // ------ // handleNameChange: function(name){ this.setState({versionName: name}); }, handleDescriptionChange: function(description){ this.setState({versionChangeLog: description}); }, onOptionsChange: function() { this.setState({showOptions: !this.state.showOptions}); }, onScriptCreate: function(scriptObj){ actions.ScriptActions.create_AddToImageVersion(this.props.version, { title: scriptObj.title, type: scriptObj.type, text: scriptObj.text }); }, onScriptAdded: function(script){ actions.ImageVersionScriptActions.add({ image_version: this.props.version, script: script }); }, onScriptRemoved: function(script){ actions.ImageVersionScriptActions.remove({ image_version: this.props.version, script: script }); }, onLicenseCreate: function(licenseObj){ actions.LicenseActions.create_AddToImageVersion(this.props.version, { title: licenseObj.title, type: licenseObj.type, text: licenseObj.text }); }, onLicenseAdded: function(license){ actions.ImageVersionLicenseActions.add({ image_version: this.props.version, license: license }); }, onLicenseRemoved: function(license){ actions.ImageVersionLicenseActions.remove({ image_version: this.props.version, license: license }); }, onMembershipAdded: function(membership){ actions.ImageVersionMembershipActions.add({ image_version: this.props.version, group: membership }); }, onMembershipRemoved: function(membership){ actions.ImageVersionMembershipActions.remove({ image_version: this.props.version, group: membership }); }, renderBody: function() { var applicationView, availabilityView, canImageView, nameView, descriptionView, startDateView, endDateView, membershipView, licensesView, scriptsView; var name = this.state.versionName, created = this.state.versionStartDate.format("MMM D, YYYY hh:mm a"), ended, advancedOptions, optionsButtonText = (this.state.showOptions) ? "Hide Advanced Options" : "Advanced Options", membershipsList = stores.MembershipStore.getAll(), licensesList = stores.LicenseStore.getAll(), activeLicensesList = stores.ImageVersionLicenseStore.getLicensesFor(this.props.version), scriptsList = stores.ScriptStore.getAll(), activeScriptsList = stores.ImageVersionScriptStore.getScriptsFor(this.props.version), versionMembers = stores.ImageVersionMembershipStore.getMembershipsFor(this.props.version); if(this.state.versionEndDate && this.state.versionEndDate._isAMomentObject && this.state.versionEndDate.isValid()) { ended = this.state.versionEndDate.format("MMM D, YYYY hh:mm a"); } else { ended = this.state.versionEndDate; } if(!name) { return (<div className="loading"/>); } licensesView = ( <EditLicensesView activeLicenses={activeLicensesList} licenses={licensesList} onLicenseAdded={this.onLicenseAdded} onLicenseRemoved={this.onLicenseRemoved} onCreateNewLicense={this.onLicenseCreate} label={"Licenses Required"} /> ); scriptsView = ( <EditScriptsView activeScripts={activeScriptsList} scripts={scriptsList} onScriptAdded={this.onScriptAdded} onScriptRemoved={this.onScriptRemoved} onCreateNewScript={this.onScriptCreate} label={"Scripts Required"} /> ); nameView = ( <VersionName update={true} value={this.state.versionName} onChange={this.handleNameChange} /> ); descriptionView = ( <VersionChanges value={this.state.versionChangeLog} onChange={this.handleDescriptionChange} /> ); availabilityView = (<EditAvailabilityView image={this.props.image} version={this.props.version} />); if(this.props.image.get('is_public')) { membershipView = (<div> Here lies a pretty view telling users they can add/edit/remove users they shared a specific version with.. ONLY IF that image is private </div>) } else { membershipView = (<EditMembershipView memberships={membershipsList} activeMemberships={versionMembers} onMembershipAdded={this.onMembershipAdded} onMembershipRemoved={this.onMembershipRemoved} label={"Version Shared With:"} />); } applicationView = ( <div className="application-select-container"> <ImageSelect imageId={this.state.versionImage.id} onChange={this.onImageSelected} /> </div> ); //FUTURE_keyTODO: Pull this functionality out if you use it anywhere else.. endDateView = (<InteractiveDateField value={ended} onChange={this.onEndDateChange} />); startDateView = (<div className='form-group'> <label htmlFor='version-version'>Version Created On</label> <input type='text' className='form-control' value={created} readOnly={true} editable={false}/> </div> ); canImageView = (<div className='form-group checkbox'> <label htmlFor='version-uncopyable'> <input type='checkbox' className='form-control' checked={this.state.versionCanImage} onChange={this.onUncopyableSelected}/> </label> </div> ); if(this.state.showOptions) { advancedOptions = ( <div className='advanced-options' > {availabilityView} <hr /> {membershipView} <hr /> {licensesView} <hr /> {scriptsView} <hr /> {applicationView} </div> ); } else { advancedOptions = null; } return ( <div role='form'> {nameView} <hr /> {descriptionView} <hr /> { //TODO: implement 'allow Imaging' in the next iteration //canImageView } {startDateView} {endDateView} <div className="form-group clearfix"> <button type="button" className="btn btn-default pull-right" onClick={this.onOptionsChange}> {optionsButtonText} <span className="caret"></span> </button> </div> {advancedOptions} </div> ); }, renderMember: function(member) { return (<li>{member}</li>); }, renderAddMember: function() { return (<li>"Add New Membership"</li>); }, render: function () { var images = stores.ImageStore.getAll(), providers = stores.ProviderStore.getAll(); var version = this.props.version, end_date = version.get('end_date'), versionId = version.id; if (!end_date) { end_date ="" } return ( <div className="modal fade"> <div className="modal-dialog"> <div id="ImageVersionEditModal" className="modal-content"> <div className="modal-header"> {this.renderCloseButton()} <h2>Edit Image Version</h2> </div> <div className="modal-body"> {this.renderBody()} </div> <div className="modal-footer"> <button type="button" className="btn btn-primary" onClick={this.confirm} disabled={!this.isSubmittable()}> Save Changes </button> </div> </div> </div> </div> ); } }); });
[ATMO-1132] Added _expected_ label text for end-date field.
troposphere/static/js/components/modals/image_version/ImageVersionEditModal.react.js
[ATMO-1132] Added _expected_ label text for end-date field.
<ide><path>roposphere/static/js/components/modals/image_version/ImageVersionEditModal.react.js <ide> //FUTURE_keyTODO: Pull this functionality out if you use it anywhere else.. <ide> endDateView = (<InteractiveDateField <ide> value={ended} <add> labelText={"Version End-dated On"} <ide> onChange={this.onEndDateChange} <ide> />); <ide> startDateView = (<div className='form-group'>
JavaScript
mit
fc166bd426bbd6d6fcd66c32ef0fd0c56e515fe0
0
filiperfernandes/trazme,filiperfernandes/trazme
Template.user.onCreated(function() { var self = this; self.autorun(function(){ var id = FlowRouter.getParam('id'); //console.log(id); self.subscribe('transactions'); self.subscribe('allUsers'); }); }); Template.user.helpers({ tripHistoryCount: function(){ var id = FlowRouter.getParam('id'); //Ser do Tipo T, estado fechado e user que fez o serviço ser igual ao da página return Transactions.find({ $and: [ { state: "closed" } , { userA : Meteor.userId() } ] }).count(); }, currentUsername: function(){ return "@" + Mongo.Collection.get('users').findOne({_id:Meteor.userId()}).username ; }, currentName: function(){ return Mongo.Collection.get('users').findOne({_id:Meteor.userId()}).profile.name ; }, userPageName: function(){ var id = FlowRouter.getParam('id'); return Mongo.Collection.get('users').findOne({_id:id}).profile.name ; }, userPageUsername: function(){ var id = FlowRouter.getParam('id'); return Mongo.Collection.get('users').findOne({_id:id}).username ; }, userPageEmail: function(){ var id = FlowRouter.getParam('id'); return Mongo.Collection.get('users').findOne({_id:id}).emails[0].address ; }, userPagePhone: function(){ var id = FlowRouter.getParam('id'); return Mongo.Collection.get('users').findOne({_id:id}).profile.phone ; }, userPageNIF: function(){ var id = FlowRouter.getParam('id'); return Mongo.Collection.get('users').findOne({_id:id}).profile.NIF ; }, userPcode: function(){ var id = FlowRouter.getParam('id'); return Mongo.Collection.get('users').findOne({_id:id}).profile.pcode ; }, checkUser: function(){ let id = FlowRouter.getParam('id'); return Mongo.Collection.get('users').findOne({_id:id})._id == Meteor.userId(); }, }); Template.pendingRequests.helpers({ allRequests: function(){ var id = FlowRouter.getParam('id'); //Ser do Tipo T, estado pendente e user que vai fazer serviço ser igual ao da página return Transactions.find({ $and: [ { state:"open" } , { userA : Meteor.userId() } ] }); }, userA: function(){ return Mongo.Collection.get('users').findOne({_id:this.userA}).username; }, userB: function(){ return Mongo.Collection.get('users').findOne({_id:this.userB}).username; }, }); Template.pendingRequests.events({ "click .openChat": function(e,t){ console.log("here"); let chatId = e.target.getAttribute("id") ; FlowRouter.go('/chat/' + chatId ) ; }, }) Template.pendingOffers.helpers({ allOffers: function(){ var id = FlowRouter.getParam('id'); //Ser do Tipo P, estado pendente e user que fez a oferta ser igual ao da página return Transactions.find({ $and: [ { type: "P" } , { state: "open" } , { userA : Meteor.userId() } ] }); }, userA: function(){ return Mongo.Collection.get('users').findOne({_id:this.userA}).username; }, userB: function(){ return Mongo.Collection.get('users').findOne({_id:this.userB}).username; }, }); Template.finishedTrips.helpers({ tripHistory: function(){ var id = FlowRouter.getParam('id'); //Ser do Tipo T, estado fechado e user que fez o serviço ser igual ao da página return Transactions.find({ $and: [ { state: "closed" } , { userA : Meteor.userId() } ] }); }, userA: function(){ return Mongo.Collection.get('users').findOne({_id:this.userA}).username; }, userB: function(){ return Mongo.Collection.get('users').findOne({_id:this.userB}).username; }, }); Template.acceptedTrips.helpers({ tripAccepted: function(){ var id = FlowRouter.getParam('id'); //Ser do Tipo T, estado aceite e user que fez o serviço ser igual ao da página return Transactions.find({ $or: [{ $and: [ { type: "P" } , { state: "accepted" } , { userA : Meteor.userId() } ]}, {$and: [ { type: "T" } , { state: "accepted" } , { userB : Meteor.userId() } ]} ]} ); }, userA: function(){ return Mongo.Collection.get('users').findOne({_id:this.userA}).username; }, userB: function(){ return Mongo.Collection.get('users').findOne({_id:this.userB}).username; }, }); Template.acceptedTrips.events({ "click .closeTransaction": function(e,t){ let orderId = e.target.getAttribute("id") ; Transactions.update({_id:orderId},{$set:{state:"closed"}}); FlowRouter.go('/login'); }, }); Template.user.events({ "click #userHistory": function(){ var id = FlowRouter.getParam('id'); FlowRouter.go('/user/' + id + '/history'); }, "click #userOffersMade": function(){ FlowRouter.go('/user/' + Meteor.userId() + '/requests'); }, "click #inTransitOffers": function(){ FlowRouter.go('/user/' + Meteor.userId() + '/transit'); }, "click #userLogout": function(){ Meteor.logout(); FlowRouter.go('/'); }, "click #userSendMessage": function(){ FlowRouter.go('/signin'); $('html, body').animate({ }, 0); }, });
trazme/client/user.js
Template.user.onCreated(function() { var self = this; self.autorun(function(){ var id = FlowRouter.getParam('id'); //console.log(id); self.subscribe('transactions'); self.subscribe('allUsers'); }); }); Template.user.helpers({ tripHistoryCount: function(){ var id = FlowRouter.getParam('id'); //Ser do Tipo T, estado fechado e user que fez o serviço ser igual ao da página return Transactions.find({ $and: [ { state: "closed" } , { userA : Meteor.userId() } ] }).count(); }, currentUsername: function(){ return "@" + Mongo.Collection.get('users').findOne({_id:Meteor.userId()}).username ; }, currentName: function(){ return Mongo.Collection.get('users').findOne({_id:Meteor.userId()}).profile.name ; }, userPageName: function(){ var id = FlowRouter.getParam('id'); return Mongo.Collection.get('users').findOne({_id:id}).profile.name ; }, userPageUsername: function(){ var id = FlowRouter.getParam('id'); return Mongo.Collection.get('users').findOne({_id:id}).username ; }, userPageEmail: function(){ var id = FlowRouter.getParam('id'); return Mongo.Collection.get('users').findOne({_id:id}).emails[0].address ; }, userPagePhone: function(){ var id = FlowRouter.getParam('id'); return Mongo.Collection.get('users').findOne({_id:id}).profile.phone ; }, userPageNIF: function(){ var id = FlowRouter.getParam('id'); return Mongo.Collection.get('users').findOne({_id:id}).profile.NIF ; }, userPcode: function(){ var id = FlowRouter.getParam('id'); return Mongo.Collection.get('users').findOne({_id:id}).profile.pcode ; }, checkUser: function(){ let id = FlowRouter.getParam('id'); return Mongo.Collection.get('users').findOne({_id:id})._id == Meteor.userId(); }, }); Template.pendingRequests.helpers({ allRequests: function(){ var id = FlowRouter.getParam('id'); //Ser do Tipo T, estado pendente e user que vai fazer serviço ser igual ao da página return Transactions.find({ $and: [ { state:"open" } , { userA : Meteor.userId() } ] }); }, userA: function(){ return Mongo.Collection.get('users').findOne({_id:this.userA}).username; }, userB: function(){ return Mongo.Collection.get('users').findOne({_id:this.userB}).username; }, }); Template.pendingRequests.events({ "click .openChat": function(e,t){ console.log("here"); let chatId = e.target.getAttribute("id") ; FlowRouter.go('/chat/' + chatId ) ; }, }) Template.pendingOffers.helpers({ allOffers: function(){ var id = FlowRouter.getParam('id'); //Ser do Tipo P, estado pendente e user que fez a oferta ser igual ao da página return Transactions.find({ $and: [ { type: "P" } , { state: "open" } , { userA : Meteor.userId() } ] }); }, userA: function(){ return Mongo.Collection.get('users').findOne({_id:this.userA}).username; }, userB: function(){ return Mongo.Collection.get('users').findOne({_id:this.userB}).username; }, }); Template.finishedTrips.helpers({ tripHistory: function(){ var id = FlowRouter.getParam('id'); //Ser do Tipo T, estado fechado e user que fez o serviço ser igual ao da página return Transactions.find({ $and: [ { state: "closed" } , { userA : Meteor.userId() } ] }); }, userA: function(){ return Mongo.Collection.get('users').findOne({_id:this.userA}).username; }, userB: function(){ return Mongo.Collection.get('users').findOne({_id:this.userB}).username; }, }); Template.acceptedTrips.helpers({ tripAccepted: function(){ var id = FlowRouter.getParam('id'); //Ser do Tipo T, estado aceite e user que fez o serviço ser igual ao da página return Transactions.find({ $and: [ { type: "P" } , { state: "accepted" } , { userA : Meteor.userId() } ] }); }, userA: function(){ return Mongo.Collection.get('users').findOne({_id:this.userA}).username; }, userB: function(){ return Mongo.Collection.get('users').findOne({_id:this.userB}).username; }, }); Template.acceptedTrips.events({ "click .closeTransaction": function(e,t){ let orderId = e.target.getAttribute("id") ; Transactions.update({_id:orderId},{$set:{state:"closed"}}); FlowRouter.go('/login'); }, }); Template.user.events({ "click #userHistory": function(){ var id = FlowRouter.getParam('id'); FlowRouter.go('/user/' + id + '/history'); }, "click #userOffersMade": function(){ FlowRouter.go('/user/' + Meteor.userId() + '/requests'); }, "click #inTransitOffers": function(){ FlowRouter.go('/user/' + Meteor.userId() + '/transit'); }, "click #userLogout": function(){ Meteor.logout(); FlowRouter.go('/'); }, "click #userSendMessage": function(){ FlowRouter.go('/signin'); $('html, body').animate({ }, 0); }, });
Viagens em transito query fixed
trazme/client/user.js
Viagens em transito query fixed
<ide><path>razme/client/user.js <ide> var id = FlowRouter.getParam('id'); <ide> //Ser do Tipo T, estado aceite e user que fez o serviço ser igual ao da página <ide> return Transactions.find({ <del> $and: [ { type: "P" } , { state: "accepted" } , { userA : Meteor.userId() } ] <del> }); <add> $or: [{ $and: [ { type: "P" } , { state: "accepted" } , { userA : Meteor.userId() } ]}, <add> {$and: [ { type: "T" } , { state: "accepted" } , { userB : Meteor.userId() } ]} <add> ]} <add> ); <ide> }, <ide> userA: function(){ <ide> return Mongo.Collection.get('users').findOne({_id:this.userA}).username;
Java
epl-1.0
28df7bfdf6a218050fd39fb7af0dacb78e812d14
0
debrief/limpet,debrief/limpet,debrief/limpet
package info.limpet.data2; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertNotNull; import static org.junit.Assert.assertTrue; import info.limpet.ICommand; import info.limpet.IContext; import info.limpet.IDocument; import info.limpet.IOperation; import info.limpet.IStoreGroup; import info.limpet.IStoreItem; import info.limpet.impl.Document; import info.limpet.impl.MockContext; import info.limpet.impl.NumberDocument; import info.limpet.impl.NumberDocumentBuilder; import info.limpet.impl.SampleData; import info.limpet.impl.StoreGroup; import info.limpet.operations.arithmetic.simple.AddLogQuantityOperation; import info.limpet.operations.arithmetic.simple.AddQuantityOperation; import info.limpet.operations.arithmetic.simple.SubtractLogQuantityOperation; import info.limpet.operations.arithmetic.simple.SubtractQuantityOperation; import info.limpet.operations.spatial.GeoSupport; import info.limpet.operations.spatial.IGeoCalculator; import info.limpet.operations.spatial.ProplossBetweenTwoTracksOperation; import info.limpet.operations.spatial.msa.BistaticAngleOperation; import info.limpet.persistence.CsvParser; import java.awt.geom.Point2D; import java.io.File; import java.io.IOException; import java.util.ArrayList; import java.util.Iterator; import java.util.List; import javax.measure.unit.SI; import org.junit.Test; public class TestBistaticAngleCalculations { final private IContext context = new MockContext(); @Test public void testLoadTracks() throws IOException { File file = TestCsvParser.getDataFile("multistatics/tx1_stat.csv"); assertTrue(file.isFile()); CsvParser parser = new CsvParser(); List<IStoreItem> items = parser.parse(file.getAbsolutePath()); assertEquals("correct group", 1, items.size()); StoreGroup group = (StoreGroup) items.get(0); assertEquals("correct num collections", 3, group.size()); IDocument<?> firstColl = (IDocument<?>) group.get(0); assertEquals("correct num rows", 541, firstColl.size()); } @Test public void testAddLogData() throws IOException { IStoreGroup store = new StoreGroup("data"); // now get our tracks File file = TestCsvParser.getDataFile("multistatics/tx1_stat.csv"); assertTrue(file.isFile()); CsvParser parser = new CsvParser(); List<IStoreItem> tx1 = parser.parse(file.getAbsolutePath()); store.addAll(tx1); file = TestCsvParser.getDataFile("multistatics/rx1_stat.csv"); assertTrue(file.isFile()); List<IStoreItem> rx1 = parser.parse(file.getAbsolutePath()); store.addAll(rx1); file = TestCsvParser.getDataFile("multistatics/ssn_stat.csv"); assertTrue(file.isFile()); List<IStoreItem> ssn = parser.parse(file.getAbsolutePath()); store.addAll(ssn); IOperation pDiff = new ProplossBetweenTwoTracksOperation(); List<IStoreItem> selection = new ArrayList<IStoreItem>(); selection.add(tx1.get(0)); selection.add(ssn.get(0)); List<ICommand> actions = pDiff.actionsFor(selection , store, context); assertNotNull("found actions"); assertEquals("got actions", 2, actions.size()); assertEquals("store has original data", 3, store.size()); // run it actions.get(0).execute(); assertEquals("has new data", 4, store.size()); Document<?> txProp = actions.get(0).getOutputs().get(0); txProp.setName("txProp"); // now the other proploss file selection.clear(); selection.add(rx1.get(0)); selection.add(ssn.get(0)); actions = pDiff.actionsFor(selection , store, context); assertNotNull("found actions"); assertEquals("got actions", 2, actions.size()); assertEquals("store has original data", 4, store.size()); // run it actions.get(0).execute(); assertEquals("has new data", 5, store.size()); Document<?> rxProp = actions.get(0).getOutputs().get(0); rxProp.setName("rxProp"); // ok, now we can try to add them IOperation addL = new AddLogQuantityOperation(); IOperation add = new AddQuantityOperation(); selection.clear(); selection.add(txProp); selection.add(rxProp); // check the normal adder drops out actions = add.actionsFor(selection, store, context); assertEquals("no actions returned", 0, actions.size()); // now the log adder actions = addL.actionsFor(selection, store, context); assertEquals("actions returned", 2, actions.size()); // ok, run the first action actions.get(0).execute(); assertEquals("has new data", 6, store.size()); // check the outputs NumberDocument propSum = (NumberDocument) actions.get(0).getOutputs().get(0); propSum.setName("propSum"); // ok, change the selection so we can do the reverse of the add selection.clear(); selection.add(propSum); selection.add(rxProp); // hmm, go for the subtract IOperation sub = new SubtractQuantityOperation(); IOperation subL = new SubtractLogQuantityOperation(); actions = sub.actionsFor(selection, store, context); assertEquals("none returned", 0, actions.size()); actions = subL.actionsFor(selection, store, context); assertEquals("actions returned", 4, actions.size()); // ok, run it actions.get(0).execute(); assertEquals("has new data", 7, store.size()); // check the results NumberDocument propDiff = (NumberDocument) actions.get(0).getOutputs().get(0); propDiff.setName("propDiff"); } @Test public void testCreateActions() throws IOException { IStoreGroup store = new StoreGroup("data"); // now get our tracks File file = TestCsvParser.getDataFile("multistatics/tx1_stat.csv"); assertTrue(file.isFile()); CsvParser parser = new CsvParser(); List<IStoreItem> tx1 = parser.parse(file.getAbsolutePath()); store.addAll(tx1); file = TestCsvParser.getDataFile("multistatics/rx1_stat.csv"); assertTrue(file.isFile()); List<IStoreItem> rx1 = parser.parse(file.getAbsolutePath()); store.addAll(rx1); file = TestCsvParser.getDataFile("multistatics/ssn_stat.csv"); assertTrue(file.isFile()); List<IStoreItem> ssn = parser.parse(file.getAbsolutePath()); store.addAll(ssn); // check data loaded assertEquals("have all 3 tracks", 3, store.size()); // ok, generate the command BistaticAngleOperation generator = new BistaticAngleOperation(); List<IStoreItem> selection = new ArrayList<IStoreItem>(); // just one track selection.add(store.iterator().next()); List<ICommand> actions = generator.actionsFor(selection, store, context); assertEquals("correct actions", 0, actions.size()); // and two tracks selection.clear(); selection.add(tx1.get(0)); selection.add(ssn.get(0)); selection.add(rx1.get(0)); actions = generator.actionsFor(selection, store, context); assertEquals("correct actions", 3, actions.size()); // check the store contents assertEquals("correct datasets", 3, store.size()); // remove the course from one track, check it doesn't get offered IStoreGroup txGroup = (IStoreGroup) store.iterator().next(); Iterator<IStoreItem> t1Iter = txGroup.iterator(); IStoreItem toDelete = null; while (t1Iter.hasNext()) { IStoreItem thisDoc = (IStoreItem) t1Iter.next(); if (thisDoc instanceof NumberDocument) { NumberDocument nd = (NumberDocument) thisDoc; if (nd.isQuantity() && nd.getUnits().equals(SampleData.DEGREE_ANGLE)) { toDelete = nd; } } } assertNotNull("found course data", toDelete); txGroup.remove(toDelete); actions = generator.actionsFor(selection, store, context); assertEquals("correct actions", 2, actions.size()); // ok, have a go at running it. actions.get(0).execute(); // check the store contents assertEquals("correct datasets", 5, store.size()); } @Test public void testCalculation() { NumberDocumentBuilder bi = new NumberDocumentBuilder("Bi angle", SampleData.DEGREE_ANGLE, null, SI.SECOND); NumberDocumentBuilder biA = new NumberDocumentBuilder("Bi Aspect angle", SampleData.DEGREE_ANGLE, null, SI.SECOND); double heading = 15; Point2D tx = new Point2D.Double(2, 1); Point2D tgt = new Point2D.Double(1, 1); Point2D rx = new Point2D.Double(1.1, 0); final double time = 1000d; final IGeoCalculator calc = GeoSupport.getCalculator(); BistaticAngleOperation.calcAndStore(calc, tx, tgt, rx, heading, time, bi, biA); // look at hte results assertEquals("correct bi angle", 85, bi.getValues().get(0), 1); assertEquals("correct bi A angle", 117, biA.getValues().get(0), 1); bi.clear(); biA.clear(); // try another permutation rx = new Point2D.Double(2, 1.5); BistaticAngleOperation.calcAndStore(calc, tx, tgt, rx, heading, time, bi, biA); // look at the results assertEquals("correct bi angle", 26, bi.getValues().get(0), 1); assertEquals("correct bi A angle", 61, biA.getValues().get(0), 1); heading = 326; bi.clear(); biA.clear(); BistaticAngleOperation.calcAndStore(calc, tx, tgt, rx, heading, time, bi, biA); // look at the results assertEquals("correct bi angle", 26, bi.getValues().get(0), 1); assertEquals("correct bi A angle", 110, biA.getValues().get(0), 1); tx.setLocation(1.4, 1.1); rx.setLocation(1.3, 1.3); tgt.setLocation(1, 1); heading = 0; bi.clear(); biA.clear(); BistaticAngleOperation.calcAndStore(calc, tx, tgt, rx, heading, time, bi, biA); // look at the results assertEquals("correct bi angle", 30, bi.getValues().get(0), 1); assertEquals("correct bi A angle", 60, biA.getValues().get(0), 1); tx.setLocation(1.2, 1.05); rx.setLocation(1.1, 1.17); tgt.setLocation(1, 1); heading = 356; bi.clear(); biA.clear(); BistaticAngleOperation.calcAndStore(calc, tx, tgt, rx, heading, time, bi, biA); // look at the results assertEquals("correct bi angle", 45, bi.getValues().get(0), 1); assertEquals("correct bi A angle", 57, biA.getValues().get(0), 1); } }
info.limpet.test/src/info/limpet/data2/TestBistaticAngleCalculations.java
package info.limpet.data2; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertNotNull; import static org.junit.Assert.assertTrue; import info.limpet.ICommand; import info.limpet.IContext; import info.limpet.IDocument; import info.limpet.IOperation; import info.limpet.IStoreGroup; import info.limpet.IStoreItem; import info.limpet.impl.Document; import info.limpet.impl.MockContext; import info.limpet.impl.NumberDocument; import info.limpet.impl.NumberDocumentBuilder; import info.limpet.impl.SampleData; import info.limpet.impl.StoreGroup; import info.limpet.operations.arithmetic.simple.AddLogQuantityOperation; import info.limpet.operations.arithmetic.simple.AddQuantityOperation; import info.limpet.operations.arithmetic.simple.SubtractLogQuantityOperation; import info.limpet.operations.arithmetic.simple.SubtractQuantityOperation; import info.limpet.operations.spatial.GeoSupport; import info.limpet.operations.spatial.IGeoCalculator; import info.limpet.operations.spatial.ProplossBetweenTwoTracksOperation; import info.limpet.operations.spatial.msa.BistaticAngleOperation; import info.limpet.persistence.CsvParser; import java.awt.geom.Point2D; import java.io.File; import java.io.IOException; import java.util.ArrayList; import java.util.Iterator; import java.util.List; import javax.measure.unit.SI; import org.junit.Test; public class TestBistaticAngleCalculations { final private IContext context = new MockContext(); @Test public void testLoadTracks() throws IOException { File file = TestCsvParser.getDataFile("multistatics/tx1_stat.csv"); assertTrue(file.isFile()); CsvParser parser = new CsvParser(); List<IStoreItem> items = parser.parse(file.getAbsolutePath()); assertEquals("correct group", 1, items.size()); StoreGroup group = (StoreGroup) items.get(0); assertEquals("correct num collections", 3, group.size()); IDocument<?> firstColl = (IDocument<?>) group.get(0); assertEquals("correct num rows", 541, firstColl.size()); } @Test public void testAddLogData() throws IOException { IStoreGroup store = new StoreGroup("data"); // now get our tracks File file = TestCsvParser.getDataFile("multistatics/tx1_stat.csv"); assertTrue(file.isFile()); CsvParser parser = new CsvParser(); List<IStoreItem> tx1 = parser.parse(file.getAbsolutePath()); store.addAll(tx1); file = TestCsvParser.getDataFile("multistatics/rx1_stat.csv"); assertTrue(file.isFile()); List<IStoreItem> rx1 = parser.parse(file.getAbsolutePath()); store.addAll(rx1); file = TestCsvParser.getDataFile("multistatics/ssn_stat.csv"); assertTrue(file.isFile()); List<IStoreItem> ssn = parser.parse(file.getAbsolutePath()); store.addAll(ssn); IOperation pDiff = new ProplossBetweenTwoTracksOperation(); List<IStoreItem> selection = new ArrayList<IStoreItem>(); selection.add(tx1.get(0)); selection.add(ssn.get(0)); List<ICommand> actions = pDiff.actionsFor(selection , store, context); assertNotNull("found actions"); assertEquals("got actions", 2, actions.size()); assertEquals("store has original data", 3, store.size()); // run it actions.get(0).execute(); assertEquals("has new data", 4, store.size()); Document<?> txProp = actions.get(0).getOutputs().get(0); txProp.setName("txProp"); // now the other proploss file selection.clear(); selection.add(rx1.get(0)); selection.add(ssn.get(0)); actions = pDiff.actionsFor(selection , store, context); assertNotNull("found actions"); assertEquals("got actions", 2, actions.size()); assertEquals("store has original data", 4, store.size()); // run it actions.get(0).execute(); assertEquals("has new data", 5, store.size()); Document<?> rxProp = actions.get(0).getOutputs().get(0); rxProp.setName("rxProp"); // ok, now we can try to add them IOperation addL = new AddLogQuantityOperation(); IOperation add = new AddQuantityOperation(); selection.clear(); selection.add(txProp); selection.add(rxProp); // check the normal adder drops out actions = add.actionsFor(selection, store, context); assertEquals("no actions returned", 0, actions.size()); // now the log adder actions = addL.actionsFor(selection, store, context); assertEquals("actions returned", 2, actions.size()); // ok, run the first action actions.get(0).execute(); assertEquals("has new data", 6, store.size()); // check the outputs NumberDocument propSum = (NumberDocument) actions.get(0).getOutputs().get(0); propSum.setName("propSum"); System.out.println(txProp.toListing()); System.out.println(rxProp.toListing()); System.out.println(propSum.toListing()); // ok, change the selection so we can do the reverse of the add selection.clear(); selection.add(propSum); selection.add(rxProp); // hmm, go for the subtract IOperation sub = new SubtractQuantityOperation(); IOperation subL = new SubtractLogQuantityOperation(); actions = sub.actionsFor(selection, store, context); assertEquals("none returned", 0, actions.size()); actions = subL.actionsFor(selection, store, context); assertEquals("actions returned", 4, actions.size()); // ok, run it actions.get(0).execute(); assertEquals("has new data", 7, store.size()); // check the results NumberDocument propDiff = (NumberDocument) actions.get(0).getOutputs().get(0); propDiff.setName("propDiff"); System.out.println(propDiff.toListing()); } @Test public void testCreateActions() throws IOException { IStoreGroup store = new StoreGroup("data"); // now get our tracks File file = TestCsvParser.getDataFile("multistatics/tx1_stat.csv"); assertTrue(file.isFile()); CsvParser parser = new CsvParser(); List<IStoreItem> tx1 = parser.parse(file.getAbsolutePath()); store.addAll(tx1); file = TestCsvParser.getDataFile("multistatics/rx1_stat.csv"); assertTrue(file.isFile()); List<IStoreItem> rx1 = parser.parse(file.getAbsolutePath()); store.addAll(rx1); file = TestCsvParser.getDataFile("multistatics/ssn_stat.csv"); assertTrue(file.isFile()); List<IStoreItem> ssn = parser.parse(file.getAbsolutePath()); store.addAll(ssn); // check data loaded assertEquals("have all 3 tracks", 3, store.size()); // ok, generate the command BistaticAngleOperation generator = new BistaticAngleOperation(); List<IStoreItem> selection = new ArrayList<IStoreItem>(); // just one track selection.add(store.iterator().next()); List<ICommand> actions = generator.actionsFor(selection, store, context); assertEquals("correct actions", 0, actions.size()); // and two tracks selection.clear(); selection.add(tx1.get(0)); selection.add(ssn.get(0)); selection.add(rx1.get(0)); actions = generator.actionsFor(selection, store, context); assertEquals("correct actions", 3, actions.size()); // check the store contents assertEquals("correct datasets", 3, store.size()); // remove the course from one track, check it doesn't get offered IStoreGroup txGroup = (IStoreGroup) store.iterator().next(); Iterator<IStoreItem> t1Iter = txGroup.iterator(); IStoreItem toDelete = null; while (t1Iter.hasNext()) { IStoreItem thisDoc = (IStoreItem) t1Iter.next(); if (thisDoc instanceof NumberDocument) { NumberDocument nd = (NumberDocument) thisDoc; if (nd.isQuantity() && nd.getUnits().equals(SampleData.DEGREE_ANGLE)) { toDelete = nd; } } } assertNotNull("found course data", toDelete); txGroup.remove(toDelete); actions = generator.actionsFor(selection, store, context); assertEquals("correct actions", 2, actions.size()); // ok, have a go at running it. actions.get(0).execute(); // check the store contents assertEquals("correct datasets", 5, store.size()); } @Test public void testCalculation() { NumberDocumentBuilder bi = new NumberDocumentBuilder("Bi angle", SampleData.DEGREE_ANGLE, null, SI.SECOND); NumberDocumentBuilder biA = new NumberDocumentBuilder("Bi Aspect angle", SampleData.DEGREE_ANGLE, null, SI.SECOND); double heading = 15; Point2D tx = new Point2D.Double(2, 1); Point2D tgt = new Point2D.Double(1, 1); Point2D rx = new Point2D.Double(1.1, 0); final double time = 1000d; final IGeoCalculator calc = GeoSupport.getCalculator(); BistaticAngleOperation.calcAndStore(calc, tx, tgt, rx, heading, time, bi, biA); // look at hte results assertEquals("correct bi angle", 85, bi.getValues().get(0), 1); assertEquals("correct bi A angle", 117, biA.getValues().get(0), 1); bi.clear(); biA.clear(); // try another permutation rx = new Point2D.Double(2, 1.5); BistaticAngleOperation.calcAndStore(calc, tx, tgt, rx, heading, time, bi, biA); // look at the results assertEquals("correct bi angle", 26, bi.getValues().get(0), 1); assertEquals("correct bi A angle", 61, biA.getValues().get(0), 1); heading = 326; bi.clear(); biA.clear(); BistaticAngleOperation.calcAndStore(calc, tx, tgt, rx, heading, time, bi, biA); // look at the results assertEquals("correct bi angle", 26, bi.getValues().get(0), 1); assertEquals("correct bi A angle", 110, biA.getValues().get(0), 1); tx.setLocation(1.4, 1.1); rx.setLocation(1.3, 1.3); tgt.setLocation(1, 1); heading = 0; bi.clear(); biA.clear(); BistaticAngleOperation.calcAndStore(calc, tx, tgt, rx, heading, time, bi, biA); // look at the results assertEquals("correct bi angle", 30, bi.getValues().get(0), 1); assertEquals("correct bi A angle", 60, biA.getValues().get(0), 1); tx.setLocation(1.2, 1.05); rx.setLocation(1.1, 1.17); tgt.setLocation(1, 1); heading = 356; bi.clear(); biA.clear(); BistaticAngleOperation.calcAndStore(calc, tx, tgt, rx, heading, time, bi, biA); // look at the results assertEquals("correct bi angle", 45, bi.getValues().get(0), 1); assertEquals("correct bi A angle", 57, biA.getValues().get(0), 1); } }
static analysis
info.limpet.test/src/info/limpet/data2/TestBistaticAngleCalculations.java
static analysis
<ide><path>nfo.limpet.test/src/info/limpet/data2/TestBistaticAngleCalculations.java <ide> NumberDocument propSum = (NumberDocument) actions.get(0).getOutputs().get(0); <ide> propSum.setName("propSum"); <ide> <del> System.out.println(txProp.toListing()); <del> System.out.println(rxProp.toListing()); <del> System.out.println(propSum.toListing()); <del> <ide> // ok, change the selection so we can do the reverse of the add <ide> selection.clear(); <ide> selection.add(propSum); <ide> <ide> // check the results <ide> NumberDocument propDiff = (NumberDocument) actions.get(0).getOutputs().get(0); <del> propDiff.setName("propDiff"); <del> System.out.println(propDiff.toListing()); <del> <add> propDiff.setName("propDiff"); <ide> <ide> } <ide>
Java
apache-2.0
5610391e78229153c00e519aca4e8b0043ee1b83
0
googleapis/java-spanner,looker-open-source/java-spanner,looker-open-source/java-spanner,googleapis/java-spanner,looker-open-source/java-spanner,googleapis/java-spanner
/* * Copyright 2017 Google LLC * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.cloud.spanner; import static com.google.cloud.spanner.SpannerExceptionFactory.newSpannerException; import com.google.cloud.Timestamp; import com.google.cloud.grpc.GrpcTransportOptions; import com.google.cloud.grpc.GrpcTransportOptions.ExecutorFactory; import com.google.cloud.spanner.Options.QueryOption; import com.google.cloud.spanner.Options.ReadOption; import com.google.cloud.spanner.SessionClient.SessionConsumer; import com.google.common.annotations.VisibleForTesting; import com.google.common.base.Function; import com.google.common.base.Preconditions; import com.google.common.base.Supplier; import com.google.common.collect.ImmutableList; import com.google.common.collect.ImmutableMap; import com.google.common.util.concurrent.ListenableFuture; import com.google.common.util.concurrent.MoreExecutors; import com.google.common.util.concurrent.SettableFuture; import com.google.common.util.concurrent.Uninterruptibles; import io.opencensus.common.Scope; import io.opencensus.trace.Annotation; import io.opencensus.trace.AttributeValue; import io.opencensus.trace.Span; import io.opencensus.trace.Status; import io.opencensus.trace.Tracer; import io.opencensus.trace.Tracing; import java.util.HashSet; import java.util.Iterator; import java.util.LinkedList; import java.util.Queue; import java.util.Random; import java.util.Set; import java.util.concurrent.ScheduledExecutorService; import java.util.concurrent.ScheduledFuture; import java.util.concurrent.SynchronousQueue; import java.util.concurrent.TimeUnit; import java.util.concurrent.atomic.AtomicLong; import java.util.logging.Level; import java.util.logging.Logger; import javax.annotation.Nullable; import javax.annotation.concurrent.GuardedBy; import org.threeten.bp.Duration; import org.threeten.bp.Instant; /** * Maintains a pool of sessions some of which might be prepared for write by invoking * BeginTransaction rpc. It maintains two queues of sessions(read and write prepared) and two queues * of waiters who are waiting for a session to become available. This class itself is thread safe * and is meant to be used concurrently across multiple threads. */ final class SessionPool { private static final Logger logger = Logger.getLogger(SessionPool.class.getName()); private static final Tracer tracer = Tracing.getTracer(); static final String WAIT_FOR_SESSION = "SessionPool.WaitForSession"; static { TraceUtil.exportSpans(WAIT_FOR_SESSION); } /** * Wrapper around current time so that we can fake it in tests. TODO(user): Replace with Java 8 * Clock. */ static class Clock { Instant instant() { return Instant.now(); } } /** * Wrapper around {@code ReadContext} that releases the session to the pool once the call is * finished, if it is a single use context. */ private static class AutoClosingReadContext<T extends ReadContext> implements ReadContext { private final Function<PooledSession, T> readContextDelegateSupplier; private T readContextDelegate; private final SessionPool sessionPool; private PooledSession session; private final boolean isSingleUse; private boolean closed; private boolean sessionUsedForQuery = false; private AutoClosingReadContext( Function<PooledSession, T> delegateSupplier, SessionPool sessionPool, PooledSession session, boolean isSingleUse) { this.readContextDelegateSupplier = delegateSupplier; this.sessionPool = sessionPool; this.session = session; this.isSingleUse = isSingleUse; while (true) { try { this.readContextDelegate = readContextDelegateSupplier.apply(this.session); break; } catch (SessionNotFoundException e) { replaceSessionIfPossible(e); } } } T getReadContextDelegate() { return readContextDelegate; } private ResultSet wrap(final Supplier<ResultSet> resultSetSupplier) { ResultSet res; while (true) { try { res = resultSetSupplier.get(); break; } catch (SessionNotFoundException e) { replaceSessionIfPossible(e); } } return new ForwardingResultSet(res) { private boolean beforeFirst = true; @Override public boolean next() throws SpannerException { while (true) { try { return internalNext(); } catch (SessionNotFoundException e) { replaceSessionIfPossible(e); replaceDelegate(resultSetSupplier.get()); } } } private boolean internalNext() { try { boolean ret = super.next(); if (beforeFirst) { session.markUsed(); beforeFirst = false; sessionUsedForQuery = true; } if (!ret && isSingleUse) { close(); } return ret; } catch (SessionNotFoundException e) { throw e; } catch (SpannerException e) { if (!closed && isSingleUse) { session.lastException = e; AutoClosingReadContext.this.close(); } throw e; } } @Override public void close() { super.close(); if (isSingleUse) { AutoClosingReadContext.this.close(); } } }; } private void replaceSessionIfPossible(SessionNotFoundException e) { if (isSingleUse || !sessionUsedForQuery) { // This class is only used by read-only transactions, so we know that we only need a // read-only session. session = sessionPool.replaceReadSession(e, session); readContextDelegate = readContextDelegateSupplier.apply(session); } else { throw e; } } @Override public ResultSet read( final String table, final KeySet keys, final Iterable<String> columns, final ReadOption... options) { return wrap( new Supplier<ResultSet>() { @Override public ResultSet get() { return readContextDelegate.read(table, keys, columns, options); } }); } @Override public ResultSet readUsingIndex( final String table, final String index, final KeySet keys, final Iterable<String> columns, final ReadOption... options) { return wrap( new Supplier<ResultSet>() { @Override public ResultSet get() { return readContextDelegate.readUsingIndex(table, index, keys, columns, options); } }); } @Override @Nullable public Struct readRow(String table, Key key, Iterable<String> columns) { try { while (true) { try { session.markUsed(); return readContextDelegate.readRow(table, key, columns); } catch (SessionNotFoundException e) { replaceSessionIfPossible(e); } } } finally { sessionUsedForQuery = true; if (isSingleUse) { close(); } } } @Override @Nullable public Struct readRowUsingIndex(String table, String index, Key key, Iterable<String> columns) { try { while (true) { try { session.markUsed(); return readContextDelegate.readRowUsingIndex(table, index, key, columns); } catch (SessionNotFoundException e) { replaceSessionIfPossible(e); } } } finally { sessionUsedForQuery = true; if (isSingleUse) { close(); } } } @Override public ResultSet executeQuery(final Statement statement, final QueryOption... options) { return wrap( new Supplier<ResultSet>() { @Override public ResultSet get() { return readContextDelegate.executeQuery(statement, options); } }); } @Override public ResultSet analyzeQuery(final Statement statement, final QueryAnalyzeMode queryMode) { return wrap( new Supplier<ResultSet>() { @Override public ResultSet get() { return readContextDelegate.analyzeQuery(statement, queryMode); } }); } @Override public void close() { if (closed) { return; } closed = true; readContextDelegate.close(); session.close(); } } private static class AutoClosingReadTransaction extends AutoClosingReadContext<ReadOnlyTransaction> implements ReadOnlyTransaction { AutoClosingReadTransaction( Function<PooledSession, ReadOnlyTransaction> txnSupplier, SessionPool sessionPool, PooledSession session, boolean isSingleUse) { super(txnSupplier, sessionPool, session, isSingleUse); } @Override public Timestamp getReadTimestamp() { return getReadContextDelegate().getReadTimestamp(); } } private static class AutoClosingTransactionManager implements TransactionManager { private class SessionPoolResultSet extends ForwardingResultSet { private SessionPoolResultSet(ResultSet delegate) { super(delegate); } @Override public boolean next() { try { return super.next(); } catch (SessionNotFoundException e) { throw handleSessionNotFound(e); } } } /** * {@link TransactionContext} that is used in combination with an {@link * AutoClosingTransactionManager}. This {@link TransactionContext} handles {@link * SessionNotFoundException}s by replacing the underlying session with a fresh one, and then * throws an {@link AbortedException} to trigger the retry-loop that has been created by the * caller. */ private class SessionPoolTransactionContext implements TransactionContext { private final TransactionContext delegate; private SessionPoolTransactionContext(TransactionContext delegate) { this.delegate = delegate; } @Override public ResultSet read( String table, KeySet keys, Iterable<String> columns, ReadOption... options) { return new SessionPoolResultSet(delegate.read(table, keys, columns, options)); } @Override public ResultSet readUsingIndex( String table, String index, KeySet keys, Iterable<String> columns, ReadOption... options) { return new SessionPoolResultSet( delegate.readUsingIndex(table, index, keys, columns, options)); } @Override public Struct readRow(String table, Key key, Iterable<String> columns) { try { return delegate.readRow(table, key, columns); } catch (SessionNotFoundException e) { throw handleSessionNotFound(e); } } @Override public void buffer(Mutation mutation) { delegate.buffer(mutation); } @Override public Struct readRowUsingIndex( String table, String index, Key key, Iterable<String> columns) { try { return delegate.readRowUsingIndex(table, index, key, columns); } catch (SessionNotFoundException e) { throw handleSessionNotFound(e); } } @Override public void buffer(Iterable<Mutation> mutations) { delegate.buffer(mutations); } @Override public long executeUpdate(Statement statement) { try { return delegate.executeUpdate(statement); } catch (SessionNotFoundException e) { throw handleSessionNotFound(e); } } @Override public long[] batchUpdate(Iterable<Statement> statements) { try { return delegate.batchUpdate(statements); } catch (SessionNotFoundException e) { throw handleSessionNotFound(e); } } @Override public ResultSet executeQuery(Statement statement, QueryOption... options) { return new SessionPoolResultSet(delegate.executeQuery(statement, options)); } @Override public ResultSet analyzeQuery(Statement statement, QueryAnalyzeMode queryMode) { return new SessionPoolResultSet(delegate.analyzeQuery(statement, queryMode)); } @Override public void close() { delegate.close(); } } private TransactionManager delegate; private final SessionPool sessionPool; private PooledSession session; private boolean closed; private boolean restartedAfterSessionNotFound; AutoClosingTransactionManager(SessionPool sessionPool, PooledSession session) { this.sessionPool = sessionPool; this.session = session; this.delegate = session.delegate.transactionManager(); } @Override public TransactionContext begin() { while (true) { try { return internalBegin(); } catch (SessionNotFoundException e) { session = sessionPool.replaceReadWriteSession(e, session); delegate = session.delegate.transactionManager(); } } } private TransactionContext internalBegin() { TransactionContext res = new SessionPoolTransactionContext(delegate.begin()); session.markUsed(); return res; } private SpannerException handleSessionNotFound(SessionNotFoundException e) { session = sessionPool.replaceReadWriteSession(e, session); delegate = session.delegate.transactionManager(); restartedAfterSessionNotFound = true; return SpannerExceptionFactory.newSpannerException(ErrorCode.ABORTED, e.getMessage(), e); } @Override public void commit() { try { delegate.commit(); } catch (SessionNotFoundException e) { throw handleSessionNotFound(e); } finally { if (getState() != TransactionState.ABORTED) { close(); } } } @Override public void rollback() { try { delegate.rollback(); } finally { close(); } } @Override public TransactionContext resetForRetry() { while (true) { try { if (restartedAfterSessionNotFound) { TransactionContext res = new SessionPoolTransactionContext(delegate.begin()); restartedAfterSessionNotFound = false; return res; } else { return new SessionPoolTransactionContext(delegate.resetForRetry()); } } catch (SessionNotFoundException e) { session = sessionPool.replaceReadWriteSession(e, session); delegate = session.delegate.transactionManager(); restartedAfterSessionNotFound = true; } } } @Override public Timestamp getCommitTimestamp() { return delegate.getCommitTimestamp(); } @Override public void close() { if (closed) { return; } closed = true; try { delegate.close(); } finally { session.close(); } } @Override public TransactionState getState() { if (restartedAfterSessionNotFound) { return TransactionState.ABORTED; } else { return delegate.getState(); } } } /** * {@link TransactionRunner} that automatically handles {@link SessionNotFoundException}s by * replacing the underlying read/write session and then restarts the transaction. */ private static final class SessionPoolTransactionRunner implements TransactionRunner { private final SessionPool sessionPool; private PooledSession session; private TransactionRunner runner; private SessionPoolTransactionRunner(SessionPool sessionPool, PooledSession session) { this.sessionPool = sessionPool; this.session = session; this.runner = session.delegate.readWriteTransaction(); } @Override @Nullable public <T> T run(TransactionCallable<T> callable) { try { T result; while (true) { try { result = runner.run(callable); break; } catch (SessionNotFoundException e) { session = sessionPool.replaceReadWriteSession(e, session); runner = session.delegate.readWriteTransaction(); } } session.markUsed(); return result; } catch (SpannerException e) { throw session.lastException = e; } finally { session.close(); } } @Override public Timestamp getCommitTimestamp() { return runner.getCommitTimestamp(); } @Override public TransactionRunner allowNestedTransaction() { runner.allowNestedTransaction(); return runner; } } // Exception class used just to track the stack trace at the point when a session was handed out // from the pool. private final class LeakedSessionException extends RuntimeException { private static final long serialVersionUID = 1451131180314064914L; private LeakedSessionException() { super("Session was checked out from the pool at " + clock.instant()); } } private enum SessionState { AVAILABLE, BUSY, CLOSING, } final class PooledSession implements Session { @VisibleForTesting SessionImpl delegate; private volatile Instant lastUseTime; private volatile SpannerException lastException; private volatile LeakedSessionException leakedException; private volatile boolean allowReplacing = true; @GuardedBy("lock") private SessionState state; private PooledSession(SessionImpl delegate) { this.delegate = delegate; this.state = SessionState.AVAILABLE; this.lastUseTime = clock.instant(); } @VisibleForTesting void setAllowReplacing(boolean allowReplacing) { this.allowReplacing = allowReplacing; } @VisibleForTesting void clearLeakedException() { this.leakedException = null; } private void markBusy() { this.state = SessionState.BUSY; this.leakedException = new LeakedSessionException(); } private void markClosing() { this.state = SessionState.CLOSING; } @Override public Timestamp write(Iterable<Mutation> mutations) throws SpannerException { try { markUsed(); return delegate.write(mutations); } catch (SpannerException e) { throw lastException = e; } finally { close(); } } @Override public long executePartitionedUpdate(Statement stmt) throws SpannerException { try { markUsed(); return delegate.executePartitionedUpdate(stmt); } catch (SpannerException e) { throw lastException = e; } finally { close(); } } @Override public Timestamp writeAtLeastOnce(Iterable<Mutation> mutations) throws SpannerException { try { markUsed(); return delegate.writeAtLeastOnce(mutations); } catch (SpannerException e) { throw lastException = e; } finally { close(); } } @Override public ReadContext singleUse() { try { return new AutoClosingReadContext<>( new Function<PooledSession, ReadContext>() { @Override public ReadContext apply(PooledSession session) { return session.delegate.singleUse(); } }, SessionPool.this, this, true); } catch (Exception e) { close(); throw e; } } @Override public ReadContext singleUse(final TimestampBound bound) { try { return new AutoClosingReadContext<>( new Function<PooledSession, ReadContext>() { @Override public ReadContext apply(PooledSession session) { return session.delegate.singleUse(bound); } }, SessionPool.this, this, true); } catch (Exception e) { close(); throw e; } } @Override public ReadOnlyTransaction singleUseReadOnlyTransaction() { return internalReadOnlyTransaction( new Function<PooledSession, ReadOnlyTransaction>() { @Override public ReadOnlyTransaction apply(PooledSession session) { return session.delegate.singleUseReadOnlyTransaction(); } }, true); } @Override public ReadOnlyTransaction singleUseReadOnlyTransaction(final TimestampBound bound) { return internalReadOnlyTransaction( new Function<PooledSession, ReadOnlyTransaction>() { @Override public ReadOnlyTransaction apply(PooledSession session) { return session.delegate.singleUseReadOnlyTransaction(bound); } }, true); } @Override public ReadOnlyTransaction readOnlyTransaction() { return internalReadOnlyTransaction( new Function<PooledSession, ReadOnlyTransaction>() { @Override public ReadOnlyTransaction apply(PooledSession session) { return session.delegate.readOnlyTransaction(); } }, false); } @Override public ReadOnlyTransaction readOnlyTransaction(final TimestampBound bound) { return internalReadOnlyTransaction( new Function<PooledSession, ReadOnlyTransaction>() { @Override public ReadOnlyTransaction apply(PooledSession session) { return session.delegate.readOnlyTransaction(bound); } }, false); } private ReadOnlyTransaction internalReadOnlyTransaction( Function<PooledSession, ReadOnlyTransaction> transactionSupplier, boolean isSingleUse) { try { return new AutoClosingReadTransaction( transactionSupplier, SessionPool.this, this, isSingleUse); } catch (Exception e) { close(); throw e; } } @Override public TransactionRunner readWriteTransaction() { return new SessionPoolTransactionRunner(SessionPool.this, this); } @Override public void close() { synchronized (lock) { numSessionsInUse--; } leakedException = null; if (lastException != null && isSessionNotFound(lastException)) { invalidateSession(this); } else { lastException = null; if (state != SessionState.CLOSING) { state = SessionState.AVAILABLE; } releaseSession(this, Position.FIRST); } } @Override public String getName() { return delegate.getName(); } @Override public void prepareReadWriteTransaction() { markUsed(); delegate.prepareReadWriteTransaction(); } private void keepAlive() { markUsed(); try (ResultSet resultSet = delegate .singleUse(TimestampBound.ofMaxStaleness(60, TimeUnit.SECONDS)) .executeQuery(Statement.newBuilder("SELECT 1").build())) { resultSet.next(); } } private void markUsed() { lastUseTime = clock.instant(); } @Override public TransactionManager transactionManager() { return new AutoClosingTransactionManager(SessionPool.this, this); } } private static final class SessionOrError { private final PooledSession session; private final SpannerException e; SessionOrError(PooledSession session) { this.session = session; this.e = null; } SessionOrError(SpannerException e) { this.session = null; this.e = e; } } private final class Waiter { private static final long MAX_SESSION_WAIT_TIMEOUT = 240_000L; private final SynchronousQueue<SessionOrError> waiter = new SynchronousQueue<>(); private void put(PooledSession session) { Uninterruptibles.putUninterruptibly(waiter, new SessionOrError(session)); } private void put(SpannerException e) { Uninterruptibles.putUninterruptibly(waiter, new SessionOrError(e)); } private PooledSession take() throws SpannerException { long currentTimeout = options.getInitialWaitForSessionTimeoutMillis(); while (true) { try (Scope waitScope = tracer.spanBuilder(WAIT_FOR_SESSION).startScopedSpan()) { SessionOrError s = pollUninterruptiblyWithTimeout(currentTimeout); if (s == null) { // Set the status to DEADLINE_EXCEEDED and retry. numWaiterTimeouts.incrementAndGet(); tracer.getCurrentSpan().setStatus(Status.DEADLINE_EXCEEDED); currentTimeout = Math.min(currentTimeout * 2, MAX_SESSION_WAIT_TIMEOUT); } else { if (s.e != null) { throw newSpannerException(s.e); } return s.session; } } catch (Exception e) { TraceUtil.endSpanWithFailure(tracer.getCurrentSpan(), e); throw e; } } } private SessionOrError pollUninterruptiblyWithTimeout(long timeoutMillis) { boolean interrupted = false; try { while (true) { try { return waiter.poll(timeoutMillis, TimeUnit.MILLISECONDS); } catch (InterruptedException e) { interrupted = true; } } } finally { if (interrupted) { Thread.currentThread().interrupt(); } } } } // Background task to maintain the pool. It closes idle sessions, keeps alive sessions that have // not been used for a user configured time and creates session if needed to bring pool up to // minimum required sessions. We keep track of the number of concurrent sessions being used. // The maximum value of that over a window (10 minutes) tells us how many sessions we need in the // pool. We close the remaining sessions. To prevent bursty traffic, we smear this out over the // window length. We also smear out the keep alive traffic over the keep alive period. final class PoolMaintainer { // Length of the window in millis over which we keep track of maximum number of concurrent // sessions in use. private final Duration windowLength = Duration.ofMillis(TimeUnit.MINUTES.toMillis(10)); // Frequency of the timer loop. @VisibleForTesting static final long LOOP_FREQUENCY = 10 * 1000L; // Number of loop iterations in which we need to to close all the sessions waiting for closure. @VisibleForTesting final long numClosureCycles = windowLength.toMillis() / LOOP_FREQUENCY; private final Duration keepAliveMilis = Duration.ofMillis(TimeUnit.MINUTES.toMillis(options.getKeepAliveIntervalMinutes())); // Number of loop iterations in which we need to keep alive all the sessions @VisibleForTesting final long numKeepAliveCycles = keepAliveMilis.toMillis() / LOOP_FREQUENCY; Instant lastResetTime = Instant.ofEpochMilli(0); int numSessionsToClose = 0; int sessionsToClosePerLoop = 0; @GuardedBy("lock") ScheduledFuture<?> scheduledFuture; @GuardedBy("lock") boolean running; void init() { // Scheduled pool maintenance worker. synchronized (lock) { scheduledFuture = executor.scheduleAtFixedRate( new Runnable() { @Override public void run() { maintainPool(); } }, LOOP_FREQUENCY, LOOP_FREQUENCY, TimeUnit.MILLISECONDS); } } void close() { synchronized (lock) { scheduledFuture.cancel(false); if (!running) { decrementPendingClosures(1); } } } // Does various pool maintenance activities. void maintainPool() { synchronized (lock) { if (isClosed()) { return; } running = true; } Instant currTime = clock.instant(); closeIdleSessions(currTime); // Now go over all the remaining sessions and see if they need to be kept alive explicitly. keepAliveSessions(currTime); replenishPool(); synchronized (lock) { running = false; if (isClosed()) { decrementPendingClosures(1); } } } private void closeIdleSessions(Instant currTime) { LinkedList<PooledSession> sessionsToClose = new LinkedList<>(); synchronized (lock) { // Every ten minutes figure out how many sessions need to be closed then close them over // next ten minutes. if (currTime.isAfter(lastResetTime.plus(windowLength))) { int sessionsToKeep = Math.max(options.getMinSessions(), maxSessionsInUse + options.getMaxIdleSessions()); numSessionsToClose = totalSessions() - sessionsToKeep; sessionsToClosePerLoop = (int) Math.ceil((double) numSessionsToClose / numClosureCycles); maxSessionsInUse = 0; lastResetTime = currTime; } if (numSessionsToClose > 0) { while (sessionsToClose.size() < Math.min(numSessionsToClose, sessionsToClosePerLoop)) { PooledSession sess = readSessions.size() > 0 ? readSessions.poll() : writePreparedSessions.poll(); if (sess != null) { if (sess.state != SessionState.CLOSING) { sess.markClosing(); sessionsToClose.add(sess); } } else { break; } } numSessionsToClose -= sessionsToClose.size(); } } for (PooledSession sess : sessionsToClose) { logger.log(Level.FINE, "Closing session {0}", sess.getName()); closeSession(sess); } } private void keepAliveSessions(Instant currTime) { long numSessionsToKeepAlive = 0; synchronized (lock) { // In each cycle only keep alive a subset of sessions to prevent burst of traffic. numSessionsToKeepAlive = (long) Math.ceil((double) totalSessions() / numKeepAliveCycles); } // Now go over all the remaining sessions and see if they need to be kept alive explicitly. Instant keepAliveThreshold = currTime.minus(keepAliveMilis); // Keep chugging till there is no session that needs to be kept alive. while (numSessionsToKeepAlive > 0) { PooledSession sessionToKeepAlive = null; synchronized (lock) { sessionToKeepAlive = findSessionToKeepAlive(readSessions, keepAliveThreshold); if (sessionToKeepAlive == null) { sessionToKeepAlive = findSessionToKeepAlive(writePreparedSessions, keepAliveThreshold); } } if (sessionToKeepAlive == null) { break; } try { logger.log(Level.FINE, "Keeping alive session " + sessionToKeepAlive.getName()); numSessionsToKeepAlive--; sessionToKeepAlive.keepAlive(); releaseSession(sessionToKeepAlive, Position.FIRST); } catch (SpannerException e) { handleException(e, sessionToKeepAlive); } } } private void replenishPool() { synchronized (lock) { // If we have gone below min pool size, create that many sessions. int sessionCount = options.getMinSessions() - (totalSessions() + numSessionsBeingCreated); if (sessionCount > 0) { createSessions(getAllowedCreateSessions(sessionCount)); } } } } private static enum Position { FIRST, RANDOM; } private final SessionPoolOptions options; private final DatabaseId db; private final SpannerImpl spanner; private final ScheduledExecutorService executor; private final ExecutorFactory<ScheduledExecutorService> executorFactory; final PoolMaintainer poolMaintainer; private final Clock clock; private final Object lock = new Object(); private final Random random = new Random(); @GuardedBy("lock") private int pendingClosure; @GuardedBy("lock") private SettableFuture<Void> closureFuture; @GuardedBy("lock") private final LinkedList<PooledSession> readSessions = new LinkedList<>(); @GuardedBy("lock") private final LinkedList<PooledSession> writePreparedSessions = new LinkedList<>(); @GuardedBy("lock") private final Queue<Waiter> readWaiters = new LinkedList<>(); @GuardedBy("lock") private final Queue<Waiter> readWriteWaiters = new LinkedList<>(); @GuardedBy("lock") private int numSessionsBeingPrepared = 0; @GuardedBy("lock") private int numSessionsBeingCreated = 0; @GuardedBy("lock") private int numSessionsInUse = 0; @GuardedBy("lock") private int maxSessionsInUse = 0; private AtomicLong numWaiterTimeouts = new AtomicLong(); @GuardedBy("lock") private final Set<PooledSession> allSessions = new HashSet<>(); private final SessionConsumer sessionConsumer = new SessionConsumerImpl(); /** * Create a session pool with the given options and for the given database. It will also start * eagerly creating sessions if {@link SessionPoolOptions#getMinSessions()} is greater than 0. * Return pool is immediately ready for use, though getting a session might block for sessions to * be created. */ static SessionPool createPool(SpannerOptions spannerOptions, DatabaseId db, SpannerImpl spanner) { return createPool( spannerOptions.getSessionPoolOptions(), ((GrpcTransportOptions) spannerOptions.getTransportOptions()).getExecutorFactory(), db, spanner); } static SessionPool createPool( SessionPoolOptions poolOptions, ExecutorFactory<ScheduledExecutorService> executorFactory, DatabaseId db, SpannerImpl spanner) { return createPool(poolOptions, executorFactory, db, spanner, new Clock()); } static SessionPool createPool( SessionPoolOptions poolOptions, ExecutorFactory<ScheduledExecutorService> executorFactory, DatabaseId db, SpannerImpl spanner, Clock clock) { SessionPool pool = new SessionPool(poolOptions, executorFactory, executorFactory.get(), db, spanner, clock); pool.initPool(); return pool; } private SessionPool( SessionPoolOptions options, ExecutorFactory<ScheduledExecutorService> executorFactory, ScheduledExecutorService executor, DatabaseId db, SpannerImpl spanner, Clock clock) { this.options = options; this.executorFactory = executorFactory; this.executor = executor; this.db = db; this.spanner = spanner; this.clock = clock; this.poolMaintainer = new PoolMaintainer(); } @VisibleForTesting int getNumberOfAvailableWritePreparedSessions() { synchronized (lock) { return writePreparedSessions.size(); } } @VisibleForTesting int getNumberOfSessionsInPool() { synchronized (lock) { return readSessions.size() + writePreparedSessions.size() + numSessionsBeingPrepared; } } @VisibleForTesting int getNumberOfSessionsBeingCreated() { synchronized (lock) { return numSessionsBeingCreated; } } @VisibleForTesting long getNumWaiterTimeouts() { return numWaiterTimeouts.get(); } private void initPool() { synchronized (lock) { poolMaintainer.init(); if (options.getMinSessions() > 0) { createSessions(options.getMinSessions()); } } } private boolean isClosed() { synchronized (lock) { return closureFuture != null; } } private void handleException(SpannerException e, PooledSession session) { if (isSessionNotFound(e)) { invalidateSession(session); } else { releaseSession(session, Position.FIRST); } } private boolean isSessionNotFound(SpannerException e) { return e.getErrorCode() == ErrorCode.NOT_FOUND && e.getMessage().contains("Session not found"); } private void invalidateSession(PooledSession session) { synchronized (lock) { if (isClosed()) { decrementPendingClosures(1); return; } allSessions.remove(session); // replenish the pool. createSessions(getAllowedCreateSessions(1)); } } private PooledSession findSessionToKeepAlive( Queue<PooledSession> queue, Instant keepAliveThreshold) { Iterator<PooledSession> iterator = queue.iterator(); while (iterator.hasNext()) { PooledSession session = iterator.next(); if (session.lastUseTime.isBefore(keepAliveThreshold)) { iterator.remove(); return session; } } return null; } /** * Returns a session to be used for read requests to spanner. It will block if a session is not * currently available. In case the pool is exhausted and {@link * SessionPoolOptions#isFailIfPoolExhausted()} has been set, it will throw an exception. Returned * session must be closed by calling {@link Session#close()}. * * <p>Implementation strategy: * * <ol> * <li>If a read session is available, return that. * <li>Otherwise if a writePreparedSession is available, return that. * <li>Otherwise if a session can be created, fire a creation request. * <li>Wait for a session to become available. Note that this can be unblocked either by a * session being returned to the pool or a new session being created. * </ol> */ PooledSession getReadSession() throws SpannerException { Span span = Tracing.getTracer().getCurrentSpan(); span.addAnnotation("Acquiring session"); Waiter waiter = null; PooledSession sess = null; synchronized (lock) { if (closureFuture != null) { span.addAnnotation("Pool has been closed"); throw new IllegalStateException("Pool has been closed"); } sess = readSessions.poll(); if (sess == null) { sess = writePreparedSessions.poll(); if (sess == null) { span.addAnnotation("No session available"); maybeCreateSession(); waiter = new Waiter(); readWaiters.add(waiter); } else { span.addAnnotation("Acquired read write session"); } } else { span.addAnnotation("Acquired read only session"); } } if (waiter != null) { logger.log( Level.FINE, "No session available in the pool. Blocking for one to become available/created"); span.addAnnotation("Waiting for read only session to be available"); sess = waiter.take(); } sess.markBusy(); incrementNumSessionsInUse(); span.addAnnotation(sessionAnnotation(sess)); return sess; } /** * Returns a session which has been prepared for writes by invoking BeginTransaction rpc. It will * block if such a session is not currently available.In case the pool is exhausted and {@link * SessionPoolOptions#isFailIfPoolExhausted()} has been set, it will throw an exception. Returned * session must closed by invoking {@link Session#close()}. * * <p>Implementation strategy: * * <ol> * <li>If a writePreparedSession is available, return that. * <li>Otherwise if we have an extra session being prepared for write, wait for that. * <li>Otherwise, if there is a read session available, start preparing that for write and wait. * <li>Otherwise start creating a new session and wait. * <li>Wait for write prepared session to become available. This can be unblocked either by the * session create/prepare request we fired in above request or by a session being released * to the pool which is then write prepared. * </ol> */ PooledSession getReadWriteSession() { Span span = Tracing.getTracer().getCurrentSpan(); span.addAnnotation("Acquiring read write session"); Waiter waiter = null; PooledSession sess = null; synchronized (lock) { if (closureFuture != null) { throw new IllegalStateException("Pool has been closed"); } sess = writePreparedSessions.poll(); if (sess == null) { if (numSessionsBeingPrepared <= readWriteWaiters.size()) { PooledSession readSession = readSessions.poll(); if (readSession != null) { span.addAnnotation("Acquired read only session. Preparing for read write transaction"); prepareSession(readSession); } else { span.addAnnotation("No session available"); maybeCreateSession(); } } waiter = new Waiter(); readWriteWaiters.add(waiter); } else { span.addAnnotation("Acquired read write session"); } } if (waiter != null) { logger.log( Level.FINE, "No session available in the pool. Blocking for one to become available/created"); span.addAnnotation("Waiting for read write session to be available"); sess = waiter.take(); } sess.markBusy(); incrementNumSessionsInUse(); span.addAnnotation(sessionAnnotation(sess)); return sess; } PooledSession replaceReadSession(SessionNotFoundException e, PooledSession session) { return replaceSession(e, session, false); } PooledSession replaceReadWriteSession(SessionNotFoundException e, PooledSession session) { return replaceSession(e, session, true); } private PooledSession replaceSession( SessionNotFoundException e, PooledSession session, boolean write) { if (!options.isFailIfSessionNotFound() && session.allowReplacing) { synchronized (lock) { numSessionsInUse--; } session.leakedException = null; invalidateSession(session); return write ? getReadWriteSession() : getReadSession(); } else { throw e; } } private Annotation sessionAnnotation(Session session) { AttributeValue sessionId = AttributeValue.stringAttributeValue(session.getName()); return Annotation.fromDescriptionAndAttributes( "Using Session", ImmutableMap.of("sessionId", sessionId)); } private void incrementNumSessionsInUse() { synchronized (lock) { if (maxSessionsInUse < ++numSessionsInUse) { maxSessionsInUse = numSessionsInUse; } } } private void maybeCreateSession() { Span span = Tracing.getTracer().getCurrentSpan(); synchronized (lock) { if (numWaiters() >= numSessionsBeingCreated) { if (canCreateSession()) { span.addAnnotation("Creating sessions"); createSessions(getAllowedCreateSessions(numWaiters() - numSessionsBeingCreated + 1)); } else if (options.isFailIfPoolExhausted()) { span.addAnnotation("Pool exhausted. Failing"); // throw specific exception throw newSpannerException( ErrorCode.RESOURCE_EXHAUSTED, "No session available in the pool. Maximum number of sessions in the pool can be" + " overridden by invoking SessionPoolOptions#Builder#setMaxSessions. Client can be made to block" + " rather than fail by setting SessionPoolOptions#Builder#setBlockIfPoolExhausted."); } } } } /** * Releases a session back to the pool. This might cause one of the waiters to be unblocked. * * <p>Implementation note: * * <ol> * <li>If there are no pending waiters, either add to the read sessions queue or start preparing * for write depending on what fraction of sessions are already prepared for writes. * <li>Otherwise either unblock a waiting reader or start preparing for a write. Exact strategy * on which option we chose, in case there are both waiting readers and writers, is * implemented in {@link #shouldUnblockReader} * </ol> */ private void releaseSession(PooledSession session, Position position) { Preconditions.checkNotNull(session); synchronized (lock) { if (closureFuture != null) { return; } if (readWaiters.size() == 0 && numSessionsBeingPrepared >= readWriteWaiters.size()) { // No pending waiters if (shouldPrepareSession()) { prepareSession(session); } else { switch (position) { case RANDOM: if (!readSessions.isEmpty()) { int pos = random.nextInt(readSessions.size() + 1); readSessions.add(pos, session); break; } // fallthrough case FIRST: default: readSessions.addFirst(session); } } } else if (shouldUnblockReader()) { readWaiters.poll().put(session); } else { prepareSession(session); } } } private void handleCreateSessionsFailure(SpannerException e, int count) { synchronized (lock) { for (int i = 0; i < count; i++) { if (readWaiters.size() > 0) { readWaiters.poll().put(e); } else if (readWriteWaiters.size() > 0) { readWriteWaiters.poll().put(e); } else { break; } } } } private void handlePrepareSessionFailure(SpannerException e, PooledSession session) { synchronized (lock) { if (isSessionNotFound(e)) { invalidateSession(session); } else if (readWriteWaiters.size() > 0) { releaseSession(session, Position.FIRST); readWriteWaiters.poll().put(e); } else { releaseSession(session, Position.FIRST); } } } private void decrementPendingClosures(int count) { pendingClosure -= count; if (pendingClosure == 0) { closureFuture.set(null); } } /** * Close all the sessions. Once this method is invoked {@link #getReadSession()} and {@link * #getReadWriteSession()} will start throwing {@code IllegalStateException}. The returned future * blocks till all the sessions created in this pool have been closed. */ ListenableFuture<Void> closeAsync() { ListenableFuture<Void> retFuture = null; synchronized (lock) { if (closureFuture != null) { throw new IllegalStateException("Close has already been invoked"); } // Fail all pending waiters. Waiter waiter = readWaiters.poll(); while (waiter != null) { waiter.put(newSpannerException(ErrorCode.INTERNAL, "Client has been closed")); waiter = readWaiters.poll(); } waiter = readWriteWaiters.poll(); while (waiter != null) { waiter.put(newSpannerException(ErrorCode.INTERNAL, "Client has been closed")); waiter = readWriteWaiters.poll(); } closureFuture = SettableFuture.create(); retFuture = closureFuture; pendingClosure = totalSessions() + numSessionsBeingCreated + 1 /* For pool maintenance thread */; poolMaintainer.close(); readSessions.clear(); writePreparedSessions.clear(); for (final PooledSession session : ImmutableList.copyOf(allSessions)) { if (session.leakedException != null) { logger.log(Level.WARNING, "Leaked session", session.leakedException); } if (session.state != SessionState.CLOSING) { closeSessionAsync(session); } } } retFuture.addListener( new Runnable() { @Override public void run() { executorFactory.release(executor); } }, MoreExecutors.directExecutor()); return retFuture; } private boolean shouldUnblockReader() { // This might not be the best strategy since a continuous burst of read requests can starve // a write request. Maybe maintain a timestamp in the queue and unblock according to that // or just flip a weighted coin. synchronized (lock) { int numWriteWaiters = readWriteWaiters.size() - numSessionsBeingPrepared; return readWaiters.size() > numWriteWaiters; } } private boolean shouldPrepareSession() { synchronized (lock) { int preparedSessions = writePreparedSessions.size() + numSessionsBeingPrepared; return preparedSessions < Math.floor(options.getWriteSessionsFraction() * totalSessions()); } } private int numWaiters() { synchronized (lock) { return readWaiters.size() + readWriteWaiters.size(); } } @VisibleForTesting int totalSessions() { synchronized (lock) { return allSessions.size(); } } private void closeSessionAsync(final PooledSession sess) { executor.submit( new Runnable() { @Override public void run() { closeSession(sess); } }); } private void closeSession(PooledSession sess) { try { sess.delegate.close(); } catch (SpannerException e) { // Backend will delete these sessions after a while even if we fail to close them. if (logger.isLoggable(Level.FINE)) { logger.log(Level.FINE, "Failed to close session: " + sess.getName(), e); } } finally { synchronized (lock) { allSessions.remove(sess); if (isClosed()) { decrementPendingClosures(1); return; } // Create a new session if needed to unblock some waiter. if (numWaiters() > numSessionsBeingCreated) { createSessions(getAllowedCreateSessions(numWaiters() - numSessionsBeingCreated)); } } } } private void prepareSession(final PooledSession sess) { synchronized (lock) { numSessionsBeingPrepared++; } executor.submit( new Runnable() { @Override public void run() { try { logger.log(Level.FINE, "Preparing session"); sess.prepareReadWriteTransaction(); logger.log(Level.FINE, "Session prepared"); synchronized (lock) { numSessionsBeingPrepared--; if (!isClosed()) { if (readWriteWaiters.size() > 0) { readWriteWaiters.poll().put(sess); } else if (readWaiters.size() > 0) { readWaiters.poll().put(sess); } else { writePreparedSessions.add(sess); } } } } catch (Throwable t) { synchronized (lock) { numSessionsBeingPrepared--; if (!isClosed()) { handlePrepareSessionFailure(newSpannerException(t), sess); } } } } }); } /** * Returns the minimum of the wanted number of sessions that the caller wants to create and the * actual max number that may be created at this moment. */ private int getAllowedCreateSessions(int wantedSessions) { synchronized (lock) { return Math.min( wantedSessions, options.getMaxSessions() - (totalSessions() + numSessionsBeingCreated)); } } private boolean canCreateSession() { synchronized (lock) { return totalSessions() + numSessionsBeingCreated < options.getMaxSessions(); } } private void createSessions(final int sessionCount) { logger.log(Level.FINE, String.format("Creating %d sessions", sessionCount)); synchronized (lock) { numSessionsBeingCreated += sessionCount; try { // Create a batch of sessions. The actual session creation can be split into multiple gRPC // calls and the session consumer consumes the returned sessions as they become available. // The batchCreateSessions method automatically spreads the sessions evenly over all // available channels. spanner.asyncBatchCreateSessions(db, sessionCount, sessionConsumer); logger.log(Level.FINE, "Sessions created"); } catch (Throwable t) { // Expose this to customer via a metric. numSessionsBeingCreated -= sessionCount; if (isClosed()) { decrementPendingClosures(sessionCount); } handleCreateSessionsFailure(newSpannerException(t), sessionCount); } } } /** * {@link SessionConsumer} that receives the created sessions from a {@link SessionClient} and * releases these into the pool. The session pool only needs one instance of this, as all sessions * should be returned to the same pool regardless of what triggered the creation of the sessions. */ class SessionConsumerImpl implements SessionConsumer { /** Release a new session to the pool. */ @Override public void onSessionReady(SessionImpl session) { PooledSession pooledSession = null; boolean closeSession = false; synchronized (lock) { pooledSession = new PooledSession(session); numSessionsBeingCreated--; if (closureFuture != null) { closeSession = true; } else { Preconditions.checkState(totalSessions() <= options.getMaxSessions() - 1); allSessions.add(pooledSession); // Release the session to a random position in the pool to prevent the case that a batch // of sessions that are affiliated with the same channel are all placed sequentially in // the pool. releaseSession(pooledSession, Position.RANDOM); } } if (closeSession) { closeSessionAsync(pooledSession); } } /** * Informs waiters for a session that session creation failed. The exception will propagate to * the waiters as a {@link SpannerException}. */ @Override public void onSessionCreateFailure(Throwable t, int createFailureForSessionCount) { synchronized (lock) { numSessionsBeingCreated -= createFailureForSessionCount; if (isClosed()) { decrementPendingClosures(createFailureForSessionCount); } handleCreateSessionsFailure(newSpannerException(t), createFailureForSessionCount); } } } }
google-cloud-spanner/src/main/java/com/google/cloud/spanner/SessionPool.java
/* * Copyright 2017 Google LLC * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.cloud.spanner; import static com.google.cloud.spanner.SpannerExceptionFactory.newSpannerException; import com.google.cloud.Timestamp; import com.google.cloud.grpc.GrpcTransportOptions; import com.google.cloud.grpc.GrpcTransportOptions.ExecutorFactory; import com.google.cloud.spanner.Options.QueryOption; import com.google.cloud.spanner.Options.ReadOption; import com.google.cloud.spanner.SessionClient.SessionConsumer; import com.google.common.annotations.VisibleForTesting; import com.google.common.base.Function; import com.google.common.base.Preconditions; import com.google.common.base.Supplier; import com.google.common.collect.ImmutableList; import com.google.common.collect.ImmutableMap; import com.google.common.util.concurrent.ListenableFuture; import com.google.common.util.concurrent.MoreExecutors; import com.google.common.util.concurrent.SettableFuture; import com.google.common.util.concurrent.Uninterruptibles; import io.opencensus.common.Scope; import io.opencensus.trace.Annotation; import io.opencensus.trace.AttributeValue; import io.opencensus.trace.Span; import io.opencensus.trace.Status; import io.opencensus.trace.Tracer; import io.opencensus.trace.Tracing; import java.util.HashSet; import java.util.Iterator; import java.util.LinkedList; import java.util.Queue; import java.util.Random; import java.util.Set; import java.util.concurrent.ScheduledExecutorService; import java.util.concurrent.ScheduledFuture; import java.util.concurrent.SynchronousQueue; import java.util.concurrent.TimeUnit; import java.util.concurrent.atomic.AtomicLong; import java.util.logging.Level; import java.util.logging.Logger; import javax.annotation.Nullable; import javax.annotation.concurrent.GuardedBy; import org.threeten.bp.Duration; import org.threeten.bp.Instant; /** * Maintains a pool of sessions some of which might be prepared for write by invoking * BeginTransaction rpc. It maintains two queues of sessions(read and write prepared) and two queues * of waiters who are waiting for a session to become available. This class itself is thread safe * and is meant to be used concurrently across multiple threads. */ final class SessionPool { private static final Logger logger = Logger.getLogger(SessionPool.class.getName()); private static final Tracer tracer = Tracing.getTracer(); static final String WAIT_FOR_SESSION = "SessionPool.WaitForSession"; static { TraceUtil.exportSpans(WAIT_FOR_SESSION); } /** * Wrapper around current time so that we can fake it in tests. TODO(user): Replace with Java 8 * Clock. */ static class Clock { Instant instant() { return Instant.now(); } } /** * Wrapper around {@code ReadContext} that releases the session to the pool once the call is * finished, if it is a single use context. */ private static class AutoClosingReadContext<T extends ReadContext> implements ReadContext { private final Function<PooledSession, T> readContextDelegateSupplier; private T readContextDelegate; private final SessionPool sessionPool; private PooledSession session; private final boolean isSingleUse; private boolean closed; private boolean sessionUsedForQuery = false; private AutoClosingReadContext( Function<PooledSession, T> delegateSupplier, SessionPool sessionPool, PooledSession session, boolean isSingleUse) { this.readContextDelegateSupplier = delegateSupplier; this.sessionPool = sessionPool; this.session = session; this.isSingleUse = isSingleUse; while (true) { try { this.readContextDelegate = readContextDelegateSupplier.apply(this.session); break; } catch (SessionNotFoundException e) { replaceSessionIfPossible(e); } } } T getReadContextDelegate() { return readContextDelegate; } private ResultSet wrap(final Supplier<ResultSet> resultSetSupplier) { ResultSet res; while (true) { try { res = resultSetSupplier.get(); break; } catch (SessionNotFoundException e) { replaceSessionIfPossible(e); } } return new ForwardingResultSet(res) { private boolean beforeFirst = true; @Override public boolean next() throws SpannerException { while (true) { try { return internalNext(); } catch (SessionNotFoundException e) { replaceSessionIfPossible(e); replaceDelegate(resultSetSupplier.get()); } } } private boolean internalNext() { try { boolean ret = super.next(); if (beforeFirst) { session.markUsed(); beforeFirst = false; sessionUsedForQuery = true; } if (!ret && isSingleUse) { close(); } return ret; } catch (SessionNotFoundException e) { throw e; } catch (SpannerException e) { if (!closed && isSingleUse) { session.lastException = e; AutoClosingReadContext.this.close(); } throw e; } } @Override public void close() { super.close(); if (isSingleUse) { AutoClosingReadContext.this.close(); } } }; } private void replaceSessionIfPossible(SessionNotFoundException e) { if (isSingleUse || !sessionUsedForQuery) { // This class is only used by read-only transactions, so we know that we only need a // read-only session. session = sessionPool.replaceReadSession(e, session); readContextDelegate = readContextDelegateSupplier.apply(session); } else { throw e; } } @Override public ResultSet read( final String table, final KeySet keys, final Iterable<String> columns, final ReadOption... options) { return wrap( new Supplier<ResultSet>() { @Override public ResultSet get() { return readContextDelegate.read(table, keys, columns, options); } }); } @Override public ResultSet readUsingIndex( final String table, final String index, final KeySet keys, final Iterable<String> columns, final ReadOption... options) { return wrap( new Supplier<ResultSet>() { @Override public ResultSet get() { return readContextDelegate.readUsingIndex(table, index, keys, columns, options); } }); } @Override @Nullable public Struct readRow(String table, Key key, Iterable<String> columns) { try { while (true) { try { session.markUsed(); return readContextDelegate.readRow(table, key, columns); } catch (SessionNotFoundException e) { replaceSessionIfPossible(e); } } } finally { sessionUsedForQuery = true; if (isSingleUse) { close(); } } } @Override @Nullable public Struct readRowUsingIndex(String table, String index, Key key, Iterable<String> columns) { try { while (true) { try { session.markUsed(); return readContextDelegate.readRowUsingIndex(table, index, key, columns); } catch (SessionNotFoundException e) { replaceSessionIfPossible(e); } } } finally { sessionUsedForQuery = true; if (isSingleUse) { close(); } } } @Override public ResultSet executeQuery(final Statement statement, final QueryOption... options) { return wrap( new Supplier<ResultSet>() { @Override public ResultSet get() { return readContextDelegate.executeQuery(statement, options); } }); } @Override public ResultSet analyzeQuery(final Statement statement, final QueryAnalyzeMode queryMode) { return wrap( new Supplier<ResultSet>() { @Override public ResultSet get() { return readContextDelegate.analyzeQuery(statement, queryMode); } }); } @Override public void close() { if (closed) { return; } closed = true; readContextDelegate.close(); session.close(); } } private static class AutoClosingReadTransaction extends AutoClosingReadContext<ReadOnlyTransaction> implements ReadOnlyTransaction { AutoClosingReadTransaction( Function<PooledSession, ReadOnlyTransaction> txnSupplier, SessionPool sessionPool, PooledSession session, boolean isSingleUse) { super(txnSupplier, sessionPool, session, isSingleUse); } @Override public Timestamp getReadTimestamp() { return getReadContextDelegate().getReadTimestamp(); } } private static class AutoClosingTransactionManager implements TransactionManager { private class SessionPoolResultSet extends ForwardingResultSet { private SessionPoolResultSet(ResultSet delegate) { super(delegate); } @Override public boolean next() { try { return super.next(); } catch (SessionNotFoundException e) { throw handleSessionNotFound(e); } } } /** * {@link TransactionContext} that is used in combination with an {@link * AutoClosingTransactionManager}. This {@link TransactionContext} handles {@link * SessionNotFoundException}s by replacing the underlying session with a fresh one, and then * throws an {@link AbortedException} to trigger the retry-loop that has been created by the * caller. */ private class SessionPoolTransactionContext implements TransactionContext { private final TransactionContext delegate; private SessionPoolTransactionContext(TransactionContext delegate) { this.delegate = delegate; } @Override public ResultSet read( String table, KeySet keys, Iterable<String> columns, ReadOption... options) { return new SessionPoolResultSet(delegate.read(table, keys, columns, options)); } @Override public ResultSet readUsingIndex( String table, String index, KeySet keys, Iterable<String> columns, ReadOption... options) { return new SessionPoolResultSet( delegate.readUsingIndex(table, index, keys, columns, options)); } @Override public Struct readRow(String table, Key key, Iterable<String> columns) { try { return delegate.readRow(table, key, columns); } catch (SessionNotFoundException e) { throw handleSessionNotFound(e); } } @Override public void buffer(Mutation mutation) { delegate.buffer(mutation); } @Override public Struct readRowUsingIndex( String table, String index, Key key, Iterable<String> columns) { try { return delegate.readRowUsingIndex(table, index, key, columns); } catch (SessionNotFoundException e) { throw handleSessionNotFound(e); } } @Override public void buffer(Iterable<Mutation> mutations) { delegate.buffer(mutations); } @Override public long executeUpdate(Statement statement) { try { return delegate.executeUpdate(statement); } catch (SessionNotFoundException e) { throw handleSessionNotFound(e); } } @Override public long[] batchUpdate(Iterable<Statement> statements) { try { return delegate.batchUpdate(statements); } catch (SessionNotFoundException e) { throw handleSessionNotFound(e); } } @Override public ResultSet executeQuery(Statement statement, QueryOption... options) { return new SessionPoolResultSet(delegate.executeQuery(statement, options)); } @Override public ResultSet analyzeQuery(Statement statement, QueryAnalyzeMode queryMode) { return new SessionPoolResultSet(delegate.analyzeQuery(statement, queryMode)); } @Override public void close() { delegate.close(); } } private TransactionManager delegate; private final SessionPool sessionPool; private PooledSession session; private boolean closed; private boolean restartedAfterSessionNotFound; AutoClosingTransactionManager(SessionPool sessionPool, PooledSession session) { this.sessionPool = sessionPool; this.session = session; this.delegate = session.delegate.transactionManager(); } @Override public TransactionContext begin() { while (true) { try { return internalBegin(); } catch (SessionNotFoundException e) { session = sessionPool.replaceReadWriteSession(e, session); delegate = session.delegate.transactionManager(); } } } private TransactionContext internalBegin() { TransactionContext res = new SessionPoolTransactionContext(delegate.begin()); session.markUsed(); return res; } private SpannerException handleSessionNotFound(SessionNotFoundException e) { session = sessionPool.replaceReadWriteSession(e, session); delegate = session.delegate.transactionManager(); restartedAfterSessionNotFound = true; return SpannerExceptionFactory.newSpannerException(ErrorCode.ABORTED, e.getMessage(), e); } @Override public void commit() { try { delegate.commit(); } catch (SessionNotFoundException e) { throw handleSessionNotFound(e); } finally { if (getState() != TransactionState.ABORTED) { close(); } } } @Override public void rollback() { try { delegate.rollback(); } finally { close(); } } @Override public TransactionContext resetForRetry() { while (true) { try { if (restartedAfterSessionNotFound) { TransactionContext res = new SessionPoolTransactionContext(delegate.begin()); restartedAfterSessionNotFound = false; return res; } else { return new SessionPoolTransactionContext(delegate.resetForRetry()); } } catch (SessionNotFoundException e) { session = sessionPool.replaceReadWriteSession(e, session); delegate = session.delegate.transactionManager(); restartedAfterSessionNotFound = true; } } } @Override public Timestamp getCommitTimestamp() { return delegate.getCommitTimestamp(); } @Override public void close() { if (closed) { return; } closed = true; try { delegate.close(); } finally { session.close(); } } @Override public TransactionState getState() { if (restartedAfterSessionNotFound) { return TransactionState.ABORTED; } else { return delegate.getState(); } } } /** * {@link TransactionRunner} that automatically handles {@link SessionNotFoundException}s by * replacing the underlying read/write session and then restarts the transaction. */ private static final class SessionPoolTransactionRunner implements TransactionRunner { private final SessionPool sessionPool; private PooledSession session; private TransactionRunner runner; private SessionPoolTransactionRunner(SessionPool sessionPool, PooledSession session) { this.sessionPool = sessionPool; this.session = session; this.runner = session.delegate.readWriteTransaction(); } @Override @Nullable public <T> T run(TransactionCallable<T> callable) { try { T result; while (true) { try { result = runner.run(callable); break; } catch (SessionNotFoundException e) { session = sessionPool.replaceReadWriteSession(e, session); runner = session.delegate.readWriteTransaction(); } } session.markUsed(); return result; } catch (SpannerException e) { throw session.lastException = e; } finally { session.close(); } } @Override public Timestamp getCommitTimestamp() { return runner.getCommitTimestamp(); } @Override public TransactionRunner allowNestedTransaction() { runner.allowNestedTransaction(); return runner; } } // Exception class used just to track the stack trace at the point when a session was handed out // from the pool. private final class LeakedSessionException extends RuntimeException { private static final long serialVersionUID = 1451131180314064914L; private LeakedSessionException() { super("Session was checked out from the pool at " + clock.instant()); } } private enum SessionState { AVAILABLE, BUSY, CLOSING, } final class PooledSession implements Session { @VisibleForTesting SessionImpl delegate; private volatile Instant lastUseTime; private volatile SpannerException lastException; private volatile LeakedSessionException leakedException; private volatile boolean allowReplacing = true; @GuardedBy("lock") private SessionState state; private PooledSession(SessionImpl delegate) { this.delegate = delegate; this.state = SessionState.AVAILABLE; this.lastUseTime = clock.instant(); } @VisibleForTesting void setAllowReplacing(boolean allowReplacing) { this.allowReplacing = allowReplacing; } @VisibleForTesting void clearLeakedException() { this.leakedException = null; } private void markBusy() { this.state = SessionState.BUSY; this.leakedException = new LeakedSessionException(); } private void markClosing() { this.state = SessionState.CLOSING; } @Override public Timestamp write(Iterable<Mutation> mutations) throws SpannerException { try { markUsed(); return delegate.write(mutations); } catch (SpannerException e) { throw lastException = e; } finally { close(); } } @Override public long executePartitionedUpdate(Statement stmt) throws SpannerException { try { markUsed(); return delegate.executePartitionedUpdate(stmt); } catch (SpannerException e) { throw lastException = e; } finally { close(); } } @Override public Timestamp writeAtLeastOnce(Iterable<Mutation> mutations) throws SpannerException { try { markUsed(); return delegate.writeAtLeastOnce(mutations); } catch (SpannerException e) { throw lastException = e; } finally { close(); } } @Override public ReadContext singleUse() { try { return new AutoClosingReadContext<>( new Function<PooledSession, ReadContext>() { @Override public ReadContext apply(PooledSession session) { return session.delegate.singleUse(); } }, SessionPool.this, this, true); } catch (Exception e) { close(); throw e; } } @Override public ReadContext singleUse(final TimestampBound bound) { try { return new AutoClosingReadContext<>( new Function<PooledSession, ReadContext>() { @Override public ReadContext apply(PooledSession session) { return session.delegate.singleUse(bound); } }, SessionPool.this, this, true); } catch (Exception e) { close(); throw e; } } @Override public ReadOnlyTransaction singleUseReadOnlyTransaction() { return internalReadOnlyTransaction( new Function<PooledSession, ReadOnlyTransaction>() { @Override public ReadOnlyTransaction apply(PooledSession session) { return session.delegate.singleUseReadOnlyTransaction(); } }, true); } @Override public ReadOnlyTransaction singleUseReadOnlyTransaction(final TimestampBound bound) { return internalReadOnlyTransaction( new Function<PooledSession, ReadOnlyTransaction>() { @Override public ReadOnlyTransaction apply(PooledSession session) { return session.delegate.singleUseReadOnlyTransaction(bound); } }, true); } @Override public ReadOnlyTransaction readOnlyTransaction() { return internalReadOnlyTransaction( new Function<PooledSession, ReadOnlyTransaction>() { @Override public ReadOnlyTransaction apply(PooledSession session) { return session.delegate.readOnlyTransaction(); } }, false); } @Override public ReadOnlyTransaction readOnlyTransaction(final TimestampBound bound) { return internalReadOnlyTransaction( new Function<PooledSession, ReadOnlyTransaction>() { @Override public ReadOnlyTransaction apply(PooledSession session) { return session.delegate.readOnlyTransaction(bound); } }, false); } private ReadOnlyTransaction internalReadOnlyTransaction( Function<PooledSession, ReadOnlyTransaction> transactionSupplier, boolean isSingleUse) { try { return new AutoClosingReadTransaction( transactionSupplier, SessionPool.this, this, isSingleUse); } catch (Exception e) { close(); throw e; } } @Override public TransactionRunner readWriteTransaction() { return new SessionPoolTransactionRunner(SessionPool.this, this); } @Override public void close() { synchronized (lock) { numSessionsInUse--; } leakedException = null; if (lastException != null && isSessionNotFound(lastException)) { invalidateSession(this); } else { lastException = null; if (state != SessionState.CLOSING) { state = SessionState.AVAILABLE; } releaseSession(this, Position.FIRST); } } @Override public String getName() { return delegate.getName(); } @Override public void prepareReadWriteTransaction() { markUsed(); delegate.prepareReadWriteTransaction(); } private void keepAlive() { markUsed(); delegate .singleUse(TimestampBound.ofMaxStaleness(60, TimeUnit.SECONDS)) .executeQuery(Statement.newBuilder("SELECT 1").build()) .next(); } private void markUsed() { lastUseTime = clock.instant(); } @Override public TransactionManager transactionManager() { return new AutoClosingTransactionManager(SessionPool.this, this); } } private static final class SessionOrError { private final PooledSession session; private final SpannerException e; SessionOrError(PooledSession session) { this.session = session; this.e = null; } SessionOrError(SpannerException e) { this.session = null; this.e = e; } } private final class Waiter { private static final long MAX_SESSION_WAIT_TIMEOUT = 240_000L; private final SynchronousQueue<SessionOrError> waiter = new SynchronousQueue<>(); private void put(PooledSession session) { Uninterruptibles.putUninterruptibly(waiter, new SessionOrError(session)); } private void put(SpannerException e) { Uninterruptibles.putUninterruptibly(waiter, new SessionOrError(e)); } private PooledSession take() throws SpannerException { long currentTimeout = options.getInitialWaitForSessionTimeoutMillis(); while (true) { try (Scope waitScope = tracer.spanBuilder(WAIT_FOR_SESSION).startScopedSpan()) { SessionOrError s = pollUninterruptiblyWithTimeout(currentTimeout); if (s == null) { // Set the status to DEADLINE_EXCEEDED and retry. numWaiterTimeouts.incrementAndGet(); tracer.getCurrentSpan().setStatus(Status.DEADLINE_EXCEEDED); currentTimeout = Math.min(currentTimeout * 2, MAX_SESSION_WAIT_TIMEOUT); } else { if (s.e != null) { throw newSpannerException(s.e); } return s.session; } } catch (Exception e) { TraceUtil.endSpanWithFailure(tracer.getCurrentSpan(), e); throw e; } } } private SessionOrError pollUninterruptiblyWithTimeout(long timeoutMillis) { boolean interrupted = false; try { while (true) { try { return waiter.poll(timeoutMillis, TimeUnit.MILLISECONDS); } catch (InterruptedException e) { interrupted = true; } } } finally { if (interrupted) { Thread.currentThread().interrupt(); } } } } // Background task to maintain the pool. It closes idle sessions, keeps alive sessions that have // not been used for a user configured time and creates session if needed to bring pool up to // minimum required sessions. We keep track of the number of concurrent sessions being used. // The maximum value of that over a window (10 minutes) tells us how many sessions we need in the // pool. We close the remaining sessions. To prevent bursty traffic, we smear this out over the // window length. We also smear out the keep alive traffic over the keep alive period. final class PoolMaintainer { // Length of the window in millis over which we keep track of maximum number of concurrent // sessions in use. private final Duration windowLength = Duration.ofMillis(TimeUnit.MINUTES.toMillis(10)); // Frequency of the timer loop. @VisibleForTesting static final long LOOP_FREQUENCY = 10 * 1000L; // Number of loop iterations in which we need to to close all the sessions waiting for closure. @VisibleForTesting final long numClosureCycles = windowLength.toMillis() / LOOP_FREQUENCY; private final Duration keepAliveMilis = Duration.ofMillis(TimeUnit.MINUTES.toMillis(options.getKeepAliveIntervalMinutes())); // Number of loop iterations in which we need to keep alive all the sessions @VisibleForTesting final long numKeepAliveCycles = keepAliveMilis.toMillis() / LOOP_FREQUENCY; Instant lastResetTime = Instant.ofEpochMilli(0); int numSessionsToClose = 0; int sessionsToClosePerLoop = 0; @GuardedBy("lock") ScheduledFuture<?> scheduledFuture; @GuardedBy("lock") boolean running; void init() { // Scheduled pool maintenance worker. synchronized (lock) { scheduledFuture = executor.scheduleAtFixedRate( new Runnable() { @Override public void run() { maintainPool(); } }, LOOP_FREQUENCY, LOOP_FREQUENCY, TimeUnit.MILLISECONDS); } } void close() { synchronized (lock) { scheduledFuture.cancel(false); if (!running) { decrementPendingClosures(1); } } } // Does various pool maintenance activities. void maintainPool() { synchronized (lock) { if (isClosed()) { return; } running = true; } Instant currTime = clock.instant(); closeIdleSessions(currTime); // Now go over all the remaining sessions and see if they need to be kept alive explicitly. keepAliveSessions(currTime); replenishPool(); synchronized (lock) { running = false; if (isClosed()) { decrementPendingClosures(1); } } } private void closeIdleSessions(Instant currTime) { LinkedList<PooledSession> sessionsToClose = new LinkedList<>(); synchronized (lock) { // Every ten minutes figure out how many sessions need to be closed then close them over // next ten minutes. if (currTime.isAfter(lastResetTime.plus(windowLength))) { int sessionsToKeep = Math.max(options.getMinSessions(), maxSessionsInUse + options.getMaxIdleSessions()); numSessionsToClose = totalSessions() - sessionsToKeep; sessionsToClosePerLoop = (int) Math.ceil((double) numSessionsToClose / numClosureCycles); maxSessionsInUse = 0; lastResetTime = currTime; } if (numSessionsToClose > 0) { while (sessionsToClose.size() < Math.min(numSessionsToClose, sessionsToClosePerLoop)) { PooledSession sess = readSessions.size() > 0 ? readSessions.poll() : writePreparedSessions.poll(); if (sess != null) { if (sess.state != SessionState.CLOSING) { sess.markClosing(); sessionsToClose.add(sess); } } else { break; } } numSessionsToClose -= sessionsToClose.size(); } } for (PooledSession sess : sessionsToClose) { logger.log(Level.FINE, "Closing session {0}", sess.getName()); closeSession(sess); } } private void keepAliveSessions(Instant currTime) { long numSessionsToKeepAlive = 0; synchronized (lock) { // In each cycle only keep alive a subset of sessions to prevent burst of traffic. numSessionsToKeepAlive = (long) Math.ceil((double) totalSessions() / numKeepAliveCycles); } // Now go over all the remaining sessions and see if they need to be kept alive explicitly. Instant keepAliveThreshold = currTime.minus(keepAliveMilis); // Keep chugging till there is no session that needs to be kept alive. while (numSessionsToKeepAlive > 0) { PooledSession sessionToKeepAlive = null; synchronized (lock) { sessionToKeepAlive = findSessionToKeepAlive(readSessions, keepAliveThreshold); if (sessionToKeepAlive == null) { sessionToKeepAlive = findSessionToKeepAlive(writePreparedSessions, keepAliveThreshold); } } if (sessionToKeepAlive == null) { break; } try { logger.log(Level.FINE, "Keeping alive session " + sessionToKeepAlive.getName()); numSessionsToKeepAlive--; sessionToKeepAlive.keepAlive(); releaseSession(sessionToKeepAlive, Position.FIRST); } catch (SpannerException e) { handleException(e, sessionToKeepAlive); } } } private void replenishPool() { synchronized (lock) { // If we have gone below min pool size, create that many sessions. int sessionCount = options.getMinSessions() - (totalSessions() + numSessionsBeingCreated); if (sessionCount > 0) { createSessions(getAllowedCreateSessions(sessionCount)); } } } } private static enum Position { FIRST, RANDOM; } private final SessionPoolOptions options; private final DatabaseId db; private final SpannerImpl spanner; private final ScheduledExecutorService executor; private final ExecutorFactory<ScheduledExecutorService> executorFactory; final PoolMaintainer poolMaintainer; private final Clock clock; private final Object lock = new Object(); private final Random random = new Random(); @GuardedBy("lock") private int pendingClosure; @GuardedBy("lock") private SettableFuture<Void> closureFuture; @GuardedBy("lock") private final LinkedList<PooledSession> readSessions = new LinkedList<>(); @GuardedBy("lock") private final LinkedList<PooledSession> writePreparedSessions = new LinkedList<>(); @GuardedBy("lock") private final Queue<Waiter> readWaiters = new LinkedList<>(); @GuardedBy("lock") private final Queue<Waiter> readWriteWaiters = new LinkedList<>(); @GuardedBy("lock") private int numSessionsBeingPrepared = 0; @GuardedBy("lock") private int numSessionsBeingCreated = 0; @GuardedBy("lock") private int numSessionsInUse = 0; @GuardedBy("lock") private int maxSessionsInUse = 0; private AtomicLong numWaiterTimeouts = new AtomicLong(); @GuardedBy("lock") private final Set<PooledSession> allSessions = new HashSet<>(); private final SessionConsumer sessionConsumer = new SessionConsumerImpl(); /** * Create a session pool with the given options and for the given database. It will also start * eagerly creating sessions if {@link SessionPoolOptions#getMinSessions()} is greater than 0. * Return pool is immediately ready for use, though getting a session might block for sessions to * be created. */ static SessionPool createPool(SpannerOptions spannerOptions, DatabaseId db, SpannerImpl spanner) { return createPool( spannerOptions.getSessionPoolOptions(), ((GrpcTransportOptions) spannerOptions.getTransportOptions()).getExecutorFactory(), db, spanner); } static SessionPool createPool( SessionPoolOptions poolOptions, ExecutorFactory<ScheduledExecutorService> executorFactory, DatabaseId db, SpannerImpl spanner) { return createPool(poolOptions, executorFactory, db, spanner, new Clock()); } static SessionPool createPool( SessionPoolOptions poolOptions, ExecutorFactory<ScheduledExecutorService> executorFactory, DatabaseId db, SpannerImpl spanner, Clock clock) { SessionPool pool = new SessionPool(poolOptions, executorFactory, executorFactory.get(), db, spanner, clock); pool.initPool(); return pool; } private SessionPool( SessionPoolOptions options, ExecutorFactory<ScheduledExecutorService> executorFactory, ScheduledExecutorService executor, DatabaseId db, SpannerImpl spanner, Clock clock) { this.options = options; this.executorFactory = executorFactory; this.executor = executor; this.db = db; this.spanner = spanner; this.clock = clock; this.poolMaintainer = new PoolMaintainer(); } @VisibleForTesting int getNumberOfAvailableWritePreparedSessions() { synchronized (lock) { return writePreparedSessions.size(); } } @VisibleForTesting int getNumberOfSessionsInPool() { synchronized (lock) { return readSessions.size() + writePreparedSessions.size() + numSessionsBeingPrepared; } } @VisibleForTesting int getNumberOfSessionsBeingCreated() { synchronized (lock) { return numSessionsBeingCreated; } } @VisibleForTesting long getNumWaiterTimeouts() { return numWaiterTimeouts.get(); } private void initPool() { synchronized (lock) { poolMaintainer.init(); if (options.getMinSessions() > 0) { createSessions(options.getMinSessions()); } } } private boolean isClosed() { synchronized (lock) { return closureFuture != null; } } private void handleException(SpannerException e, PooledSession session) { if (isSessionNotFound(e)) { invalidateSession(session); } else { releaseSession(session, Position.FIRST); } } private boolean isSessionNotFound(SpannerException e) { return e.getErrorCode() == ErrorCode.NOT_FOUND && e.getMessage().contains("Session not found"); } private void invalidateSession(PooledSession session) { synchronized (lock) { if (isClosed()) { decrementPendingClosures(1); return; } allSessions.remove(session); // replenish the pool. createSessions(getAllowedCreateSessions(1)); } } private PooledSession findSessionToKeepAlive( Queue<PooledSession> queue, Instant keepAliveThreshold) { Iterator<PooledSession> iterator = queue.iterator(); while (iterator.hasNext()) { PooledSession session = iterator.next(); if (session.lastUseTime.isBefore(keepAliveThreshold)) { iterator.remove(); return session; } } return null; } /** * Returns a session to be used for read requests to spanner. It will block if a session is not * currently available. In case the pool is exhausted and {@link * SessionPoolOptions#isFailIfPoolExhausted()} has been set, it will throw an exception. Returned * session must be closed by calling {@link Session#close()}. * * <p>Implementation strategy: * * <ol> * <li>If a read session is available, return that. * <li>Otherwise if a writePreparedSession is available, return that. * <li>Otherwise if a session can be created, fire a creation request. * <li>Wait for a session to become available. Note that this can be unblocked either by a * session being returned to the pool or a new session being created. * </ol> */ PooledSession getReadSession() throws SpannerException { Span span = Tracing.getTracer().getCurrentSpan(); span.addAnnotation("Acquiring session"); Waiter waiter = null; PooledSession sess = null; synchronized (lock) { if (closureFuture != null) { span.addAnnotation("Pool has been closed"); throw new IllegalStateException("Pool has been closed"); } sess = readSessions.poll(); if (sess == null) { sess = writePreparedSessions.poll(); if (sess == null) { span.addAnnotation("No session available"); maybeCreateSession(); waiter = new Waiter(); readWaiters.add(waiter); } else { span.addAnnotation("Acquired read write session"); } } else { span.addAnnotation("Acquired read only session"); } } if (waiter != null) { logger.log( Level.FINE, "No session available in the pool. Blocking for one to become available/created"); span.addAnnotation("Waiting for read only session to be available"); sess = waiter.take(); } sess.markBusy(); incrementNumSessionsInUse(); span.addAnnotation(sessionAnnotation(sess)); return sess; } /** * Returns a session which has been prepared for writes by invoking BeginTransaction rpc. It will * block if such a session is not currently available.In case the pool is exhausted and {@link * SessionPoolOptions#isFailIfPoolExhausted()} has been set, it will throw an exception. Returned * session must closed by invoking {@link Session#close()}. * * <p>Implementation strategy: * * <ol> * <li>If a writePreparedSession is available, return that. * <li>Otherwise if we have an extra session being prepared for write, wait for that. * <li>Otherwise, if there is a read session available, start preparing that for write and wait. * <li>Otherwise start creating a new session and wait. * <li>Wait for write prepared session to become available. This can be unblocked either by the * session create/prepare request we fired in above request or by a session being released * to the pool which is then write prepared. * </ol> */ PooledSession getReadWriteSession() { Span span = Tracing.getTracer().getCurrentSpan(); span.addAnnotation("Acquiring read write session"); Waiter waiter = null; PooledSession sess = null; synchronized (lock) { if (closureFuture != null) { throw new IllegalStateException("Pool has been closed"); } sess = writePreparedSessions.poll(); if (sess == null) { if (numSessionsBeingPrepared <= readWriteWaiters.size()) { PooledSession readSession = readSessions.poll(); if (readSession != null) { span.addAnnotation("Acquired read only session. Preparing for read write transaction"); prepareSession(readSession); } else { span.addAnnotation("No session available"); maybeCreateSession(); } } waiter = new Waiter(); readWriteWaiters.add(waiter); } else { span.addAnnotation("Acquired read write session"); } } if (waiter != null) { logger.log( Level.FINE, "No session available in the pool. Blocking for one to become available/created"); span.addAnnotation("Waiting for read write session to be available"); sess = waiter.take(); } sess.markBusy(); incrementNumSessionsInUse(); span.addAnnotation(sessionAnnotation(sess)); return sess; } PooledSession replaceReadSession(SessionNotFoundException e, PooledSession session) { return replaceSession(e, session, false); } PooledSession replaceReadWriteSession(SessionNotFoundException e, PooledSession session) { return replaceSession(e, session, true); } private PooledSession replaceSession( SessionNotFoundException e, PooledSession session, boolean write) { if (!options.isFailIfSessionNotFound() && session.allowReplacing) { synchronized (lock) { numSessionsInUse--; } session.leakedException = null; invalidateSession(session); return write ? getReadWriteSession() : getReadSession(); } else { throw e; } } private Annotation sessionAnnotation(Session session) { AttributeValue sessionId = AttributeValue.stringAttributeValue(session.getName()); return Annotation.fromDescriptionAndAttributes( "Using Session", ImmutableMap.of("sessionId", sessionId)); } private void incrementNumSessionsInUse() { synchronized (lock) { if (maxSessionsInUse < ++numSessionsInUse) { maxSessionsInUse = numSessionsInUse; } } } private void maybeCreateSession() { Span span = Tracing.getTracer().getCurrentSpan(); synchronized (lock) { if (numWaiters() >= numSessionsBeingCreated) { if (canCreateSession()) { span.addAnnotation("Creating sessions"); createSessions(getAllowedCreateSessions(numWaiters() - numSessionsBeingCreated + 1)); } else if (options.isFailIfPoolExhausted()) { span.addAnnotation("Pool exhausted. Failing"); // throw specific exception throw newSpannerException( ErrorCode.RESOURCE_EXHAUSTED, "No session available in the pool. Maximum number of sessions in the pool can be" + " overridden by invoking SessionPoolOptions#Builder#setMaxSessions. Client can be made to block" + " rather than fail by setting SessionPoolOptions#Builder#setBlockIfPoolExhausted."); } } } } /** * Releases a session back to the pool. This might cause one of the waiters to be unblocked. * * <p>Implementation note: * * <ol> * <li>If there are no pending waiters, either add to the read sessions queue or start preparing * for write depending on what fraction of sessions are already prepared for writes. * <li>Otherwise either unblock a waiting reader or start preparing for a write. Exact strategy * on which option we chose, in case there are both waiting readers and writers, is * implemented in {@link #shouldUnblockReader} * </ol> */ private void releaseSession(PooledSession session, Position position) { Preconditions.checkNotNull(session); synchronized (lock) { if (closureFuture != null) { return; } if (readWaiters.size() == 0 && numSessionsBeingPrepared >= readWriteWaiters.size()) { // No pending waiters if (shouldPrepareSession()) { prepareSession(session); } else { switch (position) { case RANDOM: if (!readSessions.isEmpty()) { int pos = random.nextInt(readSessions.size() + 1); readSessions.add(pos, session); break; } // fallthrough case FIRST: default: readSessions.addFirst(session); } } } else if (shouldUnblockReader()) { readWaiters.poll().put(session); } else { prepareSession(session); } } } private void handleCreateSessionsFailure(SpannerException e, int count) { synchronized (lock) { for (int i = 0; i < count; i++) { if (readWaiters.size() > 0) { readWaiters.poll().put(e); } else if (readWriteWaiters.size() > 0) { readWriteWaiters.poll().put(e); } else { break; } } } } private void handlePrepareSessionFailure(SpannerException e, PooledSession session) { synchronized (lock) { if (isSessionNotFound(e)) { invalidateSession(session); } else if (readWriteWaiters.size() > 0) { releaseSession(session, Position.FIRST); readWriteWaiters.poll().put(e); } else { releaseSession(session, Position.FIRST); } } } private void decrementPendingClosures(int count) { pendingClosure -= count; if (pendingClosure == 0) { closureFuture.set(null); } } /** * Close all the sessions. Once this method is invoked {@link #getReadSession()} and {@link * #getReadWriteSession()} will start throwing {@code IllegalStateException}. The returned future * blocks till all the sessions created in this pool have been closed. */ ListenableFuture<Void> closeAsync() { ListenableFuture<Void> retFuture = null; synchronized (lock) { if (closureFuture != null) { throw new IllegalStateException("Close has already been invoked"); } // Fail all pending waiters. Waiter waiter = readWaiters.poll(); while (waiter != null) { waiter.put(newSpannerException(ErrorCode.INTERNAL, "Client has been closed")); waiter = readWaiters.poll(); } waiter = readWriteWaiters.poll(); while (waiter != null) { waiter.put(newSpannerException(ErrorCode.INTERNAL, "Client has been closed")); waiter = readWriteWaiters.poll(); } closureFuture = SettableFuture.create(); retFuture = closureFuture; pendingClosure = totalSessions() + numSessionsBeingCreated + 1 /* For pool maintenance thread */; poolMaintainer.close(); readSessions.clear(); writePreparedSessions.clear(); for (final PooledSession session : ImmutableList.copyOf(allSessions)) { if (session.leakedException != null) { logger.log(Level.WARNING, "Leaked session", session.leakedException); } if (session.state != SessionState.CLOSING) { closeSessionAsync(session); } } } retFuture.addListener( new Runnable() { @Override public void run() { executorFactory.release(executor); } }, MoreExecutors.directExecutor()); return retFuture; } private boolean shouldUnblockReader() { // This might not be the best strategy since a continuous burst of read requests can starve // a write request. Maybe maintain a timestamp in the queue and unblock according to that // or just flip a weighted coin. synchronized (lock) { int numWriteWaiters = readWriteWaiters.size() - numSessionsBeingPrepared; return readWaiters.size() > numWriteWaiters; } } private boolean shouldPrepareSession() { synchronized (lock) { int preparedSessions = writePreparedSessions.size() + numSessionsBeingPrepared; return preparedSessions < Math.floor(options.getWriteSessionsFraction() * totalSessions()); } } private int numWaiters() { synchronized (lock) { return readWaiters.size() + readWriteWaiters.size(); } } @VisibleForTesting int totalSessions() { synchronized (lock) { return allSessions.size(); } } private void closeSessionAsync(final PooledSession sess) { executor.submit( new Runnable() { @Override public void run() { closeSession(sess); } }); } private void closeSession(PooledSession sess) { try { sess.delegate.close(); } catch (SpannerException e) { // Backend will delete these sessions after a while even if we fail to close them. if (logger.isLoggable(Level.FINE)) { logger.log(Level.FINE, "Failed to close session: " + sess.getName(), e); } } finally { synchronized (lock) { allSessions.remove(sess); if (isClosed()) { decrementPendingClosures(1); return; } // Create a new session if needed to unblock some waiter. if (numWaiters() > numSessionsBeingCreated) { createSessions(getAllowedCreateSessions(numWaiters() - numSessionsBeingCreated)); } } } } private void prepareSession(final PooledSession sess) { synchronized (lock) { numSessionsBeingPrepared++; } executor.submit( new Runnable() { @Override public void run() { try { logger.log(Level.FINE, "Preparing session"); sess.prepareReadWriteTransaction(); logger.log(Level.FINE, "Session prepared"); synchronized (lock) { numSessionsBeingPrepared--; if (!isClosed()) { if (readWriteWaiters.size() > 0) { readWriteWaiters.poll().put(sess); } else if (readWaiters.size() > 0) { readWaiters.poll().put(sess); } else { writePreparedSessions.add(sess); } } } } catch (Throwable t) { synchronized (lock) { numSessionsBeingPrepared--; if (!isClosed()) { handlePrepareSessionFailure(newSpannerException(t), sess); } } } } }); } /** * Returns the minimum of the wanted number of sessions that the caller wants to create and the * actual max number that may be created at this moment. */ private int getAllowedCreateSessions(int wantedSessions) { synchronized (lock) { return Math.min( wantedSessions, options.getMaxSessions() - (totalSessions() + numSessionsBeingCreated)); } } private boolean canCreateSession() { synchronized (lock) { return totalSessions() + numSessionsBeingCreated < options.getMaxSessions(); } } private void createSessions(final int sessionCount) { logger.log(Level.FINE, String.format("Creating %d sessions", sessionCount)); synchronized (lock) { numSessionsBeingCreated += sessionCount; try { // Create a batch of sessions. The actual session creation can be split into multiple gRPC // calls and the session consumer consumes the returned sessions as they become available. // The batchCreateSessions method automatically spreads the sessions evenly over all // available channels. spanner.asyncBatchCreateSessions(db, sessionCount, sessionConsumer); logger.log(Level.FINE, "Sessions created"); } catch (Throwable t) { // Expose this to customer via a metric. numSessionsBeingCreated -= sessionCount; if (isClosed()) { decrementPendingClosures(sessionCount); } handleCreateSessionsFailure(newSpannerException(t), sessionCount); } } } /** * {@link SessionConsumer} that receives the created sessions from a {@link SessionClient} and * releases these into the pool. The session pool only needs one instance of this, as all sessions * should be returned to the same pool regardless of what triggered the creation of the sessions. */ class SessionConsumerImpl implements SessionConsumer { /** Release a new session to the pool. */ @Override public void onSessionReady(SessionImpl session) { PooledSession pooledSession = null; boolean closeSession = false; synchronized (lock) { pooledSession = new PooledSession(session); numSessionsBeingCreated--; if (closureFuture != null) { closeSession = true; } else { Preconditions.checkState(totalSessions() <= options.getMaxSessions() - 1); allSessions.add(pooledSession); // Release the session to a random position in the pool to prevent the case that a batch // of sessions that are affiliated with the same channel are all placed sequentially in // the pool. releaseSession(pooledSession, Position.RANDOM); } } if (closeSession) { closeSessionAsync(pooledSession); } } /** * Informs waiters for a session that session creation failed. The exception will propagate to * the waiters as a {@link SpannerException}. */ @Override public void onSessionCreateFailure(Throwable t, int createFailureForSessionCount) { synchronized (lock) { numSessionsBeingCreated -= createFailureForSessionCount; if (isClosed()) { decrementPendingClosures(createFailureForSessionCount); } handleCreateSessionsFailure(newSpannerException(t), createFailureForSessionCount); } } } }
Spanner: Close ResultSet from session keep-alive request (#6331) Fixes #6330 Closing the ResultSet also closes the span associated with the keep-alive request, which fixes a tracing issue.
google-cloud-spanner/src/main/java/com/google/cloud/spanner/SessionPool.java
Spanner: Close ResultSet from session keep-alive request (#6331)
<ide><path>oogle-cloud-spanner/src/main/java/com/google/cloud/spanner/SessionPool.java <ide> <ide> private void keepAlive() { <ide> markUsed(); <del> delegate <del> .singleUse(TimestampBound.ofMaxStaleness(60, TimeUnit.SECONDS)) <del> .executeQuery(Statement.newBuilder("SELECT 1").build()) <del> .next(); <add> try (ResultSet resultSet = <add> delegate <add> .singleUse(TimestampBound.ofMaxStaleness(60, TimeUnit.SECONDS)) <add> .executeQuery(Statement.newBuilder("SELECT 1").build())) { <add> resultSet.next(); <add> } <ide> } <ide> <ide> private void markUsed() {
Java
mit
21bf8b4b9327a11f7a825279ce19282167162447
0
iontorrent/Torrent-Variant-Caller-stable,iontorrent/Torrent-Variant-Caller-stable,iontorrent/Torrent-Variant-Caller-stable,iontorrent/Torrent-Variant-Caller-stable,iontorrent/Torrent-Variant-Caller-stable,iontorrent/Torrent-Variant-Caller-stable,iontorrent/Torrent-Variant-Caller-stable,iontorrent/Torrent-Variant-Caller-stable
package org.broadinstitute.sting.oneoffprojects.walkers.coverage; import net.sf.samtools.SAMReadGroupRecord; import org.broadinstitute.sting.gatk.contexts.AlignmentContext; import org.broadinstitute.sting.gatk.contexts.ReferenceContext; import org.broadinstitute.sting.gatk.contexts.StratifiedAlignmentContext; import org.broadinstitute.sting.gatk.refdata.RefMetaDataTracker; import org.broadinstitute.sting.gatk.refdata.ReferenceOrderedData; import org.broadinstitute.sting.gatk.refdata.ReferenceOrderedDatum; import org.broadinstitute.sting.gatk.refdata.rodRefSeq; import org.broadinstitute.sting.gatk.refdata.utils.LocationAwareSeekableRODIterator; import org.broadinstitute.sting.gatk.refdata.utils.RODRecordList; import org.broadinstitute.sting.gatk.walkers.By; import org.broadinstitute.sting.gatk.walkers.DataSource; import org.broadinstitute.sting.gatk.walkers.LocusWalker; import org.broadinstitute.sting.gatk.walkers.TreeReducible; import org.broadinstitute.sting.gatk.walkers.coverage.DepthOfCoverageWalker; import org.broadinstitute.sting.utils.BaseUtils; import org.broadinstitute.sting.utils.GenomeLoc; import org.broadinstitute.sting.utils.Pair; import org.broadinstitute.sting.utils.StingException; import org.broadinstitute.sting.utils.cmdLine.Argument; import org.broadinstitute.sting.utils.pileup.PileupElement; import java.io.File; import java.io.IOException; import java.io.PrintStream; import java.util.*; /** * A parallelizable walker designed to quickly aggregate relevant coverage statistics across samples in the input * file. Assesses the mean and median granular coverages of each sample, and generates part of a cumulative * distribution of % bases and % targets covered for certain depths. The granularity of DOC can be set by command * line arguments. * * * @Author chartl * @Date Feb 22, 2010 */ // todo [DONE] -- add per target (e.g. regional) aggregation // todo [DONE] -- add ability to print out the calculated bins and quit (for pre-analysis bin size selection) // todo [DONE] -- refactor the location of the ALL_SAMPLE metrics [keep out of the per-sample HashMaps] // todo [DONE] -- per locus output through -o // todo [DONE] -- support for using read groups instead of samples // todo [DONE] -- coverage including deletions // todo [DONE] -- base counts // todo -- cache the map from sample names to means in the print functions, rather than regenerating each time // todo -- support for granular histograms for total depth; maybe n*[start,stop], bins*sqrt(n) // todo -- alter logarithmic scaling to spread out bins more // todo -- allow for user to set linear binning (default is logarithmic) // todo -- formatting --> do something special for end bins in getQuantile(int[] foo), this gets mushed into the end+-1 bins for now @By(DataSource.REFERENCE) public class CoverageStatistics extends LocusWalker<Map<String,int[]>, CoverageAggregator> implements TreeReducible<CoverageAggregator> { @Argument(fullName = "start", doc = "Starting (left endpoint) for granular binning", required = false) int start = 1; @Argument(fullName = "stop", doc = "Ending (right endpoint) for granular binning", required = false) int stop = 500; @Argument(fullName = "nBins", doc = "Number of bins to use for granular binning", required = false) int nBins = 499; @Argument(fullName = "minMappingQuality", shortName = "mmq", doc = "Minimum mapping quality of reads to count towards depth. Defaults to 50.", required = false) byte minMappingQuality = 50; @Argument(fullName = "minBaseQuality", shortName = "mbq", doc = "Minimum quality of bases to count towards depth. Defaults to 20.", required = false) byte minBaseQuality = 20; @Argument(fullName = "printBaseCounts", shortName = "baseCounts", doc = "Will add base counts to per-locus output.", required = false) boolean printBaseCounts = false; @Argument(fullName = "omitLocusTable", shortName = "omitLocusTable", doc = "Will not calculate the per-sample per-depth counts of loci, which should result in speedup", required = false) boolean omitLocusTable = false; @Argument(fullName = "omitIntervalStatistics", shortName = "omitIntervals", doc = "Will omit the per-interval statistics section, which should result in speedup", required = false) boolean omitIntervals = false; @Argument(fullName = "omitDepthOutputAtEachBase", shortName = "omitBaseOutput", doc = "Will omit the output of the depth of coverage at each base, which should result in speedup", required = false) boolean omitDepthOutput = false; @Argument(fullName = "printBinEndpointsAndExit", doc = "Prints the bin values and exits immediately. Use to calibrate what bins you want before running on data.", required = false) boolean printBinEndpointsAndExit = false; @Argument(fullName = "omitPerSampleStats", shortName = "omitSampleSummary", doc = "Omits the summary files per-sample. These statistics are still calculated, so this argument will not improve runtime.", required = false) boolean omitSampleSummary = false; @Argument(fullName = "useReadGroups", shortName = "rg", doc = "Split depth of coverage output by read group rather than by sample", required = false) boolean useReadGroup = false; @Argument(fullName = "useBothSampleAndReadGroup", shortName = "both", doc = "Split output by both read group and by sample", required = false) boolean useBoth = false; @Argument(fullName = "includeDeletions", shortName = "dels", doc = "Include information on deletions", required = false) boolean includeDeletions = false; @Argument(fullName = "ignoreDeletionSites", doc = "Ignore sites consisting only of deletions", required = false) boolean ignoreDeletionSites = false; @Argument(fullName = "calculateCoverageOverGenes", shortName = "geneList", doc = "Calculate the coverage statistics over this list of genes. Currently accepts RefSeq.", required = false) File refSeqGeneList = null; //////////////////////////////////////////////////////////////////////////////////// // STANDARD WALKER METHODS //////////////////////////////////////////////////////////////////////////////////// public boolean includeReadsWithDeletionAtLoci() { return includeDeletions && ! ignoreDeletionSites; } public void initialize() { if ( printBinEndpointsAndExit ) { int[] endpoints = DepthOfCoverageStats.calculateBinEndpoints(start,stop,nBins); System.out.print("[ "); for ( int e : endpoints ) { System.out.print(e+" "); } System.out.println("]"); System.exit(0); } if ( getToolkit().getArguments().outFileName == null ) { throw new StingException("This walker requires that you specify an output file (-o)"); } if ( ! omitDepthOutput ) { // print header out.printf("%s\t%s\t%s","Locus","Total_Depth","Average_Depth"); // get all the samples HashSet<String> allSamples = getSamplesFromToolKit(useReadGroup); if ( useBoth ) { allSamples.addAll(getSamplesFromToolKit(!useReadGroup)); } for ( String s : allSamples) { out.printf("\t%s_%s","Depth_for",s); if ( printBaseCounts ) { out.printf("\t%s_%s",s,"base_counts"); } } out.printf("%n"); } else { out.printf("Per-Locus Depth of Coverage output was omitted"); } } private HashSet<String> getSamplesFromToolKit( boolean getReadGroupsInstead ) { HashSet<String> partitions = new HashSet<String>(); // since the DOCS object uses a HashMap, this will be in the same order if ( getReadGroupsInstead ) { for ( SAMReadGroupRecord rg : getToolkit().getSAMFileHeader().getReadGroups() ) { partitions.add(rg.getSample()+"_rg_"+rg.getReadGroupId()); } } else { for ( Set<String> sampleSet : getToolkit().getSamplesByReaders()) { for (String s : sampleSet) { partitions.add(s); } } } return partitions; } public boolean isReduceByInterval() { return ( ! omitIntervals ); } public CoverageAggregator reduceInit() { CoverageAggregator.AggregationType agType = useBoth ? CoverageAggregator.AggregationType.BOTH : ( useReadGroup ? CoverageAggregator.AggregationType.READ : CoverageAggregator.AggregationType.SAMPLE ) ; CoverageAggregator aggro = new CoverageAggregator(agType,start,stop,nBins); if ( ! useReadGroup || useBoth ) { aggro.addSamples(getSamplesFromToolKit(false)); } if ( useReadGroup || useBoth ) { aggro.addReadGroups(getSamplesFromToolKit(true)); } aggro.initialize(includeDeletions,omitLocusTable); return aggro; } public Map<String,int[]> map(RefMetaDataTracker tracker, ReferenceContext ref, AlignmentContext context) { if ( ! omitDepthOutput ) { out.printf("%s",ref.getLocus()); // yes: print locus in map, and the rest of the info in reduce (for eventual cumulatives) //System.out.printf("\t[log]\t%s",ref.getLocus()); } Map<String,int[]> countsBySample = CoverageUtils.getBaseCountsBySample(context,minMappingQuality,minBaseQuality, useReadGroup ? CoverageUtils.PartitionType.BY_READ_GROUP : CoverageUtils.PartitionType.BY_SAMPLE); if ( useBoth ) { Map<String,int[]> countsByOther = CoverageUtils.getBaseCountsBySample(context,minMappingQuality,minBaseQuality, !useReadGroup ? CoverageUtils.PartitionType.BY_READ_GROUP : CoverageUtils.PartitionType.BY_SAMPLE); for ( String s : countsByOther.keySet()) { countsBySample.put(s,countsByOther.get(s)); } } return countsBySample; } public CoverageAggregator reduce(Map<String,int[]> thisMap, CoverageAggregator prevReduce) { if ( ! omitDepthOutput ) { printDepths(out,thisMap, prevReduce.getAllSamples()); // this is an additional iteration through thisMap, plus dealing with IO, so should be much slower without // turning on omit } prevReduce.update(thisMap); // note that in "useBoth" cases, this method alters the thisMap object return prevReduce; } public CoverageAggregator treeReduce(CoverageAggregator left, CoverageAggregator right) { left.merge(right); return left; } //////////////////////////////////////////////////////////////////////////////////// // INTERVAL ON TRAVERSAL DONE //////////////////////////////////////////////////////////////////////////////////// public void onTraversalDone( List<Pair<GenomeLoc,CoverageAggregator>> statsByInterval ) { if ( refSeqGeneList != null && ( useBoth || ! useReadGroup ) ) { printGeneStats(statsByInterval); } if ( useBoth || ! useReadGroup ) { File intervalStatisticsFile = deriveFromStream("sample_interval_statistics"); File intervalSummaryFile = deriveFromStream("sample_interval_summary"); printIntervalStats(statsByInterval,intervalSummaryFile, intervalStatisticsFile, true); } if ( useBoth || useReadGroup ) { File intervalStatisticsFile = deriveFromStream("read_group_interval_statistics"); File intervalSummaryFile = deriveFromStream("read_group_interval_summary"); printIntervalStats(statsByInterval,intervalSummaryFile, intervalStatisticsFile, false); } onTraversalDone(mergeAll(statsByInterval)); } public CoverageAggregator mergeAll(List<Pair<GenomeLoc,CoverageAggregator>> stats) { CoverageAggregator first = stats.remove(0).second; for ( Pair<GenomeLoc,CoverageAggregator> iStat : stats ) { treeReduce(first,iStat.second); } return first; } private DepthOfCoverageStats printIntervalStats(List<Pair<GenomeLoc,CoverageAggregator>> statsByInterval, File summaryFile, File statsFile, boolean isSample) { PrintStream summaryOut; PrintStream statsOut; try { summaryOut = summaryFile == null ? out : new PrintStream(summaryFile); statsOut = statsFile == null ? out : new PrintStream(statsFile); } catch ( IOException e ) { throw new StingException("Unable to open interval file on reduce", e); } Pair<GenomeLoc,CoverageAggregator> firstPair = statsByInterval.get(0); CoverageAggregator firstAggregator = firstPair.second; DepthOfCoverageStats firstStats = isSample ? firstAggregator.getCoverageBySample() : firstAggregator.getCoverageByReadGroup(); StringBuilder summaryHeader = new StringBuilder(); summaryHeader.append("Target"); summaryHeader.append("\ttotal_coverage"); summaryHeader.append("\taverage_coverage"); for ( String s : firstStats.getAllSamples() ) { summaryHeader.append("\t"); summaryHeader.append(s); summaryHeader.append("_total_cvg"); summaryHeader.append("\t"); summaryHeader.append(s); summaryHeader.append("_mean_cvg"); summaryHeader.append("\t"); summaryHeader.append(s); summaryHeader.append("_granular_Q1"); summaryHeader.append("\t"); summaryHeader.append(s); summaryHeader.append("_granular_median"); summaryHeader.append("\t"); summaryHeader.append(s); summaryHeader.append("_granular_Q3"); } summaryOut.printf("%s%n",summaryHeader); int[][] nTargetsByAvgCvgBySample = new int[firstStats.getHistograms().size()][firstStats.getEndpoints().length+1]; for ( Pair<GenomeLoc,CoverageAggregator> targetAggregator : statsByInterval ) { Pair<GenomeLoc,DepthOfCoverageStats> targetStats = new Pair<GenomeLoc,DepthOfCoverageStats>( targetAggregator.first, isSample ? targetAggregator.second.getCoverageBySample() : targetAggregator.second.getCoverageByReadGroup()); printTargetSummary(summaryOut,targetStats); updateTargetTable(nTargetsByAvgCvgBySample,targetStats.second); } printIntervalTable(statsOut,nTargetsByAvgCvgBySample,firstStats.getEndpoints()); if ( ! getToolkit().getArguments().outFileName.contains("stdout")) { summaryOut.close(); statsOut.close(); } return firstStats; } private void printGeneStats(List<Pair<GenomeLoc,CoverageAggregator>> statsByTarget) { LocationAwareSeekableRODIterator refseqIterator = initializeRefSeq(); List<Pair<String,DepthOfCoverageStats>> statsByGene = new ArrayList<Pair<String,DepthOfCoverageStats>>();// maintains order Map<String,DepthOfCoverageStats> geneNamesToStats = new HashMap<String,DepthOfCoverageStats>(); // alows indirect updating of objects in list for ( Pair<GenomeLoc,CoverageAggregator> targetStats : statsByTarget ) { String gene = getGeneName(targetStats.first,refseqIterator); if ( geneNamesToStats.keySet().contains(gene) ) { geneNamesToStats.get(gene).merge(targetStats.second.getCoverageBySample()); } else { geneNamesToStats.put(gene,targetStats.second.getCoverageBySample()); statsByGene.add(new Pair<String,DepthOfCoverageStats>(gene,targetStats.second.getCoverageBySample())); } } PrintStream geneSummaryOut = getCorrectStream(out,deriveFromStream("gene_summary")); for ( Pair<String,DepthOfCoverageStats> geneStats : statsByGene ) { printTargetSummary(geneSummaryOut,geneStats); } if ( ! getToolkit().getArguments().outFileName.contains("stdout")) { geneSummaryOut.close(); } } //blatantly stolen from Andrew Kernytsky private String getGeneName(GenomeLoc target, LocationAwareSeekableRODIterator refseqIterator) { if (refseqIterator == null) { return "UNKNOWN"; } RODRecordList annotationList = refseqIterator.seekForward(target); if (annotationList == null) { return "UNKNOWN"; } for(ReferenceOrderedDatum rec : annotationList) { if ( ((rodRefSeq)rec).overlapsExonP(target) ) { return ((rodRefSeq)rec).getGeneName(); } } return "UNKNOWN"; } private LocationAwareSeekableRODIterator initializeRefSeq() { ReferenceOrderedData<rodRefSeq> refseq = new ReferenceOrderedData<rodRefSeq>("refseq", refSeqGeneList, rodRefSeq.class); return refseq.iterator(); } private void printTargetSummary(PrintStream output, Pair<?,DepthOfCoverageStats> intervalStats) { DepthOfCoverageStats stats = intervalStats.second; int[] bins = stats.getEndpoints(); StringBuilder targetSummary = new StringBuilder(); targetSummary.append(intervalStats.first.toString()); targetSummary.append("\t"); targetSummary.append(stats.getTotalCoverage()); targetSummary.append("\t"); targetSummary.append(String.format("%.2f",stats.getTotalMeanCoverage())); for ( String s : stats.getAllSamples() ) { targetSummary.append("\t"); targetSummary.append(stats.getTotals().get(s)); targetSummary.append("\t"); targetSummary.append(String.format("%.2f", stats.getMeans().get(s))); targetSummary.append("\t"); int median = getQuantile(stats.getHistograms().get(s),0.5); int q1 = getQuantile(stats.getHistograms().get(s),0.25); int q3 = getQuantile(stats.getHistograms().get(s),0.75); targetSummary.append(formatBin(bins,q1)); targetSummary.append("\t"); targetSummary.append(formatBin(bins,median)); targetSummary.append("\t"); targetSummary.append(formatBin(bins,q3)); } output.printf("%s%n", targetSummary); } private String formatBin(int[] bins, int quartile) { if ( quartile >= bins.length ) { return String.format(">%d",bins[bins.length-1]); } else if ( quartile < 0 ) { return String.format("<%d",bins[0]); } else { return String.format("%d",bins[quartile]); } } private void printIntervalTable(PrintStream output, int[][] intervalTable, int[] cutoffs) { output.printf("\tdepth>=%d",0); for ( int col = 0; col < intervalTable[0].length-1; col ++ ) { output.printf("\tdepth>=%d",cutoffs[col]); } output.printf(String.format("%n")); for ( int row = 0; row < intervalTable.length; row ++ ) { output.printf("At_least_%d_samples",row+1); for ( int col = 0; col < intervalTable[0].length; col++ ) { output.printf("\t%d",intervalTable[row][col]); } output.printf(String.format("%n")); } } /* * @updateTargetTable * The idea is to have counts for how many *targets* have at least K samples with * median coverage of at least X. * To that end: * Iterate over the samples the DOCS object, determine how many there are with * median coverage > leftEnds[0]; how many with median coverage > leftEnds[1] * and so on. Then this target has at least N, N-1, N-2, ... 1, 0 samples covered * to leftEnds[0] and at least M,M-1,M-2,...1,0 samples covered to leftEnds[1] * and so on. */ private void updateTargetTable(int[][] table, DepthOfCoverageStats stats) { int[] cutoffs = stats.getEndpoints(); int[] countsOfMediansAboveCutoffs = new int[cutoffs.length+1]; // 0 bin to catch everything for ( int i = 0; i < countsOfMediansAboveCutoffs.length; i ++) { countsOfMediansAboveCutoffs[i]=0; } for ( String s : stats.getAllSamples() ) { int medianBin = getQuantile(stats.getHistograms().get(s),0.5); for ( int i = 0; i <= medianBin; i ++) { countsOfMediansAboveCutoffs[i]++; } } for ( int medianBin = 0; medianBin < countsOfMediansAboveCutoffs.length; medianBin++) { for ( ; countsOfMediansAboveCutoffs[medianBin] > 0; countsOfMediansAboveCutoffs[medianBin]-- ) { table[countsOfMediansAboveCutoffs[medianBin]-1][medianBin]++; // the -1 is due to counts being 1-based and offsets being 0-based } } } //////////////////////////////////////////////////////////////////////////////////// // FINAL ON TRAVERSAL DONE //////////////////////////////////////////////////////////////////////////////////// public void onTraversalDone(CoverageAggregator coverageProfiles) { /////////////////// // OPTIONAL OUTPUTS ////////////////// if ( ! omitSampleSummary ) { logger.info("Printing summary info"); if ( ! useReadGroup || useBoth ) { File summaryStatisticsFile = deriveFromStream("sample_summary_statistics"); File perSampleStatisticsFile = deriveFromStream("sample_statistics"); printSummary(out,summaryStatisticsFile,coverageProfiles.getCoverageBySample()); printPerSample(out,perSampleStatisticsFile,coverageProfiles.getCoverageBySample()); } if ( useReadGroup || useBoth ) { File rgStatsFile = deriveFromStream("read_group_summary"); File rgSumFile = deriveFromStream("read_group_statistics"); printSummary(out,rgStatsFile,coverageProfiles.getCoverageByReadGroup()); printPerSample(out,rgSumFile,coverageProfiles.getCoverageByReadGroup()); } } if ( ! omitLocusTable ) { logger.info("Printing locus summary"); if ( ! useReadGroup || useBoth ) { File perLocusStatisticsFile = deriveFromStream("sample_locus_statistics"); printPerLocus(perLocusStatisticsFile,coverageProfiles.getCoverageBySample()); } if ( useReadGroup || useBoth ) { File perLocusRGStats = deriveFromStream("read_group_locus_statistics"); printPerLocus(perLocusRGStats,coverageProfiles.getCoverageByReadGroup()); } } } public File deriveFromStream(String append) { String name = getToolkit().getArguments().outFileName; if ( name.contains("stdout") || name.contains("Stdout") || name.contains("STDOUT")) { return null; } else { return new File(name+"."+append); } } //////////////////////////////////////////////////////////////////////////////////// // HELPER OUTPUT METHODS //////////////////////////////////////////////////////////////////////////////////// private void printPerSample(PrintStream out, File optionalFile, DepthOfCoverageStats stats) { PrintStream output = getCorrectStream(out,optionalFile); int[] leftEnds = stats.getEndpoints(); StringBuilder hBuilder = new StringBuilder(); hBuilder.append("\t"); hBuilder.append(String.format("[0,%d)\t",leftEnds[0])); for ( int i = 1; i < leftEnds.length; i++ ) hBuilder.append(String.format("[%d,%d)\t",leftEnds[i-1],leftEnds[i])); hBuilder.append(String.format("[%d,inf)%n",leftEnds[leftEnds.length-1])); output.print(hBuilder.toString()); Map<String,int[]> histograms = stats.getHistograms(); for ( String s : histograms.keySet() ) { StringBuilder sBuilder = new StringBuilder(); sBuilder.append(String.format("%s",s)); for ( int count : histograms.get(s) ) { sBuilder.append(String.format("\t%d",count)); } sBuilder.append(String.format("%n")); output.print(sBuilder.toString()); } } private void printPerLocus(File locusFile, DepthOfCoverageStats stats) { PrintStream output = getCorrectStream(out,locusFile); if ( output == null ) { return; } int[] endpoints = stats.getEndpoints(); int samples = stats.getHistograms().size(); int[][] baseCoverageCumDist = stats.getLocusCounts(); // rows - # of samples // columns - depth of coverage StringBuilder header = new StringBuilder(); header.append(String.format("\t>=0")); for ( int d : endpoints ) { header.append(String.format("\t>=%d",d)); } header.append(String.format("%n")); output.print(header); for ( int row = 0; row < samples; row ++ ) { output.printf("%s_%d\t","NSamples",row+1); for ( int depthBin = 0; depthBin < baseCoverageCumDist[0].length; depthBin ++ ) { output.printf("%d\t",baseCoverageCumDist[row][depthBin]); } output.printf("%n"); } } private PrintStream getCorrectStream(PrintStream out, File optionalFile) { PrintStream output; if ( optionalFile == null ) { output = out; } else { try { output = new PrintStream(optionalFile); } catch ( IOException e ) { logger.warn("Error opening the output file "+optionalFile.getAbsolutePath()+". Defaulting to stdout"); output = out; } } return output; } private void printSummary(PrintStream out, File optionalFile, DepthOfCoverageStats stats) { PrintStream output = getCorrectStream(out,optionalFile); output.printf("%s\t%s\t%s\t%s\t%s\t%s%n","sample_id","total","mean","granular_third_quartile","granular_median","granular_first_quartile"); Map<String,int[]> histograms = stats.getHistograms(); Map<String,Double> means = stats.getMeans(); Map<String,Long> totals = stats.getTotals(); int[] leftEnds = stats.getEndpoints(); for ( String s : histograms.keySet() ) { int[] histogram = histograms.get(s); int median = getQuantile(histogram,0.5); int q1 = getQuantile(histogram,0.25); int q3 = getQuantile(histogram,0.75); // if any of these are larger than the higest bin, put the median as in the largest bin median = median == histogram.length-1 ? histogram.length-2 : median; q1 = q1 == histogram.length-1 ? histogram.length-2 : q1; q3 = q3 == histogram.length-1 ? histogram.length-2 : q3; output.printf("%s\t%d\t%.2f\t%d\t%d\t%d%n",s,totals.get(s),means.get(s),leftEnds[q3],leftEnds[median],leftEnds[q1]); } output.printf("%s\t%d\t%.2f\t%s\t%s\t%s%n","Total",stats.getTotalCoverage(),stats.getTotalMeanCoverage(),"N/A","N/A","N/A"); } private int getQuantile(int[] histogram, double prop) { int total = 0; for ( int i = 0; i < histogram.length; i ++ ) { total += histogram[i]; } int counts = 0; int bin = -1; while ( counts < prop*total ) { counts += histogram[bin+1]; bin++; } return bin; } private void printDepths(PrintStream stream, Map<String,int[]> countsBySample, Set<String> allSamples) { // get the depths per sample and build up the output string while tabulating total and average coverage // todo -- update me to deal with base counts/indels StringBuilder perSampleOutput = new StringBuilder(); int tDepth = 0; for ( String s : allSamples ) { perSampleOutput.append("\t"); long dp = countsBySample.keySet().contains(s) ? sumArray(countsBySample.get(s)) : 0; perSampleOutput.append(dp); if ( printBaseCounts ) { perSampleOutput.append("\t"); perSampleOutput.append(baseCounts(countsBySample.get(s))); } tDepth += dp; } // remember -- genome locus was printed in map() stream.printf("\t%d\t%.2f\t%s%n",tDepth,( (double) tDepth/ (double) allSamples.size()), perSampleOutput); //System.out.printf("\t%d\t%.2f\t%s%n",tDepth,( (double) tDepth/ (double) allSamples.size()), perSampleOutput); } private long sumArray(int[] array) { long i = 0; for ( int j : array ) { i += j; } return i; } private String baseCounts(int[] counts) { if ( counts == null ) { counts = new int[6]; } StringBuilder s = new StringBuilder(); int nbases = 0; for ( char b : BaseUtils.EXTENDED_BASES ) { nbases++; if ( includeDeletions || b != 'D' ) { s.append(b); s.append(":"); s.append(counts[BaseUtils.extendedBaseToBaseIndex(b)]); if ( nbases < 6 ) { s.append(" "); } } } return s.toString(); } } class CoverageAggregator { private DepthOfCoverageStats coverageByRead; private DepthOfCoverageStats coverageBySample; enum AggregationType { READ, SAMPLE, BOTH } private AggregationType agType; private Set<String> sampleNames; private Set<String> allSamples; public CoverageAggregator(AggregationType type, int start, int stop, int nBins) { if ( type == AggregationType.READ || type == AggregationType.BOTH) { coverageByRead = new DepthOfCoverageStats(DepthOfCoverageStats.calculateBinEndpoints(start,stop,nBins)); } if ( type == AggregationType.SAMPLE || type == AggregationType.BOTH) { coverageBySample = new DepthOfCoverageStats(DepthOfCoverageStats.calculateBinEndpoints(start,stop,nBins)); } agType = type; allSamples = new HashSet<String>(); } public void merge(CoverageAggregator otherAggregator) { if ( agType == AggregationType.SAMPLE || agType == AggregationType.BOTH ) { this.coverageBySample.merge(otherAggregator.coverageBySample); } if ( agType == AggregationType.READ || agType == AggregationType.BOTH) { this.coverageByRead.merge(otherAggregator.coverageByRead); } } public DepthOfCoverageStats getCoverageByReadGroup() { return coverageByRead; } public DepthOfCoverageStats getCoverageBySample() { return coverageBySample; } public void addSamples(Set<String> samples) { for ( String s : samples ) { coverageBySample.addSample(s); allSamples.add(s); } if ( agType == AggregationType.BOTH ) { sampleNames = samples; } } public void addReadGroups(Set<String> readGroupNames) { for ( String s : readGroupNames ) { coverageByRead.addSample(s); allSamples.add(s); } } public void initialize(boolean useDels, boolean omitLocusTable) { if ( agType == AggregationType.SAMPLE || agType == AggregationType.BOTH ) { if ( useDels ) { coverageBySample.initializeDeletions(); } if ( ! omitLocusTable ) { coverageBySample.initializeLocusCounts(); } } if ( agType == AggregationType.READ || agType == AggregationType.BOTH) { if ( useDels ) { coverageByRead.initializeDeletions(); } if ( ! omitLocusTable ) { coverageByRead.initializeLocusCounts(); } } } public void update(Map<String,int[]> countsByIdentifier) { if ( agType != AggregationType.BOTH ) { if ( agType == AggregationType.SAMPLE ) { coverageBySample.update(countsByIdentifier); } else { coverageByRead.update(countsByIdentifier); } } else { // have to separate samples and read groups HashMap<String,int[]> countsBySample = new HashMap<String,int[]>(sampleNames.size()); HashMap<String,int[]> countsByRG = new HashMap<String,int[]>(allSamples.size()-sampleNames.size()); for ( String s : countsByIdentifier.keySet() ) { if ( sampleNames.contains(s) ) { countsBySample.put(s,countsByIdentifier.get(s)); } else { // cannot use .remove() to save time due to concurrency issues countsByRG.put(s,countsByIdentifier.get(s)); } } coverageBySample.update(countsBySample); coverageByRead.update(countsByRG); } } public Set<String> getAllSamples() { return allSamples; } }
java/src/org/broadinstitute/sting/oneoffprojects/walkers/coverage/CoverageStatistics.java
package org.broadinstitute.sting.oneoffprojects.walkers.coverage; import net.sf.samtools.SAMReadGroupRecord; import org.broadinstitute.sting.gatk.contexts.AlignmentContext; import org.broadinstitute.sting.gatk.contexts.ReferenceContext; import org.broadinstitute.sting.gatk.contexts.StratifiedAlignmentContext; import org.broadinstitute.sting.gatk.refdata.RefMetaDataTracker; import org.broadinstitute.sting.gatk.refdata.ReferenceOrderedData; import org.broadinstitute.sting.gatk.refdata.ReferenceOrderedDatum; import org.broadinstitute.sting.gatk.refdata.rodRefSeq; import org.broadinstitute.sting.gatk.refdata.utils.LocationAwareSeekableRODIterator; import org.broadinstitute.sting.gatk.refdata.utils.RODRecordList; import org.broadinstitute.sting.gatk.walkers.By; import org.broadinstitute.sting.gatk.walkers.DataSource; import org.broadinstitute.sting.gatk.walkers.LocusWalker; import org.broadinstitute.sting.gatk.walkers.TreeReducible; import org.broadinstitute.sting.gatk.walkers.coverage.DepthOfCoverageWalker; import org.broadinstitute.sting.utils.BaseUtils; import org.broadinstitute.sting.utils.GenomeLoc; import org.broadinstitute.sting.utils.Pair; import org.broadinstitute.sting.utils.StingException; import org.broadinstitute.sting.utils.cmdLine.Argument; import org.broadinstitute.sting.utils.pileup.PileupElement; import java.io.File; import java.io.IOException; import java.io.PrintStream; import java.util.*; /** * A parallelizable walker designed to quickly aggregate relevant coverage statistics across samples in the input * file. Assesses the mean and median granular coverages of each sample, and generates part of a cumulative * distribution of % bases and % targets covered for certain depths. The granularity of DOC can be set by command * line arguments. * * * @Author chartl * @Date Feb 22, 2010 */ // todo [DONE] -- add per target (e.g. regional) aggregation // todo [DONE] -- add ability to print out the calculated bins and quit (for pre-analysis bin size selection) // todo [DONE] -- refactor the location of the ALL_SAMPLE metrics [keep out of the per-sample HashMaps] // todo [DONE] -- per locus output through -o // todo [DONE] -- support for using read groups instead of samples // todo [DONE] -- coverage including deletions // todo [DONE] -- base counts // todo -- cache the map from sample names to means in the print functions, rather than regenerating each time // todo -- support for granular histograms for total depth; maybe n*[start,stop], bins*sqrt(n) // todo -- alter logarithmic scaling to spread out bins more // todo -- allow for user to set linear binning (default is logarithmic) // todo -- formatting --> do something special for end bins in getQuantile(int[] foo), this gets mushed into the end+-1 bins for now @By(DataSource.REFERENCE) public class CoverageStatistics extends LocusWalker<Map<String,int[]>, CoverageAggregator> implements TreeReducible<CoverageAggregator> { @Argument(fullName = "start", doc = "Starting (left endpoint) for granular binning", required = false) int start = 1; @Argument(fullName = "stop", doc = "Ending (right endpoint) for granular binning", required = false) int stop = 500; @Argument(fullName = "nBins", doc = "Number of bins to use for granular binning", required = false) int nBins = 499; @Argument(fullName = "minMappingQuality", shortName = "mmq", doc = "Minimum mapping quality of reads to count towards depth. Defaults to 50.", required = false) byte minMappingQuality = 50; @Argument(fullName = "minBaseQuality", shortName = "mbq", doc = "Minimum quality of bases to count towards depth. Defaults to 20.", required = false) byte minBaseQuality = 20; @Argument(fullName = "printBaseCounts", shortName = "baseCounts", doc = "Will add base counts to per-locus output.", required = false) boolean printBaseCounts = false; @Argument(fullName = "omitLocusTable", shortName = "omitLocusTable", doc = "Will not calculate the per-sample per-depth counts of loci, which should result in speedup", required = false) boolean omitLocusTable = false; @Argument(fullName = "omitIntervalStatistics", shortName = "omitIntervals", doc = "Will omit the per-interval statistics section, which should result in speedup", required = false) boolean omitIntervals = false; @Argument(fullName = "omitDepthOutputAtEachBase", shortName = "omitBaseOutput", doc = "Will omit the output of the depth of coverage at each base, which should result in speedup", required = false) boolean omitDepthOutput = false; @Argument(fullName = "printBinEndpointsAndExit", doc = "Prints the bin values and exits immediately. Use to calibrate what bins you want before running on data.", required = false) boolean printBinEndpointsAndExit = false; @Argument(fullName = "omitPerSampleStats", shortName = "omitSampleSummary", doc = "Omits the summary files per-sample. These statistics are still calculated, so this argument will not improve runtime.", required = false) boolean omitSampleSummary = false; @Argument(fullName = "useReadGroups", shortName = "rg", doc = "Split depth of coverage output by read group rather than by sample", required = false) boolean useReadGroup = false; @Argument(fullName = "useBothSampleAndReadGroup", shortName = "both", doc = "Split output by both read group and by sample", required = false) boolean useBoth = false; @Argument(fullName = "includeDeletions", shortName = "dels", doc = "Include information on deletions", required = false) boolean includeDeletions = false; @Argument(fullName = "ignoreDeletionSites", doc = "Ignore sites consisting only of deletions", required = false) boolean ignoreDeletionSites = false; @Argument(fullName = "calculateCoverageOverGenes", shortName = "geneList", doc = "Calculate the coverage statistics over this list of genes. Currently accepts RefSeq.", required = false) File refSeqGeneList = null; //////////////////////////////////////////////////////////////////////////////////// // STANDARD WALKER METHODS //////////////////////////////////////////////////////////////////////////////////// public boolean includeReadsWithDeletionAtLoci() { return includeDeletions && ! ignoreDeletionSites; } public void initialize() { if ( printBinEndpointsAndExit ) { int[] endpoints = DepthOfCoverageStats.calculateBinEndpoints(start,stop,nBins); System.out.print("[ "); for ( int e : endpoints ) { System.out.print(e+" "); } System.out.println("]"); System.exit(0); } if ( getToolkit().getArguments().outFileName == null ) { throw new StingException("This walker requires that you specify an output file (-o)"); } if ( ! omitDepthOutput ) { // print header out.printf("%s\t%s\t%s","Locus","Total_Depth","Average_Depth"); // get all the samples HashSet<String> allSamples = getSamplesFromToolKit(useReadGroup); if ( useBoth ) { allSamples.addAll(getSamplesFromToolKit(!useReadGroup)); } for ( String s : allSamples) { out.printf("\t%s_%s","Depth_for",s); if ( printBaseCounts ) { out.printf("\t%s_%s",s,"base_counts"); } } out.printf("%n"); } else { out.printf("Per-Locus Depth of Coverage output was omitted"); } } private HashSet<String> getSamplesFromToolKit( boolean getReadGroupsInstead ) { HashSet<String> partitions = new HashSet<String>(); // since the DOCS object uses a HashMap, this will be in the same order if ( getReadGroupsInstead ) { for ( SAMReadGroupRecord rg : getToolkit().getSAMFileHeader().getReadGroups() ) { partitions.add(rg.getSample()+"_rg_"+rg.getReadGroupId()); } } else { for ( Set<String> sampleSet : getToolkit().getSamplesByReaders()) { for (String s : sampleSet) { partitions.add(s); } } } return partitions; } public boolean isReduceByInterval() { return ( ! omitIntervals ); } public CoverageAggregator reduceInit() { CoverageAggregator.AggregationType agType = useBoth ? CoverageAggregator.AggregationType.BOTH : ( useReadGroup ? CoverageAggregator.AggregationType.READ : CoverageAggregator.AggregationType.SAMPLE ) ; CoverageAggregator aggro = new CoverageAggregator(agType,start,stop,nBins); if ( ! useReadGroup || useBoth ) { aggro.addSamples(getSamplesFromToolKit(false)); } if ( useReadGroup || useBoth ) { aggro.addReadGroups(getSamplesFromToolKit(true)); } aggro.initialize(includeDeletions,omitLocusTable); return aggro; } public Map<String,int[]> map(RefMetaDataTracker tracker, ReferenceContext ref, AlignmentContext context) { if ( ! omitDepthOutput ) { out.printf("%s",ref.getLocus()); // yes: print locus in map, and the rest of the info in reduce (for eventual cumulatives) //System.out.printf("\t[log]\t%s",ref.getLocus()); } Map<String,int[]> countsBySample = CoverageUtils.getBaseCountsBySample(context,minMappingQuality,minBaseQuality, useReadGroup ? CoverageUtils.PartitionType.BY_READ_GROUP : CoverageUtils.PartitionType.BY_SAMPLE); if ( useBoth ) { Map<String,int[]> countsByOther = CoverageUtils.getBaseCountsBySample(context,minMappingQuality,minBaseQuality, !useReadGroup ? CoverageUtils.PartitionType.BY_READ_GROUP : CoverageUtils.PartitionType.BY_SAMPLE); for ( String s : countsByOther.keySet()) { countsBySample.put(s,countsByOther.get(s)); } } return countsBySample; } public CoverageAggregator reduce(Map<String,int[]> thisMap, CoverageAggregator prevReduce) { if ( ! omitDepthOutput ) { printDepths(out,thisMap, prevReduce.getAllSamples()); // this is an additional iteration through thisMap, plus dealing with IO, so should be much slower without // turning on omit } prevReduce.update(thisMap); // note that in "useBoth" cases, this method alters the thisMap object return prevReduce; } public CoverageAggregator treeReduce(CoverageAggregator left, CoverageAggregator right) { left.merge(right); return left; } //////////////////////////////////////////////////////////////////////////////////// // INTERVAL ON TRAVERSAL DONE //////////////////////////////////////////////////////////////////////////////////// public void onTraversalDone( List<Pair<GenomeLoc,CoverageAggregator>> statsByInterval ) { if ( refSeqGeneList != null && ( useBoth || ! useReadGroup ) ) { printGeneStats(statsByInterval); } if ( useBoth || ! useReadGroup ) { File intervalStatisticsFile = deriveFromStream("sample_interval_statistics"); File intervalSummaryFile = deriveFromStream("sample_interval_summary"); printIntervalStats(statsByInterval,intervalSummaryFile, intervalStatisticsFile, true); } if ( useBoth || useReadGroup ) { File intervalStatisticsFile = deriveFromStream("read_group_interval_statistics"); File intervalSummaryFile = deriveFromStream("read_group_interval_summary"); printIntervalStats(statsByInterval,intervalSummaryFile, intervalStatisticsFile, false); } onTraversalDone(mergeAll(statsByInterval)); } public CoverageAggregator mergeAll(List<Pair<GenomeLoc,CoverageAggregator>> stats) { CoverageAggregator first = stats.remove(0).second; for ( Pair<GenomeLoc,CoverageAggregator> iStat : stats ) { treeReduce(first,iStat.second); } return first; } private DepthOfCoverageStats printIntervalStats(List<Pair<GenomeLoc,CoverageAggregator>> statsByInterval, File summaryFile, File statsFile, boolean isSample) { PrintStream summaryOut; PrintStream statsOut; try { summaryOut = summaryFile == null ? out : new PrintStream(summaryFile); statsOut = statsFile == null ? out : new PrintStream(statsFile); } catch ( IOException e ) { throw new StingException("Unable to open interval file on reduce", e); } Pair<GenomeLoc,CoverageAggregator> firstPair = statsByInterval.get(0); CoverageAggregator firstAggregator = firstPair.second; DepthOfCoverageStats firstStats = isSample ? firstAggregator.getCoverageBySample() : firstAggregator.getCoverageByReadGroup(); StringBuilder summaryHeader = new StringBuilder(); summaryHeader.append("Target"); summaryHeader.append("\ttotal_coverage"); summaryHeader.append("\taverage_coverage"); for ( String s : firstStats.getAllSamples() ) { summaryHeader.append("\t"); summaryHeader.append(s); summaryHeader.append("_total_cvg"); summaryHeader.append("\t"); summaryHeader.append(s); summaryHeader.append("_mean_cvg"); summaryHeader.append("\t"); summaryHeader.append(s); summaryHeader.append("_granular_Q1"); summaryHeader.append("\t"); summaryHeader.append(s); summaryHeader.append("_granular_median"); summaryHeader.append("\t"); summaryHeader.append(s); summaryHeader.append("_granular_Q3"); } summaryOut.printf("%s%n",summaryHeader); int[][] nTargetsByAvgCvgBySample = new int[firstStats.getHistograms().size()][firstStats.getEndpoints().length+1]; for ( Pair<GenomeLoc,CoverageAggregator> targetAggregator : statsByInterval ) { Pair<GenomeLoc,DepthOfCoverageStats> targetStats = new Pair<GenomeLoc,DepthOfCoverageStats>( targetAggregator.first, isSample ? targetAggregator.second.getCoverageBySample() : targetAggregator.second.getCoverageByReadGroup()); printTargetSummary(summaryOut,targetStats); updateTargetTable(nTargetsByAvgCvgBySample,targetStats.second); } printIntervalTable(statsOut,nTargetsByAvgCvgBySample,firstStats.getEndpoints()); if ( ! getToolkit().getArguments().outFileName.contains("stdout")) { summaryOut.close(); statsOut.close(); } return firstStats; } private void printGeneStats(List<Pair<GenomeLoc,CoverageAggregator>> statsByTarget) { LocationAwareSeekableRODIterator refseqIterator = initializeRefSeq(); List<Pair<String,DepthOfCoverageStats>> statsByGene = new ArrayList<Pair<String,DepthOfCoverageStats>>();// maintains order Map<String,DepthOfCoverageStats> geneNamesToStats = new HashMap<String,DepthOfCoverageStats>(); // alows indirect updating of objects in list for ( Pair<GenomeLoc,CoverageAggregator> targetStats : statsByTarget ) { String gene = getGeneName(targetStats.first,refseqIterator); if ( geneNamesToStats.keySet().contains(gene) ) { geneNamesToStats.get(gene).merge(targetStats.second.getCoverageBySample()); } else { geneNamesToStats.put(gene,targetStats.second.getCoverageBySample()); statsByGene.add(new Pair<String,DepthOfCoverageStats>(gene,targetStats.second.getCoverageBySample())); } } PrintStream geneSummaryOut = getCorrectStream(out,deriveFromStream("gene_summary")); for ( Pair<String,DepthOfCoverageStats> geneStats : statsByGene ) { printTargetSummary(geneSummaryOut,geneStats); } if ( ! getToolkit().getArguments().outFileName.contains("stdout")) { geneSummaryOut.close(); } } //blatantly stolen from Andrew Kernytsky private String getGeneName(GenomeLoc target, LocationAwareSeekableRODIterator refseqIterator) { if (refseqIterator == null) { return "UNKNOWN"; } RODRecordList annotationList = refseqIterator.seekForward(target); if (annotationList == null) { return "UNKNOWN"; } for(ReferenceOrderedDatum rec : annotationList) { if ( ((rodRefSeq)rec).overlapsExonP(target) ) { return ((rodRefSeq)rec).getGeneName(); } } return "UNKNOWN"; } private LocationAwareSeekableRODIterator initializeRefSeq() { ReferenceOrderedData<rodRefSeq> refseq = new ReferenceOrderedData<rodRefSeq>("refseq", refSeqGeneList, rodRefSeq.class); return refseq.iterator(); } private void printTargetSummary(PrintStream output, Pair<?,DepthOfCoverageStats> intervalStats) { DepthOfCoverageStats stats = intervalStats.second; int[] bins = stats.getEndpoints(); StringBuilder targetSummary = new StringBuilder(); targetSummary.append(intervalStats.first.toString()); targetSummary.append("\t"); targetSummary.append(stats.getTotalCoverage()); targetSummary.append("\t"); targetSummary.append(String.format("%.2f",stats.getTotalMeanCoverage())); for ( String s : stats.getAllSamples() ) { targetSummary.append("\t"); targetSummary.append(stats.getTotals().get(s)); targetSummary.append("\t"); targetSummary.append(String.format("%.2f", stats.getMeans().get(s))); targetSummary.append("\t"); int median = getQuantile(stats.getHistograms().get(s),0.5); int q1 = getQuantile(stats.getHistograms().get(s),0.25); int q3 = getQuantile(stats.getHistograms().get(s),0.75); targetSummary.append(formatBin(bins,q1)); targetSummary.append("\t"); targetSummary.append(formatBin(bins,median)); targetSummary.append("\t"); targetSummary.append(formatBin(bins,q3)); } output.printf("%s%n", targetSummary); } private String formatBin(int[] bins, int quartile) { if ( quartile >= bins.length ) { return String.format(">%d",bins[quartile]); } else if ( quartile < 0 ) { return String.format("<%d",bins[0]); } else { return String.format("%d",bins[quartile]); } } private void printIntervalTable(PrintStream output, int[][] intervalTable, int[] cutoffs) { output.printf("\tdepth>=%d",0); for ( int col = 0; col < intervalTable[0].length-1; col ++ ) { output.printf("\tdepth>=%d",cutoffs[col]); } output.printf(String.format("%n")); for ( int row = 0; row < intervalTable.length; row ++ ) { output.printf("At_least_%d_samples",row+1); for ( int col = 0; col < intervalTable[0].length; col++ ) { output.printf("\t%d",intervalTable[row][col]); } output.printf(String.format("%n")); } } /* * @updateTargetTable * The idea is to have counts for how many *targets* have at least K samples with * median coverage of at least X. * To that end: * Iterate over the samples the DOCS object, determine how many there are with * median coverage > leftEnds[0]; how many with median coverage > leftEnds[1] * and so on. Then this target has at least N, N-1, N-2, ... 1, 0 samples covered * to leftEnds[0] and at least M,M-1,M-2,...1,0 samples covered to leftEnds[1] * and so on. */ private void updateTargetTable(int[][] table, DepthOfCoverageStats stats) { int[] cutoffs = stats.getEndpoints(); int[] countsOfMediansAboveCutoffs = new int[cutoffs.length+1]; // 0 bin to catch everything for ( int i = 0; i < countsOfMediansAboveCutoffs.length; i ++) { countsOfMediansAboveCutoffs[i]=0; } for ( String s : stats.getAllSamples() ) { int medianBin = getQuantile(stats.getHistograms().get(s),0.5); for ( int i = 0; i <= medianBin; i ++) { countsOfMediansAboveCutoffs[i]++; } } for ( int medianBin = 0; medianBin < countsOfMediansAboveCutoffs.length; medianBin++) { for ( ; countsOfMediansAboveCutoffs[medianBin] > 0; countsOfMediansAboveCutoffs[medianBin]-- ) { table[countsOfMediansAboveCutoffs[medianBin]-1][medianBin]++; // the -1 is due to counts being 1-based and offsets being 0-based } } } //////////////////////////////////////////////////////////////////////////////////// // FINAL ON TRAVERSAL DONE //////////////////////////////////////////////////////////////////////////////////// public void onTraversalDone(CoverageAggregator coverageProfiles) { /////////////////// // OPTIONAL OUTPUTS ////////////////// if ( ! omitSampleSummary ) { logger.info("Printing summary info"); if ( ! useReadGroup || useBoth ) { File summaryStatisticsFile = deriveFromStream("sample_summary_statistics"); File perSampleStatisticsFile = deriveFromStream("sample_statistics"); printSummary(out,summaryStatisticsFile,coverageProfiles.getCoverageBySample()); printPerSample(out,perSampleStatisticsFile,coverageProfiles.getCoverageBySample()); } if ( useReadGroup || useBoth ) { File rgStatsFile = deriveFromStream("read_group_summary"); File rgSumFile = deriveFromStream("read_group_statistics"); printSummary(out,rgStatsFile,coverageProfiles.getCoverageByReadGroup()); printPerSample(out,rgSumFile,coverageProfiles.getCoverageByReadGroup()); } } if ( ! omitLocusTable ) { logger.info("Printing locus summary"); if ( ! useReadGroup || useBoth ) { File perLocusStatisticsFile = deriveFromStream("sample_locus_statistics"); printPerLocus(perLocusStatisticsFile,coverageProfiles.getCoverageBySample()); } if ( useReadGroup || useBoth ) { File perLocusRGStats = deriveFromStream("read_group_locus_statistics"); printPerLocus(perLocusRGStats,coverageProfiles.getCoverageByReadGroup()); } } } public File deriveFromStream(String append) { String name = getToolkit().getArguments().outFileName; if ( name.contains("stdout") || name.contains("Stdout") || name.contains("STDOUT")) { return null; } else { return new File(name+"."+append); } } //////////////////////////////////////////////////////////////////////////////////// // HELPER OUTPUT METHODS //////////////////////////////////////////////////////////////////////////////////// private void printPerSample(PrintStream out, File optionalFile, DepthOfCoverageStats stats) { PrintStream output = getCorrectStream(out,optionalFile); int[] leftEnds = stats.getEndpoints(); StringBuilder hBuilder = new StringBuilder(); hBuilder.append("\t"); hBuilder.append(String.format("[0,%d)\t",leftEnds[0])); for ( int i = 1; i < leftEnds.length; i++ ) hBuilder.append(String.format("[%d,%d)\t",leftEnds[i-1],leftEnds[i])); hBuilder.append(String.format("[%d,inf)%n",leftEnds[leftEnds.length-1])); output.print(hBuilder.toString()); Map<String,int[]> histograms = stats.getHistograms(); for ( String s : histograms.keySet() ) { StringBuilder sBuilder = new StringBuilder(); sBuilder.append(String.format("%s",s)); for ( int count : histograms.get(s) ) { sBuilder.append(String.format("\t%d",count)); } sBuilder.append(String.format("%n")); output.print(sBuilder.toString()); } } private void printPerLocus(File locusFile, DepthOfCoverageStats stats) { PrintStream output = getCorrectStream(out,locusFile); if ( output == null ) { return; } int[] endpoints = stats.getEndpoints(); int samples = stats.getHistograms().size(); int[][] baseCoverageCumDist = stats.getLocusCounts(); // rows - # of samples // columns - depth of coverage StringBuilder header = new StringBuilder(); header.append(String.format("\t>=0")); for ( int d : endpoints ) { header.append(String.format("\t>=%d",d)); } header.append(String.format("%n")); output.print(header); for ( int row = 0; row < samples; row ++ ) { output.printf("%s_%d\t","NSamples",row+1); for ( int depthBin = 0; depthBin < baseCoverageCumDist[0].length; depthBin ++ ) { output.printf("%d\t",baseCoverageCumDist[row][depthBin]); } output.printf("%n"); } } private PrintStream getCorrectStream(PrintStream out, File optionalFile) { PrintStream output; if ( optionalFile == null ) { output = out; } else { try { output = new PrintStream(optionalFile); } catch ( IOException e ) { logger.warn("Error opening the output file "+optionalFile.getAbsolutePath()+". Defaulting to stdout"); output = out; } } return output; } private void printSummary(PrintStream out, File optionalFile, DepthOfCoverageStats stats) { PrintStream output = getCorrectStream(out,optionalFile); output.printf("%s\t%s\t%s\t%s\t%s\t%s%n","sample_id","total","mean","granular_third_quartile","granular_median","granular_first_quartile"); Map<String,int[]> histograms = stats.getHistograms(); Map<String,Double> means = stats.getMeans(); Map<String,Long> totals = stats.getTotals(); int[] leftEnds = stats.getEndpoints(); for ( String s : histograms.keySet() ) { int[] histogram = histograms.get(s); int median = getQuantile(histogram,0.5); int q1 = getQuantile(histogram,0.25); int q3 = getQuantile(histogram,0.75); // if any of these are larger than the higest bin, put the median as in the largest bin median = median == histogram.length-1 ? histogram.length-2 : median; q1 = q1 == histogram.length-1 ? histogram.length-2 : q1; q3 = q3 == histogram.length-1 ? histogram.length-2 : q3; output.printf("%s\t%d\t%.2f\t%d\t%d\t%d%n",s,totals.get(s),means.get(s),leftEnds[q3],leftEnds[median],leftEnds[q1]); } output.printf("%s\t%d\t%.2f\t%s\t%s\t%s%n","Total",stats.getTotalCoverage(),stats.getTotalMeanCoverage(),"N/A","N/A","N/A"); } private int getQuantile(int[] histogram, double prop) { int total = 0; for ( int i = 0; i < histogram.length; i ++ ) { total += histogram[i]; } int counts = 0; int bin = -1; while ( counts < prop*total ) { counts += histogram[bin+1]; bin++; } return bin; } private void printDepths(PrintStream stream, Map<String,int[]> countsBySample, Set<String> allSamples) { // get the depths per sample and build up the output string while tabulating total and average coverage // todo -- update me to deal with base counts/indels StringBuilder perSampleOutput = new StringBuilder(); int tDepth = 0; for ( String s : allSamples ) { perSampleOutput.append("\t"); long dp = countsBySample.keySet().contains(s) ? sumArray(countsBySample.get(s)) : 0; perSampleOutput.append(dp); if ( printBaseCounts ) { perSampleOutput.append("\t"); perSampleOutput.append(baseCounts(countsBySample.get(s))); } tDepth += dp; } // remember -- genome locus was printed in map() stream.printf("\t%d\t%.2f\t%s%n",tDepth,( (double) tDepth/ (double) allSamples.size()), perSampleOutput); //System.out.printf("\t%d\t%.2f\t%s%n",tDepth,( (double) tDepth/ (double) allSamples.size()), perSampleOutput); } private long sumArray(int[] array) { long i = 0; for ( int j : array ) { i += j; } return i; } private String baseCounts(int[] counts) { if ( counts == null ) { counts = new int[6]; } StringBuilder s = new StringBuilder(); int nbases = 0; for ( char b : BaseUtils.EXTENDED_BASES ) { nbases++; if ( includeDeletions || b != 'D' ) { s.append(b); s.append(":"); s.append(counts[BaseUtils.extendedBaseToBaseIndex(b)]); if ( nbases < 6 ) { s.append(" "); } } } return s.toString(); } } class CoverageAggregator { private DepthOfCoverageStats coverageByRead; private DepthOfCoverageStats coverageBySample; enum AggregationType { READ, SAMPLE, BOTH } private AggregationType agType; private Set<String> sampleNames; private Set<String> allSamples; public CoverageAggregator(AggregationType type, int start, int stop, int nBins) { if ( type == AggregationType.READ || type == AggregationType.BOTH) { coverageByRead = new DepthOfCoverageStats(DepthOfCoverageStats.calculateBinEndpoints(start,stop,nBins)); } if ( type == AggregationType.SAMPLE || type == AggregationType.BOTH) { coverageBySample = new DepthOfCoverageStats(DepthOfCoverageStats.calculateBinEndpoints(start,stop,nBins)); } agType = type; allSamples = new HashSet<String>(); } public void merge(CoverageAggregator otherAggregator) { if ( agType == AggregationType.SAMPLE || agType == AggregationType.BOTH ) { this.coverageBySample.merge(otherAggregator.coverageBySample); } if ( agType == AggregationType.READ || agType == AggregationType.BOTH) { this.coverageByRead.merge(otherAggregator.coverageByRead); } } public DepthOfCoverageStats getCoverageByReadGroup() { return coverageByRead; } public DepthOfCoverageStats getCoverageBySample() { return coverageBySample; } public void addSamples(Set<String> samples) { for ( String s : samples ) { coverageBySample.addSample(s); allSamples.add(s); } if ( agType == AggregationType.BOTH ) { sampleNames = samples; } } public void addReadGroups(Set<String> readGroupNames) { for ( String s : readGroupNames ) { coverageByRead.addSample(s); allSamples.add(s); } } public void initialize(boolean useDels, boolean omitLocusTable) { if ( agType == AggregationType.SAMPLE || agType == AggregationType.BOTH ) { if ( useDels ) { coverageBySample.initializeDeletions(); } if ( ! omitLocusTable ) { coverageBySample.initializeLocusCounts(); } } if ( agType == AggregationType.READ || agType == AggregationType.BOTH) { if ( useDels ) { coverageByRead.initializeDeletions(); } if ( ! omitLocusTable ) { coverageByRead.initializeLocusCounts(); } } } public void update(Map<String,int[]> countsByIdentifier) { if ( agType != AggregationType.BOTH ) { if ( agType == AggregationType.SAMPLE ) { coverageBySample.update(countsByIdentifier); } else { coverageByRead.update(countsByIdentifier); } } else { // have to separate samples and read groups HashMap<String,int[]> countsBySample = new HashMap<String,int[]>(sampleNames.size()); HashMap<String,int[]> countsByRG = new HashMap<String,int[]>(allSamples.size()-sampleNames.size()); for ( String s : countsByIdentifier.keySet() ) { if ( sampleNames.contains(s) ) { countsBySample.put(s,countsByIdentifier.get(s)); } else { // cannot use .remove() to save time due to concurrency issues countsByRG.put(s,countsByIdentifier.get(s)); } } coverageBySample.update(countsBySample); coverageByRead.update(countsByRG); } } public Set<String> getAllSamples() { return allSamples; } }
Odd, what I saw on IntelliJ hadn't saved to sting before committing. Here's the actual change. git-svn-id: 4561c0a8f080806b19201efb9525134c00b76d40@2956 348d0f76-0448-11de-a6fe-93d51630548a
java/src/org/broadinstitute/sting/oneoffprojects/walkers/coverage/CoverageStatistics.java
Odd, what I saw on IntelliJ hadn't saved to sting before committing. Here's the actual change.
<ide><path>ava/src/org/broadinstitute/sting/oneoffprojects/walkers/coverage/CoverageStatistics.java <ide> <ide> private String formatBin(int[] bins, int quartile) { <ide> if ( quartile >= bins.length ) { <del> return String.format(">%d",bins[quartile]); <add> return String.format(">%d",bins[bins.length-1]); <ide> } else if ( quartile < 0 ) { <ide> return String.format("<%d",bins[0]); <ide> } else {
JavaScript
apache-2.0
2b48840c2691d2b4cc1e90099ea005a7ac1afcc3
0
mano-mykingdom/titanium_mobile,mano-mykingdom/titanium_mobile,mano-mykingdom/titanium_mobile,mano-mykingdom/titanium_mobile,mano-mykingdom/titanium_mobile,mano-mykingdom/titanium_mobile,mano-mykingdom/titanium_mobile,mano-mykingdom/titanium_mobile
/* * Appcelerator Titanium Mobile * Copyright (c) 2011-Present by Appcelerator, Inc. All Rights Reserved. * Licensed under the terms of the Apache Public License * Please see the LICENSE included with this distribution for details. */ /* eslint-env mocha */ /* eslint no-unused-expressions: "off" */ /* eslint no-array-constructor: "off" */ /* eslint no-new-wrappers: "off" */ const should = require('./utilities/assertions'); const utilities = require('./utilities/utilities'); let util; describe('util', () => { it('should be required as core module', () => { util = require('util'); util.should.be.an.Object; }); // For copious tests, see https://github.com/nodejs/node/blob/master/test/parallel/test-util-format.js describe('#format()', () => { it('is a function', () => { util.format.should.be.a.Function; }); it('if placeholder has no corresponding argument, don\'t replace placeholder', () => { util.format('%s:%s', 'foo').should.eql('foo:%s'); }); it('extra arguments are coerced into strings and concatenated delimited by space', () => { util.format('%s:%s', 'foo', 'bar', 'baz').should.eql('foo:bar baz'); }); it('if first arg is not string, concat all args separated by spaces', () => { util.format(1, 2, 3).should.eql('1 2 3'); }); it('if only one arg, returned as-is', () => { util.format('%% %s').should.eql('%% %s'); }); describe('String placeholder', () => { it('with int', () => { util.format('%s', 1).should.eql('1'); util.format('%s', 42).should.eql('42'); util.format('%s %s', 42, 43).should.eql('42 43'); util.format('%s %s', 42).should.eql('42 %s'); }); it('with undefined', () => { util.format('%s', undefined).should.eql('undefined'); }); it('with null', () => { util.format('%s', null).should.eql('null'); }); it('with string', () => { util.format('%s', 'foo').should.eql('foo'); }); it('with string holding int value', () => { util.format('%s', '42').should.eql('42'); }); it('with floats', () => { util.format('%s', 42.0).should.eql('42'); util.format('%s', 1.5).should.eql('1.5'); util.format('%s', -0.5).should.eql('-0.5'); }); it('with Symbol', () => { util.format('%s', Symbol()).should.eql('Symbol()'); util.format('%s', Symbol('foo')).should.eql('Symbol(foo)'); }); // TODO: BigInt }); describe('Number placeholder', () => { it('with floats', () => { util.format('%d', 42.0).should.eql('42'); util.format('%d', 1.5).should.eql('1.5'); util.format('%d', -0.5).should.eql('-0.5'); }); it('with ints', () => { util.format('%d', 42).should.eql('42'); util.format('%d %d', 42, 43).should.eql('42 43'); util.format('%d %d', 42).should.eql('42 %d'); }); it('with string holding int value', () => { util.format('%d', '42').should.eql('42'); }); it('with string holding float value', () => { util.format('%d', '42.0').should.eql('42'); }); it('with empty string', () => { util.format('%d', '').should.eql('0'); }); it('with Symbol', () => { util.format('%d', Symbol()).should.eql('NaN'); }); it('with null', () => { util.format('%d', null).should.eql('0'); }); it('with undefined', () => { util.format('%d', undefined).should.eql('NaN'); }); // TODO: BigInt }); describe('Float placeholder', () => { it('with floats', () => { util.format('%f', 42.0).should.eql('42'); util.format('%f', 1.5).should.eql('1.5'); util.format('%f', -0.5).should.eql('-0.5'); }); it('with ints', () => { util.format('%f', 42).should.eql('42'); util.format('%f %f', 42, 43).should.eql('42 43'); util.format('%f %f', 42).should.eql('42 %f'); }); it('with string holding int value', () => { util.format('%f', '42').should.eql('42'); }); it('with string holding float value', () => { util.format('%f', '42.0').should.eql('42'); }); it('with empty string', () => { util.format('%f', '').should.eql('NaN'); }); it('with Symbol', () => { util.format('%f', Symbol()).should.eql('NaN'); }); it('with null', () => { util.format('%f', null).should.eql('NaN'); }); it('with undefined', () => { util.format('%f', undefined).should.eql('NaN'); }); // TODO: BigInt }); describe('Integer placeholder', () => { it('with ints', () => { util.format('%i', 42).should.eql('42'); util.format('%i %i', 42, 43).should.eql('42 43'); util.format('%i %i', 42).should.eql('42 %i'); }); it('with floats', () => { util.format('%i', 42.0).should.eql('42'); util.format('%i', 1.5).should.eql('1'); util.format('%i', -0.5).should.eql('-0'); }); it('with string holding int value', () => { util.format('%i', '42').should.eql('42'); }); it('with string holding float value', () => { util.format('%i', '42.0').should.eql('42'); }); it('with empty string', () => { util.format('%i', '').should.eql('NaN'); }); it('with Symbol', () => { util.format('%i', Symbol()).should.eql('NaN'); }); it('with null', () => { util.format('%i', null).should.eql('NaN'); }); it('with undefined', () => { util.format('%i', undefined).should.eql('NaN'); }); // TODO: BigInt }); describe('JSON placeholder', () => { it('with floats', () => { util.format('%j', 42.0).should.eql('42'); util.format('%j', 1.5).should.eql('1.5'); util.format('%j', -0.5).should.eql('-0.5'); }); it('with ints', () => { util.format('%j', 42).should.eql('42'); util.format('%j %j', 42, 43).should.eql('42 43'); util.format('%j %j', 42).should.eql('42 %j'); }); it('with string holding int value', () => { util.format('%j', '42').should.eql('"42"'); }); it('with string holding float value', () => { util.format('%j', '42.0').should.eql('"42.0"'); }); it('with empty string', () => { util.format('%j', '').should.eql('""'); }); it('with Symbol', () => { util.format('%j', Symbol()).should.eql('undefined'); }); it('with null', () => { util.format('%j', null).should.eql('null'); }); it('with undefined', () => { util.format('%j', undefined).should.eql('undefined'); }); it('with object having circular reference', () => { const o = {}; o.o = o; util.format('%j', o).should.eql('[Circular]'); }); it('with object throwing Error in toJSON() re-throws Error', () => { const o = { toJSON: () => { throw new Error('Failed!'); } }; (() => util.format('%j', o)).should.throw('Failed!'); }); // TODO: BigInt }); describe('%O - object placeholder', () => { it('with int', () => { util.format('%O', 42).should.eql('42'); }); it('with undefined', () => { util.format('%O', undefined).should.eql('undefined'); }); it('with null', () => { util.format('%O', null).should.eql('null'); }); it('with string', () => { util.format('%O', 'foo').should.eql('\'foo\''); }); it('with string holding int value', () => { util.format('%O', '42').should.eql('\'42\''); }); it('with floats', () => { util.format('%O', 42.0).should.eql('42'); util.format('%O', 1.5).should.eql('1.5'); util.format('%O', -0.5).should.eql('-0.5'); }); it('with Symbol', () => { util.format('%O', Symbol()).should.eql('Symbol()'); util.format('%O', Symbol('foo')).should.eql('Symbol(foo)'); }); it('with simple object', () => { const obj = { foo: 'bar' }; util.format('%O', obj).should.eql('{ foo: \'bar\' }'); }); it('with object', () => { const obj = { foo: 'bar', foobar: 1, func: function () {} }; util.format('%O', obj).should.eql('{ foo: \'bar\', foobar: 1, func: [Function: func] }'); }); it('with nested object', () => { const nestedObj2 = { foo: 'bar', foobar: 1, func: [ { a: function () {} } ] }; // FIXME: There's a weird edge case we fail here: when function is at cutoff depth and showHidden is true, we report '[Function: a]', while node reports '[Function]' // I don't know why. util.format('%O', nestedObj2).should.eql( '{ foo: \'bar\', foobar: 1, func: [ { a: [Function: a] } ] }'); }); it('with same object twice', () => { const obj = { foo: 'bar', foobar: 1, func: function () {} }; util.format('%O %O', obj, obj).should.eql( '{ foo: \'bar\', foobar: 1, func: [Function: func] } ' + '{ foo: \'bar\', foobar: 1, func: [Function: func] }'); }); }); describe('%o - object placeholder', () => { it('with int', () => { util.format('%o', 42).should.eql('42'); }); it('with undefined', () => { util.format('%o', undefined).should.eql('undefined'); }); it('with null', () => { util.format('%o', null).should.eql('null'); }); it('with string', () => { util.format('%o', 'foo').should.eql('\'foo\''); }); it('with string holding int value', () => { util.format('%o', '42').should.eql('\'42\''); }); it('with floats', () => { util.format('%o', 42.0).should.eql('42'); util.format('%o', 1.5).should.eql('1.5'); util.format('%o', -0.5).should.eql('-0.5'); }); it('with Symbol', () => { util.format('%o', Symbol()).should.eql('Symbol()'); util.format('%o', Symbol('foo')).should.eql('Symbol(foo)'); }); it('with simple object', () => { const obj = { foo: 'bar' }; util.format('%o', obj).should.eql('{ foo: \'bar\' }'); }); // FIXME: JSC/iOS seems to have inconsistent ordering of properties // First time around, it tends to go: arguments, caller, length, name, prototype. // Android/V8 is consistent // The property order is not consistent on iOS, which is kind of expected // since internally Object.getOwnPropertyNames is used, which does not // guarantee a specific order of returned property names. // On Android the order seems to be consistent it('with object', () => { const obj = { foo: 'bar', foobar: 1, func: function () {} }; const result = util.format('%o', obj); if (utilities.isAndroid()) { // Android/V8 result.should.eql( '{\n' + ' foo: \'bar\',\n' + ' foobar: 1,\n' + ' func: <ref *1> [Function: func] {\n' + ' [length]: 0,\n' + ' [name]: \'func\',\n' + ' [arguments]: null,\n' + ' [caller]: null,\n' + ' [prototype]: func { [constructor]: [Circular *1] }\n' + ' }\n' + '}' ); } else { // iOS/JSC result.should.eql( '{\n' + ' foo: \'bar\',\n' + ' foobar: 1,\n' + ' func: <ref *1> [Function: func] {\n' + ' [arguments]: null,\n' + ' [caller]: null,\n' + ' [length]: 0,\n' + ' [name]: \'func\',\n' + ' [prototype]: func { [constructor]: [Circular *1] }\n' + ' }\n' + '}' ); } }); it('with nested object', () => { const nestedObj2 = { foo: 'bar', foobar: 1, func: [ { a: function () {} } ] }; const result = util.format('%o', nestedObj2); if (utilities.isAndroid()) { // Android/V8 result.should.eql( '{\n' + ' foo: \'bar\',\n' + ' foobar: 1,\n' + ' func: [\n' + ' {\n' + ' a: <ref *1> [Function: a] {\n' + ' [length]: 0,\n' + ' [name]: \'a\',\n' + ' [arguments]: null,\n' + ' [caller]: null,\n' + ' [prototype]: a { [constructor]: [Circular *1] }\n' + ' }\n' + ' },\n' + ' [length]: 1\n' + ' ]\n' + '}' ); } else { // iOS/JSC result.should.eql( '{\n' + ' foo: \'bar\',\n' + ' foobar: 1,\n' + ' func: [\n' + ' {\n' + ' a: <ref *1> [Function: a] {\n' + ' [arguments]: null,\n' + ' [caller]: null,\n' + ' [length]: 0,\n' + ' [name]: \'a\',\n' + ' [prototype]: a { [constructor]: [Circular *1] }\n' + ' }\n' + ' },\n' + ' [length]: 1\n' + ' ]\n' + '}' ); } }); it('with same object twice', () => { const obj = { foo: 'bar', foobar: 1, func: function () {} }; const result = util.format('%o %o', obj, obj); if (utilities.isAndroid()) { // Android/V8 result.should.eql( '{\n' + ' foo: \'bar\',\n' + ' foobar: 1,\n' + ' func: <ref *1> [Function: func] {\n' + ' [length]: 0,\n' + ' [name]: \'func\',\n' + ' [arguments]: null,\n' + ' [caller]: null,\n' + ' [prototype]: func { [constructor]: [Circular *1] }\n' + ' }\n' + '} {\n' + ' foo: \'bar\',\n' + ' foobar: 1,\n' + ' func: <ref *1> [Function: func] {\n' + ' [length]: 0,\n' + ' [name]: \'func\',\n' + ' [arguments]: null,\n' + ' [caller]: null,\n' + ' [prototype]: func { [constructor]: [Circular *1] }\n' + ' }\n' + '}' ); } else { // iOS/JSC result.should.eql( '{\n' + ' foo: \'bar\',\n' + ' foobar: 1,\n' + ' func: <ref *1> [Function: func] {\n' + ' [arguments]: null,\n' + ' [caller]: null,\n' + ' [length]: 0,\n' + ' [name]: \'func\',\n' + ' [prototype]: func { [constructor]: [Circular *1] }\n' + ' }\n' + '} {\n' + ' foo: \'bar\',\n' + ' foobar: 1,\n' + ' func: <ref *1> [Function: func] {\n' + ' [arguments]: null,\n' + ' [caller]: null,\n' + ' [prototype]: func { [constructor]: [Circular *1] },\n' + ' [name]: \'func\',\n' + ' [length]: 0\n' + ' }\n' + '}' ); } }); }); }); describe('#inspect()', () => { it('is a function', () => { util.inspect.should.be.a.Function; }); it('handles string literal', () => { util.inspect('a').should.eql('\'a\''); }); it('handles number literal', () => { util.inspect(1).should.eql('1'); }); it('handles empty array', () => { util.inspect([]).should.eql('[]'); }); it('handles array with number values', () => { util.inspect([ 1, 2, 3 ]).should.eql('[ 1, 2, 3 ]'); }); it('handles array with mixed values', () => { util.inspect([ 'a', 2 ]).should.eql('[ \'a\', 2 ]'); }); it('handles sparse array', () => { // eslint-disable-next-line no-sparse-arrays util.inspect([ 1, , 3 ]).should.eql('[ 1, <1 empty item>, 3 ]'); }); it('handles sparse array with multiple items missing in a row', () => { // eslint-disable-next-line no-sparse-arrays util.inspect([ 1,,,, 3 ]).should.eql('[ 1, <3 empty items>, 3 ]'); }); it('handles sparse array with multiple separate gaps', () => { // eslint-disable-next-line no-sparse-arrays util.inspect([ 1,,,, 3, ,, 4 ]).should.eql('[ 1, <3 empty items>, 3, <2 empty items>, 4 ]'); }); it('handles array with length > options.maxArrayLength', () => { util.inspect([ 1, 2, 3 ], { maxArrayLength: 1 }).should.eql('[ 1, ... 2 more items ]'); }); it('handles array with length > options.maxArrayLength and is sparse', () => { // eslint-disable-next-line no-sparse-arrays util.inspect([ 1,,,, 3, ,, 4 ], { maxArrayLength: 1 }).should.eql('[ 1, ... 7 more items ]'); }); it('handles sparse array with length > options.maxArrayLength counting gaps as one item for length', () => { // eslint-disable-next-line no-sparse-arrays util.inspect([ 1,,,, ], { maxArrayLength: 2 }).should.eql('[ 1, <3 empty items> ]'); // eslint-disable-next-line no-sparse-arrays util.inspect([ 1,,,, 3, ,, 4 ], { maxArrayLength: 2 }).should.eql('[ 1, <3 empty items>, ... 4 more items ]'); // eslint-disable-next-line no-sparse-arrays util.inspect([ 1,,,, 3, ,, 4 ], { maxArrayLength: 3 }).should.eql('[ 1, <3 empty items>, 3, ... 3 more items ]'); // eslint-disable-next-line no-sparse-arrays util.inspect([ 1,,,, 3, ,, 4 ], { maxArrayLength: 4 }).should.eql('[ 1, <3 empty items>, 3, <2 empty items>, ... 1 more item ]'); }); it('handles Regexp literal', () => { util.inspect(/123/).should.eql('/123/'); }); it('handles Regexp literal with flags', () => { util.inspect(/123/ig).should.eql('/123/gi'); }); it('handles new Regexp instance', () => { util.inspect(new RegExp()).should.eql('/(?:)/'); }); it('handles object primitive literal', () => { util.inspect({}).should.eql('{}'); }); it('handles new Object', () => { // eslint-disable-next-line no-new-object util.inspect(new Object()).should.eql('{}'); }); it('handles Map instance', () => { util.inspect(new Map()).should.eql('Map {}'); }); it('handles Map instance with key/value pair', () => { util.inspect(new Map([ [ 'a', 1 ] ])).should.eql('Map { \'a\' => 1 }'); }); it('handles empty Set instance', () => { util.inspect(new Set()).should.eql('Set {}'); }); it('handles Set instance with number values', () => { util.inspect(new Set([ 1, 2, 3 ])).should.eql('Set { 1, 2, 3 }'); }); it('handles object with custom type tag', () => { const baz = Object.create({}, { [Symbol.toStringTag]: { value: 'foo' } }); util.inspect(baz).should.eql('Object [foo] {}'); }); it('handles object with null prototype', () => { const baz = Object.create(null, {}); util.inspect(baz).should.eql('[Object: null prototype] {}'); }); it('handles class instance', () => { class Bar {} util.inspect(new Bar()).should.eql('Bar {}'); }); it('handles class instance with custom type tag', () => { class Foo { get [Symbol.toStringTag]() { return 'bar'; } } util.inspect(new Foo()).should.eql('Foo [bar] {}'); }); it('handles empty function', () => { util.inspect(function () {}).should.eql('[Function (anonymous)]'); }); it('handles named function', () => { util.inspect(function bar() {}).should.eql('[Function: bar]'); }); it('handles arrow function', () => { util.inspect(() => {}).should.eql('[Function (anonymous)]'); }); it('handles function with custom property', () => { const myFunc = () => {}; myFunc.a = 1; util.inspect(myFunc).should.eql('[Function: myFunc] { a: 1 }'); }); it('handles object with getter property', () => { const obj = {}; // eslint-disable-next-line accessor-pairs Object.defineProperty(obj, 'whatever', { get: () => 1, enumerable: true }); util.inspect(obj).should.eql('{ whatever: [Getter] }'); }); it('handles object with setter property', () => { const obj = {}; // eslint-disable-next-line accessor-pairs Object.defineProperty(obj, 'whatever2', { set: () => {}, enumerable: true }); util.inspect(obj).should.eql('{ whatever2: [Setter] }'); }); it('handles object with getter/setter property', () => { const obj = {}; Object.defineProperty(obj, 'whatever3', { get: () => 1, set: () => {}, enumerable: true }); util.inspect(obj).should.eql('{ whatever3: [Getter/Setter] }'); }); it('handles object with property holding explicit undefined value', () => { const obj = {}; Object.defineProperty(obj, 'whatever4', { value: undefined, enumerable: true }); util.inspect(obj).should.eql('{ whatever4: undefined }'); }); it('with simple object', () => { const obj = { foo: 'bar' }; util.inspect(obj).should.eql('{ foo: \'bar\' }'); }); it('with same object repeated in an array', () => { const a = { id: 1 }; util.inspect([ a, a ]).should.eql('[ { id: 1 }, { id: 1 } ]'); }); it('with object', () => { const obj = { foo: 'bar', foobar: 1, func: function () {} }; // In Node 10+, we can sort the properties to ensure order to match, otherwise JSC/V8 return arguments/caller in different order on Functions util.inspect(obj, { showHidden: true, breakLength: Infinity, sorted: true }).should.eql( '{ foo: \'bar\', foobar: 1, func: <ref *1> [Function: func] { [arguments]: null, [caller]: null, [length]: 0, [name]: \'func\', [prototype]: func { [constructor]: [Circular *1] } } }' ); }); it('with nested object and infinite depth', () => { const nestedObj2 = { foo: 'bar', foobar: 1, func: [ { a: function () {} } ] }; // In Node 10+, we can sort the properties to ensure order to match, otheerwise JSC/V8 return arguments/caller in different order on Functions util.inspect(nestedObj2, { showHidden: true, breakLength: Infinity, depth: Infinity, sorted: true }).should.eql( '{\n' + ' foo: \'bar\',\n' + ' foobar: 1,\n' + ' func: [\n' + ' { a: <ref *1> [Function: a] { [arguments]: null, [caller]: null, [length]: 0, [name]: \'a\', [prototype]: a { [constructor]: [Circular *1] } } },\n' + ' [length]: 1\n' + ' ]\n' + '}' ); }); it('with nested object and default depth', () => { const nestedObj2 = { foo: 'bar', foobar: 1, func: [ { a: function () {} } ] }; util.inspect(nestedObj2, { showHidden: true, breakLength: Infinity }).should.eql( '{ foo: \'bar\', foobar: 1, func: [ { a: [Function] }, [length]: 1 ] }'); }); it('with toplevel object that breaks and nested object that doesn\'t break', () => { const nestedObj2 = { foo: 'bar', foobar: 1, func: { other: true, yeah: 'man' }, something: 'else' }; util.inspect(nestedObj2).should.eql( '{\n' + ' foo: \'bar\',\n' + ' foobar: 1,\n' + ' func: { other: true, yeah: \'man\' },\n' + ' something: \'else\'\n' + '}'); }); it('with toplevel and nested objects that break', () => { const nestedObj2 = { foo: 'bar', foobar: 1, func: { other: true, yeah: 'man', whatever: '123456789', whatever2: '123456789' } }; util.inspect(nestedObj2).should.eql( '{\n' + ' foo: \'bar\',\n' + ' foobar: 1,\n' + ' func: {\n' + ' other: true,\n' + ' yeah: \'man\',\n' + ' whatever: \'123456789\',\n' + ' whatever2: \'123456789\'\n' + ' }\n' + '}' ); }); it('with nested object and empty options', () => { const nestedObj2 = { foo: 'bar', foobar: 1, func: [ { a: function () {} } ] }; util.inspect(nestedObj2, {}).should.eql( '{ foo: \'bar\', foobar: 1, func: [ { a: [Function: a] } ] }'); }); it('with default breakLength at exact break point', () => { const obj = { foo: '', foobar: 1, something: '1', whatever: '', whatever2: '', whatever3: '' }; util.inspect(obj).should.eql('{\n foo: \'\',\n foobar: 1,\n something: \'1\',\n whatever: \'\',\n whatever2: \'\',\n whatever3: \'\'\n}'); }); it('with default breakLength just below break point', () => { const obj = { foo: '', foobar: 1, something: '1', whatever: '', whatever2: '' }; util.inspect(obj).should.eql('{ foo: \'\', foobar: 1, something: \'1\', whatever: \'\', whatever2: \'\' }'); }); }); describe('#inherits()', () => { it('is a function', () => { util.inherits.should.be.a.Function; }); it('hooks subclass to super constructor', (finished) => { function BaseClass() { this.listeners = {}; } BaseClass.prototype.on = function (eventName, listener) { const eventListeners = this.listeners[eventName] || []; eventListeners.push(listener); this.listeners[eventName] = eventListeners; }; BaseClass.prototype.emit = function (eventName, data) { const eventListeners = this.listeners[eventName] || []; for (const listener of eventListeners) { listener.call(this, data); } }; function MyStream() { BaseClass.call(this); } util.inherits(MyStream, BaseClass); MyStream.prototype.write = function (data) { this.emit('data', data); }; const stream = new MyStream(); should(stream instanceof BaseClass).eql(true); should(MyStream.super_).eql(BaseClass); stream.on('data', data => { data.should.eql('It works!'); finished(); }); stream.write('It works!'); // Received data: "It works!" }); it('throws TypeError if super constructor is null', () => { function BaseClass() { } function MyStream() { BaseClass.call(this); } should.throws(() => util.inherits(MyStream, null), TypeError ); }); it('throws TypeError if constructor is null', () => { function BaseClass() { } should.throws(() => util.inherits(null, BaseClass), TypeError ); }); it('throws TypeError if super constructor has no prototype', () => { const BaseClass = Object.create(null, {}); function MyStream() { BaseClass.call(this); } should.throws(() => util.inherits(MyStream, BaseClass), TypeError ); }); }); describe('#isArray', () => { it('should return true only if the given object is an Array', () => { should.strictEqual(util.isArray([]), true); should.strictEqual(util.isArray(Array()), true); should.strictEqual(util.isArray(new Array()), true); should.strictEqual(util.isArray(new Array(5)), true); should.strictEqual(util.isArray(new Array('with', 'some', 'entries')), true); should.strictEqual(util.isArray({}), false); should.strictEqual(util.isArray({ push: function () {} }), false); should.strictEqual(util.isArray(/regexp/), false); should.strictEqual(util.isArray(new Error()), false); should.strictEqual(util.isArray(Object.create(Array.prototype)), false); }); }); describe('#isRegExp', () => { it('should return true only if the given object is a RegExp', () => { should.strictEqual(util.isRegExp(/regexp/), true); should.strictEqual(util.isRegExp(RegExp(), 'foo'), true); should.strictEqual(util.isRegExp(new RegExp()), true); should.strictEqual(util.isRegExp({}), false); should.strictEqual(util.isRegExp([]), false); should.strictEqual(util.isRegExp(new Date()), false); should.strictEqual(util.isRegExp(Object.create(RegExp.prototype)), false); }); }); describe('#isDate', () => { it('should return true only if the given object is a Date', () => { should.strictEqual(util.isDate(new Date()), true); should.strictEqual(util.isDate(new Date(0), 'foo'), true); should.strictEqual(util.isDate(Date()), false); should.strictEqual(util.isDate({}), false); should.strictEqual(util.isDate([]), false); should.strictEqual(util.isDate(new Error()), false); should.strictEqual(util.isDate(Object.create(Date.prototype)), false); }); }); describe('#isError', () => { it('should return true only if the given object is an Error', () => { should.strictEqual(util.isError(new Error()), true); should.strictEqual(util.isError(new TypeError()), true); should.strictEqual(util.isError(new SyntaxError()), true); should.strictEqual(util.isError({}), false); should.strictEqual(util.isError({ name: 'Error', message: '' }), false); should.strictEqual(util.isError([]), false); should.strictEqual(util.isError(Object.create(Error.prototype)), true); }); }); describe('#isObject', () => { it('should return true only if the given object is an Object', () => { should.strictEqual(util.isObject({}), true); should.strictEqual(util.isObject([]), true); should.strictEqual(util.isObject(new Number(3)), true); should.strictEqual(util.isObject(Number(4)), false); should.strictEqual(util.isObject(1), false); }); }); describe('#isPrimitive', () => { it('should return true only if the given object is a primitve', () => { should.strictEqual(util.isPrimitive({}), false); should.strictEqual(util.isPrimitive(new Error()), false); should.strictEqual(util.isPrimitive(new Date()), false); should.strictEqual(util.isPrimitive([]), false); should.strictEqual(util.isPrimitive(/regexp/), false); should.strictEqual(util.isPrimitive(function () {}), false); should.strictEqual(util.isPrimitive(new Number(1)), false); should.strictEqual(util.isPrimitive(new String('bla')), false); should.strictEqual(util.isPrimitive(new Boolean(true)), false); should.strictEqual(util.isPrimitive(1), true); should.strictEqual(util.isPrimitive('bla'), true); should.strictEqual(util.isPrimitive(true), true); should.strictEqual(util.isPrimitive(undefined), true); should.strictEqual(util.isPrimitive(null), true); should.strictEqual(util.isPrimitive(Infinity), true); should.strictEqual(util.isPrimitive(NaN), true); should.strictEqual(util.isPrimitive(Symbol('symbol')), true); }); }); describe('#isBuffer', () => { it('should return true only if the given object is a Buffer', () => { should.strictEqual(util.isBuffer('foo'), false); should.strictEqual(util.isBuffer(Buffer.from('foo')), true); }); }); describe('#promisify()', () => { it('is a function', () => { util.promisify.should.be.a.Function; }); it('wraps callback function to return promise with resolve', (finished) => { function callbackOriginal(argOne, argTwo, next) { next(argOne, argTwo); } const promisified = util.promisify(callbackOriginal); const result = promisified(null, 123); should(result instanceof Promise).eql(true); result.then(value => { // eslint-disable-line promise/always-return should(value).eql(123); finished(); }).catch(err => finished(err)); }); it('wraps callback function to return promise with rejection', (finished) => { function callbackOriginal(argOne, argTwo, next) { next(argOne, argTwo); } const promisified = util.promisify(callbackOriginal); const result = promisified(new Error('example'), 123); should(result instanceof Promise).eql(true); result.then(value => { // eslint-disable-line promise/always-return should(value).eql(123); finished(new Error('Expected promise to get rejected!')); }).catch(err => { err.message.should.eql('example'); finished(); }); }); it('throws TypeError if original argument is not a function', () => { should.throws(() => util.promisify({}), TypeError ); }); }); describe('#callbackify()', () => { it('is a function', () => { util.callbackify.should.be.a.Function; }); it('wraps function returning Promise to return function accepting callback (with success)', (finished) => { function original(argOne) { return Promise.resolve(argOne); } const callbackified = util.callbackify(original); callbackified(23, (err, result) => { try { should(err).not.be.ok; should(result).eql(23); finished(); } catch (e) { finished(e); } }); }); it('wraps function returning Promise to return function accepting callback (with error)', (finished) => { function original(argOne) { return Promise.reject(argOne); } const callbackified = util.callbackify(original); callbackified(new Error('expected this'), (err, result) => { try { should(err).be.ok; should(result).not.be.ok; finished(); } catch (e) { finished(e); } }); }); it('handles special case of falsy rejection', (finished) => { function original() { return Promise.reject(null); } const callbackified = util.callbackify(original); callbackified((err, _result) => { try { should(err).be.ok; should(err instanceof Error).eql(true); should(err.reason).eql(null); finished(); } catch (e) { finished(e); } }); }); it('throws TypeError if original argument is not a function', () => { should.throws(() => util.callbackify({}), TypeError ); }); }); describe('#deprecate()', () => { it('is a function', () => { util.deprecate.should.be.a.Function; }); it('wraps function to emit warning', () => { function original(...args) { return args; } const deprecated = util.deprecate(original, 'dont call me Al'); // this should get called synchronously, so I don't think we need to do any setTimeout/async finished stuff process.on('warning', warning => { warning.name.should.eql('DeprecationWarning'); warning.message.should.eql('dont call me Al'); }); const result = deprecated(null, 123); should(result).eql([ null, 123 ]); }); // TODO: Test that we return original function if process.noDeprecation is true! }); describe('#log()', () => { it('is a function', () => { util.log.should.be.a.Function; }); it('prepends timestamp to message', () => { // Hijack console.log! NOTE: This doesn't work on iOS until we move to obj-c API! const original = console.log; try { console.log = string => { string.should.match(/^\d{1,2} \w{3} \d{2}:\d{2}:\d{2} - message$/); }; util.log('message'); } finally { console.log = original; } }); }); describe('#print()', () => { it('is a function', () => { util.print.should.be.a.Function; }); it('concatenates with no join', () => { // Hijack console.log! NOTE: This doesn't work on iOS until we move to obj-c API! const original = console.log; try { console.log = string => { string.should.eql('123'); }; util.print(1, 2, 3); } finally { console.log = original; } }); }); describe('#puts()', () => { it('is a function', () => { util.puts.should.be.a.Function; }); it('concatenates with newline join', () => { // Hijack console.log! NOTE: This doesn't work on iOS until we move to obj-c API! const original = console.log; try { console.log = string => { string.should.eql('1\n2\n3'); }; util.puts(1, 2, 3); } finally { console.log = original; } }); }); describe('#debug()', () => { it('is a function', () => { util.debug.should.be.a.Function; }); it('concatenates with newline join', () => { // Hijack console.error! NOTE: This doesn't work on iOS until we move to obj-c API! const original = console.error; try { console.error = string => { string.should.eql('DEBUG: message'); }; util.debug('message'); } finally { console.error = original; } }); }); describe('#error()', () => { it('is a function', () => { util.error.should.be.a.Function; }); it('concatenates with newline join', () => { // Hijack console.error! NOTE: This doesn't work on iOS until we move to obj-c API! const original = console.error; try { console.error = string => { string.should.eql('1\n2\n3'); }; util.error(1, 2, 3); } finally { console.error = original; } }); }); describe('.types', () => { describe('#isAnyArrayBuffer()', () => { it('should return true for built-in ArrayBuffer', () => { const ab = new ArrayBuffer(); util.types.isAnyArrayBuffer(ab).should.be.true; }); it.skip('should return true for built-in SharedArrayBuffer', () => { // SharedArrayBuffer is disabled in all major JS engines due to Spectre & Meltrdown vulnerabilities }); it('should return false for other values', () => { util.types.isAnyArrayBuffer({}).should.be.false; util.types.isAnyArrayBuffer(new Float32Array()).should.be.false; }); }); describe('#isArgumentsObject()', () => { it('should return true for function arguments object', () => { (function () { util.types.isArgumentsObject(arguments).should.be.true; }()); }); it('should return false for other values', () => { util.types.isArgumentsObject([]).should.be.false; util.types.isArgumentsObject({ [Symbol.toStringTag]: 'Arguments' }).should.be.false; }); }); describe('#isArrayBuffer()', () => { it('should return true for built-in ArrayBuffer instance', () => { const ab = new ArrayBuffer(); util.types.isArrayBuffer(ab).should.be.true; }); it('should return false for other values', () => { util.types.isArrayBuffer([]).should.be.false; util.types.isArrayBuffer(new Float32Array()).should.be.false; }); }); describe('#isAsyncFunction()', () => { it('should return true for async functions', () => { util.types.isAsyncFunction(async () => {}).should.be.true; }); it('should return false for normal functions', () => { util.types.isAsyncFunction(() => {}).should.be.true; }); }); describe('#isNativeError()', () => { it('is a function', () => { util.types.isNativeError.should.be.a.Function; }); it('returns true for Error instance', () => { util.types.isNativeError(new Error()).should.eql(true); }); it('returns true for EvalError instance', () => { util.types.isNativeError(new EvalError()).should.eql(true); }); it('returns true for RangeError instance', () => { util.types.isNativeError(new RangeError()).should.eql(true); }); it('returns true for ReferenceError instance', () => { util.types.isNativeError(new ReferenceError()).should.eql(true); }); it('returns true for SyntaxError instance', () => { util.types.isNativeError(new SyntaxError()).should.eql(true); }); it('returns true for TypeError instance', () => { util.types.isNativeError(new TypeError()).should.eql(true); }); it('returns true for URIError instance', () => { util.types.isNativeError(new URIError()).should.eql(true); }); it('returns false for custom Error subclass', () => { class SubError extends Error {} util.types.isNativeError(new SubError()).should.eql(false); }); }); describe('#isNumberObject()', () => { it('is a function', () => { util.types.isNumberObject.should.be.a.Function; }); it('returns true for boxed Number', () => { // eslint-disable-next-line no-new-wrappers util.types.isNumberObject(new Number()).should.eql(true); }); it('returns false for primitive Number', () => { util.types.isNumberObject(0).should.eql(false); }); }); describe('#isStringObject()', () => { it('is a function', () => { util.types.isStringObject.should.be.a.Function; }); it('returns true for boxed String', () => { // eslint-disable-next-line no-new-wrappers util.types.isStringObject(new String('foo')).should.eql(true); }); it('returns false for primitive String', () => { util.types.isStringObject('foo').should.eql(false); }); }); describe('#isBooleanObject()', () => { it('is a function', () => { util.types.isBooleanObject.should.be.a.Function; }); it('returns true for boxed Boolean', () => { // eslint-disable-next-line no-new-wrappers util.types.isBooleanObject(new Boolean(false)).should.eql(true); }); it('returns false for primitive Boolean', () => { util.types.isBooleanObject(true).should.eql(false); }); }); // TODO: Re-enable when we have BigInt support // describe('#isBigIntObject()', () => { // it('is a function', () => { // util.types.isBigIntObject.should.be.a.Function; // }); // it('returns true for boxed BigInt', () => { // // eslint-disable-next-line no-new-wrappers,no-undef // util.types.isSymbolObject(Object(BigInt(9007199254740991))).should.eql(true); // }); // it('returns false for BigInt instance', () => { // // eslint-disable-next-line no-undef // util.types.isSymbolObject(BigInt(9007199254740991)).should.eql(false); // }); // it('returns false for primitive BigInt', () => { // util.types.isSymbolObject(9007199254740991n).should.eql(false); // }); // }); describe('#isSymbolObject()', () => { it('is a function', () => { util.types.isSymbolObject.should.be.a.Function; }); it('returns true for boxed Symbol', () => { // eslint-disable-next-line no-new-wrappers util.types.isSymbolObject(Object(Symbol('foo'))).should.eql(true); }); it('returns false for primitive Symbol', () => { util.types.isSymbolObject(Symbol('foo')).should.eql(false); }); }); describe('#isBoxedPrimitive()', () => { it('is a function', () => { util.types.isBoxedPrimitive.should.be.a.Function; }); it('returns false for primitive Boolean', () => { util.types.isBoxedPrimitive(false).should.eql(false); }); it('returns true for boxed Boolean', () => { // eslint-disable-next-line no-new-wrappers util.types.isBoxedPrimitive(new Boolean(false)).should.eql(true); }); it('returns false for primitive Symbol', () => { util.types.isBoxedPrimitive(Symbol('foo')).should.eql(false); }); it('returns true for boxed Symbol', () => { util.types.isBoxedPrimitive(Object(Symbol('foo'))).should.eql(true); }); // it('returns true for boxed BigInt', () => { // // eslint-disable-next-line no-undef // util.types.isBoxedPrimitive(Object(BigInt(5))).should.eql(true); // }); }); describe('#isSet()', () => { it('is a function', () => { util.types.isSet.should.be.a.Function; }); it('returns true for Set instance', () => { util.types.isSet(new Set()).should.eql(true); }); }); describe('#isSetIterator()', () => { it('should return true if the value is an iterator returned for a built-in Set instance', () => { const set = new Set(); util.types.isSetIterator(set.keys()).should.be.true; util.types.isSetIterator(set.values()).should.be.true; util.types.isSetIterator(set.entries()).should.be.true; util.types.isSetIterator(set[Symbol.iterator]()).should.be.true; }); it('should return false for other iterators', () => { const map = new Map(); util.types.isSetIterator(map.values()).should.be.false; }); }); describe('#isMap()', () => { it('is a function', () => { util.types.isMap.should.be.a.Function; }); it('returns true for Map instance', () => { util.types.isMap(new Map()).should.eql(true); }); }); describe('#isMapIterator()', () => { it('should return true if the value is an iterator retunred for a built-in Map instance', () => { const map = new Map(); util.types.isMapIterator(map.keys()).should.be.true; util.types.isMapIterator(map.values()).should.be.true; util.types.isMapIterator(map.entries()).should.be.true; util.types.isMapIterator(map[Symbol.iterator]()).should.be.true; }); it('should return false for other iterators', () => { const set = new Set(); util.types.isMapIterator(set.values()).should.be.false; }); }); describe('#isDataView()', () => { const ab = new ArrayBuffer(20); it('should return true for built-in DataView instance', () => { util.types.isDataView(new DataView(ab)).should.be.true; }); it('should return false for typed array instance', () => { util.types.isDataView(new Float64Array()).should.be.false; }); }); describe('#isDate()', () => { it('is a function', () => { util.types.isDate.should.be.a.Function; }); it('returns true for built-in Date instance', () => { util.types.isDate(new Date()).should.eql(true); }); }); describe('#isPromise()', () => { it('should return true for built-in Promise', () => { util.types.isPromise(Promise.resolve(42)).should.be.true; }); it('should return false for Promise like objects', () => { util.types.isPromise({ then: () => {}, catch: () => {} }).should.be.false; }); }); describe('#isRegExp()', () => { it('is a function', () => { util.types.isRegExp.should.be.a.Function; }); it('returns true for RegExp instance', () => { util.types.isRegExp(/abc/).should.eql(true); }); it('returns true for RegExp primitive', () => { util.types.isRegExp(new RegExp('abc')).should.eql(true); }); }); describe('#isGeneratorFunction()', () => { it('should return true for generator function', () => { util.types.isGeneratorFunction(function *foo() {}).should.be.true; }); it('should return false for normal function', () => { util.types.isGeneratorFunction(function foo() {}).should.be.false; }); }); describe('#isGeneratorObject()', () => { it('should return true for generator object', () => { function *foo() {} const generator = foo(); util.types.isGeneratorObject(generator).should.be.true; }); it('should return false for any other object', () => { util.types.isGeneratorObject({}).should.be.false; }); }); describe('#isWeakMap()', () => { it('should return true for built-in WeakMap', () => { const map = new WeakMap(); util.types.isWeakMap(map).should.be.true; }); it('should return false for other values', () => { util.types.isWeakMap({}).should.be.false; util.types.isWeakMap(new Map()).should.be.false; }); }); describe('#isWeakSet()', () => { it('should return true for built-in WeakSet', () => { const map = new WeakSet(); util.types.isWeakSet(map).should.be.true; }); it('should return false for other values', () => { util.types.isWeakSet({}).should.be.false; util.types.isWeakSet(new Set()).should.be.false; }); }); describe('#isTypedArray()', () => { it('should return true for built-in typed arrays', () => { should(util.types.isTypedArray(new Uint8Array())).be.true; should(util.types.isTypedArray(new Uint8ClampedArray())).be.true; should(util.types.isTypedArray(new Uint16Array())).be.true; should(util.types.isTypedArray(new Uint32Array())).be.true; should(util.types.isTypedArray(new Int8Array())).be.true; should(util.types.isTypedArray(new Int16Array())).be.true; should(util.types.isTypedArray(new Int32Array())).be.true; should(util.types.isTypedArray(new Float32Array())).be.true; should(util.types.isTypedArray(new Float64Array())).be.true; }); it('should return true for our own Buffer', () => { should(util.types.isTypedArray(Buffer.alloc())).be.true; }); it('should return false for other values', () => { util.types.isTypedArray({}).should.be.false; util.types.isTypedArray([]).should.be.false; }); }); describe('Typed Arrays', () => { it('should correctly check typed arrays', () => { should(!util.types.isUint8Array({ [Symbol.toStringTag]: 'Uint8Array' })).be.true; should(util.types.isUint8Array(new Uint8Array())).be.true; should(!util.types.isUint8ClampedArray({ [Symbol.toStringTag]: 'Uint8ClampedArray' })).be.true; should(util.types.isUint8ClampedArray(new Uint8ClampedArray())).be.true; should(!util.types.isUint16Array({ [Symbol.toStringTag]: 'Uint16Array' })).be.true; should(util.types.isUint16Array(new Uint16Array())).be.true; should(!util.types.isUint32Array({ [Symbol.toStringTag]: 'Uint32Array' })).be.true; should(util.types.isUint32Array(new Uint32Array())).be.true; should(!util.types.isInt8Array({ [Symbol.toStringTag]: 'Int8Array' })).be.true; should(util.types.isInt8Array(new Int8Array())).be.true; should(!util.types.isInt16Array({ [Symbol.toStringTag]: 'Int16Array' })).be.true; should(util.types.isInt16Array(new Int16Array())).be.true; should(!util.types.isInt32Array({ [Symbol.toStringTag]: 'Int32Array' })).be.true; should(util.types.isInt32Array(new Int32Array())).be.true; should(!util.types.isFloat32Array({ [Symbol.toStringTag]: 'Float32Array' })).be.true; should(util.types.isFloat32Array(new Float32Array())).be.true; should(!util.types.isFloat64Array({ [Symbol.toStringTag]: 'Float64Array' })).be.true; should(util.types.isFloat64Array(new Float64Array())).be.true; /* @todo enable when we have BigInt64 support should(!util.types.isBigInt64Array({ [Symbol.toStringTag]: 'BigInt64Array' })).be.true; should(util.types.isBigInt64Array(new BigInt64Array)).be.true; should(!util.types.isBigUint64Array({ [Symbol.toStringTag]: 'BigUint64Array' })).be.true; should(util.types.isBigUint64Array(new BigUint64Array)).be.true; */ }); }); }); });
tests/Resources/util.test.js
/* * Appcelerator Titanium Mobile * Copyright (c) 2011-Present by Appcelerator, Inc. All Rights Reserved. * Licensed under the terms of the Apache Public License * Please see the LICENSE included with this distribution for details. */ /* eslint-env mocha */ /* eslint no-unused-expressions: "off" */ /* eslint no-array-constructor: "off" */ /* eslint no-new-wrappers: "off" */ const should = require('./utilities/assertions'); let util; describe('util', () => { it('should be required as core module', () => { util = require('util'); util.should.be.an.Object; }); // For copious tests, see https://github.com/nodejs/node/blob/master/test/parallel/test-util-format.js describe('#format()', () => { it('is a function', () => { util.format.should.be.a.Function; }); it('if placeholder has no corresponding argument, don\'t replace placeholder', () => { util.format('%s:%s', 'foo').should.eql('foo:%s'); }); it('extra arguments are coerced into strings and concatenated delimited by space', () => { util.format('%s:%s', 'foo', 'bar', 'baz').should.eql('foo:bar baz'); }); it('if first arg is not string, concat all args separated by spaces', () => { util.format(1, 2, 3).should.eql('1 2 3'); }); it('if only one arg, returned as-is', () => { util.format('%% %s').should.eql('%% %s'); }); describe('String placeholder', () => { it('with int', () => { util.format('%s', 1).should.eql('1'); util.format('%s', 42).should.eql('42'); util.format('%s %s', 42, 43).should.eql('42 43'); util.format('%s %s', 42).should.eql('42 %s'); }); it('with undefined', () => { util.format('%s', undefined).should.eql('undefined'); }); it('with null', () => { util.format('%s', null).should.eql('null'); }); it('with string', () => { util.format('%s', 'foo').should.eql('foo'); }); it('with string holding int value', () => { util.format('%s', '42').should.eql('42'); }); it('with floats', () => { util.format('%s', 42.0).should.eql('42'); util.format('%s', 1.5).should.eql('1.5'); util.format('%s', -0.5).should.eql('-0.5'); }); it('with Symbol', () => { util.format('%s', Symbol()).should.eql('Symbol()'); util.format('%s', Symbol('foo')).should.eql('Symbol(foo)'); }); // TODO: BigInt }); describe('Number placeholder', () => { it('with floats', () => { util.format('%d', 42.0).should.eql('42'); util.format('%d', 1.5).should.eql('1.5'); util.format('%d', -0.5).should.eql('-0.5'); }); it('with ints', () => { util.format('%d', 42).should.eql('42'); util.format('%d %d', 42, 43).should.eql('42 43'); util.format('%d %d', 42).should.eql('42 %d'); }); it('with string holding int value', () => { util.format('%d', '42').should.eql('42'); }); it('with string holding float value', () => { util.format('%d', '42.0').should.eql('42'); }); it('with empty string', () => { util.format('%d', '').should.eql('0'); }); it('with Symbol', () => { util.format('%d', Symbol()).should.eql('NaN'); }); it('with null', () => { util.format('%d', null).should.eql('0'); }); it('with undefined', () => { util.format('%d', undefined).should.eql('NaN'); }); // TODO: BigInt }); describe('Float placeholder', () => { it('with floats', () => { util.format('%f', 42.0).should.eql('42'); util.format('%f', 1.5).should.eql('1.5'); util.format('%f', -0.5).should.eql('-0.5'); }); it('with ints', () => { util.format('%f', 42).should.eql('42'); util.format('%f %f', 42, 43).should.eql('42 43'); util.format('%f %f', 42).should.eql('42 %f'); }); it('with string holding int value', () => { util.format('%f', '42').should.eql('42'); }); it('with string holding float value', () => { util.format('%f', '42.0').should.eql('42'); }); it('with empty string', () => { util.format('%f', '').should.eql('NaN'); }); it('with Symbol', () => { util.format('%f', Symbol()).should.eql('NaN'); }); it('with null', () => { util.format('%f', null).should.eql('NaN'); }); it('with undefined', () => { util.format('%f', undefined).should.eql('NaN'); }); // TODO: BigInt }); describe('Integer placeholder', () => { it('with ints', () => { util.format('%i', 42).should.eql('42'); util.format('%i %i', 42, 43).should.eql('42 43'); util.format('%i %i', 42).should.eql('42 %i'); }); it('with floats', () => { util.format('%i', 42.0).should.eql('42'); util.format('%i', 1.5).should.eql('1'); util.format('%i', -0.5).should.eql('-0'); }); it('with string holding int value', () => { util.format('%i', '42').should.eql('42'); }); it('with string holding float value', () => { util.format('%i', '42.0').should.eql('42'); }); it('with empty string', () => { util.format('%i', '').should.eql('NaN'); }); it('with Symbol', () => { util.format('%i', Symbol()).should.eql('NaN'); }); it('with null', () => { util.format('%i', null).should.eql('NaN'); }); it('with undefined', () => { util.format('%i', undefined).should.eql('NaN'); }); // TODO: BigInt }); describe('JSON placeholder', () => { it('with floats', () => { util.format('%j', 42.0).should.eql('42'); util.format('%j', 1.5).should.eql('1.5'); util.format('%j', -0.5).should.eql('-0.5'); }); it('with ints', () => { util.format('%j', 42).should.eql('42'); util.format('%j %j', 42, 43).should.eql('42 43'); util.format('%j %j', 42).should.eql('42 %j'); }); it('with string holding int value', () => { util.format('%j', '42').should.eql('"42"'); }); it('with string holding float value', () => { util.format('%j', '42.0').should.eql('"42.0"'); }); it('with empty string', () => { util.format('%j', '').should.eql('""'); }); it('with Symbol', () => { util.format('%j', Symbol()).should.eql('undefined'); }); it('with null', () => { util.format('%j', null).should.eql('null'); }); it('with undefined', () => { util.format('%j', undefined).should.eql('undefined'); }); it('with object having circular reference', () => { const o = {}; o.o = o; util.format('%j', o).should.eql('[Circular]'); }); it('with object throwing Error in toJSON() re-throws Error', () => { const o = { toJSON: () => { throw new Error('Failed!'); } }; (() => util.format('%j', o)).should.throw('Failed!'); }); // TODO: BigInt }); describe('%O - object placeholder', () => { it('with int', () => { util.format('%O', 42).should.eql('42'); }); it('with undefined', () => { util.format('%O', undefined).should.eql('undefined'); }); it('with null', () => { util.format('%O', null).should.eql('null'); }); it('with string', () => { util.format('%O', 'foo').should.eql('\'foo\''); }); it('with string holding int value', () => { util.format('%O', '42').should.eql('\'42\''); }); it('with floats', () => { util.format('%O', 42.0).should.eql('42'); util.format('%O', 1.5).should.eql('1.5'); util.format('%O', -0.5).should.eql('-0.5'); }); it('with Symbol', () => { util.format('%O', Symbol()).should.eql('Symbol()'); util.format('%O', Symbol('foo')).should.eql('Symbol(foo)'); }); it('with simple object', () => { const obj = { foo: 'bar' }; util.format('%O', obj).should.eql('{ foo: \'bar\' }'); }); it('with object', () => { const obj = { foo: 'bar', foobar: 1, func: function () {} }; util.format('%O', obj).should.eql('{ foo: \'bar\', foobar: 1, func: [Function: func] }'); }); it('with nested object', () => { const nestedObj2 = { foo: 'bar', foobar: 1, func: [ { a: function () {} } ] }; // FIXME: There's a weird edge case we fail here: when function is at cutoff depth and showHidden is true, we report '[Function: a]', while node reports '[Function]' // I don't know why. util.format('%O', nestedObj2).should.eql( '{ foo: \'bar\', foobar: 1, func: [ { a: [Function: a] } ] }'); }); it('with same object twice', () => { const obj = { foo: 'bar', foobar: 1, func: function () {} }; util.format('%O %O', obj, obj).should.eql( '{ foo: \'bar\', foobar: 1, func: [Function: func] } ' + '{ foo: \'bar\', foobar: 1, func: [Function: func] }'); }); }); describe('%o - object placeholder', () => { it('with int', () => { util.format('%o', 42).should.eql('42'); }); it('with undefined', () => { util.format('%o', undefined).should.eql('undefined'); }); it('with null', () => { util.format('%o', null).should.eql('null'); }); it('with string', () => { util.format('%o', 'foo').should.eql('\'foo\''); }); it('with string holding int value', () => { util.format('%o', '42').should.eql('\'42\''); }); it('with floats', () => { util.format('%o', 42.0).should.eql('42'); util.format('%o', 1.5).should.eql('1.5'); util.format('%o', -0.5).should.eql('-0.5'); }); it('with Symbol', () => { util.format('%o', Symbol()).should.eql('Symbol()'); util.format('%o', Symbol('foo')).should.eql('Symbol(foo)'); }); it('with simple object', () => { const obj = { foo: 'bar' }; util.format('%o', obj).should.eql('{ foo: \'bar\' }'); }); it('with object', () => { const obj = { foo: 'bar', foobar: 1, func: function () {} }; util.format('%o', obj).should.eql( '{\n' + ' foo: \'bar\',\n' + ' foobar: 1,\n' + ' func: <ref *1> [Function: func] {\n' + ' [arguments]: null,\n' + ' [caller]: null,\n' + ' [length]: 0,\n' + ' [name]: \'func\',\n' + ' [prototype]: func { [constructor]: [Circular *1] }\n' + ' }\n' + '}' ); }); it('with nested object', () => { const nestedObj2 = { foo: 'bar', foobar: 1, func: [ { a: function () {} } ] }; util.format('%o', nestedObj2).should.eql( '{\n' + ' foo: \'bar\',\n' + ' foobar: 1,\n' + ' func: [\n' + ' {\n' + ' a: <ref *1> [Function: a] {\n' + ' [arguments]: null,\n' + ' [caller]: null,\n' + ' [length]: 0,\n' + ' [name]: \'a\',\n' + ' [prototype]: a { [constructor]: [Circular *1] }\n' + ' }\n' + ' },\n' + ' [length]: 1\n' + ' ]\n' + '}' ); }); // The property order is not consistent on iOS, which is kind of expected // since internally Object.getOwnPropertyNames is used, which does not // guarantee a specific order of returned property names. // On Android the order seems to be consistent it.iosBroken('with same object twice', () => { const obj = { foo: 'bar', foobar: 1, func: function () {} }; util.format('%o %o', obj, obj).should.eql( '{\n' + ' foo: \'bar\',\n' + ' foobar: 1,\n' + ' func: <ref *1> [Function: func] {\n' + ' [arguments]: null,\n' + ' [caller]: null,\n' + ' [length]: 0,\n' + ' [name]: \'func\',\n' + ' [prototype]: func { [constructor]: [Circular *1] }\n' + ' }\n' + '} {\n' + ' foo: \'bar\',\n' + ' foobar: 1,\n' + ' func: <ref *1> [Function: func] {\n' + ' [arguments]: null,\n' + ' [caller]: null,\n' + ' [length]: 0,\n' + ' [name]: \'func\',\n' + ' [prototype]: func { [constructor]: [Circular *1] }\n' + ' }\n' + '}' ); }); }); }); describe('#inspect()', () => { it('is a function', () => { util.inspect.should.be.a.Function; }); it('handles string literal', () => { util.inspect('a').should.eql('\'a\''); }); it('handles number literal', () => { util.inspect(1).should.eql('1'); }); it('handles empty array', () => { util.inspect([]).should.eql('[]'); }); it('handles array with number values', () => { util.inspect([ 1, 2, 3 ]).should.eql('[ 1, 2, 3 ]'); }); it('handles array with mixed values', () => { util.inspect([ 'a', 2 ]).should.eql('[ \'a\', 2 ]'); }); it('handles sparse array', () => { // eslint-disable-next-line no-sparse-arrays util.inspect([ 1, , 3 ]).should.eql('[ 1, <1 empty item>, 3 ]'); }); it('handles sparse array with multiple items missing in a row', () => { // eslint-disable-next-line no-sparse-arrays util.inspect([ 1,,,, 3 ]).should.eql('[ 1, <3 empty items>, 3 ]'); }); it('handles sparse array with multiple separate gaps', () => { // eslint-disable-next-line no-sparse-arrays util.inspect([ 1,,,, 3, ,, 4 ]).should.eql('[ 1, <3 empty items>, 3, <2 empty items>, 4 ]'); }); it('handles array with length > options.maxArrayLength', () => { util.inspect([ 1, 2, 3 ], { maxArrayLength: 1 }).should.eql('[ 1, ... 2 more items ]'); }); it('handles array with length > options.maxArrayLength and is sparse', () => { // eslint-disable-next-line no-sparse-arrays util.inspect([ 1,,,, 3, ,, 4 ], { maxArrayLength: 1 }).should.eql('[ 1, ... 7 more items ]'); }); it('handles sparse array with length > options.maxArrayLength counting gaps as one item for length', () => { // eslint-disable-next-line no-sparse-arrays util.inspect([ 1,,,, ], { maxArrayLength: 2 }).should.eql('[ 1, <3 empty items> ]'); // eslint-disable-next-line no-sparse-arrays util.inspect([ 1,,,, 3, ,, 4 ], { maxArrayLength: 2 }).should.eql('[ 1, <3 empty items>, ... 4 more items ]'); // eslint-disable-next-line no-sparse-arrays util.inspect([ 1,,,, 3, ,, 4 ], { maxArrayLength: 3 }).should.eql('[ 1, <3 empty items>, 3, ... 3 more items ]'); // eslint-disable-next-line no-sparse-arrays util.inspect([ 1,,,, 3, ,, 4 ], { maxArrayLength: 4 }).should.eql('[ 1, <3 empty items>, 3, <2 empty items>, ... 1 more item ]'); }); it('handles Regexp literal', () => { util.inspect(/123/).should.eql('/123/'); }); it('handles Regexp literal with flags', () => { util.inspect(/123/ig).should.eql('/123/gi'); }); it('handles new Regexp instance', () => { util.inspect(new RegExp()).should.eql('/(?:)/'); }); it('handles object primitive literal', () => { util.inspect({}).should.eql('{}'); }); it('handles new Object', () => { // eslint-disable-next-line no-new-object util.inspect(new Object()).should.eql('{}'); }); it('handles Map instance', () => { util.inspect(new Map()).should.eql('Map {}'); }); it('handles Map instance with key/value pair', () => { util.inspect(new Map([ [ 'a', 1 ] ])).should.eql('Map { \'a\' => 1 }'); }); it('handles empty Set instance', () => { util.inspect(new Set()).should.eql('Set {}'); }); it('handles Set instance with number values', () => { util.inspect(new Set([ 1, 2, 3 ])).should.eql('Set { 1, 2, 3 }'); }); it('handles object with custom type tag', () => { const baz = Object.create({}, { [Symbol.toStringTag]: { value: 'foo' } }); util.inspect(baz).should.eql('Object [foo] {}'); }); it('handles object with null prototype', () => { const baz = Object.create(null, {}); util.inspect(baz).should.eql('[Object: null prototype] {}'); }); it('handles class instance', () => { class Bar {} util.inspect(new Bar()).should.eql('Bar {}'); }); it('handles class instance with custom type tag', () => { class Foo { get [Symbol.toStringTag]() { return 'bar'; } } util.inspect(new Foo()).should.eql('Foo [bar] {}'); }); it('handles empty function', () => { util.inspect(function () {}).should.eql('[Function (anonymous)]'); }); it('handles named function', () => { util.inspect(function bar() {}).should.eql('[Function: bar]'); }); it('handles arrow function', () => { util.inspect(() => {}).should.eql('[Function (anonymous)]'); }); it('handles function with custom property', () => { const myFunc = () => {}; myFunc.a = 1; util.inspect(myFunc).should.eql('[Function: myFunc] { a: 1 }'); }); it('handles object with getter property', () => { const obj = {}; // eslint-disable-next-line accessor-pairs Object.defineProperty(obj, 'whatever', { get: () => 1, enumerable: true }); util.inspect(obj).should.eql('{ whatever: [Getter] }'); }); it('handles object with setter property', () => { const obj = {}; // eslint-disable-next-line accessor-pairs Object.defineProperty(obj, 'whatever2', { set: () => {}, enumerable: true }); util.inspect(obj).should.eql('{ whatever2: [Setter] }'); }); it('handles object with getter/setter property', () => { const obj = {}; Object.defineProperty(obj, 'whatever3', { get: () => 1, set: () => {}, enumerable: true }); util.inspect(obj).should.eql('{ whatever3: [Getter/Setter] }'); }); it('handles object with property holding explicit undefined value', () => { const obj = {}; Object.defineProperty(obj, 'whatever4', { value: undefined, enumerable: true }); util.inspect(obj).should.eql('{ whatever4: undefined }'); }); it('with simple object', () => { const obj = { foo: 'bar' }; util.inspect(obj).should.eql('{ foo: \'bar\' }'); }); it('with same object repeated in an array', () => { const a = { id: 1 }; util.inspect([ a, a ]).should.eql('[ { id: 1 }, { id: 1 } ]'); }); it('with object', () => { const obj = { foo: 'bar', foobar: 1, func: function () {} }; // In Node 10+, we can sort the properties to ensure order to match, otherwise JSC/V8 return arguments/caller in different order on Functions util.inspect(obj, { showHidden: true, breakLength: Infinity, sorted: true }).should.eql( '{ foo: \'bar\', foobar: 1, func: <ref *1> [Function: func] { [arguments]: null, [caller]: null, [length]: 0, [name]: \'func\', [prototype]: func { [constructor]: [Circular *1] } } }' ); }); it('with nested object and infinite depth', () => { const nestedObj2 = { foo: 'bar', foobar: 1, func: [ { a: function () {} } ] }; // In Node 10+, we can sort the properties to ensure order to match, otheerwise JSC/V8 return arguments/caller in different order on Functions util.inspect(nestedObj2, { showHidden: true, breakLength: Infinity, depth: Infinity, sorted: true }).should.eql( '{\n' + ' foo: \'bar\',\n' + ' foobar: 1,\n' + ' func: [\n' + ' { a: <ref *1> [Function: a] { [arguments]: null, [caller]: null, [length]: 0, [name]: \'a\', [prototype]: a { [constructor]: [Circular *1] } } },\n' + ' [length]: 1\n' + ' ]\n' + '}' ); }); it('with nested object and default depth', () => { const nestedObj2 = { foo: 'bar', foobar: 1, func: [ { a: function () {} } ] }; util.inspect(nestedObj2, { showHidden: true, breakLength: Infinity }).should.eql( '{ foo: \'bar\', foobar: 1, func: [ { a: [Function] }, [length]: 1 ] }'); }); it('with toplevel object that breaks and nested object that doesn\'t break', () => { const nestedObj2 = { foo: 'bar', foobar: 1, func: { other: true, yeah: 'man' }, something: 'else' }; util.inspect(nestedObj2).should.eql( '{\n' + ' foo: \'bar\',\n' + ' foobar: 1,\n' + ' func: { other: true, yeah: \'man\' },\n' + ' something: \'else\'\n' + '}'); }); it('with toplevel and nested objects that break', () => { const nestedObj2 = { foo: 'bar', foobar: 1, func: { other: true, yeah: 'man', whatever: '123456789', whatever2: '123456789' } }; util.inspect(nestedObj2).should.eql( '{\n' + ' foo: \'bar\',\n' + ' foobar: 1,\n' + ' func: {\n' + ' other: true,\n' + ' yeah: \'man\',\n' + ' whatever: \'123456789\',\n' + ' whatever2: \'123456789\'\n' + ' }\n' + '}' ); }); it('with nested object and empty options', () => { const nestedObj2 = { foo: 'bar', foobar: 1, func: [ { a: function () {} } ] }; util.inspect(nestedObj2, {}).should.eql( '{ foo: \'bar\', foobar: 1, func: [ { a: [Function: a] } ] }'); }); it('with default breakLength at exact break point', () => { const obj = { foo: '', foobar: 1, something: '1', whatever: '', whatever2: '', whatever3: '' }; util.inspect(obj).should.eql('{\n foo: \'\',\n foobar: 1,\n something: \'1\',\n whatever: \'\',\n whatever2: \'\',\n whatever3: \'\'\n}'); }); it('with default breakLength just below break point', () => { const obj = { foo: '', foobar: 1, something: '1', whatever: '', whatever2: '' }; util.inspect(obj).should.eql('{ foo: \'\', foobar: 1, something: \'1\', whatever: \'\', whatever2: \'\' }'); }); }); describe('#inherits()', () => { it('is a function', () => { util.inherits.should.be.a.Function; }); it('hooks subclass to super constructor', (finished) => { function BaseClass() { this.listeners = {}; } BaseClass.prototype.on = function (eventName, listener) { const eventListeners = this.listeners[eventName] || []; eventListeners.push(listener); this.listeners[eventName] = eventListeners; }; BaseClass.prototype.emit = function (eventName, data) { const eventListeners = this.listeners[eventName] || []; for (const listener of eventListeners) { listener.call(this, data); } }; function MyStream() { BaseClass.call(this); } util.inherits(MyStream, BaseClass); MyStream.prototype.write = function (data) { this.emit('data', data); }; const stream = new MyStream(); should(stream instanceof BaseClass).eql(true); should(MyStream.super_).eql(BaseClass); stream.on('data', data => { data.should.eql('It works!'); finished(); }); stream.write('It works!'); // Received data: "It works!" }); it('throws TypeError if super constructor is null', () => { function BaseClass() { } function MyStream() { BaseClass.call(this); } should.throws(() => util.inherits(MyStream, null), TypeError ); }); it('throws TypeError if constructor is null', () => { function BaseClass() { } should.throws(() => util.inherits(null, BaseClass), TypeError ); }); it('throws TypeError if super constructor has no prototype', () => { const BaseClass = Object.create(null, {}); function MyStream() { BaseClass.call(this); } should.throws(() => util.inherits(MyStream, BaseClass), TypeError ); }); }); describe('#isArray', () => { it('should return true only if the given object is an Array', () => { should.strictEqual(util.isArray([]), true); should.strictEqual(util.isArray(Array()), true); should.strictEqual(util.isArray(new Array()), true); should.strictEqual(util.isArray(new Array(5)), true); should.strictEqual(util.isArray(new Array('with', 'some', 'entries')), true); should.strictEqual(util.isArray({}), false); should.strictEqual(util.isArray({ push: function () {} }), false); should.strictEqual(util.isArray(/regexp/), false); should.strictEqual(util.isArray(new Error()), false); should.strictEqual(util.isArray(Object.create(Array.prototype)), false); }); }); describe('#isRegExp', () => { it('should return true only if the given object is a RegExp', () => { should.strictEqual(util.isRegExp(/regexp/), true); should.strictEqual(util.isRegExp(RegExp(), 'foo'), true); should.strictEqual(util.isRegExp(new RegExp()), true); should.strictEqual(util.isRegExp({}), false); should.strictEqual(util.isRegExp([]), false); should.strictEqual(util.isRegExp(new Date()), false); should.strictEqual(util.isRegExp(Object.create(RegExp.prototype)), false); }); }); describe('#isDate', () => { it('should return true only if the given object is a Date', () => { should.strictEqual(util.isDate(new Date()), true); should.strictEqual(util.isDate(new Date(0), 'foo'), true); should.strictEqual(util.isDate(Date()), false); should.strictEqual(util.isDate({}), false); should.strictEqual(util.isDate([]), false); should.strictEqual(util.isDate(new Error()), false); should.strictEqual(util.isDate(Object.create(Date.prototype)), false); }); }); describe('#isError', () => { it('should return true only if the given object is an Error', () => { should.strictEqual(util.isError(new Error()), true); should.strictEqual(util.isError(new TypeError()), true); should.strictEqual(util.isError(new SyntaxError()), true); should.strictEqual(util.isError({}), false); should.strictEqual(util.isError({ name: 'Error', message: '' }), false); should.strictEqual(util.isError([]), false); should.strictEqual(util.isError(Object.create(Error.prototype)), true); }); }); describe('#isObject', () => { it('should return true only if the given object is an Object', () => { should.strictEqual(util.isObject({}), true); should.strictEqual(util.isObject([]), true); should.strictEqual(util.isObject(new Number(3)), true); should.strictEqual(util.isObject(Number(4)), false); should.strictEqual(util.isObject(1), false); }); }); describe('#isPrimitive', () => { it('should return true only if the given object is a primitve', () => { should.strictEqual(util.isPrimitive({}), false); should.strictEqual(util.isPrimitive(new Error()), false); should.strictEqual(util.isPrimitive(new Date()), false); should.strictEqual(util.isPrimitive([]), false); should.strictEqual(util.isPrimitive(/regexp/), false); should.strictEqual(util.isPrimitive(function () {}), false); should.strictEqual(util.isPrimitive(new Number(1)), false); should.strictEqual(util.isPrimitive(new String('bla')), false); should.strictEqual(util.isPrimitive(new Boolean(true)), false); should.strictEqual(util.isPrimitive(1), true); should.strictEqual(util.isPrimitive('bla'), true); should.strictEqual(util.isPrimitive(true), true); should.strictEqual(util.isPrimitive(undefined), true); should.strictEqual(util.isPrimitive(null), true); should.strictEqual(util.isPrimitive(Infinity), true); should.strictEqual(util.isPrimitive(NaN), true); should.strictEqual(util.isPrimitive(Symbol('symbol')), true); }); }); describe('#isBuffer', () => { it('should return true only if the given object is a Buffer', () => { should.strictEqual(util.isBuffer('foo'), false); should.strictEqual(util.isBuffer(Buffer.from('foo')), true); }); }); describe('#promisify()', () => { it('is a function', () => { util.promisify.should.be.a.Function; }); it('wraps callback function to return promise with resolve', (finished) => { function callbackOriginal(argOne, argTwo, next) { next(argOne, argTwo); } const promisified = util.promisify(callbackOriginal); const result = promisified(null, 123); should(result instanceof Promise).eql(true); result.then(value => { // eslint-disable-line promise/always-return should(value).eql(123); finished(); }).catch(err => finished(err)); }); it('wraps callback function to return promise with rejection', (finished) => { function callbackOriginal(argOne, argTwo, next) { next(argOne, argTwo); } const promisified = util.promisify(callbackOriginal); const result = promisified(new Error('example'), 123); should(result instanceof Promise).eql(true); result.then(value => { // eslint-disable-line promise/always-return should(value).eql(123); finished(new Error('Expected promise to get rejected!')); }).catch(err => { err.message.should.eql('example'); finished(); }); }); it('throws TypeError if original argument is not a function', () => { should.throws(() => util.promisify({}), TypeError ); }); }); describe('#callbackify()', () => { it('is a function', () => { util.callbackify.should.be.a.Function; }); it('wraps function returning Promise to return function accepting callback (with success)', (finished) => { function original(argOne) { return Promise.resolve(argOne); } const callbackified = util.callbackify(original); callbackified(23, (err, result) => { try { should(err).not.be.ok; should(result).eql(23); finished(); } catch (e) { finished(e); } }); }); it('wraps function returning Promise to return function accepting callback (with error)', (finished) => { function original(argOne) { return Promise.reject(argOne); } const callbackified = util.callbackify(original); callbackified(new Error('expected this'), (err, result) => { try { should(err).be.ok; should(result).not.be.ok; finished(); } catch (e) { finished(e); } }); }); it('handles special case of falsy rejection', (finished) => { function original() { return Promise.reject(null); } const callbackified = util.callbackify(original); callbackified((err, _result) => { try { should(err).be.ok; should(err instanceof Error).eql(true); should(err.reason).eql(null); finished(); } catch (e) { finished(e); } }); }); it('throws TypeError if original argument is not a function', () => { should.throws(() => util.callbackify({}), TypeError ); }); }); describe('#deprecate()', () => { it('is a function', () => { util.deprecate.should.be.a.Function; }); it('wraps function to emit warning', () => { function original(...args) { return args; } const deprecated = util.deprecate(original, 'dont call me Al'); // this should get called synchronously, so I don't think we need to do any setTimeout/async finished stuff process.on('warning', warning => { warning.name.should.eql('DeprecationWarning'); warning.message.should.eql('dont call me Al'); }); const result = deprecated(null, 123); should(result).eql([ null, 123 ]); }); // TODO: Test that we return original function if process.noDeprecation is true! }); describe('#log()', () => { it('is a function', () => { util.log.should.be.a.Function; }); it('prepends timestamp to message', () => { // Hijack console.log! NOTE: This doesn't work on iOS until we move to obj-c API! const original = console.log; try { console.log = string => { string.should.match(/^\d{1,2} \w{3} \d{2}:\d{2}:\d{2} - message$/); }; util.log('message'); } finally { console.log = original; } }); }); describe('#print()', () => { it('is a function', () => { util.print.should.be.a.Function; }); it('concatenates with no join', () => { // Hijack console.log! NOTE: This doesn't work on iOS until we move to obj-c API! const original = console.log; try { console.log = string => { string.should.eql('123'); }; util.print(1, 2, 3); } finally { console.log = original; } }); }); describe('#puts()', () => { it('is a function', () => { util.puts.should.be.a.Function; }); it('concatenates with newline join', () => { // Hijack console.log! NOTE: This doesn't work on iOS until we move to obj-c API! const original = console.log; try { console.log = string => { string.should.eql('1\n2\n3'); }; util.puts(1, 2, 3); } finally { console.log = original; } }); }); describe('#debug()', () => { it('is a function', () => { util.debug.should.be.a.Function; }); it('concatenates with newline join', () => { // Hijack console.error! NOTE: This doesn't work on iOS until we move to obj-c API! const original = console.error; try { console.error = string => { string.should.eql('DEBUG: message'); }; util.debug('message'); } finally { console.error = original; } }); }); describe('#error()', () => { it('is a function', () => { util.error.should.be.a.Function; }); it('concatenates with newline join', () => { // Hijack console.error! NOTE: This doesn't work on iOS until we move to obj-c API! const original = console.error; try { console.error = string => { string.should.eql('1\n2\n3'); }; util.error(1, 2, 3); } finally { console.error = original; } }); }); describe('.types', () => { describe('#isAnyArrayBuffer()', () => { it('should return true for built-in ArrayBuffer', () => { const ab = new ArrayBuffer(); util.types.isAnyArrayBuffer(ab).should.be.true; }); it.skip('should return true for built-in SharedArrayBuffer', () => { // SharedArrayBuffer is disabled in all major JS engines due to Spectre & Meltrdown vulnerabilities }); it('should return false for other values', () => { util.types.isAnyArrayBuffer({}).should.be.false; util.types.isAnyArrayBuffer(new Float32Array()).should.be.false; }); }); describe('#isArgumentsObject()', () => { it('should return true for function arguments object', () => { (function () { util.types.isArgumentsObject(arguments).should.be.true; }()); }); it('should return false for other values', () => { util.types.isArgumentsObject([]).should.be.false; util.types.isArgumentsObject({ [Symbol.toStringTag]: 'Arguments' }).should.be.false; }); }); describe('#isArrayBuffer()', () => { it('should return true for built-in ArrayBuffer instance', () => { const ab = new ArrayBuffer(); util.types.isArrayBuffer(ab).should.be.true; }); it('should return false for other values', () => { util.types.isArrayBuffer([]).should.be.false; util.types.isArrayBuffer(new Float32Array()).should.be.false; }); }); describe('#isAsyncFunction()', () => { it('should return true for async functions', () => { util.types.isAsyncFunction(async () => {}).should.be.true; }); it('should return false for normal functions', () => { util.types.isAsyncFunction(() => {}).should.be.true; }); }); describe('#isNativeError()', () => { it('is a function', () => { util.types.isNativeError.should.be.a.Function; }); it('returns true for Error instance', () => { util.types.isNativeError(new Error()).should.eql(true); }); it('returns true for EvalError instance', () => { util.types.isNativeError(new EvalError()).should.eql(true); }); it('returns true for RangeError instance', () => { util.types.isNativeError(new RangeError()).should.eql(true); }); it('returns true for ReferenceError instance', () => { util.types.isNativeError(new ReferenceError()).should.eql(true); }); it('returns true for SyntaxError instance', () => { util.types.isNativeError(new SyntaxError()).should.eql(true); }); it('returns true for TypeError instance', () => { util.types.isNativeError(new TypeError()).should.eql(true); }); it('returns true for URIError instance', () => { util.types.isNativeError(new URIError()).should.eql(true); }); it('returns false for custom Error subclass', () => { class SubError extends Error {} util.types.isNativeError(new SubError()).should.eql(false); }); }); describe('#isNumberObject()', () => { it('is a function', () => { util.types.isNumberObject.should.be.a.Function; }); it('returns true for boxed Number', () => { // eslint-disable-next-line no-new-wrappers util.types.isNumberObject(new Number()).should.eql(true); }); it('returns false for primitive Number', () => { util.types.isNumberObject(0).should.eql(false); }); }); describe('#isStringObject()', () => { it('is a function', () => { util.types.isStringObject.should.be.a.Function; }); it('returns true for boxed String', () => { // eslint-disable-next-line no-new-wrappers util.types.isStringObject(new String('foo')).should.eql(true); }); it('returns false for primitive String', () => { util.types.isStringObject('foo').should.eql(false); }); }); describe('#isBooleanObject()', () => { it('is a function', () => { util.types.isBooleanObject.should.be.a.Function; }); it('returns true for boxed Boolean', () => { // eslint-disable-next-line no-new-wrappers util.types.isBooleanObject(new Boolean(false)).should.eql(true); }); it('returns false for primitive Boolean', () => { util.types.isBooleanObject(true).should.eql(false); }); }); // TODO: Re-enable when we have BigInt support // describe('#isBigIntObject()', () => { // it('is a function', () => { // util.types.isBigIntObject.should.be.a.Function; // }); // it('returns true for boxed BigInt', () => { // // eslint-disable-next-line no-new-wrappers,no-undef // util.types.isSymbolObject(Object(BigInt(9007199254740991))).should.eql(true); // }); // it('returns false for BigInt instance', () => { // // eslint-disable-next-line no-undef // util.types.isSymbolObject(BigInt(9007199254740991)).should.eql(false); // }); // it('returns false for primitive BigInt', () => { // util.types.isSymbolObject(9007199254740991n).should.eql(false); // }); // }); describe('#isSymbolObject()', () => { it('is a function', () => { util.types.isSymbolObject.should.be.a.Function; }); it('returns true for boxed Symbol', () => { // eslint-disable-next-line no-new-wrappers util.types.isSymbolObject(Object(Symbol('foo'))).should.eql(true); }); it('returns false for primitive Symbol', () => { util.types.isSymbolObject(Symbol('foo')).should.eql(false); }); }); describe('#isBoxedPrimitive()', () => { it('is a function', () => { util.types.isBoxedPrimitive.should.be.a.Function; }); it('returns false for primitive Boolean', () => { util.types.isBoxedPrimitive(false).should.eql(false); }); it('returns true for boxed Boolean', () => { // eslint-disable-next-line no-new-wrappers util.types.isBoxedPrimitive(new Boolean(false)).should.eql(true); }); it('returns false for primitive Symbol', () => { util.types.isBoxedPrimitive(Symbol('foo')).should.eql(false); }); it('returns true for boxed Symbol', () => { util.types.isBoxedPrimitive(Object(Symbol('foo'))).should.eql(true); }); // it('returns true for boxed BigInt', () => { // // eslint-disable-next-line no-undef // util.types.isBoxedPrimitive(Object(BigInt(5))).should.eql(true); // }); }); describe('#isSet()', () => { it('is a function', () => { util.types.isSet.should.be.a.Function; }); it('returns true for Set instance', () => { util.types.isSet(new Set()).should.eql(true); }); }); describe('#isSetIterator()', () => { it('should return true if the value is an iterator returned for a built-in Set instance', () => { const set = new Set(); util.types.isSetIterator(set.keys()).should.be.true; util.types.isSetIterator(set.values()).should.be.true; util.types.isSetIterator(set.entries()).should.be.true; util.types.isSetIterator(set[Symbol.iterator]()).should.be.true; }); it('should return false for other iterators', () => { const map = new Map(); util.types.isSetIterator(map.values()).should.be.false; }); }); describe('#isMap()', () => { it('is a function', () => { util.types.isMap.should.be.a.Function; }); it('returns true for Map instance', () => { util.types.isMap(new Map()).should.eql(true); }); }); describe('#isMapIterator()', () => { it('should return true if the value is an iterator retunred for a built-in Map instance', () => { const map = new Map(); util.types.isMapIterator(map.keys()).should.be.true; util.types.isMapIterator(map.values()).should.be.true; util.types.isMapIterator(map.entries()).should.be.true; util.types.isMapIterator(map[Symbol.iterator]()).should.be.true; }); it('should return false for other iterators', () => { const set = new Set(); util.types.isMapIterator(set.values()).should.be.false; }); }); describe('#isDataView()', () => { const ab = new ArrayBuffer(20); it('should return true for built-in DataView instance', () => { util.types.isDataView(new DataView(ab)).should.be.true; }); it('should return false for typed array instance', () => { util.types.isDataView(new Float64Array()).should.be.false; }); }); describe('#isDate()', () => { it('is a function', () => { util.types.isDate.should.be.a.Function; }); it('returns true for built-in Date instance', () => { util.types.isDate(new Date()).should.eql(true); }); }); describe('#isPromise()', () => { it('should return true for built-in Promise', () => { util.types.isPromise(Promise.resolve(42)).should.be.true; }); it('should return false for Promise like objects', () => { util.types.isPromise({ then: () => {}, catch: () => {} }).should.be.false; }); }); describe('#isRegExp()', () => { it('is a function', () => { util.types.isRegExp.should.be.a.Function; }); it('returns true for RegExp instance', () => { util.types.isRegExp(/abc/).should.eql(true); }); it('returns true for RegExp primitive', () => { util.types.isRegExp(new RegExp('abc')).should.eql(true); }); }); describe('#isGeneratorFunction()', () => { it('should return true for generator function', () => { util.types.isGeneratorFunction(function *foo() {}).should.be.true; }); it('should return false for normal function', () => { util.types.isGeneratorFunction(function foo() {}).should.be.false; }); }); describe('#isGeneratorObject()', () => { it('should return true for generator object', () => { function *foo() {} const generator = foo(); util.types.isGeneratorObject(generator).should.be.true; }); it('should return false for any other object', () => { util.types.isGeneratorObject({}).should.be.false; }); }); describe('#isWeakMap()', () => { it('should return true for built-in WeakMap', () => { const map = new WeakMap(); util.types.isWeakMap(map).should.be.true; }); it('should return false for other values', () => { util.types.isWeakMap({}).should.be.false; util.types.isWeakMap(new Map()).should.be.false; }); }); describe('#isWeakSet()', () => { it('should return true for built-in WeakSet', () => { const map = new WeakSet(); util.types.isWeakSet(map).should.be.true; }); it('should return false for other values', () => { util.types.isWeakSet({}).should.be.false; util.types.isWeakSet(new Set()).should.be.false; }); }); describe('#isTypedArray()', () => { it('should return true for built-in typed arrays', () => { should(util.types.isTypedArray(new Uint8Array())).be.true; should(util.types.isTypedArray(new Uint8ClampedArray())).be.true; should(util.types.isTypedArray(new Uint16Array())).be.true; should(util.types.isTypedArray(new Uint32Array())).be.true; should(util.types.isTypedArray(new Int8Array())).be.true; should(util.types.isTypedArray(new Int16Array())).be.true; should(util.types.isTypedArray(new Int32Array())).be.true; should(util.types.isTypedArray(new Float32Array())).be.true; should(util.types.isTypedArray(new Float64Array())).be.true; }); it('should return true for our own Buffer', () => { should(util.types.isTypedArray(Buffer.alloc())).be.true; }); it('should return false for other values', () => { util.types.isTypedArray({}).should.be.false; util.types.isTypedArray([]).should.be.false; }); }); describe('Typed Arrays', () => { it('should correctly check typed arrays', () => { should(!util.types.isUint8Array({ [Symbol.toStringTag]: 'Uint8Array' })).be.true; should(util.types.isUint8Array(new Uint8Array())).be.true; should(!util.types.isUint8ClampedArray({ [Symbol.toStringTag]: 'Uint8ClampedArray' })).be.true; should(util.types.isUint8ClampedArray(new Uint8ClampedArray())).be.true; should(!util.types.isUint16Array({ [Symbol.toStringTag]: 'Uint16Array' })).be.true; should(util.types.isUint16Array(new Uint16Array())).be.true; should(!util.types.isUint32Array({ [Symbol.toStringTag]: 'Uint32Array' })).be.true; should(util.types.isUint32Array(new Uint32Array())).be.true; should(!util.types.isInt8Array({ [Symbol.toStringTag]: 'Int8Array' })).be.true; should(util.types.isInt8Array(new Int8Array())).be.true; should(!util.types.isInt16Array({ [Symbol.toStringTag]: 'Int16Array' })).be.true; should(util.types.isInt16Array(new Int16Array())).be.true; should(!util.types.isInt32Array({ [Symbol.toStringTag]: 'Int32Array' })).be.true; should(util.types.isInt32Array(new Int32Array())).be.true; should(!util.types.isFloat32Array({ [Symbol.toStringTag]: 'Float32Array' })).be.true; should(util.types.isFloat32Array(new Float32Array())).be.true; should(!util.types.isFloat64Array({ [Symbol.toStringTag]: 'Float64Array' })).be.true; should(util.types.isFloat64Array(new Float64Array())).be.true; /* @todo enable when we have BigInt64 support should(!util.types.isBigInt64Array({ [Symbol.toStringTag]: 'BigInt64Array' })).be.true; should(util.types.isBigInt64Array(new BigInt64Array)).be.true; should(!util.types.isBigUint64Array({ [Symbol.toStringTag]: 'BigUint64Array' })).be.true; should(util.types.isBigUint64Array(new BigUint64Array)).be.true; */ }); }); }); });
test(util): update format tests to pass on ios and android
tests/Resources/util.test.js
test(util): update format tests to pass on ios and android
<ide><path>ests/Resources/util.test.js <ide> /* eslint no-new-wrappers: "off" */ <ide> <ide> const should = require('./utilities/assertions'); <add>const utilities = require('./utilities/utilities'); <ide> <ide> let util; <ide> <ide> util.format('%o', obj).should.eql('{ foo: \'bar\' }'); <ide> }); <ide> <add> // FIXME: JSC/iOS seems to have inconsistent ordering of properties <add> // First time around, it tends to go: arguments, caller, length, name, prototype. <add> // Android/V8 is consistent <add> // The property order is not consistent on iOS, which is kind of expected <add> // since internally Object.getOwnPropertyNames is used, which does not <add> // guarantee a specific order of returned property names. <add> // On Android the order seems to be consistent <ide> it('with object', () => { <ide> const obj = { <ide> foo: 'bar', <ide> foobar: 1, <ide> func: function () {} <ide> }; <del> util.format('%o', obj).should.eql( <del> '{\n' <del> + ' foo: \'bar\',\n' <del> + ' foobar: 1,\n' <del> + ' func: <ref *1> [Function: func] {\n' <del> + ' [arguments]: null,\n' <del> + ' [caller]: null,\n' <del> + ' [length]: 0,\n' <del> + ' [name]: \'func\',\n' <del> + ' [prototype]: func { [constructor]: [Circular *1] }\n' <del> + ' }\n' <del> + '}' <del> ); <add> const result = util.format('%o', obj); <add> if (utilities.isAndroid()) { // Android/V8 <add> result.should.eql( <add> '{\n' <add> + ' foo: \'bar\',\n' <add> + ' foobar: 1,\n' <add> + ' func: <ref *1> [Function: func] {\n' <add> + ' [length]: 0,\n' <add> + ' [name]: \'func\',\n' <add> + ' [arguments]: null,\n' <add> + ' [caller]: null,\n' <add> + ' [prototype]: func { [constructor]: [Circular *1] }\n' <add> + ' }\n' <add> + '}' <add> ); <add> } else { // iOS/JSC <add> result.should.eql( <add> '{\n' <add> + ' foo: \'bar\',\n' <add> + ' foobar: 1,\n' <add> + ' func: <ref *1> [Function: func] {\n' <add> + ' [arguments]: null,\n' <add> + ' [caller]: null,\n' <add> + ' [length]: 0,\n' <add> + ' [name]: \'func\',\n' <add> + ' [prototype]: func { [constructor]: [Circular *1] }\n' <add> + ' }\n' <add> + '}' <add> ); <add> } <ide> }); <ide> <ide> it('with nested object', () => { <ide> foobar: 1, <ide> func: [ { a: function () {} } ] <ide> }; <del> util.format('%o', nestedObj2).should.eql( <del> '{\n' <del> + ' foo: \'bar\',\n' <del> + ' foobar: 1,\n' <del> + ' func: [\n' <del> + ' {\n' <del> + ' a: <ref *1> [Function: a] {\n' <del> + ' [arguments]: null,\n' <del> + ' [caller]: null,\n' <del> + ' [length]: 0,\n' <del> + ' [name]: \'a\',\n' <del> + ' [prototype]: a { [constructor]: [Circular *1] }\n' <del> + ' }\n' <del> + ' },\n' <del> + ' [length]: 1\n' <del> + ' ]\n' <del> + '}' <del> ); <del> }); <del> <del> // The property order is not consistent on iOS, which is kind of expected <del> // since internally Object.getOwnPropertyNames is used, which does not <del> // guarantee a specific order of returned property names. <del> // On Android the order seems to be consistent <del> it.iosBroken('with same object twice', () => { <add> const result = util.format('%o', nestedObj2); <add> if (utilities.isAndroid()) { // Android/V8 <add> result.should.eql( <add> '{\n' <add> + ' foo: \'bar\',\n' <add> + ' foobar: 1,\n' <add> + ' func: [\n' <add> + ' {\n' <add> + ' a: <ref *1> [Function: a] {\n' <add> + ' [length]: 0,\n' <add> + ' [name]: \'a\',\n' <add> + ' [arguments]: null,\n' <add> + ' [caller]: null,\n' <add> + ' [prototype]: a { [constructor]: [Circular *1] }\n' <add> + ' }\n' <add> + ' },\n' <add> + ' [length]: 1\n' <add> + ' ]\n' <add> + '}' <add> ); <add> } else { // iOS/JSC <add> result.should.eql( <add> '{\n' <add> + ' foo: \'bar\',\n' <add> + ' foobar: 1,\n' <add> + ' func: [\n' <add> + ' {\n' <add> + ' a: <ref *1> [Function: a] {\n' <add> + ' [arguments]: null,\n' <add> + ' [caller]: null,\n' <add> + ' [length]: 0,\n' <add> + ' [name]: \'a\',\n' <add> + ' [prototype]: a { [constructor]: [Circular *1] }\n' <add> + ' }\n' <add> + ' },\n' <add> + ' [length]: 1\n' <add> + ' ]\n' <add> + '}' <add> ); <add> } <add> }); <add> <add> it('with same object twice', () => { <ide> const obj = { <ide> foo: 'bar', <ide> foobar: 1, <ide> func: function () {} <ide> }; <del> util.format('%o %o', obj, obj).should.eql( <del> '{\n' <del> + ' foo: \'bar\',\n' <del> + ' foobar: 1,\n' <del> + ' func: <ref *1> [Function: func] {\n' <del> + ' [arguments]: null,\n' <del> + ' [caller]: null,\n' <del> + ' [length]: 0,\n' <del> + ' [name]: \'func\',\n' <del> + ' [prototype]: func { [constructor]: [Circular *1] }\n' <del> + ' }\n' <del> + '} {\n' <del> + ' foo: \'bar\',\n' <del> + ' foobar: 1,\n' <del> + ' func: <ref *1> [Function: func] {\n' <del> + ' [arguments]: null,\n' <del> + ' [caller]: null,\n' <del> + ' [length]: 0,\n' <del> + ' [name]: \'func\',\n' <del> + ' [prototype]: func { [constructor]: [Circular *1] }\n' <del> + ' }\n' <del> + '}' <del> ); <add> const result = util.format('%o %o', obj, obj); <add> if (utilities.isAndroid()) { // Android/V8 <add> result.should.eql( <add> '{\n' <add> + ' foo: \'bar\',\n' <add> + ' foobar: 1,\n' <add> + ' func: <ref *1> [Function: func] {\n' <add> + ' [length]: 0,\n' <add> + ' [name]: \'func\',\n' <add> + ' [arguments]: null,\n' <add> + ' [caller]: null,\n' <add> + ' [prototype]: func { [constructor]: [Circular *1] }\n' <add> + ' }\n' <add> + '} {\n' <add> + ' foo: \'bar\',\n' <add> + ' foobar: 1,\n' <add> + ' func: <ref *1> [Function: func] {\n' <add> + ' [length]: 0,\n' <add> + ' [name]: \'func\',\n' <add> + ' [arguments]: null,\n' <add> + ' [caller]: null,\n' <add> + ' [prototype]: func { [constructor]: [Circular *1] }\n' <add> + ' }\n' <add> + '}' <add> ); <add> } else { // iOS/JSC <add> result.should.eql( <add> '{\n' <add> + ' foo: \'bar\',\n' <add> + ' foobar: 1,\n' <add> + ' func: <ref *1> [Function: func] {\n' <add> + ' [arguments]: null,\n' <add> + ' [caller]: null,\n' <add> + ' [length]: 0,\n' <add> + ' [name]: \'func\',\n' <add> + ' [prototype]: func { [constructor]: [Circular *1] }\n' <add> + ' }\n' <add> + '} {\n' <add> + ' foo: \'bar\',\n' <add> + ' foobar: 1,\n' <add> + ' func: <ref *1> [Function: func] {\n' <add> + ' [arguments]: null,\n' <add> + ' [caller]: null,\n' <add> + ' [prototype]: func { [constructor]: [Circular *1] },\n' <add> + ' [name]: \'func\',\n' <add> + ' [length]: 0\n' <add> + ' }\n' <add> + '}' <add> ); <add> } <ide> }); <ide> }); <ide> });
JavaScript
mit
02758a68ce3ad015bf8522e60b6f808a6c91021f
0
withlovee/instamarket-meanjs,withlovee/instamarket-meanjs,withlovee/instamarket-meanjs
'use strict'; /** * Module dependencies. */ var path = require('path'), mongoose = require('mongoose'), Shop = mongoose.model('Shop'), errorHandler = require(path.resolve('./modules/core/server/controllers/errors.server.controller')); /** * Show the current shop */ exports.read = function (req, res) { res.json(req.shop); }; /** * List of Shops */ exports.list = function (req, res) { Shop.find({is_shop: 1}).limit(100).exec(function (err, shops) { // Shop.find().sort('-created').limit(10).populate('user', 'displayName').exec(function (err, shops) { if (err) { return res.status(400).send({ message: errorHandler.getErrorMessage(err) }); } else { res.json(shops); } }); }; exports.list_by_category = function (req, res, next, category) { Shop.find({ is_shop: 1, bio: new RegExp(category, 'i') }).limit(200).exec(function (err, shops) { // Shop.find().sort('-created').limit(10).populate('user', 'displayName').exec(function (err, shops) { if (err) { return res.status(400).send({ message: errorHandler.getErrorMessage(err) }); } else { res.json(shops); } }); }; /** * Shop middleware */ exports.shopByID = function (req, res, next, id) { if (!mongoose.Types.ObjectId.isValid(id)) { return res.status(400).send({ message: 'Shop is invalid' }); } Shop.findById(id).populate('user', 'displayName').exec(function (err, shop) { if (err) { return next(err); } else if (!shop) { return res.status(404).send({ message: 'No shop with that identifier has been found' }); } req.shop = shop; next(); }); };
modules/shops/server/controllers/shops.server.controller.js
'use strict'; /** * Module dependencies. */ var path = require('path'), mongoose = require('mongoose'), Shop = mongoose.model('Shop'), errorHandler = require(path.resolve('./modules/core/server/controllers/errors.server.controller')); /** * Show the current shop */ exports.read = function (req, res) { res.json(req.shop); }; /** * List of Shops */ exports.list = function (req, res) { Shop.find({is_shop: 1}).limit(100).exec(function (err, shops) { // Shop.find().sort('-created').limit(10).populate('user', 'displayName').exec(function (err, shops) { if (err) { return res.status(400).send({ message: errorHandler.getErrorMessage(err) }); } else { res.json(shops); } }); }; exports.list_by_category = function (req, res, next, category) { Shop.find({ is_shop: 1, bio: new RegExp(category, 'i') }).limit(10).exec(function (err, shops) { // Shop.find().sort('-created').limit(10).populate('user', 'displayName').exec(function (err, shops) { if (err) { return res.status(400).send({ message: errorHandler.getErrorMessage(err) }); } else { res.json(shops); } }); }; /** * Shop middleware */ exports.shopByID = function (req, res, next, id) { if (!mongoose.Types.ObjectId.isValid(id)) { return res.status(400).send({ message: 'Shop is invalid' }); } Shop.findById(id).populate('user', 'displayName').exec(function (err, shop) { if (err) { return next(err); } else if (!shop) { return res.status(404).send({ message: 'No shop with that identifier has been found' }); } req.shop = shop; next(); }); };
Edit results limitation
modules/shops/server/controllers/shops.server.controller.js
Edit results limitation
<ide><path>odules/shops/server/controllers/shops.server.controller.js <ide> Shop.find({ <ide> is_shop: 1, <ide> bio: new RegExp(category, 'i') <del> }).limit(10).exec(function (err, shops) { <add> }).limit(200).exec(function (err, shops) { <ide> // Shop.find().sort('-created').limit(10).populate('user', 'displayName').exec(function (err, shops) { <ide> if (err) { <ide> return res.status(400).send({
JavaScript
apache-2.0
96a0ab15a0f52836048d1846015522d0359881f8
0
google/blockly-devtools,google/blockly-devtools
/** * Blockly DevTools * * Copyright 2017 Google Inc. * https://developers.google.com/blockly/ * * 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. */ /* * @fileoverview This file attempts to import all the library files and class * files used by Blockly DevTools in the correct order. It is a crude * solution to dealing with the incompatible mix of node requires(), Closure * goog.requires(), and app specific local libraries in the browser-like * (but not quite a browser) context. */ (function() { var appendScript = function(src) { document.write(`<script src="${src}"></script>`); }; var appendStylesheet = function(src) { document.write(`<link rel="stylesheet" href="${src}">`); }; appendScript('node_modules/jquery/dist/jquery.min.js'); // TODO: Replace with local NPM managed file. https://www.npmjs.com/package/google-code-prettify appendScript('https://cdn.rawgit.com/google/code-prettify/master/loader/run_prettify.js'); appendScript('lib/blockly_compressed.js'); appendScript('msg/js/en.js'); appendScript('lib/blocks_compressed.js'); appendScript('closure-library/closure/goog/base.js'); // Must be after Blockly appendScript('src/factory_utils.js'); appendScript('src/list_element.js'); appendScript('res/standard_categories.js'); appendScript('src/workspacefactory/wfactory_model.js'); appendScript('res/devtools_toolboxes.js'); appendScript('src/block_option.js'); appendScript('src/model/resource.js'); appendScript('src/model/block_definition.js'); appendScript('src/view/navigation_tree.js'); appendScript('src/model/block_library.js'); appendScript('src/model/workspace_configuration.js'); appendScript('src/model/workspace_contents.js'); appendScript('src/model/toolbox.js'); appendScript('src/model/resource_set.js'); appendScript('src/model/toolbox_set.js'); appendScript('src/model/block_library_set.js'); appendScript('src/model/workspace_configuration_set.js'); appendScript('src/model/workspace_contents_set.js'); appendScript('src/model/project.js'); appendScript('src/controller/block_editor_controller.js'); appendScript('src/controller/popup_controller.js'); appendScript('src/controller/toolbox_controller.js'); appendScript('src/controller/workspace_controller.js'); appendScript('src/controller/project_controller.js'); appendScript('src/controller/editor_controller.js'); appendScript('src/new_block_dialog_controller.js'); appendScript('src/controller/app_controller_2.js'); appendScript('src/view/block_editor_view.js'); appendScript('src/view/app_view.js'); appendScript('src/new_block_dialog_view.js'); appendScript('src/view/toolbox_editor_view.js'); appendScript('src/view/workspace_editor_view.js'); appendScript('node_modules/jstree/dist/jstree.min.js'); appendStylesheet('src/factory.css'); appendStylesheet('node_modules/jstree/dist/themes/default/style.min.css'); })();
src/all_libs_classes_stylesheets.js
/** * Blockly DevTools * * Copyright 2017 Google Inc. * https://developers.google.com/blockly/ * * 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. */ /* * @fileoverview This file attempts to import all the library files and class * files used by Blockly DevTools in the correct order. It is a crude * solution to dealing with the incompatible mix of node requires(), Closure * goog.requires(), and app specific local libraries in the browser-like * (but not quite a browser) context. */ (function() { var appendScript = function(src) { document.write(`<script src="${src}"></script>`); }; var appendStylesheet = function(src) { document.write(`<link rel="stylesheet" href="${src}">`); }; appendScript('node_modules/jquery/dist/jquery.min.js'); // TODO: Replace with local NPM managed file. https://www.npmjs.com/package/google-code-prettify appendScript('https://cdn.rawgit.com/google/code-prettify/master/loader/run_prettify.js'); appendScript('lib/blockly_compressed.js'); appendScript('msg/js/en.js'); appendScript('lib/blocks_compressed.js'); appendScript('closure-library/closure/goog/base.js'); // Must be after Blockly appendScript('src/factory_utils.js'); appendScript('src/list_element.js'); appendScript('res/standard_categories.js'); appendScript('src/workspacefactory/wfactory_model.js'); appendScript('res/devtools_toolboxes.js'); appendScript('src/block_option.js'); /* appendScript('src/workspacefactory/wfactory_controller.js'); appendScript('src/workspacefactory/wfactory_generator.js'); appendScript('src/block_library_view.js'); appendScript('src/workspacefactory/wfactory_view.js'); appendScript('src/workspacefactory/wfactory_generator.js'); appendScript('src/workspacefactory/wfactory_init.js'); appendScript('src/factory.js'); appendScript('src/block_library_storage.js'); appendScript('src/block_library_controller.js'); appendScript('src/block_exporter_tools.js'); appendScript('src/block_exporter_view.js'); appendScript('src/block_exporter_controller.js'); appendScript('src/blocks.js'); */ appendScript('src/model/resource.js'); appendScript('src/model/block_definition.js'); appendScript('src/view/navigation_tree.js'); appendScript('src/model/block_library.js'); appendScript('src/model/workspace_configuration.js'); appendScript('src/model/workspace_contents.js'); appendScript('src/model/toolbox.js'); appendScript('src/model/resource_set.js'); appendScript('src/model/toolbox_set.js'); appendScript('src/model/block_library_set.js'); appendScript('src/model/workspace_configuration_set.js'); appendScript('src/model/workspace_contents_set.js'); appendScript('src/model/project.js'); appendScript('src/controller/block_editor_controller.js'); appendScript('src/controller/popup_controller.js'); appendScript('src/controller/toolbox_controller.js'); appendScript('src/controller/workspace_controller.js'); appendScript('src/controller/project_controller.js'); appendScript('src/controller/editor_controller.js'); appendScript('src/new_block_dialog_controller.js'); appendScript('src/controller/app_controller_2.js'); appendScript('src/view/block_editor_view.js'); appendScript('src/view/app_view.js'); appendScript('src/new_block_dialog_view.js'); appendScript('src/view/toolbox_editor_view.js'); appendScript('src/view/workspace_editor_view.js'); appendScript('node_modules/jstree/dist/jstree.min.js'); appendStylesheet('src/factory.css'); appendStylesheet('node_modules/jstree/dist/themes/default/style.min.css'); })();
Removed old file imports from import script
src/all_libs_classes_stylesheets.js
Removed old file imports from import script
<ide><path>rc/all_libs_classes_stylesheets.js <ide> appendScript('res/devtools_toolboxes.js'); <ide> appendScript('src/block_option.js'); <ide> <del>/* <del> appendScript('src/workspacefactory/wfactory_controller.js'); <del> appendScript('src/workspacefactory/wfactory_generator.js'); <del> appendScript('src/block_library_view.js'); <del> appendScript('src/workspacefactory/wfactory_view.js'); <del> appendScript('src/workspacefactory/wfactory_generator.js'); <del> appendScript('src/workspacefactory/wfactory_init.js'); <del> appendScript('src/factory.js'); <del> appendScript('src/block_library_storage.js'); <del> appendScript('src/block_library_controller.js'); <del> appendScript('src/block_exporter_tools.js'); <del> appendScript('src/block_exporter_view.js'); <del> appendScript('src/block_exporter_controller.js'); <del> appendScript('src/blocks.js'); <del>*/ <del> <ide> appendScript('src/model/resource.js'); <ide> appendScript('src/model/block_definition.js'); <ide> appendScript('src/view/navigation_tree.js');
Java
apache-2.0
bdb4a09ceaceab7e3d214b1beadb93bd9c911342
0
apache/commons-cli,apache/commons-cli,apache/commons-cli,apache/commons-cli
/** * 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.cli; import java.util.ArrayList; import java.util.Enumeration; import java.util.List; import java.util.Properties; /** * Default parser. * * @since 1.3 */ public class DefaultParser implements CommandLineParser { /** The command-line instance. */ protected CommandLine cmd; /** The current options. */ protected Options options; /** * Flag indicating how unrecognized tokens are handled. <tt>true</tt> to stop * the parsing and add the remaining tokens to the args list. * <tt>false</tt> to throw an exception. */ protected boolean stopAtNonOption; /** The token currently processed. */ protected String currentToken; /** The last option parsed. */ protected Option currentOption; /** Flag indicating if tokens should no longer be analyzed and simply added as arguments of the command line. */ protected boolean skipParsing; /** The required options and groups expected to be found when parsing the command line. */ protected List expectedOpts; /** Flag indicating if partial matching of long options is supported. */ private boolean allowPartialMatching; /** Creates a new DefaultParser instance with partial matching enabled. */ public DefaultParser() { this.allowPartialMatching = true; } /** * Create a new DefaultParser instance with the specified partial matching policy. * * @param allowPartialMatching if partial matching of long options shall be enabled */ public DefaultParser(final boolean allowPartialMatching) { this.allowPartialMatching = allowPartialMatching; } public CommandLine parse(final Options options, final String[] arguments) throws ParseException { return parse(options, arguments, null); } /** * Parse the arguments according to the specified options and properties. * * @param options the specified Options * @param arguments the command line arguments * @param properties command line option name-value pairs * @return the list of atomic option and value tokens * * @throws ParseException if there are any problems encountered * while parsing the command line tokens. */ public CommandLine parse(final Options options, final String[] arguments, final Properties properties) throws ParseException { return parse(options, arguments, properties, false); } public CommandLine parse(final Options options, final String[] arguments, final boolean stopAtNonOption) throws ParseException { return parse(options, arguments, null, stopAtNonOption); } /** * Parse the arguments according to the specified options and properties. * * @param options the specified Options * @param arguments the command line arguments * @param properties command line option name-value pairs * @param stopAtNonOption if <tt>true</tt> an unrecognized argument stops * the parsing and the remaining arguments are added to the * {@link CommandLine}s args list. If <tt>false</tt> an unrecognized * argument triggers a ParseException. * * @return the list of atomic option and value tokens * @throws ParseException if there are any problems encountered * while parsing the command line tokens. */ public CommandLine parse(final Options options, final String[] arguments, final Properties properties, final boolean stopAtNonOption) throws ParseException { this.options = options; this.stopAtNonOption = stopAtNonOption; skipParsing = false; currentOption = null; expectedOpts = new ArrayList(options.getRequiredOptions()); // clear the data from the groups for (final OptionGroup group : options.getOptionGroups()) { group.setSelected(null); } cmd = new CommandLine(); if (arguments != null) { for (final String argument : arguments) { handleToken(argument); } } // check the arguments of the last option checkRequiredArgs(); // add the default options handleProperties(properties); checkRequiredOptions(); return cmd; } /** * Sets the values of Options using the values in <code>properties</code>. * * @param properties The value properties to be processed. */ private void handleProperties(final Properties properties) throws ParseException { if (properties == null) { return; } for (final Enumeration<?> e = properties.propertyNames(); e.hasMoreElements();) { final String option = e.nextElement().toString(); final Option opt = options.getOption(option); if (opt == null) { throw new UnrecognizedOptionException("Default option wasn't defined", option); } // if the option is part of a group, check if another option of the group has been selected final OptionGroup group = options.getOptionGroup(opt); final boolean selected = group != null && group.getSelected() != null; if (!cmd.hasOption(option) && !selected) { // get the value from the properties final String value = properties.getProperty(option); if (opt.hasArg()) { if (opt.getValues() == null || opt.getValues().length == 0) { opt.addValueForProcessing(value); } } else if (!("yes".equalsIgnoreCase(value) || "true".equalsIgnoreCase(value) || "1".equalsIgnoreCase(value))) { // if the value is not yes, true or 1 then don't add the option to the CommandLine continue; } handleOption(opt); currentOption = null; } } } /** * Throws a {@link MissingOptionException} if all of the required options * are not present. * * @throws MissingOptionException if any of the required Options * are not present. */ protected void checkRequiredOptions() throws MissingOptionException { // if there are required options that have not been processed if (!expectedOpts.isEmpty()) { throw new MissingOptionException(expectedOpts); } } /** * Throw a {@link MissingArgumentException} if the current option * didn't receive the number of arguments expected. */ private void checkRequiredArgs() throws ParseException { if (currentOption != null && currentOption.requiresArg()) { throw new MissingArgumentException(currentOption); } } /** * Handle any command line token. * * @param token the command line token to handle * @throws ParseException */ private void handleToken(final String token) throws ParseException { currentToken = token; if (skipParsing) { cmd.addArg(token); } else if ("--".equals(token)) { skipParsing = true; } else if (currentOption != null && currentOption.acceptsArg() && isArgument(token)) { currentOption.addValueForProcessing(Util.stripLeadingAndTrailingQuotes(token)); } else if (token.startsWith("--")) { handleLongOption(token); } else if (token.startsWith("-") && !"-".equals(token)) { handleShortAndLongOption(token); } else { handleUnknownToken(token); } if (currentOption != null && !currentOption.acceptsArg()) { currentOption = null; } } /** * Returns true is the token is a valid argument. * * @param token */ private boolean isArgument(final String token) { return !isOption(token) || isNegativeNumber(token); } /** * Check if the token is a negative number. * * @param token */ private boolean isNegativeNumber(final String token) { try { Double.parseDouble(token); return true; } catch (final NumberFormatException e) { return false; } } /** * Tells if the token looks like an option. * * @param token */ private boolean isOption(final String token) { return isLongOption(token) || isShortOption(token); } /** * Tells if the token looks like a short option. * * @param token */ private boolean isShortOption(final String token) { // short options (-S, -SV, -S=V, -SV1=V2, -S1S2) if (!token.startsWith("-") || token.length() == 1) { return false; } // remove leading "-" and "=value" final int pos = token.indexOf("="); final String optName = pos == -1 ? token.substring(1) : token.substring(1, pos); if (options.hasShortOption(optName)) { return true; } // check for several concatenated short options return optName.length() > 0 && options.hasShortOption(String.valueOf(optName.charAt(0))); } /** * Tells if the token looks like a long option. * * @param token */ private boolean isLongOption(final String token) { if (!token.startsWith("-") || token.length() == 1) { return false; } final int pos = token.indexOf("="); final String t = pos == -1 ? token : token.substring(0, pos); if (!getMatchingLongOptions(t).isEmpty()) { // long or partial long options (--L, -L, --L=V, -L=V, --l, --l=V) return true; } else if (getLongPrefix(token) != null && !token.startsWith("--")) { // -LV return true; } return false; } /** * Handles an unknown token. If the token starts with a dash an * UnrecognizedOptionException is thrown. Otherwise the token is added * to the arguments of the command line. If the stopAtNonOption flag * is set, this stops the parsing and the remaining tokens are added * as-is in the arguments of the command line. * * @param token the command line token to handle */ private void handleUnknownToken(final String token) throws ParseException { if (token.startsWith("-") && token.length() > 1 && !stopAtNonOption) { throw new UnrecognizedOptionException("Unrecognized option: " + token, token); } cmd.addArg(token); if (stopAtNonOption) { skipParsing = true; } } /** * Handles the following tokens: * * --L * --L=V * --L V * --l * * @param token the command line token to handle */ private void handleLongOption(final String token) throws ParseException { if (token.indexOf('=') == -1) { handleLongOptionWithoutEqual(token); } else { handleLongOptionWithEqual(token); } } /** * Handles the following tokens: * * --L * -L * --l * -l * * @param token the command line token to handle */ private void handleLongOptionWithoutEqual(final String token) throws ParseException { final List<String> matchingOpts = getMatchingLongOptions(token); if (matchingOpts.isEmpty()) { handleUnknownToken(currentToken); } else if (matchingOpts.size() > 1 && !options.hasLongOption(token)) { throw new AmbiguousOptionException(token, matchingOpts); } else { final String key = options.hasLongOption(token) ? token : matchingOpts.get(0); handleOption(options.getOption(key)); } } /** * Handles the following tokens: * * --L=V * -L=V * --l=V * -l=V * * @param token the command line token to handle */ private void handleLongOptionWithEqual(final String token) throws ParseException { final int pos = token.indexOf('='); final String value = token.substring(pos + 1); final String opt = token.substring(0, pos); final List<String> matchingOpts = getMatchingLongOptions(opt); if (matchingOpts.isEmpty()) { handleUnknownToken(currentToken); } else if (matchingOpts.size() > 1 && !options.hasLongOption(opt)) { throw new AmbiguousOptionException(opt, matchingOpts); } else { final String key = options.hasLongOption(opt) ? opt : matchingOpts.get(0); final Option option = options.getOption(key); if (option.acceptsArg()) { handleOption(option); currentOption.addValueForProcessing(value); currentOption = null; } else { handleUnknownToken(currentToken); } } } /** * Handles the following tokens: * * -S * -SV * -S V * -S=V * -S1S2 * -S1S2 V * -SV1=V2 * * -L * -LV * -L V * -L=V * -l * * @param token the command line token to handle */ private void handleShortAndLongOption(final String token) throws ParseException { final String t = Util.stripLeadingHyphens(token); final int pos = t.indexOf('='); if (t.length() == 1) { // -S if (options.hasShortOption(t)) { handleOption(options.getOption(t)); } else { handleUnknownToken(token); } } else if (pos == -1) { // no equal sign found (-xxx) if (options.hasShortOption(t)) { handleOption(options.getOption(t)); } else if (!getMatchingLongOptions(t).isEmpty()) { // -L or -l handleLongOptionWithoutEqual(token); } else { // look for a long prefix (-Xmx512m) final String opt = getLongPrefix(t); if (opt != null && options.getOption(opt).acceptsArg()) { handleOption(options.getOption(opt)); currentOption.addValueForProcessing(t.substring(opt.length())); currentOption = null; } else if (isJavaProperty(t)) { // -SV1 (-Dflag) handleOption(options.getOption(t.substring(0, 1))); currentOption.addValueForProcessing(t.substring(1)); currentOption = null; } else { // -S1S2S3 or -S1S2V handleConcatenatedOptions(token); } } } else { // equal sign found (-xxx=yyy) final String opt = t.substring(0, pos); final String value = t.substring(pos + 1); if (opt.length() == 1) { // -S=V final Option option = options.getOption(opt); if (option != null && option.acceptsArg()) { handleOption(option); currentOption.addValueForProcessing(value); currentOption = null; } else { handleUnknownToken(token); } } else if (isJavaProperty(opt)) { // -SV1=V2 (-Dkey=value) handleOption(options.getOption(opt.substring(0, 1))); currentOption.addValueForProcessing(opt.substring(1)); currentOption.addValueForProcessing(value); currentOption = null; } else { // -L=V or -l=V handleLongOptionWithEqual(token); } } } /** * Search for a prefix that is the long name of an option (-Xmx512m) * * @param token */ private String getLongPrefix(final String token) { final String t = Util.stripLeadingHyphens(token); int i; String opt = null; for (i = t.length() - 2; i > 1; i--) { final String prefix = t.substring(0, i); if (options.hasLongOption(prefix)) { opt = prefix; break; } } return opt; } /** * Check if the specified token is a Java-like property (-Dkey=value). */ private boolean isJavaProperty(final String token) { final String opt = token.substring(0, 1); final Option option = options.getOption(opt); return option != null && (option.getArgs() >= 2 || option.getArgs() == Option.UNLIMITED_VALUES); } private void handleOption(Option option) throws ParseException { // check the previous option before handling the next one checkRequiredArgs(); option = (Option) option.clone(); updateRequiredOptions(option); cmd.addOption(option); if (option.hasArg()) { currentOption = option; } else { currentOption = null; } } /** * Removes the option or its group from the list of expected elements. * * @param option */ private void updateRequiredOptions(final Option option) throws AlreadySelectedException { if (option.isRequired()) { expectedOpts.remove(option.getKey()); } // if the option is in an OptionGroup make that option the selected option of the group if (options.getOptionGroup(option) != null) { final OptionGroup group = options.getOptionGroup(option); if (group.isRequired()) { expectedOpts.remove(group); } group.setSelected(option); } } /** * Returns a list of matching option strings for the given token, depending * on the selected partial matching policy. * * @param token the token (may contain leading dashes) * @return the list of matching option strings or an empty list if no matching option could be found */ private List<String> getMatchingLongOptions(final String token) { if (allowPartialMatching) { return options.getMatchingOptions(token); } else { List<String> matches = new ArrayList<String>(1); if (options.hasLongOption(token)) { Option option = options.getOption(token); matches.add(option.getLongOpt()); } return matches; } } /** * Breaks <code>token</code> into its constituent parts * using the following algorithm. * * <ul> * <li>ignore the first character ("<b>-</b>")</li> * <li>for each remaining character check if an {@link Option} * exists with that id.</li> * <li>if an {@link Option} does exist then add that character * prepended with "<b>-</b>" to the list of processed tokens.</li> * <li>if the {@link Option} can have an argument value and there * are remaining characters in the token then add the remaining * characters as a token to the list of processed tokens.</li> * <li>if an {@link Option} does <b>NOT</b> exist <b>AND</b> * <code>stopAtNonOption</code> <b>IS</b> set then add the special token * "<b>--</b>" followed by the remaining characters and also * the remaining tokens directly to the processed tokens list.</li> * <li>if an {@link Option} does <b>NOT</b> exist <b>AND</b> * <code>stopAtNonOption</code> <b>IS NOT</b> set then add that * character prepended with "<b>-</b>".</li> * </ul> * * @param token The current token to be <b>burst</b> * at the first non-Option encountered. * @throws ParseException if there are any problems encountered * while parsing the command line token. */ protected void handleConcatenatedOptions(final String token) throws ParseException { for (int i = 1; i < token.length(); i++) { final String ch = String.valueOf(token.charAt(i)); if (options.hasOption(ch)) { handleOption(options.getOption(ch)); if (currentOption != null && token.length() != i + 1) { // add the trail as an argument of the option currentOption.addValueForProcessing(token.substring(i + 1)); break; } } else { handleUnknownToken(stopAtNonOption && i > 1 ? token.substring(i) : token); break; } } } }
src/main/java/org/apache/commons/cli/DefaultParser.java
/** * 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.cli; import java.util.ArrayList; import java.util.Enumeration; import java.util.List; import java.util.Properties; /** * Default parser. * * @since 1.3 */ public class DefaultParser implements CommandLineParser { /** The command-line instance. */ protected CommandLine cmd; /** The current options. */ protected Options options; /** * Flag indicating how unrecognized tokens are handled. <tt>true</tt> to stop * the parsing and add the remaining tokens to the args list. * <tt>false</tt> to throw an exception. */ protected boolean stopAtNonOption; /** The token currently processed. */ protected String currentToken; /** The last option parsed. */ protected Option currentOption; /** Flag indicating if tokens should no longer be analyzed and simply added as arguments of the command line. */ protected boolean skipParsing; /** The required options and groups expected to be found when parsing the command line. */ protected List expectedOpts; public CommandLine parse(final Options options, final String[] arguments) throws ParseException { return parse(options, arguments, null); } /** * Parse the arguments according to the specified options and properties. * * @param options the specified Options * @param arguments the command line arguments * @param properties command line option name-value pairs * @return the list of atomic option and value tokens * * @throws ParseException if there are any problems encountered * while parsing the command line tokens. */ public CommandLine parse(final Options options, final String[] arguments, final Properties properties) throws ParseException { return parse(options, arguments, properties, false); } public CommandLine parse(final Options options, final String[] arguments, final boolean stopAtNonOption) throws ParseException { return parse(options, arguments, null, stopAtNonOption); } /** * Parse the arguments according to the specified options and properties. * * @param options the specified Options * @param arguments the command line arguments * @param properties command line option name-value pairs * @param stopAtNonOption if <tt>true</tt> an unrecognized argument stops * the parsing and the remaining arguments are added to the * {@link CommandLine}s args list. If <tt>false</tt> an unrecognized * argument triggers a ParseException. * * @return the list of atomic option and value tokens * @throws ParseException if there are any problems encountered * while parsing the command line tokens. */ public CommandLine parse(final Options options, final String[] arguments, final Properties properties, final boolean stopAtNonOption) throws ParseException { this.options = options; this.stopAtNonOption = stopAtNonOption; skipParsing = false; currentOption = null; expectedOpts = new ArrayList(options.getRequiredOptions()); // clear the data from the groups for (final OptionGroup group : options.getOptionGroups()) { group.setSelected(null); } cmd = new CommandLine(); if (arguments != null) { for (final String argument : arguments) { handleToken(argument); } } // check the arguments of the last option checkRequiredArgs(); // add the default options handleProperties(properties); checkRequiredOptions(); return cmd; } /** * Sets the values of Options using the values in <code>properties</code>. * * @param properties The value properties to be processed. */ private void handleProperties(final Properties properties) throws ParseException { if (properties == null) { return; } for (final Enumeration<?> e = properties.propertyNames(); e.hasMoreElements();) { final String option = e.nextElement().toString(); final Option opt = options.getOption(option); if (opt == null) { throw new UnrecognizedOptionException("Default option wasn't defined", option); } // if the option is part of a group, check if another option of the group has been selected final OptionGroup group = options.getOptionGroup(opt); final boolean selected = group != null && group.getSelected() != null; if (!cmd.hasOption(option) && !selected) { // get the value from the properties final String value = properties.getProperty(option); if (opt.hasArg()) { if (opt.getValues() == null || opt.getValues().length == 0) { opt.addValueForProcessing(value); } } else if (!("yes".equalsIgnoreCase(value) || "true".equalsIgnoreCase(value) || "1".equalsIgnoreCase(value))) { // if the value is not yes, true or 1 then don't add the option to the CommandLine continue; } handleOption(opt); currentOption = null; } } } /** * Throws a {@link MissingOptionException} if all of the required options * are not present. * * @throws MissingOptionException if any of the required Options * are not present. */ protected void checkRequiredOptions() throws MissingOptionException { // if there are required options that have not been processed if (!expectedOpts.isEmpty()) { throw new MissingOptionException(expectedOpts); } } /** * Throw a {@link MissingArgumentException} if the current option * didn't receive the number of arguments expected. */ private void checkRequiredArgs() throws ParseException { if (currentOption != null && currentOption.requiresArg()) { throw new MissingArgumentException(currentOption); } } /** * Handle any command line token. * * @param token the command line token to handle * @throws ParseException */ private void handleToken(final String token) throws ParseException { currentToken = token; if (skipParsing) { cmd.addArg(token); } else if ("--".equals(token)) { skipParsing = true; } else if (currentOption != null && currentOption.acceptsArg() && isArgument(token)) { currentOption.addValueForProcessing(Util.stripLeadingAndTrailingQuotes(token)); } else if (token.startsWith("--")) { handleLongOption(token); } else if (token.startsWith("-") && !"-".equals(token)) { handleShortAndLongOption(token); } else { handleUnknownToken(token); } if (currentOption != null && !currentOption.acceptsArg()) { currentOption = null; } } /** * Returns true is the token is a valid argument. * * @param token */ private boolean isArgument(final String token) { return !isOption(token) || isNegativeNumber(token); } /** * Check if the token is a negative number. * * @param token */ private boolean isNegativeNumber(final String token) { try { Double.parseDouble(token); return true; } catch (final NumberFormatException e) { return false; } } /** * Tells if the token looks like an option. * * @param token */ private boolean isOption(final String token) { return isLongOption(token) || isShortOption(token); } /** * Tells if the token looks like a short option. * * @param token */ private boolean isShortOption(final String token) { // short options (-S, -SV, -S=V, -SV1=V2, -S1S2) if (!token.startsWith("-") || token.length() == 1) { return false; } // remove leading "-" and "=value" final int pos = token.indexOf("="); final String optName = pos == -1 ? token.substring(1) : token.substring(1, pos); if (options.hasShortOption(optName)) { return true; } // check for several concatenated short options return optName.length() > 0 && options.hasShortOption(String.valueOf(optName.charAt(0))); } /** * Tells if the token looks like a long option. * * @param token */ private boolean isLongOption(final String token) { if (!token.startsWith("-") || token.length() == 1) { return false; } final int pos = token.indexOf("="); final String t = pos == -1 ? token : token.substring(0, pos); if (!options.getMatchingOptions(t).isEmpty()) { // long or partial long options (--L, -L, --L=V, -L=V, --l, --l=V) return true; } else if (getLongPrefix(token) != null && !token.startsWith("--")) { // -LV return true; } return false; } /** * Handles an unknown token. If the token starts with a dash an * UnrecognizedOptionException is thrown. Otherwise the token is added * to the arguments of the command line. If the stopAtNonOption flag * is set, this stops the parsing and the remaining tokens are added * as-is in the arguments of the command line. * * @param token the command line token to handle */ private void handleUnknownToken(final String token) throws ParseException { if (token.startsWith("-") && token.length() > 1 && !stopAtNonOption) { throw new UnrecognizedOptionException("Unrecognized option: " + token, token); } cmd.addArg(token); if (stopAtNonOption) { skipParsing = true; } } /** * Handles the following tokens: * * --L * --L=V * --L V * --l * * @param token the command line token to handle */ private void handleLongOption(final String token) throws ParseException { if (token.indexOf('=') == -1) { handleLongOptionWithoutEqual(token); } else { handleLongOptionWithEqual(token); } } /** * Handles the following tokens: * * --L * -L * --l * -l * * @param token the command line token to handle */ private void handleLongOptionWithoutEqual(final String token) throws ParseException { final List<String> matchingOpts = options.getMatchingOptions(token); if (matchingOpts.isEmpty()) { handleUnknownToken(currentToken); } else if (matchingOpts.size() > 1) { throw new AmbiguousOptionException(token, matchingOpts); } else { handleOption(options.getOption(matchingOpts.get(0))); } } /** * Handles the following tokens: * * --L=V * -L=V * --l=V * -l=V * * @param token the command line token to handle */ private void handleLongOptionWithEqual(final String token) throws ParseException { final int pos = token.indexOf('='); final String value = token.substring(pos + 1); final String opt = token.substring(0, pos); final List<String> matchingOpts = options.getMatchingOptions(opt); if (matchingOpts.isEmpty()) { handleUnknownToken(currentToken); } else if (matchingOpts.size() > 1) { throw new AmbiguousOptionException(opt, matchingOpts); } else { final Option option = options.getOption(matchingOpts.get(0)); if (option.acceptsArg()) { handleOption(option); currentOption.addValueForProcessing(value); currentOption = null; } else { handleUnknownToken(currentToken); } } } /** * Handles the following tokens: * * -S * -SV * -S V * -S=V * -S1S2 * -S1S2 V * -SV1=V2 * * -L * -LV * -L V * -L=V * -l * * @param token the command line token to handle */ private void handleShortAndLongOption(final String token) throws ParseException { final String t = Util.stripLeadingHyphens(token); final int pos = t.indexOf('='); if (t.length() == 1) { // -S if (options.hasShortOption(t)) { handleOption(options.getOption(t)); } else { handleUnknownToken(token); } } else if (pos == -1) { // no equal sign found (-xxx) if (options.hasShortOption(t)) { handleOption(options.getOption(t)); } else if (!options.getMatchingOptions(t).isEmpty()) { // -L or -l handleLongOptionWithoutEqual(token); } else { // look for a long prefix (-Xmx512m) final String opt = getLongPrefix(t); if (opt != null && options.getOption(opt).acceptsArg()) { handleOption(options.getOption(opt)); currentOption.addValueForProcessing(t.substring(opt.length())); currentOption = null; } else if (isJavaProperty(t)) { // -SV1 (-Dflag) handleOption(options.getOption(t.substring(0, 1))); currentOption.addValueForProcessing(t.substring(1)); currentOption = null; } else { // -S1S2S3 or -S1S2V handleConcatenatedOptions(token); } } } else { // equal sign found (-xxx=yyy) final String opt = t.substring(0, pos); final String value = t.substring(pos + 1); if (opt.length() == 1) { // -S=V final Option option = options.getOption(opt); if (option != null && option.acceptsArg()) { handleOption(option); currentOption.addValueForProcessing(value); currentOption = null; } else { handleUnknownToken(token); } } else if (isJavaProperty(opt)) { // -SV1=V2 (-Dkey=value) handleOption(options.getOption(opt.substring(0, 1))); currentOption.addValueForProcessing(opt.substring(1)); currentOption.addValueForProcessing(value); currentOption = null; } else { // -L=V or -l=V handleLongOptionWithEqual(token); } } } /** * Search for a prefix that is the long name of an option (-Xmx512m) * * @param token */ private String getLongPrefix(final String token) { final String t = Util.stripLeadingHyphens(token); int i; String opt = null; for (i = t.length() - 2; i > 1; i--) { final String prefix = t.substring(0, i); if (options.hasLongOption(prefix)) { opt = prefix; break; } } return opt; } /** * Check if the specified token is a Java-like property (-Dkey=value). */ private boolean isJavaProperty(final String token) { final String opt = token.substring(0, 1); final Option option = options.getOption(opt); return option != null && (option.getArgs() >= 2 || option.getArgs() == Option.UNLIMITED_VALUES); } private void handleOption(Option option) throws ParseException { // check the previous option before handling the next one checkRequiredArgs(); option = (Option) option.clone(); updateRequiredOptions(option); cmd.addOption(option); if (option.hasArg()) { currentOption = option; } else { currentOption = null; } } /** * Removes the option or its group from the list of expected elements. * * @param option */ private void updateRequiredOptions(final Option option) throws AlreadySelectedException { if (option.isRequired()) { expectedOpts.remove(option.getKey()); } // if the option is in an OptionGroup make that option the selected option of the group if (options.getOptionGroup(option) != null) { final OptionGroup group = options.getOptionGroup(option); if (group.isRequired()) { expectedOpts.remove(group); } group.setSelected(option); } } /** * Breaks <code>token</code> into its constituent parts * using the following algorithm. * * <ul> * <li>ignore the first character ("<b>-</b>")</li> * <li>for each remaining character check if an {@link Option} * exists with that id.</li> * <li>if an {@link Option} does exist then add that character * prepended with "<b>-</b>" to the list of processed tokens.</li> * <li>if the {@link Option} can have an argument value and there * are remaining characters in the token then add the remaining * characters as a token to the list of processed tokens.</li> * <li>if an {@link Option} does <b>NOT</b> exist <b>AND</b> * <code>stopAtNonOption</code> <b>IS</b> set then add the special token * "<b>--</b>" followed by the remaining characters and also * the remaining tokens directly to the processed tokens list.</li> * <li>if an {@link Option} does <b>NOT</b> exist <b>AND</b> * <code>stopAtNonOption</code> <b>IS NOT</b> set then add that * character prepended with "<b>-</b>".</li> * </ul> * * @param token The current token to be <b>burst</b> * at the first non-Option encountered. * @throws ParseException if there are any problems encountered * while parsing the command line token. */ protected void handleConcatenatedOptions(final String token) throws ParseException { for (int i = 1; i < token.length(); i++) { final String ch = String.valueOf(token.charAt(i)); if (options.hasOption(ch)) { handleOption(options.getOption(ch)); if (currentOption != null && token.length() != i + 1) { // add the trail as an argument of the option currentOption.addValueForProcessing(token.substring(i + 1)); break; } } else { handleUnknownToken(stopAtNonOption && i > 1 ? token.substring(i) : token); break; } } } }
Added support for disabling partial option matching
src/main/java/org/apache/commons/cli/DefaultParser.java
Added support for disabling partial option matching
<ide><path>rc/main/java/org/apache/commons/cli/DefaultParser.java <ide> <ide> /** The required options and groups expected to be found when parsing the command line. */ <ide> protected List expectedOpts; <del> <add> <add> /** Flag indicating if partial matching of long options is supported. */ <add> private boolean allowPartialMatching; <add> <add> /** Creates a new DefaultParser instance with partial matching enabled. */ <add> public DefaultParser() { <add> this.allowPartialMatching = true; <add> } <add> <add> /** <add> * Create a new DefaultParser instance with the specified partial matching policy. <add> * <add> * @param allowPartialMatching if partial matching of long options shall be enabled <add> */ <add> public DefaultParser(final boolean allowPartialMatching) { <add> this.allowPartialMatching = allowPartialMatching; <add> } <add> <ide> public CommandLine parse(final Options options, final String[] arguments) throws ParseException <ide> { <ide> return parse(options, arguments, null); <ide> final int pos = token.indexOf("="); <ide> final String t = pos == -1 ? token : token.substring(0, pos); <ide> <del> if (!options.getMatchingOptions(t).isEmpty()) <add> if (!getMatchingLongOptions(t).isEmpty()) <ide> { <ide> // long or partial long options (--L, -L, --L=V, -L=V, --l, --l=V) <ide> return true; <ide> */ <ide> private void handleLongOptionWithoutEqual(final String token) throws ParseException <ide> { <del> final List<String> matchingOpts = options.getMatchingOptions(token); <add> final List<String> matchingOpts = getMatchingLongOptions(token); <ide> if (matchingOpts.isEmpty()) <ide> { <ide> handleUnknownToken(currentToken); <ide> } <del> else if (matchingOpts.size() > 1) <add> else if (matchingOpts.size() > 1 && !options.hasLongOption(token)) <ide> { <ide> throw new AmbiguousOptionException(token, matchingOpts); <ide> } <ide> else <ide> { <del> handleOption(options.getOption(matchingOpts.get(0))); <add> final String key = options.hasLongOption(token) ? token : matchingOpts.get(0); <add> handleOption(options.getOption(key)); <ide> } <ide> } <ide> <ide> <ide> final String opt = token.substring(0, pos); <ide> <del> final List<String> matchingOpts = options.getMatchingOptions(opt); <add> final List<String> matchingOpts = getMatchingLongOptions(opt); <ide> if (matchingOpts.isEmpty()) <ide> { <ide> handleUnknownToken(currentToken); <ide> } <del> else if (matchingOpts.size() > 1) <add> else if (matchingOpts.size() > 1 && !options.hasLongOption(opt)) <ide> { <ide> throw new AmbiguousOptionException(opt, matchingOpts); <ide> } <ide> else <ide> { <del> final Option option = options.getOption(matchingOpts.get(0)); <add> final String key = options.hasLongOption(opt) ? opt : matchingOpts.get(0); <add> final Option option = options.getOption(key); <ide> <ide> if (option.acceptsArg()) <ide> { <ide> { <ide> handleOption(options.getOption(t)); <ide> } <del> else if (!options.getMatchingOptions(t).isEmpty()) <add> else if (!getMatchingLongOptions(t).isEmpty()) <ide> { <ide> // -L or -l <ide> handleLongOptionWithoutEqual(token); <ide> } <ide> <ide> /** <add> * Returns a list of matching option strings for the given token, depending <add> * on the selected partial matching policy. <add> * <add> * @param token the token (may contain leading dashes) <add> * @return the list of matching option strings or an empty list if no matching option could be found <add> */ <add> private List<String> getMatchingLongOptions(final String token) <add> { <add> if (allowPartialMatching) <add> { <add> return options.getMatchingOptions(token); <add> } <add> else <add> { <add> List<String> matches = new ArrayList<String>(1); <add> if (options.hasLongOption(token)) <add> { <add> Option option = options.getOption(token); <add> matches.add(option.getLongOpt()); <add> } <add> <add> return matches; <add> } <add> } <add> <add> /** <ide> * Breaks <code>token</code> into its constituent parts <ide> * using the following algorithm. <ide> *
JavaScript
agpl-3.0
d9528b17ff86c801c067af48bbf72895bcfb3877
0
ianopolous/Peergos,Peergos/Peergos,Peergos/Peergos,ianopolous/Peergos,Peergos/Peergos,ianopolous/Peergos
if (typeof module !== "undefined") var nacl = require("./nacl"); if (typeof module !== "undefined") var erasure = require("./erasure"); // API for the User interface to use ///////////////////////////// ///////////////////////////// // UserPublicKey methods function UserPublicKey(publicSignKey, publicBoxKey) { this.pSignKey = publicSignKey; // 32 bytes this.pBoxKey = publicBoxKey; // 32 bytes // ((err, publicKeyString) -> ()) this.getPublicKeys = function() { var tmp = new Uint8Array(this.pSignKey.length + this.pBoxKey.length); tmp.set(this.pSignKey, 0); tmp.set(this.pBoxKey, this.pSignKey.length); return tmp; } // (Uint8Array, User, (nonce, cipher) -> ()) this.encryptMessageFor = function(input, us) { var nonce = createNonce(); return concat(nacl.box(input, nonce, this.pBoxKey, us.sBoxKey), nonce); } // Uint8Array => boolean this.unsignMessage = function(sig) { return nacl.sign.open(sig, this.pSignKey); } } //Uint8Array => UserPublicKey UserPublicKey.fromPublicKeys = function(both) { var pSign = slice(both, 0, 32); var pBox = slice(both, 32, 64); return new UserPublicKey(pSign, pBox); } UserPublicKey.HASH_BYTES = 32; // Uint8Array => Uint8Array UserPublicKey.hash = function(arr) { return sha256(arr); } function createNonce(){ return window.nacl.randomBytes(24); } ///////////////////////////// // User methods // (string, string, (User -> ()) function generateKeyPairs(username, password, cb) { var hash = UserPublicKey.hash(nacl.util.decodeUTF8(password)); var salt = nacl.util.decodeUTF8(username) return new Promise(function(resolve, reject) { scrypt(hash, salt, 17, 8, 64, 1000, function(keyBytes) { var bothBytes = nacl.util.decodeBase64(keyBytes); var signBytes = bothBytes.subarray(0, 32); var boxBytes = bothBytes.subarray(32, 64); resolve(new User(nacl.sign.keyPair.fromSeed(signBytes), nacl.box.keyPair.fromSecretKey(new Uint8Array(boxBytes)))); }, 'base64'); }); } function User(signKeyPair, boxKeyPair) { UserPublicKey.call(this, signKeyPair.publicKey, boxKeyPair.publicKey); this.sSignKey = signKeyPair.secretKey; // 64 bytes this.sBoxKey = boxKeyPair.secretKey; // 32 bytes // (Uint8Array, (nonce, sig) => ()) this.hashAndSignMessage = function(input, cb) { signMessage(this.hash(input), cb); } // (Uint8Array, (nonce, sig) => ()) this.signMessage = function(input) { return nacl.sign(input, this.sSignKey); } // (Uint8Array, (err, literals) -> ()) this.decryptMessage = function(cipher, them) { var nonce = slice(cipher, cipher.length-24, cipher.length); cipher = slice(cipher, 0, cipher.length-24); return nacl.box.open(cipher, nonce, them.pBoxKey, this.sBoxKey); } this.getSecretKeys = function() { var tmp = new Uint8Array(this.sSignKey.length + this.sBoxKey.length); tmp.set(this.sSignKey, 0); tmp.set(this.sBoxKey, this.sSignKey.length); return tmp; } } User.fromEncodedKeys = function(publicKeys, secretKeys) { return new User(toKeyPair(slice(publicKeys, 0, 32), slice(secretKeys, 0, 64)), toKeyPair(slice(publicKeys, 32, 64), slice(secretKeys, 64, 96))); } User.fromSecretKeys = function(secretKeys) { var publicBoxKey = new Uint8Array(32); nacl.lowlevel.crypto_scalarmult_base(publicBoxKey, slice(secretKeys, 64, 96)) return User.fromEncodedKeys(concat(slice(secretKeys, 32, 64), publicBoxKey), secretKeys); } User.random = function() { var secretKeys = window.nacl.randomBytes(96); return User.fromSecretKeys(secretKeys); } function toKeyPair(pub, sec) { return {publicKey:pub, secretKey:sec}; } ///////////////////////////// // SymmetricKey methods function SymmetricKey(key) { if (key.length != nacl.secretbox.keyLength) throw "Invalid symmetric key: "+key; this.key = key; // (Uint8Array, Uint8Array[24]) => Uint8Array this.encrypt = function(data, nonce) { return nacl.secretbox(data, nonce, this.key); } // (Uint8Array, Uint8Array) => Uint8Array this.decrypt = function(cipher, nonce) { return nacl.secretbox.open(cipher, nonce, this.key); } // () => Uint8Array this.createNonce = function() { return nacl.randomBytes(24); } } SymmetricKey.NONCE_BYTES = 24; SymmetricKey.random = function() { return new SymmetricKey(nacl.randomBytes(32)); } function FileProperties(name, size) { this.name = name; this.size = size; this.serialize = function() { var buf = new ByteArrayOutputStream(); buf.writeString(name); buf.writeDouble(size); return buf.toByteArray(); } this.getSize = function() { return size; } } FileProperties.deserialize = function(raw) { const buf = new ByteArrayInputStream(raw); var name = buf.readString(); var size = buf.readDouble(); return new FileProperties(name, size); } function Fragment(data) { this.data = data; this.getHash = function() { return UserPublicKey.hash(data); } this.getData = function() { return data; } } Fragment.SIZE = 128*1024; function EncryptedChunk(encrypted) { this.auth = slice(encrypted, 0, window.nacl.secretbox.overheadLength); this.cipher = slice(encrypted, window.nacl.secretbox.overheadLength, encrypted.length); this.generateFragments = function() { var bfrags = erasure.split(this.cipher, EncryptedChunk.ERASURE_ORIGINAL, EncryptedChunk.ERASURE_ALLOWED_FAILURES); var frags = []; for (var i=0; i < bfrags.length; i++) frags[i] = new Fragment(bfrags[i]); return frags; } this.getAuth = function() { return this.auth; } this.decrypt = function(key, nonce) { return key.decrypt(concat(this.auth, this.cipher), nonce); } } EncryptedChunk.ERASURE_ORIGINAL = 40; EncryptedChunk.ERASURE_ALLOWED_FAILURES = 10; function Chunk(data, key) { this.data = data; this.key = key; this.nonce = window.nacl.randomBytes(SymmetricKey.NONCE_BYTES); this.mapKey = window.nacl.randomBytes(32); this.encrypt = function() { return new EncryptedChunk(key.encrypt(data, this.nonce)); } } Chunk.MAX_SIZE = Fragment.SIZE*EncryptedChunk.ERASURE_ORIGINAL function FileUploader(name, contents, key, parentLocation, parentparentKey) { this.props = new FileProperties(name, contents.length); this.chunks = []; if (key == null) key = SymmetricKey.random(); for (var i=0; i < contents.length; i+= Chunk.MAX_SIZE) this.chunks.push(new Chunk(slice(contents, i, Math.min(contents.length, i + Chunk.MAX_SIZE)), key)); this.upload = function(context, owner, writer) { var proms = []; const chunk0 = this.chunks[0]; console.log(new ReadableFilePointer(owner, writer, chunk0.mapKey, chunk0.key).toLink()); const that = this; for (var i=0; i < this.chunks.length; i++) proms.push(new Promise(function(resolve, reject) { const chunk = that.chunks[i]; const encryptedChunk = chunk.encrypt(); const fragments = encryptedChunk.generateFragments(); console.log("Uploading chunk with %d fragments\n", fragments.length); var hashes = []; for (var f in fragments) hashes.push(fragments[f].getHash()); const retriever = new EncryptedChunkRetriever(chunk.nonce, encryptedChunk.getAuth(), hashes, i+1 < that.chunks.length ? new Location(owner, writer, that.chunks[i+1].mapKey) : null); const metaBlob = FileAccess.create(chunk.key, that.props, retriever, parentLocation, parentparentKey); resolve(context.uploadChunk(metaBlob, fragments, owner, writer, chunk.mapKey)); })); return Promise.all(proms).then(function(res){ return Promise.resolve(new Location(owner, writer, chunk0.mapKey)); }); } } ///////////////////////////// // Util methods // byte[] input and return function encryptBytesToBytes(input, pubKey) { return Java.to(encryptUint8ToUint8(input, pubKey), "byte[]"); } // byte[] cipher and return function decryptBytesToBytes(cipher, privKey) { return Java.to(decryptUint8ToUint8(cipher, privKey), "byte[]"); } function uint8ArrayToByteArray(arr) { return Java.to(arr, "byte[]"); } function slice(arr, start, end) { if (end < start) throw "negative slice size! "+start + " -> " + end; var r = new Uint8Array(end-start); for (var i=start; i < end; i++) r[i-start] = arr[i]; return r; } function concat(a, b, c) { if (a instanceof Array) { var size = 0; for (var i=0; i < a.length; i++) size += a[i].length; var r = new Uint8Array(size); var index = 0; for (var i=0; i < a.length; i++) for (var j=0; j < a[i].length; j++) r[index++] = a[i][j]; return r; } var r = new Uint8Array(a.length+b.length+(c != null ? c.length : 0)); for (var i=0; i < a.length; i++) r[i] = a[i]; for (var i=0; i < b.length; i++) r[a.length+i] = b[i]; if (c != null) for (var i=0; i < c.length; i++) r[a.length+b.length+i] = c[i]; return r; } function arraysEqual(a, b) { if (a.length != b.length) return false; for (var i=0; i < a.length; i++) if (a[i] != b[i]) return false; return true; } function get(path, onSuccess, onError) { var request = new XMLHttpRequest(); request.open("GET", path); request.onreadystatechange=function() { if (request.readyState != 4) return; if (request.status == 200) onSuccess(request.response); else onError(request.status); } request.send(); } function getProm(url) { return new Promise(function(resolve, reject) { var req = new XMLHttpRequest(); req.open('GET', url); req.onload = function() { // This is called even on 404 etc // so check the status if (req.status == 200) { resolve(new Uint8Array(req.response)); } else { reject(Error(req.statusText)); } }; req.onerror = function() { reject(Error("Network Error")); }; req.send(); }); } function post(path, data, onSuccess, onError) { var request = new XMLHttpRequest(); request.open("POST" , path); request.responseType = 'arraybuffer'; request.onreadystatechange=function() { if (request.readyState != 4) return; if (request.status == 200) onSuccess(request.response); else onError(request.status); } request.send(data); } function postProm(url, data) { return new Promise(function(resolve, reject) { var req = new XMLHttpRequest(); req.open('POST', window.location.origin + "/" + url); req.responseType = 'arraybuffer'; req.onload = function() { // This is called even on 404 etc // so check the status if (req.status == 200) { resolve(new Uint8Array(req.response)); } else { reject(Error(req.statusText)); } }; req.onerror = function() { reject(Error("Network Error")); }; req.send(data); }); } //Java is Big-endian function readInt(bytes, position) { var count = 0; for(var i = position; i < position +4 ; i++) count = count << 8 + bytes[i]; return count; } //Java is Big-endian function writeInt(bytes, position, intValue) { intValue |= 0; for(var i = position + 3; position <= i ; i--) bytes[position] = intValue & 0xff; intValue >>= 8; } function DHTClient() { // //put // this.put = function(keyData, valueData, owner, sharingKeyData, mapKeyData, proofData) { var arrays = [keyData, valueData, owner, sharingKeyData, mapKeyData, proofData]; var buffer = new ByteArrayOutputStream(); buffer.writeInt(0); // PUT Message for (var iArray=0; iArray < arrays.length; iArray++) buffer.writeArray(arrays[iArray]); return postProm("dht/put", buffer.toByteArray()).then(function(resBuf){ var res = new ByteArrayInputStream(resBuf).readInt(); if (res == 1) return Promise.resolve(true); return Promise.reject("Fragment upload failed"); }); }; // //get // this.get = function(keyData) { var buffer = new ByteArrayOutputStream(); buffer.writeInt(1); // GET Message buffer.writeArray(keyData); return postProm("dht/get", buffer.toByteArray()).then(function(res) { var buf = new ByteArrayInputStream(res); var success = buf.readInt(); if (success == 1) return Promise.resolve(buf.readArray()); return Promise.reject("Fragment download failed"); }); }; // //contains // this.contains = function(keyData) { var buffer = new ByteArrayOutputStream(); buffer.writeInt(2); // CONTAINS Message buffer.writeArray(keyData); return postProm("dht/contains", buffer.toByteArray()); }; } function CoreNodeClient() { //String -> fn- >fn -> void this.getPublicKey = function(username) { var buffer = new ByteArrayOutputStream(); buffer.writeInt(username.length); buffer.writeString(username); return postProm("core/getPublicKey", buffer.toByteArray()); }; //UserPublicKey -> Uint8Array -> Uint8Array -> fn -> fn -> void this.updateStaticData = function(owner, signedStaticData) { var buffer = new ByteArrayOutputStream(); buffer.writeArray(owner.getPublicKeys()); buffer.writeArray(signedStaticData); return postProm("core/updateStaticData", buffer.toByteArray()); }; //String -> fn- >fn -> void this.getStaticData = function(owner) { var buffer = new ByteArrayOutputStream(); buffer.writeArray(owner.getPublicKeys()); return postProm("core/getStaticData", buffer.toByteArray()); }; //Uint8Array -> fn -> fn -> void this.getUsername = function(publicKey) { var buffer = new ByteArrayOutputStream(); buffer.writeArray(publicKey); return postProm("core/getUsername", buffer.toByteArray()).then(function(res) { const name = new ByteArrayInputStream(res).readString(); return Promise.resolve(name); }); }; //String -> Uint8Array -> Uint8Array -> fn -> fn -> boolean this.addUsername = function(username, encodedUserKey, signed, staticData) { var buffer = new ByteArrayOutputStream(); buffer.writeString(username); buffer.writeArray(encodedUserKey); buffer.writeArray(signed); buffer.writeArray(staticData); return postProm("core/addUsername", buffer.toByteArray()).then( function(res){ return Promise.resolve(res[0]); }); }; //Uint8Array -> Uint8Array -> fn -> fn -> void this.followRequest = function( target, encryptedPermission) { var buffer = new ByteArrayOutputStream(); buffer.writeArray(target); buffer.writeArray(encryptedPermission); return postProm("core/followRequest", buffer.toByteArray()); }; //String -> Uint8Array -> fn -> fn -> void this.getFollowRequests = function( user) { var buffer = new ByteArrayOutputStream(); buffer.writeArray(user); return postProm("core/getFollowRequests", buffer.toByteArray()).then(function(res) { var buf = new ByteArrayInputStream(res); var size = buf.readInt(); var n = buf.readInt(); var arr = []; for (var i=0; i < n; i++) { var t = buf.readArray(); arr.push(t); } return Promise.resolve(arr); }); }; //String -> Uint8Array -> Uint8Array -> fn -> fn -> void this.removeFollowRequest = function( target, data, signed) { var buffer = new ByteArrayOutputStream(); buffer.writeString(target); buffer.writeArray(data); buffer.writeArray(signed); return postProm("core/removeFollowRequest", buffer.toByteArray()); }; //String -> Uint8Array -> Uint8Array -> fn -> fn -> void this.allowSharingKey = function(owner, signedWriter) { var buffer = new ByteArrayOutputStream(); buffer.writeArray(owner); buffer.writeArray(signedWriter); return postProm("core/allowSharingKey", buffer.toByteArray()); }; //String -> Uint8Array -> Uint8Array -> fn -> fn -> void this.banSharingKey = function(username, encodedSharingPublicKey, signedHash) { var buffer = new ByteArrayOutputStream(); buffer.writeString(username); buffer.writeArray(encodedSharingPublicKey); buffer.writeArray(signedHash); return postProm("core/banSharingKey", buffer.toByteArray()); }; //Uint8Array -> Uint8Array -> Uint8Array -> Uint8Array -> Uint8Array -> fn -> fn -> void this.addMetadataBlob = function( owner, encodedSharingPublicKey, mapKey, metadataBlob, sharingKeySignedHash) { var buffer = new ByteArrayOutputStream(); buffer.writeArray(owner); buffer.writeArray(encodedSharingPublicKey); buffer.writeArray(mapKey); buffer.writeArray(metadataBlob); buffer.writeArray(sharingKeySignedHash); return postProm("core/addMetadataBlob", buffer.toByteArray()).then(function(res) { return Promise.resolve(new ByteArrayInputStream(res).readByte() == 1); }); }; //String -> Uint8Array -> Uint8Array -> Uint8Array -> fn -> fn -> void this.removeMetadataBlob = function( owner, writer, mapKey) { var buffer = new ByteArrayOutputStream(); buffer.writeArray(owner.getPublicKeys()); buffer.writeArray(writer.getPublicKeys()); buffer.writeArray(mapKey); buffer.writeArray(writer.signMessage(mapKey)); return postProm("core/removeMetadataBlob", buffer.toByteArray()); }; //String -> Uint8Array -> Uint8Array -> fn -> fn -> void this.removeUsername = function( username, userKey, signedHash) { var buffer = new ByteArrayOutputStream(); buffer.writeString(username); buffer.writeArray(userKey); buffer.writeArray(signedHash); return post("core/removeUsername", buffer.toByteArray()); }; //String -> fn -> fn -> void this.getSharingKeys = function( username) { var buffer = new ByteArrayOutputStream(); buffer.writeString(username); return postProm("core/getSharingKeys", buffer.toByteArray()); }; //String -> Uint8Array -> fn -> fn -> void this.getMetadataBlob = function( owner, encodedSharingKey, mapKey) { var buffer = new ByteArrayOutputStream(); buffer.writeArray(owner.getPublicKeys()); buffer.writeArray(encodedSharingKey.getPublicKeys()); buffer.writeArray(mapKey); return postProm("core/getMetadataBlob", buffer.toByteArray()); }; //String -> Uint8Array -> Uint8Array -> fn -> fn -> void this.isFragmentAllowed = function( owner, encodedSharingKey, mapkey, hash) { var buffer = new ByteArrayOutputStream(); buffer.writeString(owner); buffer.writeArray(encodedSharingKey); buffer.writeArray(mapKey); buffer.writeArray(hash); return postProm("core/isFragmentAllowed", buffer.toByteArray()); }; //String -> fn -> fn -> void this.getQuota = function(user) { var buffer = new ByteArrayOutputStream(); buffer.writeArray(user.getPublicKeys()); return postProm("core/getQuota", buffer.toByteArray()).then(function(res) { var buf = new ByteArrayInputStream(res); var quota = buf.readInt() << 32; quota += buf.readInt(); return Promise.resolve(quota); }); }; //String -> fn -> fn -> void this.getUsage = function(username) { var buffer = new ByteArrayOutputStream(); buffer.writeString(username); return postProm("core/getUsage", buffer.toByteArray()); }; //String -> Uint8Array -> Uint8Array -> fn -> fn -> void this.getFragmentHashes = function( username, sharingKey, mapKey) { var buffer = new ByteArrayOutputStream(); buffer.writeString(username); buffer.writeArray(sharingKey); buffer.writeArray(mapKey); return postProm("core/getFragmentHashes", buffer.toByteArray()); }; //String -> Uint8Array -> Uint8Array -> Uint8Array -> [Uint8Array] -> Uint8Array -> fn -> fn -> void this.addFragmentHashes = function(username, encodedSharingPublicKey, mapKey, metadataBlob, allHashes, sharingKeySignedHash) { var buffer = new ByteArrayOutputStream(); buffer.writeString(username); buffer.writeArray(encodedShaaringPublicKey); buffer.writeArray(mapKey); buffer.writeArray(metadataBlob); buffer.writeInt(allHashes.length); for (var iHash=0; iHash < allHashes.length; iHash++) buffer.writeArray(allHashes[iHash]); buffer.writeArray(sharingKeySignedHash); return postProm("core/addFragmentHashes", buffer.toByteArray()); }; this.registerFragmentStorage = function(spaceDonor, address, port, owner, signedKeyPlusHash) { var buffer = new ByteArrayOutputStream(); buffer.writeArray(spaceDonor.getPublicKeys()); buffer.writeArray(address); buffer.writeInt(port); buffer.writeArray(owner.getPublicKeys()); buffer.writeArray(signedKeyPlusHash); return postProm("core/registerFragmentStorage", buffer.toByteArray()); }; }; function UserContext(username, user, dhtClient, corenodeClient) { this.username = username; this.user = user; this.dhtClient = dhtClient; this.corenodeClient = corenodeClient; this.staticData = []; // array of map entry pairs this.isRegistered = function() { return corenodeClient.getUsername(user.getPublicKeys()).then(function(res){ return Promise.resolve(username == res); }); } this.serializeStatic = function() { var buf = new ByteArrayOutputStream(); buf.writeInt(this.staticData.length); for (var i = 0; i < this.staticData.length; i++) buf.writeArray(this.staticData[i][1].serializeAndEncrypt(this.user, this.user)); return buf.toByteArray(); } this.register = function() { console.log("registering "+username); var rawStatic = this.serializeStatic(); var signed = user.signMessage(concat(nacl.util.decodeUTF8(username), user.getPublicKeys(), rawStatic)); return corenodeClient.addUsername(username, user.getPublicKeys(), signed, rawStatic); } this.createEntryDirectory = function(directoryName) { var writer = User.random(); var rootMapKey = window.nacl.randomBytes(32); // root will be stored under this in the core node var rootRKey = SymmetricKey.random(); // and authorise the writer key const rootPointer = new ReadableFilePointer(this.user, writer, rootMapKey, rootRKey); const entry = new EntryPoint(rootPointer, this.username, [], []); return this.addSharingKey(writer).then(function(res) { return this.addToStaticData(entry); }.bind(this)).then(function(res) { var root = DirAccess.create(writer, rootRKey, new FileProperties(directoryName, 0)); return this.uploadChunk(root, [], this.user, writer, rootMapKey).then(function(res) { if (res) return Promise.resolve(new RetrievedFilePointer(rootPointer, root)); return Promise.reject(); }); }.bind(this)); } this.getSharingFolder = function() { //TODO } this.getFriends = function() { //TODO } // UserPublicKey, RetrievedFilePointer this.sendFriendRequest = function(targetUser, sharingFolder) { return this.corenodeClient.getUsername(targetUser.getPublicKeys()).then(function(name) { var rootMapKey = window.nacl.randomBytes(32); var friendRoot = new ReadableFilePointer(user, sharingFolder.filePointer.writer, rootMapKey, SymmetricKey.random()); // create subdirectory in sharing folder with friend's name return sharingFolder.fileAccess.mkdir(name, this, friendRoot.writer, sharingFolder.filePointer.mapKey, friendRoot.baseKey).then(function(res) { // add a note to our static data so we know who we sent the private key to const entry = new EntryPoint(friendRoot, this.username, [], [name]); return this.addToStaticData(entry).then(function(res) { // send details to allow friend to follow us // create a tmp keypair whose public key we can append to the request without leaking information var tmp = User.random(); var payload = entry.serializeAndEncrypt(tmp, targetUser); return corenodeClient.followRequest(targetUser.getPublicKeys(), concat(tmp.pBoxKey, payload)); }); }.bind(this)); }.bind(this)); }.bind(this); this.sendFollowRequest = function(targetUser) { return this.sendWriteAccess(targetUser); } this.sendWriteAccess = function(targetUser) { // create sharing keypair and give it write access var sharing = User.random(); var rootMapKey = window.nacl.randomBytes(32); // add a note to our static data so we know who we sent the private key to var friendRoot = new ReadableFilePointer(user, sharing, rootMapKey, SymmetricKey.random()); return this.addSharingKey(sharing).then(function(res) { return this.corenodeClient.getUsername(targetUser.getPublicKeys()).then(function(name) { const entry = new EntryPoint(friendRoot, this.username, [], [name]); return this.addToStaticData(entry).then(function(res) { // send details to allow friend to share with us (i.e. we follow them) // create a tmp keypair whose public key we can append to the request without leaking information var tmp = User.random(); var payload = entry.serializeAndEncrypt(tmp, targetUser); return corenodeClient.followRequest(targetUser.getPublicKeys(), concat(tmp.pBoxKey, payload)); }); }.bind(this)); }.bind(this)); }.bind(this); this.addSharingKey = function(pub) { var signed = user.signMessage(pub.getPublicKeys()); return corenodeClient.allowSharingKey(user.getPublicKeys(), signed); } this.addToStaticData = function(entry) { this.staticData.push([entry.pointer.writer, entry]); var rawStatic = new Uint8Array(this.serializeStatic()); return corenodeClient.updateStaticData(user, user.signMessage(rawStatic)); } this.getFollowRequests = function() { return corenodeClient.getFollowRequests(user.getPublicKeys()); } this.decodeFollowRequest = function(raw) { var pBoxKey = new Uint8Array(32); for (var i=0; i < 32; i++) pBoxKey[i] = raw[i]; // signing key is not used var tmp = new UserPublicKey(null, pBoxKey); var buf = new ByteArrayInputStream(raw); buf.read(32); var cipher = new Uint8Array(buf.read(raw.length - 32)); return EntryPoint.decryptAndDeserialize(cipher, user, tmp); } this.uploadFragment = function(f, targetUser, sharer, mapKey) { return dhtClient.put(f.getHash(), f.getData(), targetUser.getPublicKeys(), sharer.getPublicKeys(), mapKey, sharer.signMessage(concat(sharer.getPublicKeys(), f.getHash()))); } this.uploadChunk = function(metadata, fragments, owner, sharer, mapKey) { var buf = new ByteArrayOutputStream(); metadata.serialize(buf); var metaBlob = buf.toByteArray(); console.log("Storing metadata blob of " + metaBlob.length + " bytes."); return corenodeClient.addMetadataBlob(owner.getPublicKeys(), sharer.getPublicKeys(), mapKey, metaBlob, sharer.signMessage(concat(mapKey, metaBlob))) .then(function(added) { if (!added) { console.log("Meta blob store failed."); } }).then(function() { if (fragments.length == 0 ) return Promise.resolve(true); // now upload fragments to DHT var futures = []; for (var i=0; i < fragments.length; i++) futures[i] = this.uploadFragment(fragments[i], owner, sharer, mapKey); // wait for all fragments to upload return Promise.all(futures); }.bind(this)); } this.getRoots = function() { const context = this; return corenodeClient.getStaticData(user).then(function(raw) { var buf = new ByteArrayInputStream(raw); var totalStaticLength = buf.readInt(); var count = buf.readInt(); var res = []; for (var i=0; i < count; i++) { var entry = EntryPoint.decryptAndDeserialize(buf.readArray(), context.user, context.user); res.push(entry); } // download the metadata blobs for these entry points var proms = []; for (var i=0; i < res.length; i++) proms[i] = corenodeClient.getMetadataBlob(res[i].pointer.owner, res[i].pointer.writer, res[i].pointer.mapKey); return Promise.all(proms).then(function(result) { var entryPoints = []; for (var i=0; i < result.length; i++) { if (result[i].byteLength > 8) { var unwrapped = new ByteArrayInputStream(result[i]).readArray(); entryPoints.push([res[i], FileAccess.deserialize(unwrapped)]); } else entryPoints.push([res[i], null]); } return Promise.resolve(entryPoints); }); }); } this.getTreeRoot = function() { return this.getRoots().then(function(roots){ var entrypoints = roots.map(function(x) {return new FileTreeNode(new RetrievedFilePointer(x[0].pointer, x[1]), x[0].owner, x[0].readers, x[0].writers, x[0].pointer.writer);}); console.log(entrypoints); var globalRoot = FileTreeNode.ROOT; var proms = []; var getAncestors = function(treeNode, context) { return treeNode.retrieveParent(context).then(function(parent) { if (parent == null) return Promise.resolve(true); parent.addChild(treeNode); return getAncestors(parent, context); }); } for (var i=0; i < entrypoints.length; i++) { var current = entrypoints[i]; proms.push(getAncestors(current)); } return Promise.all(proms).then(function(res) { return Promise.resolve(globalRoot); }); }.bind(this)); }.bind(this); // [SymmetricLocationLink], SymmetricKey this.retrieveAllMetadata = function(links, baseKey) { var proms = []; for (var i=0; i < links.length; i++) { var loc = links[i].targetLocation(baseKey); proms[i] = corenodeClient.getMetadataBlob(loc.owner, loc.writer, loc.mapKey); } return Promise.all(proms).then(function(rawBlobs) { var accesses = []; for (var i=0; i < rawBlobs.length; i++) { var unwrapped = new ByteArrayInputStream(rawBlobs[i]).readArray(); accesses[i] = [links[i].toReadableFilePointer(baseKey), unwrapped.length > 0 ? FileAccess.deserialize(unwrapped) : null]; } const res = []; for (var i=0; i < accesses.length; i++) if (accesses[i][1] != null) res.push(accesses[i]); return Promise.resolve(res); }); } this.getMetadata = function(loc) { return corenodeClient.getMetadataBlob(loc.owner, loc.writer, loc.mapKey).then(function(buf) { var unwrapped = new ByteArrayInputStream(buf).readArray(); return FileAccess.deserialize(unwrapped); }); } this.downloadFragments = function(hashes, nRequired) { var result = {}; result.fragments = []; result.nError = 0; var proms = []; for (var i=0; i < hashes.length; i++) proms.push(dhtClient.get(hashes[i]).then(function(val) { result.fragments.push(val); console.log("Got Fragment."); }).catch(function() { result.nError++; })); return Promise.all(proms).then(function (all) { console.log("All done."); if (result.fragments.length < nRequired) throw "Not enough fragments!"; return Promise.resolve(result.fragments); }); } } function ReadableFilePointer(owner, writer, mapKey, baseKey) { this.owner = owner; //UserPublicKey this.writer = writer; //User / UserPublicKey this.mapKey = mapKey; //ByteArrayWrapper this.baseKey = baseKey; //SymmetricKey this.serialize = function() { var bout = new ByteArrayOutputStream(); bout.writeArray(owner.getPublicKeys()); if (writer instanceof User) bout.writeArray(writer.getSecretKeys()); else bout.writeArray(writer.getPublicKeys()); bout.writeArray(mapKey); bout.writeArray(baseKey.key); return bout.toByteArray(); } this.isWritable = function() { return this.writer instanceof User; } this.toLink = function() { return "/public/" + bytesToHex(owner.getPublicKeys()) + "/" + bytesToHex(writer.getPublicKeys()) + "/" + bytesToHex(mapKey) + "/" + bytesToHex(baseKey.key); } } ReadableFilePointer.fromLink = function(keysString) { const split = keysString.split("/"); const owner = UserPublicKey.fromPublicKeys(hexToBytes(split[0])); const writer = UserPublicKey.fromPublicKeys(hexToBytes(split[1])); const mapKey = hexToBytes(split[2]); const baseKey = new SymmetricKey(hexToBytes(split[3])); return new ReadableFilePointer(owner, writer, mapKey, baseKey); } ReadableFilePointer.deserialize = function(arr) { const bin = new ByteArrayInputStream(arr); const owner = bin.readArray(); const writerRaw = bin.readArray(); const mapKey = bin.readArray(); const rootDirKeySecret = bin.readArray(); const writer = writerRaw.length == window.nacl.box.secretKeyLength + window.nacl.sign.secretKeyLength ? User.fromSecretKeys(writerRaw) : UserPublicKey.fromPublicKeys(writerRaw); return new ReadableFilePointer(UserPublicKey.fromPublicKeys(owner), writer, mapKey, new SymmetricKey(rootDirKeySecret)); } // RetrievedFilePointer, string, [string], [string] function FileTreeNode(pointer, ownername, readers, writers, entryWriterKey) { var pointer = pointer; // O/W/M/K + FileAccess var children = []; var childrenByName = {}; var owner = ownername; var readers = readers; var writers = writers; var entryWriterKey = entryWriterKey; this.addChild = function(child) { var name = child.getFileProperties().name; if (childrenByName[name] != null) { if (pointer != null) { throw "Child already exists with name: "+name; } else return; } children.push(child); childrenByName[name] = child; } this.isWritable = function() { return pointer.filePointer.writer instanceof User; } this.retrieveParent = function(context) { if (pointer == null) return Promise.resolve(null); var parentKey = pointer.filePointer.baseKey; if (this.isDirectory()) parentKey = pointer.fileAccess.getParentKey(parentKey); return pointer.fileAccess.getParent(parentKey, context).then(function(parentRFP) { if (parentRFP == null) return Promise.resolve(FileTreeNode.ROOT); return Promise.resolve(new FileTreeNode(parentRFP, owner, [], [], entryWriterKey)); }); } this.getChildren = function(context) { if (this == FileTreeNode.ROOT) return Promise.resolve(children); return retrieveChildren(context).then(function(childrenRFPs){ return Promise.resolve(childrenRFPs.map(function(x) {return new FileTreeNode(x, owner, readers, writers, entryWriterKey);})); }); } var retrieveChildren = function(context) { const filePointer = pointer.filePointer; const fileAccess = pointer.fileAccess; const rootDirKey = filePointer.baseKey; return fileAccess.getChildren(userContext, rootDirKey) } this.isDirectory = function() { return pointer.fileAccess.isDirectory(); } this.uploadFile = function(filename, data, context) { const fileKey = SymmetricKey.random(); const rootRKey = pointer.filePointer.baseKey; const owner = pointer.filePointer.owner; const dirMapKey = pointer.filePointer.mapKey; const writer = pointer.filePointer.writer; const dirAccess = pointer.fileAccess; const parentLocation = new Location(owner, writer, dirMapKey); const dirParentKey = dirAccess.getParentKey(rootRKey); const file = new FileUploader(filename, data, fileKey, parentLocation, dirParentKey); return file.upload(context, owner, entryWriterKey).then(function(fileLocation) { dirAccess.addFile(fileLocation, rootRKey, fileKey); return userContext.uploadChunk(dirAccess, [], owner, entryWriterKey, dirMapKey); }); } this.mkdir = function(newFolderName, context) { if (!this.isDirectory()) return Promise.resolve(false); const dirPointer = pointer.filePointer; const dirAccess = pointer.fileAccess; var rootDirKey = dirPointer.baseKey; return dirAccess.mkdir(newFolderName, context, entryWriterKey, dirPointer.mapKey, rootDirKey); } this.rename = function(newName, context) { //get current props const filePointer = pointer.filePointer; const baseKey = filePointer.baseKey; const fileAccess = pointer.fileAccess; const key = this.isDirectory() ? fileAccess.getParentKey(baseKey) : baseKey; const currentProps = fileAccess.getFileProperties(key); const newProps = new FileProperties(newName, currentProps.size); return fileAccess.rename(writableFilePointer(), newProps, context); } var writableFilePointer = function() { const filePointer = pointer.filePointer; const fileAccess = pointer.fileAccess; const baseKey = filePointer.baseKey; return new ReadableFilePointer(filePointer.owner, entryWriterKey, filePointer.mapKey, baseKey); }.bind(this); this.remove = function(context) { return new RetrievedFilePointer(writableFilePointer(), pointer.fileAccess).remove(context); } this.getInputStream = function(context, size) { const baseKey = pointer.filePointer.baseKey; return pointer.fileAccess.retriever.getFile(context, baseKey, size) } this.getFileProperties = function() { const parentKey = this.isDirectory() ? pointer.fileAccess.getParentKey(pointer.filePointer.baseKey) : pointer.filePointer.baseKey return pointer.fileAccess.getFileProperties(parentKey); } } FileTreeNode.ROOT = new FileTreeNode(null, null, [], [], null); function logout() { FileTreeNode.ROOT = new FileTreeNode(null, null, [], [], null); } //ReadableFilePointer, FileAccess function RetrievedFilePointer(pointer, access) { this.filePointer = pointer; this.fileAccess = access; this.remove = function(context, parentRetrievedFilePointer) { if (!this.filePointer.isWritable()) return Promise.resolve(false); if (!this.fileAccess.isDirectory()) return this.fileAccess.removeFragments(context).then(function() { context.corenodeClient.removeMetadataBlob(this.filePointer.owner, this.filePointer.writer, this.filePointer.mapKey); }.bind(this)).then(function() { // remove from parent if (parentRetrievedFilePointer != null) parentRetrievedFilePointer.fileAccess.removeChild(this, parentRetrievedFilePointer.filePointer, context); }.bind(this)); return this.fileAccess.getChildren(context, this.filePointer.baseKey).then(function(files) { const proms = []; for (var i=0; i < files.length; i++) proms.push(files[i].remove(context, null)); return Promise.all(proms).then(function() { return context.corenodeClient.removeMetadataBlob(this.filePointer.owner, this.filePointer.writer, this.filePointer.mapKey); }.bind(this)).then(function() { // remove from parent if (parentRetrievedFilePointer != null) parentRetrievedFilePointer.fileAccess.removeChild(this, parentRetrievedFilePointer.filePointer, context); }); }.bind(this)); }.bind(this); } // ReadableFilePinter, String, [String], [String] function EntryPoint(pointer, owner, readers, writers) { this.pointer = pointer; this.owner = owner; this.readers = readers; this.writers = writers; // User, UserPublicKey this.serializeAndEncrypt = function(user, target) { return target.encryptMessageFor(this.serialize(), user); } this.serialize = function() { const dout = new ByteArrayOutputStream(); dout.writeArray(this.pointer.serialize()); dout.writeString(this.owner); dout.writeInt(this.readers.length); for (var i = 0; i < this.readers.length; i++) { dout.writetring(this.readers[i]); } dout.writeInt(this.writers.length); for (var i=0; i < this.writers.length; i++) { dout.writeString(this.writers[i]); } return dout.toByteArray(); } } // byte[], User, UserPublicKey EntryPoint.decryptAndDeserialize = function(input, user, from) { const raw = new Uint8Array(user.decryptMessage(input, from)); const din = new ByteArrayInputStream(raw); const pointer = ReadableFilePointer.deserialize(din.readArray()); const owner = din.readString(); const nReaders = din.readInt(); const readers = []; for (var i=0; i < nReaders; i++) readers.push(din.readString()); const nWriters = din.readInt(); const writers = []; for (var i=0; i < nWriters; i++) writers.push(din.readString()); return new EntryPoint(pointer, owner, readers, writers); } function SymmetricLink(link) { this.link = slice(link, SymmetricKey.NONCE_BYTES, link.length); this.nonce = slice(link, 0, SymmetricKey.NONCE_BYTES); this.serialize = function() { return concat(this.nonce, this.link); } this.target = function(from) { var encoded = from.decrypt(this.link, this.nonce); return new SymmetricKey(encoded); } } SymmetricLink.fromPair = function(from, to, nonce) { return new SymmetricLink(concat(nonce, from.encrypt(to.key, nonce))); } // UserPublicKey, UserPublicKey, Uint8Array function Location(owner, writer, mapKey) { this.owner = owner; this.writer = writer; this.mapKey = mapKey; this.serialize = function() { var bout = new ByteArrayOutputStream(); bout.writeArray(owner.getPublicKeys()); bout.writeArray(writer.getPublicKeys()); bout.writeArray(mapKey); return bout.toByteArray(); } this.encrypt = function(key, nonce) { return key.encrypt(this.serialize(), nonce); } } Location.deserialize = function(raw) { const buf = raw instanceof ByteArrayInputStream ? raw : new ByteArrayInputStream(raw); var owner = buf.readArray(); var writer = buf.readArray(); var mapKey = buf.readArray(); return new Location(UserPublicKey.fromPublicKeys(owner), UserPublicKey.fromPublicKeys(writer), mapKey); } Location.decrypt = function(from, nonce, loc) { var raw = from.decrypt(loc, nonce); return Location.deserialize(raw); } function SymmetricLocationLink(arr) { const buf = new ByteArrayInputStream(arr); this.link = buf.readArray(); this.loc = buf.readArray(); // SymmetricKey -> Location this.targetLocation = function(from) { var nonce = slice(this.link, 0, SymmetricKey.NONCE_BYTES); return Location.decrypt(from, nonce, this.loc); } this.target = function(from) { var nonce = slice(this.link, 0, SymmetricKey.NONCE_BYTES); var rest = slice(this.link, SymmetricKey.NONCE_BYTES, this.link.length); var encoded = from.decrypt(rest, nonce); return new SymmetricKey(encoded); } this.serialize = function() { var buf = new ByteArrayOutputStream(); buf.writeArray(this.link); buf.writeArray(this.loc); return buf.toByteArray(); } this.toReadableFilePointer = function(baseKey) { const loc = this.targetLocation(baseKey); const key = this.target(baseKey); return new ReadableFilePointer(loc.owner, loc.writer, loc.mapKey, key); } } SymmetricLocationLink.create = function(fromKey, toKey, location) { var nonce = fromKey.createNonce(); var loc = location.encrypt(fromKey, nonce); var link = concat(nonce, fromKey.encrypt(toKey.key, nonce)); var buf = new ByteArrayOutputStream(); buf.writeArray(link); buf.writeArray(loc); return new SymmetricLocationLink(buf.toByteArray()); } function FileAccess(parent2meta, properties, retriever, parentLink) { this.parent2meta = parent2meta; this.properties = properties; this.retriever = retriever; this.parentLink = parentLink; this.serialize = function(bout) { bout.writeArray(parent2meta.serialize()); bout.writeArray(properties); bout.writeByte(retriever != null ? 1 : 0); if (retriever != null) retriever.serialize(bout); bout.writeByte(parentLink != null ? 1: 0); if (parentLink != null) bout.writeArray(this.parentLink.serialize()); bout.writeByte(this.getType()); } // 0=FILE, 1=DIR this.getType = function() { return 0; } this.isDirectory = function() { return this.getType() == 1; } this.getMetaKey = function(parentKey) { return parent2meta.target(parentKey); } this.removeFragments = function(context) { if (this.isDirectory()) return Promise.resolve(true); // TODO delete fragments return Promise.resolve(true); } this.getFileProperties = function(parentKey) { var nonce = slice(this.properties, 0, SymmetricKey.NONCE_BYTES); var cipher = slice(this.properties, SymmetricKey.NONCE_BYTES, this.properties.length); return FileProperties.deserialize(this.getMetaKey(parentKey).decrypt(cipher, nonce)); } this.getParent = function(parentKey, context) { if (this.parentLink == null) return Promise.resolve(null); return context.retrieveAllMetadata([this.parentLink], parentKey).then( function(res) { const retrievedFilePointer = res.map(function(entry) { return new RetrievedFilePointer(entry[0], entry[1]); })[0]; return Promise.resolve(retrievedFilePointer); }) } this.rename = function(writableFilePointer, newProps, context) { if (!writableFilePointer.isWritable()) throw "Need a writable pointer!"; var metaKey; if (this.isDirectory()) { const parentKey = this.subfolders2parent.target(writableFilePointer.baseKey); metaKey = this.getMetaKey(parentKey); const metaNonce = metaKey.createNonce(); const dira = new DirAccess(this.subfolders2files, this.subfolders2parent, this.subfolders, this.files, this.parent2meta, concat(metaNonce, metaKey.encrypt(newProps.serialize(), metaNonce)) ); return context.uploadChunk(dira, [], writableFilePointer.owner, writableFilePointer.writer, writableFilePointer.mapKey); } else { metaKey = this.getMetaKey(writableFilePointer.baseKey); const nonce = metaKey.createNonce(); const fa = new FileAccess(this.parent2meta, concat(nonce, metaKey.encrypt(newProps.serialize(), nonce)), this.retriever, this.parentLink); return context.uploadChunk(fa, [], writableFilePointer.owner, writableFilePointer.writer, writableFilePointer.mapKey); } } } FileAccess.deserialize = function(raw) { const buf = new ByteArrayInputStream(raw); var p2m = buf.readArray(); var properties = buf.readArray(); var hasRetreiver = buf.readByte(); var retriever = (hasRetreiver == 1) ? FileRetriever.deserialize(buf) : null; var hasParent = buf.readByte(); var parentLink = (hasParent == 1) ? new SymmetricLocationLink(buf.readArray()) : null; var type = buf.readByte(); var fileAccess = new FileAccess(new SymmetricLink(p2m), properties, retriever, parentLink); switch(type) { case 0: return fileAccess; case 1: return DirAccess.deserialize(fileAccess, buf); default: throw new Error("Unknown Metadata type: "+type); } } FileAccess.create = function(parentKey, props, retriever, parentLocation, parentparentKey) { var metaKey = SymmetricKey.random(); var nonce = metaKey.createNonce(); return new FileAccess(SymmetricLink.fromPair(parentKey, metaKey, parentKey.createNonce()), concat(nonce, metaKey.encrypt(props.serialize(), nonce)), retriever, SymmetricLocationLink.create(parentKey, parentparentKey, parentLocation)); } function DirAccess(subfolders2files, subfolders2parent, subfolders, files, parent2meta, properties, retriever, parentLink) { FileAccess.call(this, parent2meta, properties, retriever, parentLink); this.subfolders2files = subfolders2files; this.subfolders2parent = subfolders2parent; this.subfolders = subfolders; this.files = files; this.superSerialize = this.serialize; this.serialize = function(bout) { this.superSerialize(bout); bout.writeArray(subfolders2parent.serialize()); bout.writeArray(subfolders2files.serialize()); bout.writeInt(0); bout.writeInt(subfolders.length) for (var i=0; i < subfolders.length; i++) bout.writeArray(subfolders[i].serialize()); bout.writeInt(files.length) for (var i=0; i < files.length; i++) bout.writeArray(files[i].serialize()); } // Location, SymmetricKey, SymmetricKey this.addFile = function(location, ourSubfolders, targetParent) { const filesKey = subfolders2files.target(ourSubfolders); var nonce = filesKey.createNonce(); var loc = location.encrypt(filesKey, nonce); var link = concat(nonce, filesKey.encrypt(targetParent.key, nonce)); var buf = new ByteArrayOutputStream(); buf.writeArray(link); buf.writeArray(loc); this.files.push(SymmetricLocationLink.create(filesKey, targetParent, location)); } this.removeChild = function(childRetrievedPointer, readablePointer, context) { if (childRetrievedPointer.fileAccess.isDirectory()) { const newsubfolders = []; for (var i=0; i < subfolders.length; i++) { const target = subfolders[i].targetLocation(readablePointer.baseKey); var keep = true; if (arraysEqual(target.mapKey, childRetrievedPointer.filePointer.mapKey)) if (arraysEqual(target.writer.getPublicKeys(), childRetrievedPointer.filePointer.writer.getPublicKeys())) if (arraysEqual(target.owner.getPublicKeys(), childRetrievedPointer.filePointer.owner.getPublicKeys())) keep = false; if (keep) newsubfolders.push(subfolders[i]); } this.subfolders = newsubfolders; } else { const newfiles = []; const filesKey = subfolders2files.target(readablePointer.baseKey) for (var i=0; i < files.length; i++) { const target = files[i].targetLocation(filesKey); var keep = true; if (arraysEqual(target.mapKey, childRetrievedPointer.filePointer.mapKey)) if (arraysEqual(target.writer.getPublicKeys(), childRetrievedPointer.filePointer.writer.getPublicKeys())) if (arraysEqual(target.owner.getPublicKeys(), childRetrievedPointer.filePointer.owner.getPublicKeys())) keep = false; if (keep) newfiles.push(files[i]); } this.files = newfiles; } return context.uploadChunk(this, [], readablePointer.owner, readablePointer.writer, readablePointer.mapKey); } // 0=FILE, 1=DIR this.getType = function() { return 1; } // returns [RetrievedFilePointer] this.getChildren = function(context, baseKey) { const prom1 = context.retrieveAllMetadata(this.subfolders, baseKey); const prom2 = context.retrieveAllMetadata(this.files, this.subfolders2files.target(baseKey)); return Promise.all([prom1, prom2]).then(function(mapArr) { const res = mapArr[0]; for (var i=0; i < mapArr[1].length; i++) res.push(mapArr[1][i]); const retrievedFilePointers = res.map(function(entry) { return new RetrievedFilePointer(entry[0], entry[1]); }) return Promise.resolve(retrievedFilePointers); }) } this.getParentKey = function(subfoldersKey) { return this.subfolders2parent.target(subfoldersKey); } this.getFilesKey = function(subfoldersKey) { return this.subfolders2files.target(subfoldersKey); } //String, UserContext, User -> this.mkdir = function(name, userContext, writer, ourMapKey, baseKey) { if (!(writer instanceof User)) throw "Can't modify a directory without write permission (writer must be a User)!"; const dirReadKey = SymmetricKey.random(); const dirMapKey = window.nacl.randomBytes(32); // root will be stored under this in the core node const ourParentKey = this.getParentKey(baseKey); const ourLocation = new Location(userContext.user, writer, ourMapKey); const dir = DirAccess.create(null, dirReadKey, new FileProperties(name, 0), ourLocation, ourParentKey); const that = this; return userContext.uploadChunk(dir, [], userContext.user, writer, dirMapKey) .then(function(success) { if (success) { that.addSubdir(new Location(userContext.user, writer, dirMapKey), baseKey, dirReadKey); // now upload the changed metadata blob for dir return userContext.uploadChunk(that, [], userContext.user, writer, ourMapKey); } return Promise.resolve(false); }); } this.addSubdir = function(location, ourSubfolders, targetBaseKey) { this.subfolders.push(SymmetricLocationLink.create(ourSubfolders, targetBaseKey, location)); } } DirAccess.deserialize = function(base, bin) { var s2p = bin.readArray(); var s2f = bin.readArray(); var nSharingKeys = bin.readInt(); var files = [], subfolders = []; var nsubfolders = bin.readInt(); for (var i=0; i < nsubfolders; i++) subfolders[i] = new SymmetricLocationLink(bin.readArray()); var nfiles = bin.readInt(); for (var i=0; i < nfiles; i++) files[i] = new SymmetricLocationLink(bin.readArray()); return new DirAccess(new SymmetricLink(s2f), new SymmetricLink(s2p), subfolders, files, base.parent2meta, base.properties, base.retriever, base.parentLink); } // User, SymmetricKey, FileProperties //TODO remove owner arg. DirAccess.create = function(owner, subfoldersKey, metadata, parentLocation, parentParentKey) { var metaKey = SymmetricKey.random(); var parentKey = SymmetricKey.random(); var filesKey = SymmetricKey.random(); var metaNonce = metaKey.createNonce(); var parentLink = parentLocation == null ? null : SymmetricLocationLink.create(parentKey, parentParentKey, parentLocation); return new DirAccess(SymmetricLink.fromPair(subfoldersKey, filesKey, subfoldersKey.createNonce()), SymmetricLink.fromPair(subfoldersKey, parentKey, subfoldersKey.createNonce()), [], [], SymmetricLink.fromPair(parentKey, metaKey, parentKey.createNonce()), concat(metaNonce, metaKey.encrypt(metadata.serialize(), metaNonce)), null, parentLink ); } function FileRetriever() { } FileRetriever.deserialize = function(bin) { var type = bin.readByte(); switch (type) { case 0: throw new Exception("Simple FileRetriever not implemented!"); case 1: return EncryptedChunkRetriever.deserialize(bin); default: throw new Exception("Unknown FileRetriever type: "+type); } } function EncryptedChunkRetriever(chunkNonce, chunkAuth, fragmentHashes, nextChunk) { this.chunkNonce = chunkNonce; this.chunkAuth = chunkAuth; this.fragmentHashes = fragmentHashes; this.nextChunk = nextChunk; this.getFile = function(context, dataKey, len) { const stream = this; return this.getChunkInputStream(context, dataKey, len).then(function(chunk) { return Promise.resolve(new LazyInputStreamCombiner(stream, context, dataKey, chunk)); }); } this.getNext = function() { return nextChunk; } this.getChunkInputStream = function(context, dataKey, len) { var fragmentsProm = context.downloadFragments(fragmentHashes); return fragmentsProm.then(function(fragments) { fragments = reorder(fragments, fragmentHashes); var cipherText = erasure.recombine(fragments, len != 0 ? len : Chunk.MAX_SIZE, EncryptedChunk.ERASURE_ORIGINAL, EncryptedChunk.ERASURE_ALLOWED_FAILURES); if (len != 0) cipherText = cipherText.subarray(0, len); var fullEncryptedChunk = new EncryptedChunk(concat(chunkAuth, cipherText)); var original = fullEncryptedChunk.decrypt(dataKey, chunkNonce); return Promise.resolve(original); }); } this.serialize = function(buf) { buf.writeByte(1); // This class buf.writeArray(chunkNonce); buf.writeArray(chunkAuth); buf.writeArray(concat(fragmentHashes)); buf.writeByte(nextChunk != null ? 1 : 0); if (nextChunk != null) buf.write(nextChunk.serialize()); } } EncryptedChunkRetriever.deserialize = function(buf) { var chunkNonce = buf.readArray(); var chunkAuth = buf.readArray(); var concatFragmentHashes = buf.readArray(); var fragmentHashes = split(concatFragmentHashes, UserPublicKey.HASH_BYTES); var hasNext = buf.readByte(); var nextChunk = null; if (hasNext == 1) nextChunk = Location.deserialize(buf); return new EncryptedChunkRetriever(chunkNonce, chunkAuth, fragmentHashes, nextChunk); } function split(arr, size) { var length = arr.byteLength/size; var res = []; for (var i=0; i < length; i++) res[i] = slice(arr, i*size, (i+1)*size); return res; } function LazyInputStreamCombiner(stream, context, dataKey, chunk) { if (!chunk) throw "Invalid current chunk!"; this.context = context; this.dataKey = dataKey; this.current = chunk; this.index = 0; this.next = stream.getNext(); this.getNextStream = function(len) { if (this.next != null) { const lazy = this; return context.getMetadata(this.next).then(function(meta) { var nextRet = meta.retriever; lazy.next = nextRet.getNext(); return nextRet.getChunkInputStream(context, dataKey, len); }); } throw "EOFException"; } this.bytesReady = function() { return this.current.length - this.index; } this.readByte = function() { try { return this.current[this.index++]; } catch (e) {} const lazy = this; this.getNextStream().then(function(res){ lazy.index = 0; lazy.current = res; return lazy.current.readByte(); }); } this.read = function(len, res, offset) { const lazy = this; if (res == null) { res = new Uint8Array(len); offset = 0; } const available = lazy.bytesReady(); const toRead = Math.min(available, len); for (var i=0; i < toRead; i++) res[offset + i] = lazy.readByte(); if (available >= len) return Promise.resolve(res); return this.getNextStream((len-toRead) % Chunk.MAX_SIZE).then(function(chunk){ lazy.index = 0; lazy.current = chunk; return lazy.read(len-toRead, res, offset + toRead); }); } } const GF = new (function(){ this.size = 256; this.expa = new Uint8Array(2*this.size); this.loga = new Uint8Array(this.size); this.expa[0] = 1; var x = 1; for (var i=1; i < 255; i++) { x <<= 1; // field generator polynomial is p(x) = x^8 + x^4 + x^3 + x^2 + 1 if ((x & this.size) != 0) x ^= (this.size | 0x1D); // x^8 = x^4 + x^3 + x^2 + 1 ==> 0001_1101 this.expa[i] = x; this.loga[x] = i; } for (var i=255; i < 512; i++) this.expa[i] = this.expa[i-255]; this.mask = function() { return this.size-1; } this.exp = function(y) { return this.expa[y]; } this.mul = function(x, y) { if ((x==0) || (y==0)) return 0; return this.expa[this.loga[x]+this.loga[y]]; } this.div = function(x, y) { if (y==0) throw new IllegalStateException("Divided by zero! Blackhole created.. "); if (x==0) return 0; return this.expa[this.loga[x]+255-this.loga[y]]; } })(); // Uint8Array, GaloisField GaloisPolynomial = {}; GaloisPolynomial.check = function(coefficients, f) { if (coefficients.length > f.size) throw "Polynomial order must be less than or equal to the degree of the Galois field. " + coefficients.length + " !> " + f.size; } GaloisPolynomial.order = function(coefficients) { return coefficients.length; } GaloisPolynomial.evalu = function(f, coefficients, x) { var y = coefficients[0]; for (var i=1; i < coefficients.length; i++) y = f.mul(y, x) ^ coefficients[i]; return y; } // Uint8 -> GaloisPolynomial GaloisPolynomial.scale = function(f, coefficients, x) { const res = new Uint8Array(coefficients.length); for (var i=0; i < res.length; i++) res[i] = f.mul(x, coefficients[i]); return res; } // GaloisPolynomial -> GaloisPolynomial GaloisPolynomial.add = function(f, coefficients, other) { const order = GaloisPolynomial.order(coefficients); const res = new Uint8Array(Math.max(order, GaloisPolynomial.order(other))); for (var i=0; i < order; i++) res[i + res.length - order] = coefficients[i]; for (var i=0; i < GaloisPolynomial.order(other); i++) res[i + res.length - GaloisPolynomial.order(other)] ^= other[i]; return res; } // GaloisPolynomial -> GaloisPolynomial GaloisPolynomial.mul = function(f, coefficients, other) { const order = GaloisPolynomial.order(coefficients); const res = new Uint8Array(order + GaloisPolynomial.order(other) - 1); for (var i=0; i < order; i++) for (var j=0; j < GaloisPolynomial.order(other); j++) res[i+j] ^= f.mul(coefficients[i], other[j]); return res; } // Uint8 -> GaloisPolynomial GaloisPolynomial.append = function(coefficients, x) { const res = new Uint8Array(coefficients.length+1); for (var i=0; i < coefficients.length; i++) res[i] = coefficients[i]; res[res.length-1] = x; return res; } // (int, GaloisField) -> GaloisPolynomial GaloisPolynomial.generator = function(nECSymbols, f) { const one = new Uint8Array(1); one[0] = 1; var g = one; for (var i=0; i < nECSymbols; i++) { var multiplicand = new Uint8Array(2); multiplicand[0] = 1; multiplicand[0] = f.exp(i); g = GaloisPolynomial.mul(f, g, multiplicand); } return g; } // (Uint8Array, int, GaloisField) -> Uint8Array GaloisPolynomial.encode = function(input, nEC, f) { const gen = GaloisPolynomial.generator(nEC, f); const res = new Uint8Array(input.length + nEC); for (var i=0; i < input.length; i++) res[i] = input[i]; for (var i=0; i < input.length; i++) { const c = res[i]; if (c != 0) for (var j=0; j < GaloisPolynomial.order(gen); j++) res[i+j] ^= f.mul(gen[j], c); } for (var i=0; i < input.length; i++) res[i] = input[i]; return res; } // -> Uint8Array GaloisPolynomial.syndromes = function(input, nEC, f) { const res = new Uint8Array(nEC); const poly = input; for (var i=0; i < nEC; i++) res[i] = GaloisPolynomial.evalu(f, poly, f.exp(i)); return res; } // (Uint8Array, Uint8Array, Int[], GaloisField) -> () GaloisPolynomial.correctErrata = function(input, synd, pos, f) { if (pos.length == 0) return; const one = new Uint8Array(1); one[0] = 1; var q = one; for (var j=0; j < pos.length; j++) { var i = pos[j]; const x = f.exp(input.length - 1 - i); q = GaloisPolynomial.mul(f, q, GaloisPolynomial.create([x, 1], f)); } var t = new Uint8Array(pos.size()); for (var i=0; i < t.length; i++) t[i] = synd[t.length-1-i]; var p = GaloisPolynomial.mul(f, t, q); t = new Uint8Array(pos.size()); for (var i=0; i < t.length; i++) t[i] = p[i + p.order()-t.length]; p = t; const qorder = GaloisPolynomial.order(q); t = new Uint8Array((qorder- (qorder & 1))/2); for (var i=qorder & 1; i < qorder; i+= 2) t[i/2] = q.coefficients[i]; const qprime = t; for (var j=0; j < pos.length; j++) { const i = pos[j]; const x = f.exp(i + f.size - input.length); const y = GaloisPolynomial.evalu(f, p, x); const z = GaloisPolynomial.evalu(f, qprime, f.mul(x, x)); input[i] ^= f.div(y, f.mul(x, z)); } } // (Int[], int, GaloisField) -> Int[] GaloisPolynomial.findErrors = function(synd, nmess, f) { var errPoly = GaloisPolynomial.create([1], f); var oldPoly = GaloisPolynomial.create([1], f); for (var i=0; i < synd.length; i++) { oldPoly = GaloisPolynomial.append(oldPoly, 0); var delta = synd[i]; for (var j=1; j < GaloisPolynomial.order(errPoly); j++) delta ^= f.mul(errPoly[GaloisPolynomial.order(errPoly) - 1 - j], synd[i - j]); if (delta != 0) { if (GaloisPolynomial.order(oldPoly) > GaloisPolynomial.order(errPoly)) { var newPoly = GaloisPolynomial.scale(f, oldPoly, delta); oldPoly = GaloisPolynomial.scale(f, errPoly, f.div(1, delta)); errPoly = newPoly; } errPoly = GaloisPolynomial.add(f, errPoly, GaloisPolynomial.scale(f, oldPoly, delta)); } } const errs = GaloisPolynomial.order(errPoly)-1; if (2*errs > synd.length) throw "Too many errors to correct! ("+errs+")"; const errorPos = []; for (var i=0; i < nmess; i++) if (GaloisPolynomial.evalu(f, errPoly, f.exp(f.size - 1 - i)) == 0) errorPos.push(nmess - 1 - i); if (errorPos.length != errs) throw "couldn't find error positions! ("+errorPos.length+"!="+errs+") ( missing fragments)"; return errorPos; } // (Uint8Array, int, GaloisField) -> Uint8Array GaloisPolynomial.decode = function(message, nec, f) { const synd = GaloisPolynomial.syndromes(message, nec, f); var max = 0; for (var j=0; j < synd.length; j++) if (synd[j] > max) max = synd[j]; if (max == 0) return message; const errPos = GaloisPolynomial.findErrors(synd, message.length, f); GaloisPolynomial.correctErrata(message, synd, errPos, f); return message; } GaloisPolynomial.create = function(coeffs, f) { const c = new Uint8Array(coeffs.length); for (var i=0; i < coeffs.length; i++) c[i] = coeffs[i]; return c; } function reorder(fragments, hashes) { var hashMap = new Map(); //ba dum che for (var i=0; i < hashes.length; i++) hashMap.set(nacl.util.encodeBase64(hashes[i]), i); // Seems Map can't handle array contents equality var res = []; for (var i=0; i < fragments.length; i++) { var hash = nacl.util.encodeBase64(UserPublicKey.hash(fragments[i])); var index = hashMap.get(hash); res[index] = fragments[i]; } return res; } function string2arraybuffer(str) { var buf = new ArrayBuffer(str.length); var bufView = new Uint8Array(buf); for (var i=0, strLen=str.length; i<strLen; i++) { bufView[i] = str.charCodeAt(i); } return bufView; } function bytesToHex(p) { /** @const */ var enc = '0123456789abcdef'.split(''); var len = p.length, arr = [], i = 0; for (; i < len; i++) { arr.push(enc[(p[i]>>>4) & 15]); arr.push(enc[(p[i]>>>0) & 15]); } return arr.join(''); } function hexToBytes(hex) { var result = new Uint8Array(hex.length/2); for (var i=0; i + 1 < 2*result.length; i+= 2) result[i/2] = parseInt(hex.substring(i, i+2), 16); return result; } if (typeof module !== "undefined"){ module.exports.randomSymmetricKey = randomSymmetricKey; module.exports.SymmetricKey = SymmetricKey; }
ui/scripts/api.js
if (typeof module !== "undefined") var nacl = require("./nacl"); if (typeof module !== "undefined") var erasure = require("./erasure"); // API for the User interface to use ///////////////////////////// ///////////////////////////// // UserPublicKey methods function UserPublicKey(publicSignKey, publicBoxKey) { this.pSignKey = publicSignKey; // 32 bytes this.pBoxKey = publicBoxKey; // 32 bytes // ((err, publicKeyString) -> ()) this.getPublicKeys = function() { var tmp = new Uint8Array(this.pSignKey.length + this.pBoxKey.length); tmp.set(this.pSignKey, 0); tmp.set(this.pBoxKey, this.pSignKey.length); return tmp; } // (Uint8Array, User, (nonce, cipher) -> ()) this.encryptMessageFor = function(input, us) { var nonce = createNonce(); return concat(nacl.box(input, nonce, this.pBoxKey, us.sBoxKey), nonce); } // Uint8Array => boolean this.unsignMessage = function(sig) { return nacl.sign.open(sig, this.pSignKey); } } UserPublicKey.fromPublicKeys = function(both) { var pSign = slice(both, 0, 32); var pBox = slice(both, 32, 64); return new UserPublicKey(pSign, pBox); } UserPublicKey.HASH_BYTES = 32; // Uint8Array => Uint8Array UserPublicKey.hash = function(arr) { return sha256(arr); } function createNonce(){ return window.nacl.randomBytes(24); } ///////////////////////////// // User methods // (string, string, (User -> ()) function generateKeyPairs(username, password, cb) { var hash = UserPublicKey.hash(nacl.util.decodeUTF8(password)); var salt = nacl.util.decodeUTF8(username) return new Promise(function(resolve, reject) { scrypt(hash, salt, 17, 8, 64, 1000, function(keyBytes) { var bothBytes = nacl.util.decodeBase64(keyBytes); var signBytes = bothBytes.subarray(0, 32); var boxBytes = bothBytes.subarray(32, 64); resolve(new User(nacl.sign.keyPair.fromSeed(signBytes), nacl.box.keyPair.fromSecretKey(new Uint8Array(boxBytes)))); }, 'base64'); }); } function User(signKeyPair, boxKeyPair) { UserPublicKey.call(this, signKeyPair.publicKey, boxKeyPair.publicKey); this.sSignKey = signKeyPair.secretKey; // 64 bytes this.sBoxKey = boxKeyPair.secretKey; // 32 bytes // (Uint8Array, (nonce, sig) => ()) this.hashAndSignMessage = function(input, cb) { signMessage(this.hash(input), cb); } // (Uint8Array, (nonce, sig) => ()) this.signMessage = function(input) { return nacl.sign(input, this.sSignKey); } // (Uint8Array, (err, literals) -> ()) this.decryptMessage = function(cipher, them) { var nonce = slice(cipher, cipher.length-24, cipher.length); cipher = slice(cipher, 0, cipher.length-24); return nacl.box.open(cipher, nonce, them.pBoxKey, this.sBoxKey); } this.getSecretKeys = function() { var tmp = new Uint8Array(this.sSignKey.length + this.sBoxKey.length); tmp.set(this.sSignKey, 0); tmp.set(this.sBoxKey, this.sSignKey.length); return tmp; } } User.fromEncodedKeys = function(publicKeys, secretKeys) { return new User(toKeyPair(slice(publicKeys, 0, 32), slice(secretKeys, 0, 64)), toKeyPair(slice(publicKeys, 32, 64), slice(secretKeys, 64, 96))); } User.fromSecretKeys = function(secretKeys) { var publicBoxKey = new Uint8Array(32); nacl.lowlevel.crypto_scalarmult_base(publicBoxKey, slice(secretKeys, 64, 96)) return User.fromEncodedKeys(concat(slice(secretKeys, 32, 64), publicBoxKey), secretKeys); } User.random = function() { var secretKeys = window.nacl.randomBytes(96); return User.fromSecretKeys(secretKeys); } function toKeyPair(pub, sec) { return {publicKey:pub, secretKey:sec}; } ///////////////////////////// // SymmetricKey methods function SymmetricKey(key) { if (key.length != nacl.secretbox.keyLength) throw "Invalid symmetric key: "+key; this.key = key; // (Uint8Array, Uint8Array[24]) => Uint8Array this.encrypt = function(data, nonce) { return nacl.secretbox(data, nonce, this.key); } // (Uint8Array, Uint8Array) => Uint8Array this.decrypt = function(cipher, nonce) { return nacl.secretbox.open(cipher, nonce, this.key); } // () => Uint8Array this.createNonce = function() { return nacl.randomBytes(24); } } SymmetricKey.NONCE_BYTES = 24; SymmetricKey.random = function() { return new SymmetricKey(nacl.randomBytes(32)); } function FileProperties(name, size) { this.name = name; this.size = size; this.serialize = function() { var buf = new ByteArrayOutputStream(); buf.writeString(name); buf.writeDouble(size); return buf.toByteArray(); } this.getSize = function() { return size; } } FileProperties.deserialize = function(raw) { const buf = new ByteArrayInputStream(raw); var name = buf.readString(); var size = buf.readDouble(); return new FileProperties(name, size); } function Fragment(data) { this.data = data; this.getHash = function() { return UserPublicKey.hash(data); } this.getData = function() { return data; } } Fragment.SIZE = 128*1024; function EncryptedChunk(encrypted) { this.auth = slice(encrypted, 0, window.nacl.secretbox.overheadLength); this.cipher = slice(encrypted, window.nacl.secretbox.overheadLength, encrypted.length); this.generateFragments = function() { var bfrags = erasure.split(this.cipher, EncryptedChunk.ERASURE_ORIGINAL, EncryptedChunk.ERASURE_ALLOWED_FAILURES); var frags = []; for (var i=0; i < bfrags.length; i++) frags[i] = new Fragment(bfrags[i]); return frags; } this.getAuth = function() { return this.auth; } this.decrypt = function(key, nonce) { return key.decrypt(concat(this.auth, this.cipher), nonce); } } EncryptedChunk.ERASURE_ORIGINAL = 40; EncryptedChunk.ERASURE_ALLOWED_FAILURES = 10; function Chunk(data, key) { this.data = data; this.key = key; this.nonce = window.nacl.randomBytes(SymmetricKey.NONCE_BYTES); this.mapKey = window.nacl.randomBytes(32); this.encrypt = function() { return new EncryptedChunk(key.encrypt(data, this.nonce)); } } Chunk.MAX_SIZE = Fragment.SIZE*EncryptedChunk.ERASURE_ORIGINAL function FileUploader(name, contents, key, parentLocation, parentparentKey) { this.props = new FileProperties(name, contents.length); this.chunks = []; if (key == null) key = SymmetricKey.random(); for (var i=0; i < contents.length; i+= Chunk.MAX_SIZE) this.chunks.push(new Chunk(slice(contents, i, Math.min(contents.length, i + Chunk.MAX_SIZE)), key)); this.upload = function(context, owner, writer) { var proms = []; const chunk0 = this.chunks[0]; console.log(new ReadableFilePointer(owner, writer, chunk0.mapKey, chunk0.key).toLink()); const that = this; for (var i=0; i < this.chunks.length; i++) proms.push(new Promise(function(resolve, reject) { const chunk = that.chunks[i]; const encryptedChunk = chunk.encrypt(); const fragments = encryptedChunk.generateFragments(); console.log("Uploading chunk with %d fragments\n", fragments.length); var hashes = []; for (var f in fragments) hashes.push(fragments[f].getHash()); const retriever = new EncryptedChunkRetriever(chunk.nonce, encryptedChunk.getAuth(), hashes, i+1 < that.chunks.length ? new Location(owner, writer, that.chunks[i+1].mapKey) : null); const metaBlob = FileAccess.create(chunk.key, that.props, retriever, parentLocation, parentparentKey); resolve(context.uploadChunk(metaBlob, fragments, owner, writer, chunk.mapKey)); })); return Promise.all(proms).then(function(res){ return Promise.resolve(new Location(owner, writer, chunk0.mapKey)); }); } } ///////////////////////////// // Util methods // byte[] input and return function encryptBytesToBytes(input, pubKey) { return Java.to(encryptUint8ToUint8(input, pubKey), "byte[]"); } // byte[] cipher and return function decryptBytesToBytes(cipher, privKey) { return Java.to(decryptUint8ToUint8(cipher, privKey), "byte[]"); } function uint8ArrayToByteArray(arr) { return Java.to(arr, "byte[]"); } function slice(arr, start, end) { if (end < start) throw "negative slice size! "+start + " -> " + end; var r = new Uint8Array(end-start); for (var i=start; i < end; i++) r[i-start] = arr[i]; return r; } function concat(a, b, c) { if (a instanceof Array) { var size = 0; for (var i=0; i < a.length; i++) size += a[i].length; var r = new Uint8Array(size); var index = 0; for (var i=0; i < a.length; i++) for (var j=0; j < a[i].length; j++) r[index++] = a[i][j]; return r; } var r = new Uint8Array(a.length+b.length+(c != null ? c.length : 0)); for (var i=0; i < a.length; i++) r[i] = a[i]; for (var i=0; i < b.length; i++) r[a.length+i] = b[i]; if (c != null) for (var i=0; i < c.length; i++) r[a.length+b.length+i] = c[i]; return r; } function arraysEqual(a, b) { if (a.length != b.length) return false; for (var i=0; i < a.length; i++) if (a[i] != b[i]) return false; return true; } function get(path, onSuccess, onError) { var request = new XMLHttpRequest(); request.open("GET", path); request.onreadystatechange=function() { if (request.readyState != 4) return; if (request.status == 200) onSuccess(request.response); else onError(request.status); } request.send(); } function getProm(url) { return new Promise(function(resolve, reject) { var req = new XMLHttpRequest(); req.open('GET', url); req.onload = function() { // This is called even on 404 etc // so check the status if (req.status == 200) { resolve(new Uint8Array(req.response)); } else { reject(Error(req.statusText)); } }; req.onerror = function() { reject(Error("Network Error")); }; req.send(); }); } function post(path, data, onSuccess, onError) { var request = new XMLHttpRequest(); request.open("POST" , path); request.responseType = 'arraybuffer'; request.onreadystatechange=function() { if (request.readyState != 4) return; if (request.status == 200) onSuccess(request.response); else onError(request.status); } request.send(data); } function postProm(url, data) { return new Promise(function(resolve, reject) { var req = new XMLHttpRequest(); req.open('POST', window.location.origin + "/" + url); req.responseType = 'arraybuffer'; req.onload = function() { // This is called even on 404 etc // so check the status if (req.status == 200) { resolve(new Uint8Array(req.response)); } else { reject(Error(req.statusText)); } }; req.onerror = function() { reject(Error("Network Error")); }; req.send(data); }); } //Java is Big-endian function readInt(bytes, position) { var count = 0; for(var i = position; i < position +4 ; i++) count = count << 8 + bytes[i]; return count; } //Java is Big-endian function writeInt(bytes, position, intValue) { intValue |= 0; for(var i = position + 3; position <= i ; i--) bytes[position] = intValue & 0xff; intValue >>= 8; } function DHTClient() { // //put // this.put = function(keyData, valueData, owner, sharingKeyData, mapKeyData, proofData) { var arrays = [keyData, valueData, owner, sharingKeyData, mapKeyData, proofData]; var buffer = new ByteArrayOutputStream(); buffer.writeInt(0); // PUT Message for (var iArray=0; iArray < arrays.length; iArray++) buffer.writeArray(arrays[iArray]); return postProm("dht/put", buffer.toByteArray()).then(function(resBuf){ var res = new ByteArrayInputStream(resBuf).readInt(); if (res == 1) return Promise.resolve(true); return Promise.reject("Fragment upload failed"); }); }; // //get // this.get = function(keyData) { var buffer = new ByteArrayOutputStream(); buffer.writeInt(1); // GET Message buffer.writeArray(keyData); return postProm("dht/get", buffer.toByteArray()).then(function(res) { var buf = new ByteArrayInputStream(res); var success = buf.readInt(); if (success == 1) return Promise.resolve(buf.readArray()); return Promise.reject("Fragment download failed"); }); }; // //contains // this.contains = function(keyData) { var buffer = new ByteArrayOutputStream(); buffer.writeInt(2); // CONTAINS Message buffer.writeArray(keyData); return postProm("dht/contains", buffer.toByteArray()); }; } function CoreNodeClient() { //String -> fn- >fn -> void this.getPublicKey = function(username) { var buffer = new ByteArrayOutputStream(); buffer.writeInt(username.length); buffer.writeString(username); return postProm("core/getPublicKey", buffer.toByteArray()); }; //UserPublicKey -> Uint8Array -> Uint8Array -> fn -> fn -> void this.updateStaticData = function(owner, signedStaticData) { var buffer = new ByteArrayOutputStream(); buffer.writeArray(owner.getPublicKeys()); buffer.writeArray(signedStaticData); return postProm("core/updateStaticData", buffer.toByteArray()); }; //String -> fn- >fn -> void this.getStaticData = function(owner) { var buffer = new ByteArrayOutputStream(); buffer.writeArray(owner.getPublicKeys()); return postProm("core/getStaticData", buffer.toByteArray()); }; //Uint8Array -> fn -> fn -> void this.getUsername = function(publicKey) { var buffer = new ByteArrayOutputStream(); buffer.writeArray(publicKey); return postProm("core/getUsername", buffer.toByteArray()).then(function(res) { const name = new ByteArrayInputStream(res).readString(); return Promise.resolve(name); }); }; //String -> Uint8Array -> Uint8Array -> fn -> fn -> boolean this.addUsername = function(username, encodedUserKey, signed, staticData) { var buffer = new ByteArrayOutputStream(); buffer.writeString(username); buffer.writeArray(encodedUserKey); buffer.writeArray(signed); buffer.writeArray(staticData); return postProm("core/addUsername", buffer.toByteArray()).then( function(res){ return Promise.resolve(res[0]); }); }; //Uint8Array -> Uint8Array -> fn -> fn -> void this.followRequest = function( target, encryptedPermission) { var buffer = new ByteArrayOutputStream(); buffer.writeArray(target); buffer.writeArray(encryptedPermission); return postProm("core/followRequest", buffer.toByteArray()); }; //String -> Uint8Array -> fn -> fn -> void this.getFollowRequests = function( user) { var buffer = new ByteArrayOutputStream(); buffer.writeArray(user); return postProm("core/getFollowRequests", buffer.toByteArray()).then(function(res) { var buf = new ByteArrayInputStream(res); var size = buf.readInt(); var n = buf.readInt(); var arr = []; for (var i=0; i < n; i++) { var t = buf.readArray(); arr.push(t); } return Promise.resolve(arr); }); }; //String -> Uint8Array -> Uint8Array -> fn -> fn -> void this.removeFollowRequest = function( target, data, signed) { var buffer = new ByteArrayOutputStream(); buffer.writeString(target); buffer.writeArray(data); buffer.writeArray(signed); return postProm("core/removeFollowRequest", buffer.toByteArray()); }; //String -> Uint8Array -> Uint8Array -> fn -> fn -> void this.allowSharingKey = function(owner, signedWriter) { var buffer = new ByteArrayOutputStream(); buffer.writeArray(owner); buffer.writeArray(signedWriter); return postProm("core/allowSharingKey", buffer.toByteArray()); }; //String -> Uint8Array -> Uint8Array -> fn -> fn -> void this.banSharingKey = function(username, encodedSharingPublicKey, signedHash) { var buffer = new ByteArrayOutputStream(); buffer.writeString(username); buffer.writeArray(encodedSharingPublicKey); buffer.writeArray(signedHash); return postProm("core/banSharingKey", buffer.toByteArray()); }; //Uint8Array -> Uint8Array -> Uint8Array -> Uint8Array -> Uint8Array -> fn -> fn -> void this.addMetadataBlob = function( owner, encodedSharingPublicKey, mapKey, metadataBlob, sharingKeySignedHash) { var buffer = new ByteArrayOutputStream(); buffer.writeArray(owner); buffer.writeArray(encodedSharingPublicKey); buffer.writeArray(mapKey); buffer.writeArray(metadataBlob); buffer.writeArray(sharingKeySignedHash); return postProm("core/addMetadataBlob", buffer.toByteArray()).then(function(res) { return Promise.resolve(new ByteArrayInputStream(res).readByte() == 1); }); }; //String -> Uint8Array -> Uint8Array -> Uint8Array -> fn -> fn -> void this.removeMetadataBlob = function( owner, writer, mapKey) { var buffer = new ByteArrayOutputStream(); buffer.writeArray(owner.getPublicKeys()); buffer.writeArray(writer.getPublicKeys()); buffer.writeArray(mapKey); buffer.writeArray(writer.signMessage(mapKey)); return postProm("core/removeMetadataBlob", buffer.toByteArray()); }; //String -> Uint8Array -> Uint8Array -> fn -> fn -> void this.removeUsername = function( username, userKey, signedHash) { var buffer = new ByteArrayOutputStream(); buffer.writeString(username); buffer.writeArray(userKey); buffer.writeArray(signedHash); return post("core/removeUsername", buffer.toByteArray()); }; //String -> fn -> fn -> void this.getSharingKeys = function( username) { var buffer = new ByteArrayOutputStream(); buffer.writeString(username); return postProm("core/getSharingKeys", buffer.toByteArray()); }; //String -> Uint8Array -> fn -> fn -> void this.getMetadataBlob = function( owner, encodedSharingKey, mapKey) { var buffer = new ByteArrayOutputStream(); buffer.writeArray(owner.getPublicKeys()); buffer.writeArray(encodedSharingKey.getPublicKeys()); buffer.writeArray(mapKey); return postProm("core/getMetadataBlob", buffer.toByteArray()); }; //String -> Uint8Array -> Uint8Array -> fn -> fn -> void this.isFragmentAllowed = function( owner, encodedSharingKey, mapkey, hash) { var buffer = new ByteArrayOutputStream(); buffer.writeString(owner); buffer.writeArray(encodedSharingKey); buffer.writeArray(mapKey); buffer.writeArray(hash); return postProm("core/isFragmentAllowed", buffer.toByteArray()); }; //String -> fn -> fn -> void this.getQuota = function(user) { var buffer = new ByteArrayOutputStream(); buffer.writeArray(user.getPublicKeys()); return postProm("core/getQuota", buffer.toByteArray()).then(function(res) { var buf = new ByteArrayInputStream(res); var quota = buf.readInt() << 32; quota += buf.readInt(); return Promise.resolve(quota); }); }; //String -> fn -> fn -> void this.getUsage = function(username) { var buffer = new ByteArrayOutputStream(); buffer.writeString(username); return postProm("core/getUsage", buffer.toByteArray()); }; //String -> Uint8Array -> Uint8Array -> fn -> fn -> void this.getFragmentHashes = function( username, sharingKey, mapKey) { var buffer = new ByteArrayOutputStream(); buffer.writeString(username); buffer.writeArray(sharingKey); buffer.writeArray(mapKey); return postProm("core/getFragmentHashes", buffer.toByteArray()); }; //String -> Uint8Array -> Uint8Array -> Uint8Array -> [Uint8Array] -> Uint8Array -> fn -> fn -> void this.addFragmentHashes = function(username, encodedSharingPublicKey, mapKey, metadataBlob, allHashes, sharingKeySignedHash) { var buffer = new ByteArrayOutputStream(); buffer.writeString(username); buffer.writeArray(encodedShaaringPublicKey); buffer.writeArray(mapKey); buffer.writeArray(metadataBlob); buffer.writeInt(allHashes.length); for (var iHash=0; iHash < allHashes.length; iHash++) buffer.writeArray(allHashes[iHash]); buffer.writeArray(sharingKeySignedHash); return postProm("core/addFragmentHashes", buffer.toByteArray()); }; this.registerFragmentStorage = function(spaceDonor, address, port, owner, signedKeyPlusHash) { var buffer = new ByteArrayOutputStream(); buffer.writeArray(spaceDonor.getPublicKeys()); buffer.writeArray(address); buffer.writeInt(port); buffer.writeArray(owner.getPublicKeys()); buffer.writeArray(signedKeyPlusHash); return postProm("core/registerFragmentStorage", buffer.toByteArray()); }; }; function UserContext(username, user, dhtClient, corenodeClient) { this.username = username; this.user = user; this.dhtClient = dhtClient; this.corenodeClient = corenodeClient; this.staticData = []; // array of map entry pairs this.isRegistered = function() { return corenodeClient.getUsername(user.getPublicKeys()).then(function(res){ return Promise.resolve(username == res); }); } this.serializeStatic = function() { var buf = new ByteArrayOutputStream(); buf.writeInt(this.staticData.length); for (var i = 0; i < this.staticData.length; i++) buf.writeArray(this.staticData[i][1].serializeAndEncrypt(this.user, this.user)); return buf.toByteArray(); } this.register = function() { console.log("registering "+username); var rawStatic = this.serializeStatic(); var signed = user.signMessage(concat(nacl.util.decodeUTF8(username), user.getPublicKeys(), rawStatic)); return corenodeClient.addUsername(username, user.getPublicKeys(), signed, rawStatic); } this.createEntryDirectory = function(directoryName) { var writer = User.random(); var rootMapKey = window.nacl.randomBytes(32); // root will be stored under this in the core node var rootRKey = SymmetricKey.random(); // and authorise the writer key const rootPointer = new ReadableFilePointer(this.user, writer, rootMapKey, rootRKey); const entry = new EntryPoint(rootPointer, this.username, [], []); return this.addSharingKey(writer).then(function(res) { return this.addToStaticData(entry); }.bind(this)).then(function(res) { var root = DirAccess.create(writer, rootRKey, new FileProperties(directoryName, 0)); return this.uploadChunk(root, [], this.user, writer, rootMapKey).then(function(res) { if (res) return Promise.resolve(new RetrievedFilePointer(rootPointer, root)); return Promise.reject(); }); }.bind(this)); } this.getSharingFolder = function() { //TODO } this.getFriends = function() { //TODO } // UserPublicKey, RetrievedFilePointer this.sendFriendRequest = function(targetUser, sharingFolder) { return this.corenodeClient.getUsername(targetUser.getPublicKeys()).then(function(name) { var rootMapKey = window.nacl.randomBytes(32); var friendRoot = new ReadableFilePointer(user, sharingFolder.filePointer.writer, rootMapKey, SymmetricKey.random()); // create subdirectory in sharing folder with friend's name return sharingFolder.fileAccess.mkdir(name, this, friendRoot.writer, sharingFolder.filePointer.mapKey, friendRoot.baseKey).then(function(res) { // add a note to our static data so we know who we sent the private key to const entry = new EntryPoint(friendRoot, this.username, [], [name]); return this.addToStaticData(entry).then(function(res) { // send details to allow friend to follow us // create a tmp keypair whose public key we can append to the request without leaking information var tmp = User.random(); var payload = entry.serializeAndEncrypt(tmp, targetUser); return corenodeClient.followRequest(targetUser.getPublicKeys(), concat(tmp.pBoxKey, payload)); }); }.bind(this)); }.bind(this)); }.bind(this); this.sendFollowRequest = function(targetUser) { return this.sendWriteAccess(targetUser); } this.sendWriteAccess = function(targetUser) { // create sharing keypair and give it write access var sharing = User.random(); var rootMapKey = window.nacl.randomBytes(32); // add a note to our static data so we know who we sent the private key to var friendRoot = new ReadableFilePointer(user, sharing, rootMapKey, SymmetricKey.random()); return this.addSharingKey(sharing).then(function(res) { return this.corenodeClient.getUsername(targetUser.getPublicKeys()).then(function(name) { const entry = new EntryPoint(friendRoot, this.username, [], [name]); return this.addToStaticData(entry).then(function(res) { // send details to allow friend to share with us (i.e. we follow them) // create a tmp keypair whose public key we can append to the request without leaking information var tmp = User.random(); var payload = entry.serializeAndEncrypt(tmp, targetUser); return corenodeClient.followRequest(targetUser.getPublicKeys(), concat(tmp.pBoxKey, payload)); }); }.bind(this)); }.bind(this)); }.bind(this); this.addSharingKey = function(pub) { var signed = user.signMessage(pub.getPublicKeys()); return corenodeClient.allowSharingKey(user.getPublicKeys(), signed); } this.addToStaticData = function(entry) { this.staticData.push([entry.pointer.writer, entry]); var rawStatic = new Uint8Array(this.serializeStatic()); return corenodeClient.updateStaticData(user, user.signMessage(rawStatic)); } this.getFollowRequests = function() { return corenodeClient.getFollowRequests(user.getPublicKeys()); } this.decodeFollowRequest = function(raw) { var pBoxKey = new Uint8Array(32); for (var i=0; i < 32; i++) pBoxKey[i] = raw[i]; // signing key is not used var tmp = new UserPublicKey(null, pBoxKey); var buf = new ByteArrayInputStream(raw); buf.read(32); var cipher = new Uint8Array(buf.read(raw.length - 32)); return EntryPoint.decryptAndDeserialize(cipher, user, tmp); } this.uploadFragment = function(f, targetUser, sharer, mapKey) { return dhtClient.put(f.getHash(), f.getData(), targetUser.getPublicKeys(), sharer.getPublicKeys(), mapKey, sharer.signMessage(concat(sharer.getPublicKeys(), f.getHash()))); } this.uploadChunk = function(metadata, fragments, owner, sharer, mapKey) { var buf = new ByteArrayOutputStream(); metadata.serialize(buf); var metaBlob = buf.toByteArray(); console.log("Storing metadata blob of " + metaBlob.length + " bytes."); return corenodeClient.addMetadataBlob(owner.getPublicKeys(), sharer.getPublicKeys(), mapKey, metaBlob, sharer.signMessage(concat(mapKey, metaBlob))) .then(function(added) { if (!added) { console.log("Meta blob store failed."); } }).then(function() { if (fragments.length == 0 ) return Promise.resolve(true); // now upload fragments to DHT var futures = []; for (var i=0; i < fragments.length; i++) futures[i] = this.uploadFragment(fragments[i], owner, sharer, mapKey); // wait for all fragments to upload return Promise.all(futures); }.bind(this)); } this.getRoots = function() { const context = this; return corenodeClient.getStaticData(user).then(function(raw) { var buf = new ByteArrayInputStream(raw); var totalStaticLength = buf.readInt(); var count = buf.readInt(); var res = []; for (var i=0; i < count; i++) { var entry = EntryPoint.decryptAndDeserialize(buf.readArray(), context.user, context.user); res.push(entry); } // download the metadata blobs for these entry points var proms = []; for (var i=0; i < res.length; i++) proms[i] = corenodeClient.getMetadataBlob(res[i].pointer.owner, res[i].pointer.writer, res[i].pointer.mapKey); return Promise.all(proms).then(function(result) { var entryPoints = []; for (var i=0; i < result.length; i++) { if (result[i].byteLength > 8) { var unwrapped = new ByteArrayInputStream(result[i]).readArray(); entryPoints.push([res[i], FileAccess.deserialize(unwrapped)]); } else entryPoints.push([res[i], null]); } return Promise.resolve(entryPoints); }); }); } this.getTreeRoot = function() { return this.getRoots().then(function(roots){ var entrypoints = roots.map(function(x) {return new FileTreeNode(new RetrievedFilePointer(x[0].pointer, x[1]), x[0].owner, x[0].readers, x[0].writers, x[0].pointer.writer);}); console.log(entrypoints); var globalRoot = FileTreeNode.ROOT; var proms = []; var getAncestors = function(treeNode, context) { return treeNode.retrieveParent(context).then(function(parent) { if (parent == null) return Promise.resolve(true); parent.addChild(treeNode); return getAncestors(parent, context); }); } for (var i=0; i < entrypoints.length; i++) { var current = entrypoints[i]; proms.push(getAncestors(current)); } return Promise.all(proms).then(function(res) { return Promise.resolve(globalRoot); }); }.bind(this)); }.bind(this); // [SymmetricLocationLink], SymmetricKey this.retrieveAllMetadata = function(links, baseKey) { var proms = []; for (var i=0; i < links.length; i++) { var loc = links[i].targetLocation(baseKey); proms[i] = corenodeClient.getMetadataBlob(loc.owner, loc.writer, loc.mapKey); } return Promise.all(proms).then(function(rawBlobs) { var accesses = []; for (var i=0; i < rawBlobs.length; i++) { var unwrapped = new ByteArrayInputStream(rawBlobs[i]).readArray(); accesses[i] = [links[i].toReadableFilePointer(baseKey), unwrapped.length > 0 ? FileAccess.deserialize(unwrapped) : null]; } const res = []; for (var i=0; i < accesses.length; i++) if (accesses[i][1] != null) res.push(accesses[i]); return Promise.resolve(res); }); } this.getMetadata = function(loc) { return corenodeClient.getMetadataBlob(loc.owner, loc.writer, loc.mapKey).then(function(buf) { var unwrapped = new ByteArrayInputStream(buf).readArray(); return FileAccess.deserialize(unwrapped); }); } this.downloadFragments = function(hashes, nRequired) { var result = {}; result.fragments = []; result.nError = 0; var proms = []; for (var i=0; i < hashes.length; i++) proms.push(dhtClient.get(hashes[i]).then(function(val) { result.fragments.push(val); console.log("Got Fragment."); }).catch(function() { result.nError++; })); return Promise.all(proms).then(function (all) { console.log("All done."); if (result.fragments.length < nRequired) throw "Not enough fragments!"; return Promise.resolve(result.fragments); }); } } function ReadableFilePointer(owner, writer, mapKey, baseKey) { this.owner = owner; //UserPublicKey this.writer = writer; //User / UserPublicKey this.mapKey = mapKey; //ByteArrayWrapper this.baseKey = baseKey; //SymmetricKey this.serialize = function() { var bout = new ByteArrayOutputStream(); bout.writeArray(owner.getPublicKeys()); if (writer instanceof User) bout.writeArray(writer.getSecretKeys()); else bout.writeArray(writer.getPublicKeys()); bout.writeArray(mapKey); bout.writeArray(baseKey.key); return bout.toByteArray(); } this.isWritable = function() { return this.writer instanceof User; } this.toLink = function() { return "/public/" + bytesToHex(owner.getPublicKeys()) + "/" + bytesToHex(writer.getPublicKeys()) + "/" + bytesToHex(mapKey) + "/" + bytesToHex(baseKey.key); } } ReadableFilePointer.fromLink = function(keysString) { const split = keysString.split("/"); const owner = UserPublicKey.fromPublicKeys(hexToBytes(split[0])); const writer = UserPublicKey.fromPublicKeys(hexToBytes(split[1])); const mapKey = hexToBytes(split[2]); const baseKey = new SymmetricKey(hexToBytes(split[3])); return new ReadableFilePointer(owner, writer, mapKey, baseKey); } ReadableFilePointer.deserialize = function(arr) { const bin = new ByteArrayInputStream(arr); const owner = bin.readArray(); const writerRaw = bin.readArray(); const mapKey = bin.readArray(); const rootDirKeySecret = bin.readArray(); const writer = writerRaw.length == window.nacl.box.secretKeyLength + window.nacl.sign.secretKeyLength ? User.fromSecretKeys(writerRaw) : UserPublicKey.fromPublicKeys(writerRaw); return new ReadableFilePointer(UserPublicKey.fromPublicKeys(owner), writer, mapKey, new SymmetricKey(rootDirKeySecret)); } // RetrievedFilePointer, string, [string], [string] function FileTreeNode(pointer, ownername, readers, writers, entryWriterKey) { var pointer = pointer; // O/W/M/K + FileAccess var children = []; var childrenByName = {}; var owner = ownername; var readers = readers; var writers = writers; var entryWriterKey = entryWriterKey; this.addChild = function(child) { var name = child.getFileProperties().name; if (childrenByName[name] != null) { if (pointer != null) { throw "Child already exists with name: "+name; } else return; } children.push(child); childrenByName[name] = child; } this.isWritable = function() { return pointer.filePointer.writer instanceof User; } this.retrieveParent = function(context) { if (pointer == null) return Promise.resolve(null); var parentKey = pointer.filePointer.baseKey; if (this.isDirectory()) parentKey = pointer.fileAccess.getParentKey(parentKey); return pointer.fileAccess.getParent(parentKey, context).then(function(parentRFP) { if (parentRFP == null) return Promise.resolve(FileTreeNode.ROOT); return Promise.resolve(new FileTreeNode(parentRFP, owner, [], [], entryWriterKey)); }); } this.getChildren = function(context) { if (this == FileTreeNode.ROOT) return Promise.resolve(children); return retrieveChildren(context).then(function(childrenRFPs){ return Promise.resolve(childrenRFPs.map(function(x) {return new FileTreeNode(x, owner, readers, writers, entryWriterKey);})); }); } var retrieveChildren = function(context) { const filePointer = pointer.filePointer; const fileAccess = pointer.fileAccess; const rootDirKey = filePointer.baseKey; return fileAccess.getChildren(userContext, rootDirKey) } this.isDirectory = function() { return pointer.fileAccess.isDirectory(); } this.uploadFile = function(filename, data, context) { const fileKey = SymmetricKey.random(); const rootRKey = pointer.filePointer.baseKey; const owner = pointer.filePointer.owner; const dirMapKey = pointer.filePointer.mapKey; const writer = pointer.filePointer.writer; const dirAccess = pointer.fileAccess; const parentLocation = new Location(owner, writer, dirMapKey); const dirParentKey = dirAccess.getParentKey(rootRKey); const file = new FileUploader(filename, data, fileKey, parentLocation, dirParentKey); return file.upload(context, owner, entryWriterKey).then(function(fileLocation) { dirAccess.addFile(fileLocation, rootRKey, fileKey); return userContext.uploadChunk(dirAccess, [], owner, entryWriterKey, dirMapKey); }); } this.mkdir = function(newFolderName, context) { if (!this.isDirectory()) return Promise.resolve(false); const dirPointer = pointer.filePointer; const dirAccess = pointer.fileAccess; var rootDirKey = dirPointer.baseKey; return dirAccess.mkdir(newFolderName, context, entryWriterKey, dirPointer.mapKey, rootDirKey); } this.rename = function(newName, context) { //get current props const filePointer = pointer.filePointer; const baseKey = filePointer.baseKey; const fileAccess = pointer.fileAccess; const key = this.isDirectory() ? fileAccess.getParentKey(baseKey) : baseKey; const currentProps = fileAccess.getFileProperties(key); const newProps = new FileProperties(newName, currentProps.size); return fileAccess.rename(writableFilePointer(), newProps, context); } var writableFilePointer = function() { const filePointer = pointer.filePointer; const fileAccess = pointer.fileAccess; const baseKey = filePointer.baseKey; return new ReadableFilePointer(filePointer.owner, entryWriterKey, filePointer.mapKey, baseKey); }.bind(this); this.remove = function(context) { return new RetrievedFilePointer(writableFilePointer(), pointer.fileAccess).remove(context); } this.getInputStream = function(context, size) { const baseKey = pointer.filePointer.baseKey; return pointer.fileAccess.retriever.getFile(context, baseKey, size) } this.getFileProperties = function() { const parentKey = this.isDirectory() ? pointer.fileAccess.getParentKey(pointer.filePointer.baseKey) : pointer.filePointer.baseKey return pointer.fileAccess.getFileProperties(parentKey); } } FileTreeNode.ROOT = new FileTreeNode(null, null, [], [], null); function logout() { FileTreeNode.ROOT = new FileTreeNode(null, null, [], [], null); } //ReadableFilePointer, FileAccess function RetrievedFilePointer(pointer, access) { this.filePointer = pointer; this.fileAccess = access; this.remove = function(context, parentRetrievedFilePointer) { if (!this.filePointer.isWritable()) return Promise.resolve(false); if (!this.fileAccess.isDirectory()) return this.fileAccess.removeFragments(context).then(function() { context.corenodeClient.removeMetadataBlob(this.filePointer.owner, this.filePointer.writer, this.filePointer.mapKey); }.bind(this)).then(function() { // remove from parent if (parentRetrievedFilePointer != null) parentRetrievedFilePointer.fileAccess.removeChild(this, parentRetrievedFilePointer.filePointer, context); }.bind(this)); return this.fileAccess.getChildren(context, this.filePointer.baseKey).then(function(files) { const proms = []; for (var i=0; i < files.length; i++) proms.push(files[i].remove(context, null)); return Promise.all(proms).then(function() { return context.corenodeClient.removeMetadataBlob(this.filePointer.owner, this.filePointer.writer, this.filePointer.mapKey); }.bind(this)).then(function() { // remove from parent if (parentRetrievedFilePointer != null) parentRetrievedFilePointer.fileAccess.removeChild(this, parentRetrievedFilePointer.filePointer, context); }); }.bind(this)); }.bind(this); } // ReadableFilePinter, String, [String], [String] function EntryPoint(pointer, owner, readers, writers) { this.pointer = pointer; this.owner = owner; this.readers = readers; this.writers = writers; // User, UserPublicKey this.serializeAndEncrypt = function(user, target) { return target.encryptMessageFor(this.serialize(), user); } this.serialize = function() { const dout = new ByteArrayOutputStream(); dout.writeArray(this.pointer.serialize()); dout.writeString(this.owner); dout.writeInt(this.readers.length); for (var i = 0; i < this.readers.length; i++) { dout.writetring(this.readers[i]); } dout.writeInt(this.writers.length); for (var i=0; i < this.writers.length; i++) { dout.writeString(this.writers[i]); } return dout.toByteArray(); } } // byte[], User, UserPublicKey EntryPoint.decryptAndDeserialize = function(input, user, from) { const raw = new Uint8Array(user.decryptMessage(input, from)); const din = new ByteArrayInputStream(raw); const pointer = ReadableFilePointer.deserialize(din.readArray()); const owner = din.readString(); const nReaders = din.readInt(); const readers = []; for (var i=0; i < nReaders; i++) readers.push(din.readString()); const nWriters = din.readInt(); const writers = []; for (var i=0; i < nWriters; i++) writers.push(din.readString()); return new EntryPoint(pointer, owner, readers, writers); } function SymmetricLink(link) { this.link = slice(link, SymmetricKey.NONCE_BYTES, link.length); this.nonce = slice(link, 0, SymmetricKey.NONCE_BYTES); this.serialize = function() { return concat(this.nonce, this.link); } this.target = function(from) { var encoded = from.decrypt(this.link, this.nonce); return new SymmetricKey(encoded); } } SymmetricLink.fromPair = function(from, to, nonce) { return new SymmetricLink(concat(nonce, from.encrypt(to.key, nonce))); } // UserPublicKey, UserPublicKey, Uint8Array function Location(owner, writer, mapKey) { this.owner = owner; this.writer = writer; this.mapKey = mapKey; this.serialize = function() { var bout = new ByteArrayOutputStream(); bout.writeArray(owner.getPublicKeys()); bout.writeArray(writer.getPublicKeys()); bout.writeArray(mapKey); return bout.toByteArray(); } this.encrypt = function(key, nonce) { return key.encrypt(this.serialize(), nonce); } } Location.deserialize = function(raw) { const buf = raw instanceof ByteArrayInputStream ? raw : new ByteArrayInputStream(raw); var owner = buf.readArray(); var writer = buf.readArray(); var mapKey = buf.readArray(); return new Location(UserPublicKey.fromPublicKeys(owner), UserPublicKey.fromPublicKeys(writer), mapKey); } Location.decrypt = function(from, nonce, loc) { var raw = from.decrypt(loc, nonce); return Location.deserialize(raw); } function SymmetricLocationLink(arr) { const buf = new ByteArrayInputStream(arr); this.link = buf.readArray(); this.loc = buf.readArray(); // SymmetricKey -> Location this.targetLocation = function(from) { var nonce = slice(this.link, 0, SymmetricKey.NONCE_BYTES); return Location.decrypt(from, nonce, this.loc); } this.target = function(from) { var nonce = slice(this.link, 0, SymmetricKey.NONCE_BYTES); var rest = slice(this.link, SymmetricKey.NONCE_BYTES, this.link.length); var encoded = from.decrypt(rest, nonce); return new SymmetricKey(encoded); } this.serialize = function() { var buf = new ByteArrayOutputStream(); buf.writeArray(this.link); buf.writeArray(this.loc); return buf.toByteArray(); } this.toReadableFilePointer = function(baseKey) { const loc = this.targetLocation(baseKey); const key = this.target(baseKey); return new ReadableFilePointer(loc.owner, loc.writer, loc.mapKey, key); } } SymmetricLocationLink.create = function(fromKey, toKey, location) { var nonce = fromKey.createNonce(); var loc = location.encrypt(fromKey, nonce); var link = concat(nonce, fromKey.encrypt(toKey.key, nonce)); var buf = new ByteArrayOutputStream(); buf.writeArray(link); buf.writeArray(loc); return new SymmetricLocationLink(buf.toByteArray()); } function FileAccess(parent2meta, properties, retriever, parentLink) { this.parent2meta = parent2meta; this.properties = properties; this.retriever = retriever; this.parentLink = parentLink; this.serialize = function(bout) { bout.writeArray(parent2meta.serialize()); bout.writeArray(properties); bout.writeByte(retriever != null ? 1 : 0); if (retriever != null) retriever.serialize(bout); bout.writeByte(parentLink != null ? 1: 0); if (parentLink != null) bout.writeArray(this.parentLink.serialize()); bout.writeByte(this.getType()); } // 0=FILE, 1=DIR this.getType = function() { return 0; } this.isDirectory = function() { return this.getType() == 1; } this.getMetaKey = function(parentKey) { return parent2meta.target(parentKey); } this.removeFragments = function(context) { if (this.isDirectory()) return Promise.resolve(true); // TODO delete fragments return Promise.resolve(true); } this.getFileProperties = function(parentKey) { var nonce = slice(this.properties, 0, SymmetricKey.NONCE_BYTES); var cipher = slice(this.properties, SymmetricKey.NONCE_BYTES, this.properties.length); return FileProperties.deserialize(this.getMetaKey(parentKey).decrypt(cipher, nonce)); } this.getParent = function(parentKey, context) { if (this.parentLink == null) return Promise.resolve(null); return context.retrieveAllMetadata([this.parentLink], parentKey).then( function(res) { const retrievedFilePointer = res.map(function(entry) { return new RetrievedFilePointer(entry[0], entry[1]); })[0]; return Promise.resolve(retrievedFilePointer); }) } this.rename = function(writableFilePointer, newProps, context) { if (!writableFilePointer.isWritable()) throw "Need a writable pointer!"; var metaKey; if (this.isDirectory()) { const parentKey = this.subfolders2parent.target(writableFilePointer.baseKey); metaKey = this.getMetaKey(parentKey); const metaNonce = metaKey.createNonce(); const dira = new DirAccess(this.subfolders2files, this.subfolders2parent, this.subfolders, this.files, this.parent2meta, concat(metaNonce, metaKey.encrypt(newProps.serialize(), metaNonce)) ); return context.uploadChunk(dira, [], writableFilePointer.owner, writableFilePointer.writer, writableFilePointer.mapKey); } else { metaKey = this.getMetaKey(writableFilePointer.baseKey); const nonce = metaKey.createNonce(); const fa = new FileAccess(this.parent2meta, concat(nonce, metaKey.encrypt(newProps.serialize(), nonce)), this.retriever, this.parentLink); return context.uploadChunk(fa, [], writableFilePointer.owner, writableFilePointer.writer, writableFilePointer.mapKey); } } } FileAccess.deserialize = function(raw) { const buf = new ByteArrayInputStream(raw); var p2m = buf.readArray(); var properties = buf.readArray(); var hasRetreiver = buf.readByte(); var retriever = (hasRetreiver == 1) ? FileRetriever.deserialize(buf) : null; var hasParent = buf.readByte(); var parentLink = (hasParent == 1) ? new SymmetricLocationLink(buf.readArray()) : null; var type = buf.readByte(); var fileAccess = new FileAccess(new SymmetricLink(p2m), properties, retriever, parentLink); switch(type) { case 0: return fileAccess; case 1: return DirAccess.deserialize(fileAccess, buf); default: throw new Error("Unknown Metadata type: "+type); } } FileAccess.create = function(parentKey, props, retriever, parentLocation, parentparentKey) { var metaKey = SymmetricKey.random(); var nonce = metaKey.createNonce(); return new FileAccess(SymmetricLink.fromPair(parentKey, metaKey, parentKey.createNonce()), concat(nonce, metaKey.encrypt(props.serialize(), nonce)), retriever, SymmetricLocationLink.create(parentKey, parentparentKey, parentLocation)); } function DirAccess(subfolders2files, subfolders2parent, subfolders, files, parent2meta, properties, retriever, parentLink) { FileAccess.call(this, parent2meta, properties, retriever, parentLink); this.subfolders2files = subfolders2files; this.subfolders2parent = subfolders2parent; this.subfolders = subfolders; this.files = files; this.superSerialize = this.serialize; this.serialize = function(bout) { this.superSerialize(bout); bout.writeArray(subfolders2parent.serialize()); bout.writeArray(subfolders2files.serialize()); bout.writeInt(0); bout.writeInt(subfolders.length) for (var i=0; i < subfolders.length; i++) bout.writeArray(subfolders[i].serialize()); bout.writeInt(files.length) for (var i=0; i < files.length; i++) bout.writeArray(files[i].serialize()); } // Location, SymmetricKey, SymmetricKey this.addFile = function(location, ourSubfolders, targetParent) { const filesKey = subfolders2files.target(ourSubfolders); var nonce = filesKey.createNonce(); var loc = location.encrypt(filesKey, nonce); var link = concat(nonce, filesKey.encrypt(targetParent.key, nonce)); var buf = new ByteArrayOutputStream(); buf.writeArray(link); buf.writeArray(loc); this.files.push(SymmetricLocationLink.create(filesKey, targetParent, location)); } this.removeChild = function(childRetrievedPointer, readablePointer, context) { if (childRetrievedPointer.fileAccess.isDirectory()) { const newsubfolders = []; for (var i=0; i < subfolders.length; i++) { const target = subfolders[i].targetLocation(readablePointer.baseKey); var keep = true; if (arraysEqual(target.mapKey, childRetrievedPointer.filePointer.mapKey)) if (arraysEqual(target.writer.getPublicKeys(), childRetrievedPointer.filePointer.writer.getPublicKeys())) if (arraysEqual(target.owner.getPublicKeys(), childRetrievedPointer.filePointer.owner.getPublicKeys())) keep = false; if (keep) newsubfolders.push(subfolders[i]); } this.subfolders = newsubfolders; } else { const newfiles = []; const filesKey = subfolders2files.target(readablePointer.baseKey) for (var i=0; i < files.length; i++) { const target = files[i].targetLocation(filesKey); var keep = true; if (arraysEqual(target.mapKey, childRetrievedPointer.filePointer.mapKey)) if (arraysEqual(target.writer.getPublicKeys(), childRetrievedPointer.filePointer.writer.getPublicKeys())) if (arraysEqual(target.owner.getPublicKeys(), childRetrievedPointer.filePointer.owner.getPublicKeys())) keep = false; if (keep) newfiles.push(files[i]); } this.files = newfiles; } return context.uploadChunk(this, [], readablePointer.owner, readablePointer.writer, readablePointer.mapKey); } // 0=FILE, 1=DIR this.getType = function() { return 1; } // returns [RetrievedFilePointer] this.getChildren = function(context, baseKey) { const prom1 = context.retrieveAllMetadata(this.subfolders, baseKey); const prom2 = context.retrieveAllMetadata(this.files, this.subfolders2files.target(baseKey)); return Promise.all([prom1, prom2]).then(function(mapArr) { const res = mapArr[0]; for (var i=0; i < mapArr[1].length; i++) res.push(mapArr[1][i]); const retrievedFilePointers = res.map(function(entry) { return new RetrievedFilePointer(entry[0], entry[1]); }) return Promise.resolve(retrievedFilePointers); }) } this.getParentKey = function(subfoldersKey) { return this.subfolders2parent.target(subfoldersKey); } this.getFilesKey = function(subfoldersKey) { return this.subfolders2files.target(subfoldersKey); } //String, UserContext, User -> this.mkdir = function(name, userContext, writer, ourMapKey, baseKey) { if (!(writer instanceof User)) throw "Can't modify a directory without write permission (writer must be a User)!"; const dirReadKey = SymmetricKey.random(); const dirMapKey = window.nacl.randomBytes(32); // root will be stored under this in the core node const ourParentKey = this.getParentKey(baseKey); const ourLocation = new Location(userContext.user, writer, ourMapKey); const dir = DirAccess.create(null, dirReadKey, new FileProperties(name, 0), ourLocation, ourParentKey); const that = this; return userContext.uploadChunk(dir, [], userContext.user, writer, dirMapKey) .then(function(success) { if (success) { that.addSubdir(new Location(userContext.user, writer, dirMapKey), baseKey, dirReadKey); // now upload the changed metadata blob for dir return userContext.uploadChunk(that, [], userContext.user, writer, ourMapKey); } return Promise.resolve(false); }); } this.addSubdir = function(location, ourSubfolders, targetBaseKey) { this.subfolders.push(SymmetricLocationLink.create(ourSubfolders, targetBaseKey, location)); } } DirAccess.deserialize = function(base, bin) { var s2p = bin.readArray(); var s2f = bin.readArray(); var nSharingKeys = bin.readInt(); var files = [], subfolders = []; var nsubfolders = bin.readInt(); for (var i=0; i < nsubfolders; i++) subfolders[i] = new SymmetricLocationLink(bin.readArray()); var nfiles = bin.readInt(); for (var i=0; i < nfiles; i++) files[i] = new SymmetricLocationLink(bin.readArray()); return new DirAccess(new SymmetricLink(s2f), new SymmetricLink(s2p), subfolders, files, base.parent2meta, base.properties, base.retriever, base.parentLink); } // User, SymmetricKey, FileProperties //TODO remove owner arg. DirAccess.create = function(owner, subfoldersKey, metadata, parentLocation, parentParentKey) { var metaKey = SymmetricKey.random(); var parentKey = SymmetricKey.random(); var filesKey = SymmetricKey.random(); var metaNonce = metaKey.createNonce(); var parentLink = parentLocation == null ? null : SymmetricLocationLink.create(parentKey, parentParentKey, parentLocation); return new DirAccess(SymmetricLink.fromPair(subfoldersKey, filesKey, subfoldersKey.createNonce()), SymmetricLink.fromPair(subfoldersKey, parentKey, subfoldersKey.createNonce()), [], [], SymmetricLink.fromPair(parentKey, metaKey, parentKey.createNonce()), concat(metaNonce, metaKey.encrypt(metadata.serialize(), metaNonce)), null, parentLink ); } function FileRetriever() { } FileRetriever.deserialize = function(bin) { var type = bin.readByte(); switch (type) { case 0: throw new Exception("Simple FileRetriever not implemented!"); case 1: return EncryptedChunkRetriever.deserialize(bin); default: throw new Exception("Unknown FileRetriever type: "+type); } } function EncryptedChunkRetriever(chunkNonce, chunkAuth, fragmentHashes, nextChunk) { this.chunkNonce = chunkNonce; this.chunkAuth = chunkAuth; this.fragmentHashes = fragmentHashes; this.nextChunk = nextChunk; this.getFile = function(context, dataKey, len) { const stream = this; return this.getChunkInputStream(context, dataKey, len).then(function(chunk) { return Promise.resolve(new LazyInputStreamCombiner(stream, context, dataKey, chunk)); }); } this.getNext = function() { return nextChunk; } this.getChunkInputStream = function(context, dataKey, len) { var fragmentsProm = context.downloadFragments(fragmentHashes); return fragmentsProm.then(function(fragments) { fragments = reorder(fragments, fragmentHashes); var cipherText = erasure.recombine(fragments, len != 0 ? len : Chunk.MAX_SIZE, EncryptedChunk.ERASURE_ORIGINAL, EncryptedChunk.ERASURE_ALLOWED_FAILURES); if (len != 0) cipherText = cipherText.subarray(0, len); var fullEncryptedChunk = new EncryptedChunk(concat(chunkAuth, cipherText)); var original = fullEncryptedChunk.decrypt(dataKey, chunkNonce); return Promise.resolve(original); }); } this.serialize = function(buf) { buf.writeByte(1); // This class buf.writeArray(chunkNonce); buf.writeArray(chunkAuth); buf.writeArray(concat(fragmentHashes)); buf.writeByte(nextChunk != null ? 1 : 0); if (nextChunk != null) buf.write(nextChunk.serialize()); } } EncryptedChunkRetriever.deserialize = function(buf) { var chunkNonce = buf.readArray(); var chunkAuth = buf.readArray(); var concatFragmentHashes = buf.readArray(); var fragmentHashes = split(concatFragmentHashes, UserPublicKey.HASH_BYTES); var hasNext = buf.readByte(); var nextChunk = null; if (hasNext == 1) nextChunk = Location.deserialize(buf); return new EncryptedChunkRetriever(chunkNonce, chunkAuth, fragmentHashes, nextChunk); } function split(arr, size) { var length = arr.byteLength/size; var res = []; for (var i=0; i < length; i++) res[i] = slice(arr, i*size, (i+1)*size); return res; } function LazyInputStreamCombiner(stream, context, dataKey, chunk) { if (!chunk) throw "Invalid current chunk!"; this.context = context; this.dataKey = dataKey; this.current = chunk; this.index = 0; this.next = stream.getNext(); this.getNextStream = function(len) { if (this.next != null) { const lazy = this; return context.getMetadata(this.next).then(function(meta) { var nextRet = meta.retriever; lazy.next = nextRet.getNext(); return nextRet.getChunkInputStream(context, dataKey, len); }); } throw "EOFException"; } this.bytesReady = function() { return this.current.length - this.index; } this.readByte = function() { try { return this.current[this.index++]; } catch (e) {} const lazy = this; this.getNextStream().then(function(res){ lazy.index = 0; lazy.current = res; return lazy.current.readByte(); }); } this.read = function(len, res, offset) { const lazy = this; if (res == null) { res = new Uint8Array(len); offset = 0; } const available = lazy.bytesReady(); const toRead = Math.min(available, len); for (var i=0; i < toRead; i++) res[offset + i] = lazy.readByte(); if (available >= len) return Promise.resolve(res); return this.getNextStream((len-toRead) % Chunk.MAX_SIZE).then(function(chunk){ lazy.index = 0; lazy.current = chunk; return lazy.read(len-toRead, res, offset + toRead); }); } } const GF = new (function(){ this.size = 256; this.expa = new Uint8Array(2*this.size); this.loga = new Uint8Array(this.size); this.expa[0] = 1; var x = 1; for (var i=1; i < 255; i++) { x <<= 1; // field generator polynomial is p(x) = x^8 + x^4 + x^3 + x^2 + 1 if ((x & this.size) != 0) x ^= (this.size | 0x1D); // x^8 = x^4 + x^3 + x^2 + 1 ==> 0001_1101 this.expa[i] = x; this.loga[x] = i; } for (var i=255; i < 512; i++) this.expa[i] = this.expa[i-255]; this.mask = function() { return this.size-1; } this.exp = function(y) { return this.expa[y]; } this.mul = function(x, y) { if ((x==0) || (y==0)) return 0; return this.expa[this.loga[x]+this.loga[y]]; } this.div = function(x, y) { if (y==0) throw new IllegalStateException("Divided by zero! Blackhole created.. "); if (x==0) return 0; return this.expa[this.loga[x]+255-this.loga[y]]; } })(); // Uint8Array, GaloisField GaloisPolynomial = {}; GaloisPolynomial.check = function(coefficients, f) { if (coefficients.length > f.size) throw "Polynomial order must be less than or equal to the degree of the Galois field. " + coefficients.length + " !> " + f.size; } GaloisPolynomial.order = function(coefficients) { return coefficients.length; } GaloisPolynomial.evalu = function(f, coefficients, x) { var y = coefficients[0]; for (var i=1; i < coefficients.length; i++) y = f.mul(y, x) ^ coefficients[i]; return y; } // Uint8 -> GaloisPolynomial GaloisPolynomial.scale = function(f, coefficients, x) { const res = new Uint8Array(coefficients.length); for (var i=0; i < res.length; i++) res[i] = f.mul(x, coefficients[i]); return res; } // GaloisPolynomial -> GaloisPolynomial GaloisPolynomial.add = function(f, coefficients, other) { const order = GaloisPolynomial.order(coefficients); const res = new Uint8Array(Math.max(order, GaloisPolynomial.order(other))); for (var i=0; i < order; i++) res[i + res.length - order] = coefficients[i]; for (var i=0; i < GaloisPolynomial.order(other); i++) res[i + res.length - GaloisPolynomial.order(other)] ^= other[i]; return res; } // GaloisPolynomial -> GaloisPolynomial GaloisPolynomial.mul = function(f, coefficients, other) { const order = GaloisPolynomial.order(coefficients); const res = new Uint8Array(order + GaloisPolynomial.order(other) - 1); for (var i=0; i < order; i++) for (var j=0; j < GaloisPolynomial.order(other); j++) res[i+j] ^= f.mul(coefficients[i], other[j]); return res; } // Uint8 -> GaloisPolynomial GaloisPolynomial.append = function(coefficients, x) { const res = new Uint8Array(coefficients.length+1); for (var i=0; i < coefficients.length; i++) res[i] = coefficients[i]; res[res.length-1] = x; return res; } // (int, GaloisField) -> GaloisPolynomial GaloisPolynomial.generator = function(nECSymbols, f) { const one = new Uint8Array(1); one[0] = 1; var g = one; for (var i=0; i < nECSymbols; i++) { var multiplicand = new Uint8Array(2); multiplicand[0] = 1; multiplicand[0] = f.exp(i); g = GaloisPolynomial.mul(f, g, multiplicand); } return g; } // (Uint8Array, int, GaloisField) -> Uint8Array GaloisPolynomial.encode = function(input, nEC, f) { const gen = GaloisPolynomial.generator(nEC, f); const res = new Uint8Array(input.length + nEC); for (var i=0; i < input.length; i++) res[i] = input[i]; for (var i=0; i < input.length; i++) { const c = res[i]; if (c != 0) for (var j=0; j < GaloisPolynomial.order(gen); j++) res[i+j] ^= f.mul(gen[j], c); } for (var i=0; i < input.length; i++) res[i] = input[i]; return res; } // -> Uint8Array GaloisPolynomial.syndromes = function(input, nEC, f) { const res = new Uint8Array(nEC); const poly = input; for (var i=0; i < nEC; i++) res[i] = GaloisPolynomial.evalu(f, poly, f.exp(i)); return res; } // (Uint8Array, Uint8Array, Int[], GaloisField) -> () GaloisPolynomial.correctErrata = function(input, synd, pos, f) { if (pos.length == 0) return; const one = new Uint8Array(1); one[0] = 1; var q = one; for (var j=0; j < pos.length; j++) { var i = pos[j]; const x = f.exp(input.length - 1 - i); q = GaloisPolynomial.mul(f, q, GaloisPolynomial.create([x, 1], f)); } var t = new Uint8Array(pos.size()); for (var i=0; i < t.length; i++) t[i] = synd[t.length-1-i]; var p = GaloisPolynomial.mul(f, t, q); t = new Uint8Array(pos.size()); for (var i=0; i < t.length; i++) t[i] = p[i + p.order()-t.length]; p = t; const qorder = GaloisPolynomial.order(q); t = new Uint8Array((qorder- (qorder & 1))/2); for (var i=qorder & 1; i < qorder; i+= 2) t[i/2] = q.coefficients[i]; const qprime = t; for (var j=0; j < pos.length; j++) { const i = pos[j]; const x = f.exp(i + f.size - input.length); const y = GaloisPolynomial.evalu(f, p, x); const z = GaloisPolynomial.evalu(f, qprime, f.mul(x, x)); input[i] ^= f.div(y, f.mul(x, z)); } } // (Int[], int, GaloisField) -> Int[] GaloisPolynomial.findErrors = function(synd, nmess, f) { var errPoly = GaloisPolynomial.create([1], f); var oldPoly = GaloisPolynomial.create([1], f); for (var i=0; i < synd.length; i++) { oldPoly = GaloisPolynomial.append(oldPoly, 0); var delta = synd[i]; for (var j=1; j < GaloisPolynomial.order(errPoly); j++) delta ^= f.mul(errPoly[GaloisPolynomial.order(errPoly) - 1 - j], synd[i - j]); if (delta != 0) { if (GaloisPolynomial.order(oldPoly) > GaloisPolynomial.order(errPoly)) { var newPoly = GaloisPolynomial.scale(f, oldPoly, delta); oldPoly = GaloisPolynomial.scale(f, errPoly, f.div(1, delta)); errPoly = newPoly; } errPoly = GaloisPolynomial.add(f, errPoly, GaloisPolynomial.scale(f, oldPoly, delta)); } } const errs = GaloisPolynomial.order(errPoly)-1; if (2*errs > synd.length) throw "Too many errors to correct! ("+errs+")"; const errorPos = []; for (var i=0; i < nmess; i++) if (GaloisPolynomial.evalu(f, errPoly, f.exp(f.size - 1 - i)) == 0) errorPos.push(nmess - 1 - i); if (errorPos.length != errs) throw "couldn't find error positions! ("+errorPos.length+"!="+errs+") ( missing fragments)"; return errorPos; } // (Uint8Array, int, GaloisField) -> Uint8Array GaloisPolynomial.decode = function(message, nec, f) { const synd = GaloisPolynomial.syndromes(message, nec, f); var max = 0; for (var j=0; j < synd.length; j++) if (synd[j] > max) max = synd[j]; if (max == 0) return message; const errPos = GaloisPolynomial.findErrors(synd, message.length, f); GaloisPolynomial.correctErrata(message, synd, errPos, f); return message; } GaloisPolynomial.create = function(coeffs, f) { const c = new Uint8Array(coeffs.length); for (var i=0; i < coeffs.length; i++) c[i] = coeffs[i]; return c; } function reorder(fragments, hashes) { var hashMap = new Map(); //ba dum che for (var i=0; i < hashes.length; i++) hashMap.set(nacl.util.encodeBase64(hashes[i]), i); // Seems Map can't handle array contents equality var res = []; for (var i=0; i < fragments.length; i++) { var hash = nacl.util.encodeBase64(UserPublicKey.hash(fragments[i])); var index = hashMap.get(hash); res[index] = fragments[i]; } return res; } function string2arraybuffer(str) { var buf = new ArrayBuffer(str.length); var bufView = new Uint8Array(buf); for (var i=0, strLen=str.length; i<strLen; i++) { bufView[i] = str.charCodeAt(i); } return bufView; } function bytesToHex(p) { /** @const */ var enc = '0123456789abcdef'.split(''); var len = p.length, arr = [], i = 0; for (; i < len; i++) { arr.push(enc[(p[i]>>>4) & 15]); arr.push(enc[(p[i]>>>0) & 15]); } return arr.join(''); } function hexToBytes(hex) { var result = new Uint8Array(hex.length/2); for (var i=0; i + 1 < 2*result.length; i+= 2) result[i/2] = parseInt(hex.substring(i, i+2), 16); return result; } if (typeof module !== "undefined"){ module.exports.randomSymmetricKey = randomSymmetricKey; module.exports.SymmetricKey = SymmetricKey; }
added type signature comment.
ui/scripts/api.js
added type signature comment.
<ide><path>i/scripts/api.js <ide> return nacl.sign.open(sig, this.pSignKey); <ide> } <ide> } <del> <add>//Uint8Array => UserPublicKey <ide> UserPublicKey.fromPublicKeys = function(both) { <ide> var pSign = slice(both, 0, 32); <ide> var pBox = slice(both, 32, 64);
JavaScript
mit
17ac26d209cd1ec12b60bb5f8aa22f2be7a94447
0
devsy-io/devsy-editor
import {join} from 'path' import {HotModuleReplacementPlugin} from 'webpack' const SRC_PATH = join(__dirname, '/src') const APP_PATH = join(__dirname, '/examples') export default { context: APP_PATH, entry: './', output: { path: join(__dirname, 'dist'), filename: '[name].js', publicPath: 'http://localhost:3000/dist' }, resolve: { alias: { 'devsy-editor': SRC_PATH }, extensions: ['', '.js', '.scss'] }, module: { loaders: [{ test: /\.scss$/, loaders: ['style', 'css', 'sass'], include: [APP_PATH, SRC_PATH] }, { test: /\.js$/, loaders: ['babel'], include: [APP_PATH, SRC_PATH] }] }, devtool: 'eval', devServer: { port: 3000, stats: { colors: true }, inline: true, publicPath: '/dist/' }, plugins: [ new HotModuleReplacementPlugin() ] }
webpack.config.dev.babel.js
import {join} from 'path' import {HotModuleReplacementPlugin} from 'webpack' const SRC_PATH = join(__dirname, '/src') const APP_PATH = join(__dirname, '/examples') export default { context: APP_PATH, entry: './', output: { path: join(__dirname, 'dist'), filename: '[name].js', publicPath: 'http://localhost:3000/dist' }, resolve: { alias: { 'devsy-editor': SRC_PATH }, extensions: ['', '.js', '.scss'] }, module: { loaders: [{ test: /\.scss$/, loaders: ['style', 'css', 'sass'], include: [APP_PATH, SRC_PATH] }, { test: /\.js$/, loaders: ['babel'], include: [APP_PATH, SRC_PATH] }] }, devServer: { port: 3000, stats: { colors: true }, inline: true, publicPath: '/dist/' }, plugins: [ new HotModuleReplacementPlugin() ] }
add eval as devtool
webpack.config.dev.babel.js
add eval as devtool
<ide><path>ebpack.config.dev.babel.js <ide> include: [APP_PATH, SRC_PATH] <ide> }] <ide> }, <add> devtool: 'eval', <ide> devServer: { <ide> port: 3000, <ide> stats: { colors: true },
Java
mit
error: pathspec 'src/main/java/net/davidvoid/thor/lightning/data/access/Counter.java' did not match any file(s) known to git
855c914d1764fa24bede4569c003c2d3193f3e74
1
dahakawang/lightning
package net.davidvoid.thor.lightning.data.access; import net.davidvoid.thor.lightning.data.source.MongoDataSource; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Component; import com.mongodb.BasicDBObject; import com.mongodb.DBCollection; import com.mongodb.DBObject; /** * Created by david on 3/22/16. * {_id: XX, name: string, seq: long } * index 1: name, unique * */ @Component public class Counter { @Autowired MongoDataSource data_source = null; public long getNextId(String col_name) { BasicDBObject query = new BasicDBObject("name", col_name); BasicDBObject update = new BasicDBObject("$inc", new BasicDBObject("seq", 1)); DBCollection col = data_source.getDatabase().getCollection("counter"); DBObject returned = col.findAndModify(query, null, null, false, update, true, true); return (long) returned.get("seq"); } }
src/main/java/net/davidvoid/thor/lightning/data/access/Counter.java
add a counter class to generate auto incremental ids
src/main/java/net/davidvoid/thor/lightning/data/access/Counter.java
add a counter class to generate auto incremental ids
<ide><path>rc/main/java/net/davidvoid/thor/lightning/data/access/Counter.java <add>package net.davidvoid.thor.lightning.data.access; <add> <add>import net.davidvoid.thor.lightning.data.source.MongoDataSource; <add> <add>import org.springframework.beans.factory.annotation.Autowired; <add>import org.springframework.stereotype.Component; <add> <add>import com.mongodb.BasicDBObject; <add>import com.mongodb.DBCollection; <add>import com.mongodb.DBObject; <add> <add>/** <add> * Created by david on 3/22/16. <add> * {_id: XX, name: string, seq: long } <add> * index 1: name, unique <add> * <add> */ <add>@Component <add>public class Counter { <add> @Autowired <add> MongoDataSource data_source = null; <add> <add> public long getNextId(String col_name) { <add> BasicDBObject query = new BasicDBObject("name", col_name); <add> BasicDBObject update = new BasicDBObject("$inc", new BasicDBObject("seq", 1)); <add> <add> DBCollection col = data_source.getDatabase().getCollection("counter"); <add> DBObject returned = col.findAndModify(query, null, null, false, update, true, true); <add> <add> return (long) returned.get("seq"); <add> } <add>}
Java
apache-2.0
b81ad6e7aaa04a96fac6361d0fa49d34ebf74d8e
0
FreeMannLH/Android-ActionItemBadge,swapnilbhai90/Android-ActionItemBadge,chianghomer/Android-ActionItemBadge,MaTriXy/Android-ActionItemBadge,confile/Android-ActionItemBadge,eneim/Android-ActionItemBadge,hgl888/Android-ActionItemBadge,mikepenz/Android-ActionItemBadge
package com.mikepenz.actionitembadge.library; import android.annotation.SuppressLint; import android.app.Activity; import android.graphics.drawable.Drawable; import android.view.Menu; import android.view.MenuItem; import android.view.View; import android.widget.Button; import android.widget.ImageView; import android.widget.TextView; import com.mikepenz.iconics.IconicsDrawable; import com.mikepenz.iconics.typeface.IIcon; /** * Created by mikepenz on 23.07.14. */ public class ActionItemBadge { public enum BadgeStyle { GREY(Style.DEFAULT, R.drawable.menu_grey_badge, R.layout.menu_badge), DARKGREY(Style.DEFAULT, R.drawable.menu_darkgrey_badge, R.layout.menu_badge), RED(Style.DEFAULT, R.drawable.menu_red_badge, R.layout.menu_badge), BLUE(Style.DEFAULT, R.drawable.menu_blue_badge, R.layout.menu_badge), GREEN(Style.DEFAULT, R.drawable.menu_green_badge, R.layout.menu_badge), PURPLE(Style.DEFAULT, R.drawable.menu_purple_badge, R.layout.menu_badge), YELLOW(Style.DEFAULT, R.drawable.menu_yellow_badge, R.layout.menu_badge), GREY_LARGE(Style.LARGE, R.drawable.menu_grey_badge_large, R.layout.menu_badge_large), DARKGREY_LARGE(Style.LARGE, R.drawable.menu_darkgrey_badge_large, R.layout.menu_badge_large), RED_LARGE(Style.LARGE, R.drawable.menu_red_badge_large, R.layout.menu_badge_large), BLUE_LARGE(Style.LARGE, R.drawable.menu_blue_badge_large, R.layout.menu_badge_large), GREEN_LARGE(Style.LARGE, R.drawable.menu_green_badge_large, R.layout.menu_badge_large), PURPLE_LARGE(Style.LARGE, R.drawable.menu_purple_badge_large, R.layout.menu_badge_large), YELLOW_LARGE(Style.LARGE, R.drawable.menu_yellow_badge_large, R.layout.menu_badge_large); private Style style; private int drawable; private int layout; BadgeStyle(Style style, int drawable, int layout) { this.style = style; this.drawable = drawable; this.layout = layout; } public Style getStyle() { return style; } public int getDrawable() { return drawable; } public int getLayout() { return layout; } public enum Style { DEFAULT(1), LARGE(2); private int style; Style(int style) { this.style = style; } public int getStyle() { return style; } } } public static class Add { public Add() { } public Add(Activity activity, Menu menu, String title) { this.activity = activity; this.menu = menu; this.title = title; } private Activity activity; public Add act(Activity activity) { this.activity = activity; return this; } private Menu menu; public Add menu(Menu menu) { this.menu = menu; return this; } private String title; public Add title(String title) { this.title = title; return this; } public Add title(int resId) { if (activity == null) { throw new RuntimeException("Activity not set"); } this.title = activity.getString(resId); return this; } private Integer groupId; private Integer itemId; private Integer order; public Add itemDetails(int groupId, int itemId, int order) { this.groupId = groupId; this.itemId = itemId; this.order = order; return this; } private Integer showAsAction; public Add showAsAction(int showAsAction) { this.showAsAction = showAsAction; return this; } public Menu build(int badgeCount) { return build((Drawable) null, BadgeStyle.GREY_LARGE, badgeCount); } public Menu build(BadgeStyle style, int badgeCount) { return build((Drawable) null, style, badgeCount); } public Menu build(IIcon icon, int badgeCount) { return build(new IconicsDrawable(activity, icon).colorRes(R.color.actionbar_text).actionBarSize(), BadgeStyle.GREY, badgeCount); } public Menu build(Drawable icon, int badgeCount) { return build(icon, BadgeStyle.GREY, badgeCount); } public Menu build(IIcon icon, BadgeStyle style, int badgeCount) { return build(new IconicsDrawable(activity, icon).colorRes(R.color.actionbar_text).actionBarSize(), style, badgeCount); } public Menu build(Drawable icon, BadgeStyle style, int badgeCount) { MenuItem item; if (groupId != null && itemId != null && order != null) { item = menu.add(groupId, itemId, order, title); } else { item = menu.add(title); } if (showAsAction != null) { item.setShowAsAction(showAsAction); } item.setActionView(style.getLayout()); update(activity, item, icon, style, badgeCount); return menu; } } public static void update(final Activity act, final MenuItem menu, int badgeCount) { update(act, menu, (Drawable) null, null, badgeCount); } public static void update(final Activity act, final MenuItem menu, BadgeStyle style, int badgeCount) { if (style.getStyle() != BadgeStyle.Style.LARGE) { throw new RuntimeException("You are not allowed to call update without an icon on a Badge with default style"); } update(act, menu, (Drawable) null, style, badgeCount); } public static void update(final Activity act, final MenuItem menu, IIcon icon, int badgeCount) { update(act, menu, new IconicsDrawable(act, icon).colorRes(R.color.actionbar_text).actionBarSize(), BadgeStyle.GREY, badgeCount); } public static void update(final Activity act, final MenuItem menu, Drawable icon, int badgeCount) { update(act, menu, icon, BadgeStyle.GREY, badgeCount); } public static void update(final Activity act, final MenuItem menu, IIcon icon, BadgeStyle style, int badgeCount) { update(act, menu, new IconicsDrawable(act, icon).colorRes(R.color.actionbar_text).actionBarSize(), style, badgeCount); } public static void update(final Activity act, final MenuItem menu, Drawable icon, BadgeStyle style, int badgeCount) { if (menu != null) { View badge = menu.getActionView(); if (style != null) { if (style.getStyle() == BadgeStyle.Style.DEFAULT) { ImageView imageView = (ImageView) badge.findViewById(R.id.menu_badge_icon); if (icon != null) { ActionItemBadge.setBackground(imageView, icon); } TextView textView = (TextView) badge.findViewById(R.id.menu_badge_text); if (badgeCount < 0) { textView.setVisibility(View.GONE); } else { textView.setVisibility(View.VISIBLE); textView.setText(String.valueOf(badgeCount)); textView.setBackgroundResource(style.getDrawable()); } } else { Button button = (Button) badge.findViewById(R.id.menu_badge_button); if (button != null) { button.setBackgroundResource(style.getDrawable()); button.setText(String.valueOf(badgeCount)); } } } else { // i know this is not nice but the best solution to allow doing an update without a style ImageView imageView = (ImageView) badge.findViewById(R.id.menu_badge_icon); if (imageView != null) { if (icon != null) { ActionItemBadge.setBackground(imageView, icon); } TextView textView = (TextView) badge.findViewById(R.id.menu_badge_text); if (badgeCount < 0) { textView.setVisibility(View.GONE); } else { textView.setVisibility(View.VISIBLE); textView.setText(String.valueOf(badgeCount)); } } else { Button button = (Button) badge.findViewById(R.id.menu_badge_button); if (style != null) { button.setBackgroundResource(style.getDrawable()); } button.setText(String.valueOf(badgeCount)); } } badge.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { act.onOptionsItemSelected(menu); } }); menu.setVisible(true); } } public static void hide(MenuItem menu) { menu.setVisible(false); } @SuppressLint("NewApi") private static void setBackground(View v, Drawable d) { int sdk = android.os.Build.VERSION.SDK_INT; if (sdk < android.os.Build.VERSION_CODES.JELLY_BEAN) { v.setBackgroundDrawable(d); } else { v.setBackground(d); } } }
library/src/main/java/com/mikepenz/actionitembadge/library/ActionItemBadge.java
package com.mikepenz.actionitembadge.library; import android.annotation.SuppressLint; import android.app.Activity; import android.graphics.drawable.Drawable; import android.view.Menu; import android.view.MenuItem; import android.view.View; import android.widget.Button; import android.widget.ImageView; import android.widget.TextView; import com.mikepenz.iconics.IconicsDrawable; import com.mikepenz.iconics.typeface.IIcon; /** * Created by mikepenz on 23.07.14. */ public class ActionItemBadge { public enum BadgeStyle { GREY(Style.DEFAULT, R.drawable.menu_grey_badge, R.layout.menu_badge), DARKGREY(Style.DEFAULT, R.drawable.menu_darkgrey_badge, R.layout.menu_badge), RED(Style.DEFAULT, R.drawable.menu_red_badge, R.layout.menu_badge), BLUE(Style.DEFAULT, R.drawable.menu_blue_badge, R.layout.menu_badge), GREEN(Style.DEFAULT, R.drawable.menu_green_badge, R.layout.menu_badge), PURPLE(Style.DEFAULT, R.drawable.menu_purple_badge, R.layout.menu_badge), YELLOW(Style.DEFAULT, R.drawable.menu_yellow_badge, R.layout.menu_badge), GREY_LARGE(Style.LARGE, R.drawable.menu_grey_badge_large, R.layout.menu_badge_large), DARKGREY_LARGE(Style.LARGE, R.drawable.menu_darkgrey_badge_large, R.layout.menu_badge_large), RED_LARGE(Style.LARGE, R.drawable.menu_red_badge_large, R.layout.menu_badge_large), BLUE_LARGE(Style.LARGE, R.drawable.menu_blue_badge_large, R.layout.menu_badge_large), GREEN_LARGE(Style.LARGE, R.drawable.menu_green_badge_large, R.layout.menu_badge_large), PURPLE_LARGE(Style.LARGE, R.drawable.menu_purple_badge_large, R.layout.menu_badge_large), YELLOW_LARGE(Style.LARGE, R.drawable.menu_yellow_badge_large, R.layout.menu_badge_large); private Style style; private int drawable; private int layout; private BadgeStyle(Style style, int drawable, int layout) { this.style = style; this.drawable = drawable; this.layout = layout; } public Style getStyle() { return style; } public int getDrawable() { return drawable; } public int getLayout() { return layout; } public enum Style { DEFAULT(1), LARGE(2); private int style; private Style(int style) { this.style = style; } public int getStyle() { return style; } } } public static class Add { public Add() { } public Add(Activity activity, Menu menu, String title) { this.activity = activity; this.menu = menu; this.title = title; } private Activity activity; public Add act(Activity activity) { this.activity = activity; return this; } private Menu menu; public Add menu(Menu menu) { this.menu = menu; return this; } private String title; public Add title(String title) { this.title = title; return this; } public Add title(int resId) { if (activity == null) { throw new RuntimeException("Activity not set"); } this.title = activity.getString(resId); return this; } private Integer groupId; private Integer itemId; private Integer order; public Add itemDetails(int groupId, int itemId, int order) { this.groupId = groupId; this.itemId = itemId; this.order = order; return this; } private Integer showAsAction; public Add showAsAction(int showAsAction) { this.showAsAction = showAsAction; return this; } public Menu build(int badgeCount) { return build((Drawable) null, BadgeStyle.GREY_LARGE, badgeCount); } public Menu build(BadgeStyle style, int badgeCount) { return build((Drawable) null, style, badgeCount); } public Menu build(IIcon icon, int badgeCount) { return build(new IconicsDrawable(activity, icon).colorRes(R.color.actionbar_text).actionBarSize(), BadgeStyle.GREY, badgeCount); } public Menu build(Drawable icon, int badgeCount) { return build(icon, BadgeStyle.GREY, badgeCount); } public Menu build(IIcon icon, BadgeStyle style, int badgeCount) { return build(new IconicsDrawable(activity, icon).colorRes(R.color.actionbar_text).actionBarSize(), style, badgeCount); } public Menu build(Drawable icon, BadgeStyle style, int badgeCount) { MenuItem item; if (groupId != null && itemId != null && order != null) { item = menu.add(groupId, itemId, order, title); } else { item = menu.add(title); } if (showAsAction != null) { item.setShowAsAction(showAsAction); } item.setActionView(style.getLayout()); update(activity, item, icon, style, badgeCount); return menu; } } public static void update(final Activity act, final MenuItem menu, int badgeCount) { update(act, menu, (Drawable) null, null, badgeCount); } public static void update(final Activity act, final MenuItem menu, BadgeStyle style, int badgeCount) { if (style.getStyle() != BadgeStyle.Style.LARGE) { throw new RuntimeException("You are not allowed to call update without an icon on a Badge with default style"); } update(act, menu, (Drawable) null, style, badgeCount); } public static void update(final Activity act, final MenuItem menu, IIcon icon, int badgeCount) { update(act, menu, new IconicsDrawable(act, icon).colorRes(R.color.actionbar_text).actionBarSize(), BadgeStyle.GREY, badgeCount); } public static void update(final Activity act, final MenuItem menu, Drawable icon, int badgeCount) { update(act, menu, icon, BadgeStyle.GREY, badgeCount); } public static void update(final Activity act, final MenuItem menu, IIcon icon, BadgeStyle style, int badgeCount) { update(act, menu, new IconicsDrawable(act, icon).colorRes(R.color.actionbar_text).actionBarSize(), style, badgeCount); } public static void update(final Activity act, final MenuItem menu, Drawable icon, BadgeStyle style, int badgeCount) { if (menu != null) { View badge = menu.getActionView(); if (style != null) { if (style.getStyle() == BadgeStyle.Style.DEFAULT) { ImageView imageView = (ImageView) badge.findViewById(R.id.menu_badge_icon); if (icon != null) { ActionItemBadge.setBackground(imageView, icon); } TextView textView = (TextView) badge.findViewById(R.id.menu_badge_text); if (badgeCount < 0) { textView.setVisibility(View.GONE); } else { textView.setVisibility(View.VISIBLE); textView.setText(String.valueOf(badgeCount)); textView.setBackgroundResource(style.getDrawable()); } } else { Button button = (Button) badge.findViewById(R.id.menu_badge_button); button.setBackgroundResource(style.getDrawable()); button.setText(String.valueOf(badgeCount)); } } else { // i know this is not nice but the best solution to allow doing an update without a style ImageView imageView = (ImageView) badge.findViewById(R.id.menu_badge_icon); if (imageView != null) { if (icon != null) { ActionItemBadge.setBackground(imageView, icon); } TextView textView = (TextView) badge.findViewById(R.id.menu_badge_text); if (badgeCount < 0) { textView.setVisibility(View.GONE); } else { textView.setVisibility(View.VISIBLE); textView.setText(String.valueOf(badgeCount)); } } else { Button button = (Button) badge.findViewById(R.id.menu_badge_button); if (style != null) { button.setBackgroundResource(style.getDrawable()); } button.setText(String.valueOf(badgeCount)); } } badge.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { act.onOptionsItemSelected(menu); } }); menu.setVisible(true); } } public static void hide(MenuItem menu) { menu.setVisible(false); } @SuppressLint("NewApi") private static void setBackground(View v, Drawable d) { int sdk = android.os.Build.VERSION.SDK_INT; if (sdk < android.os.Build.VERSION_CODES.JELLY_BEAN) { v.setBackgroundDrawable(d); } else { v.setBackground(d); } } }
* add additional checks
library/src/main/java/com/mikepenz/actionitembadge/library/ActionItemBadge.java
* add additional checks
<ide><path>ibrary/src/main/java/com/mikepenz/actionitembadge/library/ActionItemBadge.java <ide> private int drawable; <ide> private int layout; <ide> <del> private BadgeStyle(Style style, int drawable, int layout) { <add> BadgeStyle(Style style, int drawable, int layout) { <ide> this.style = style; <ide> this.drawable = drawable; <ide> this.layout = layout; <ide> <ide> private int style; <ide> <del> private Style(int style) { <add> Style(int style) { <ide> this.style = style; <ide> } <ide> <ide> } <ide> } else { <ide> Button button = (Button) badge.findViewById(R.id.menu_badge_button); <del> button.setBackgroundResource(style.getDrawable()); <del> button.setText(String.valueOf(badgeCount)); <add> if (button != null) { <add> button.setBackgroundResource(style.getDrawable()); <add> button.setText(String.valueOf(badgeCount)); <add> } <ide> } <ide> } else { <ide> // i know this is not nice but the best solution to allow doing an update without a style
Java
bsd-3-clause
37a8d8f448cf4a7bb74607a59409da0073d06f57
0
sammymax/nullpomino,sammymax/nullpomino
/* Copyright (c) 2010, NullNoname All rights reserved. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: * Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. * Neither the name of NullNoname nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ package mu.nu.nullpo.game.subsystem.mode; import java.util.Random; import mu.nu.nullpo.game.component.BGMStatus; import mu.nu.nullpo.game.component.Block; import mu.nu.nullpo.game.component.Controller; import mu.nu.nullpo.game.component.Field; import mu.nu.nullpo.game.component.Piece; import mu.nu.nullpo.game.event.EventReceiver; import mu.nu.nullpo.game.play.GameEngine; import mu.nu.nullpo.game.play.GameManager; import mu.nu.nullpo.util.CustomProperties; import mu.nu.nullpo.util.GeneralUtil; import org.apache.log4j.Logger; /** * SPF VS-BATTLE mode (Beta) */ public class SPFMode extends DummyMode { /** Log (Apache log4j) */ static Logger log = Logger.getLogger(SPFMode.class); /** Current version */ private static final int CURRENT_VERSION = 0; /** Enabled piece types */ private static final int[] PIECE_ENABLE = {0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0}; /** Block colors */ private static final int[] BLOCK_COLORS = { Block.BLOCK_COLOR_RED, Block.BLOCK_COLOR_RED, Block.BLOCK_COLOR_RED, Block.BLOCK_COLOR_RED, Block.BLOCK_COLOR_GEM_RED, Block.BLOCK_COLOR_GREEN, Block.BLOCK_COLOR_GREEN, Block.BLOCK_COLOR_GREEN, Block.BLOCK_COLOR_GREEN, Block.BLOCK_COLOR_GEM_GREEN, Block.BLOCK_COLOR_BLUE, Block.BLOCK_COLOR_BLUE, Block.BLOCK_COLOR_BLUE, Block.BLOCK_COLOR_BLUE, Block.BLOCK_COLOR_GEM_BLUE, Block.BLOCK_COLOR_YELLOW, Block.BLOCK_COLOR_YELLOW, Block.BLOCK_COLOR_YELLOW, Block.BLOCK_COLOR_YELLOW, Block.BLOCK_COLOR_GEM_YELLOW }; private static final double[] ROW_VALUES = { 2.3, 2.2, 2.1, 2.0, 1.9, 1.8, 1.7, 1.6, 1.5, 1.4, 1.3, 1.2, 1.1, 1.0 }; private static final int DIAMOND_COLOR = Block.BLOCK_COLOR_GEM_RAINBOW; /** Number of players */ private static final int MAX_PLAYERS = 2; /** Names of drop map sets */ private static final String[] DROP_SET_NAMES = {"CLASSIC", "REMIX", "SWORD", "S-MIRROR"}; private static final int[][][][] DROP_PATTERNS = { { {{2,2,2,2}, {5,5,5,5}, {7,7,7,7}, {4,4,4,4}}, {{2,2,4,4}, {2,2,4,4}, {5,5,2,2}, {5,5,2,2}, {7,7,5,5}, {7,7,5,5}}, {{5,5,5,5}, {2,7,2,7}, {2,7,2,7}, {2,7,2,7}, {2,7,2,7}, {4,4,4,4}}, {{2,5,7,4}}, {{7,7,4,4}, {4,4,7,7}, {2,2,5,5}, {2,2,5,5}, {4,4,7,7}, {7,7,4,4}}, {{4,7,7,5}, {7,7,5,5}, {7,5,5,2}, {5,5,2,2}, {5,2,2,4}, {2,2,4,4}}, {{2,2,5,5}, {4,4,5,5}, {2,2,5,5}, {4,4,7,7}, {2,2,7,7}, {4,4,7,7}}, {{5,5,5,5}, {2,2,7,7}, {2,2,7,7}, {7,7,2,2}, {7,7,2,2}, {4,4,4,4}}, {{5,7,4,2}, {2,5,7,4}, {4,2,5,7}, {7,4,2,5}}, {{2,5,7,4}, {5,7,4,2}, {7,4,2,5}, {4,2,5,7}}, {{2,2,2,2}} }, { {{2,2,7,2}, {5,5,4,5}, {7,7,5,7}, {4,4,2,4}}, {{2,2,4,4}, {2,2,4,4}, {5,5,2,2}, {5,5,2,2}, {7,7,5,5}, {7,7,5,5}}, {{5,5,4,4}, {2,7,2,7}, {2,7,2,7}, {2,7,2,7}, {2,7,2,7}, {4,4,5,5}}, {{2,5,7,4}}, {{7,7,4,4}, {4,4,7,7}, {2,5,5,5}, {2,2,2,5}, {4,4,7,7}, {7,7,4,4}}, {{7,7,7,7}, {5,7,4,2}, {7,4,2,5}, {4,2,5,7}, {2,5,7,4}, {5,5,5,5}}, {{2,2,5,5}, {4,4,5,5}, {2,2,5,5}, {4,4,7,7}, {2,2,7,7}, {4,4,7,7}}, {{5,4,5,4}, {2,2,2,7}, {2,7,7,7}, {7,2,2,2}, {7,7,7,2}, {4,5,4,5}}, {{5,7,4,2}, {2,5,7,4}, {4,2,5,7}, {7,4,2,5}}, {{2,5,7,4}, {5,7,4,2}, {7,4,2,5}, {4,2,5,7}}, {{2,2,2,2}} }, { {{2,5,5,5}, {5,2,2,5}, {5,5,2,2}, {4,4,7,7}, {4,7,7,4}, {7,4,4,4}}, {{2,2,2,5,5,5}, {5,3,7,5,4,5}, {5,5,7,7,4,4}, {4,4,2,4,4,7}, {4,2,4,4,7,4}, {2,4,4,7,4,4}}, {{4,4,5,5,7,2}, {4,4,5,5,7,2}, {5,5,7,7,7,5}, {5,7,7,7,4,5}, {7,7,2,2,5,4}, {7,2,2,2,5,4}}, {{2,2,5,4,2,7}, {2,7,4,5,7,2}, {2,7,4,4,7,7}, {2,7,5,5,2,2}, {2,7,5,4,2,7}, {7,7,4,5,7,2}}, {{2,7,7,7,7}, {2,7,5,7,7}, {2,2,5,5,5}, {2,2,2,5,5}, {2,4,2,4,4}, {4,4,4,4,4}}, {{2,2,5,5}, {2,7,7,5}, {5,7,4,4}, {5,5,2,4}, {4,2,2,7}, {4,4,7,7}}, {{2,2,5,5}, {2,2,5,5}, {5,5,7,7}, {5,5,7,7}, {7,7,4,4}, {7,7,4,4}}, {{2,2,5,4,2,7}, {2,2,4,5,7,2}, {7,7,4,5,7,2}, {7,7,5,4,2,7}, {2,2,5,4,2,7}, {2,2,4,5,7,2}}, {{7,7,4,4,7,7}, {7,7,7,7,5,7}, {2,5,2,2,5,2}, {2,5,2,2,5,2}, {4,4,4,4,5,4}, {4,4,7,7,4,4}}, {{2,5,5,5,5,4}, {5,2,5,5,4,4}, {2,2,2,2,2,2}, {7,7,7,7,7,7}, {4,7,4,4,5,5}, {7,4,4,4,4,5}}, {{2,2,5,2,2,4}, {2,5,5,2,5,5}, {5,5,5,7,7,2}, {7,7,7,5,5,4}, {4,7,7,4,7,7}, {4,4,7,4,4,2}}, {{7,7,5,5,5,5}, {7,2,2,5,5,7}, {7,2,2,4,4,7}, {2,7,7,4,4,2}, {2,7,7,5,5,2}, {7,7,5,5,5,5}}, {{7,7,5,5}, {7,2,5,2}, {5,5,5,2}, {4,4,4,2}, {7,2,4,2}, {7,7,4,4}}, {{2,2,5,5}, {2,7,5,5}, {5,5,7,7}, {5,5,7,7}, {4,7,4,4}, {7,7,4,4}}, {{7,7,5,5,5}, {4,7,7,7,5}, {5,4,4,4,4}, {5,2,2,2,2}, {2,7,7,7,5}, {7,7,5,5,5}}, {{2,2,4}, {2,2,2}, {7,7,7}, {7,7,7}, {5,5,5}, {5,5,4}}, {{7,7,7,7}, {7,2,2,7}, {2,7,5,4}, {4,5,7,2}, {5,4,4,5}, {5,5,5,5}} }, { {{7,4,4,4}, {4,7,7,4}, {4,4,7,7}, {5,5,2,2}, {5,2,2,5}, {2,5,5,5}}, {{2,4,4,7,4,4}, {4,2,4,4,7,4}, {4,4,2,4,4,7}, {5,5,7,7,4,4}, {5,3,7,5,4,5}, {2,2,2,5,5,5}}, {{7,2,2,2,5,4}, {7,7,2,2,5,4}, {5,7,7,7,4,5}, {5,5,7,7,7,5}, {4,4,5,5,7,2}, {4,4,5,5,7,2}}, {{7,7,4,5,7,2}, {2,7,5,4,2,7}, {2,7,5,5,2,2}, {2,7,4,4,7,7}, {2,7,4,5,7,2}, {2,2,5,4,2,7}}, {{4,4,4,4,4}, {2,4,2,4,4}, {2,2,2,5,5}, {2,2,5,5,5}, {2,7,5,7,7}, {2,7,7,7,7}}, {{4,4,7,7}, {4,2,2,7}, {5,5,2,4}, {5,7,4,4}, {2,7,7,5}, {2,2,5,5}}, {{7,7,4,4}, {7,7,4,4}, {5,5,7,7}, {5,5,7,7}, {2,2,5,5}, {2,2,5,5}}, {{2,2,4,5,7,2}, {2,2,5,4,2,7}, {7,7,5,4,2,7}, {7,7,4,5,7,2}, {2,2,4,5,7,2}, {2,2,5,4,2,7}}, {{4,4,7,7,4,4}, {4,4,4,4,5,4}, {2,5,2,2,5,2}, {2,5,2,2,5,2}, {7,7,7,7,5,7}, {7,7,4,4,7,7}}, {{7,4,4,4,4,5}, {4,7,4,4,5,5}, {7,7,7,7,7,7}, {2,2,2,2,2,2}, {5,2,5,5,4,4}, {2,5,5,5,5,4}}, {{4,4,7,4,4,2}, {4,7,7,4,7,7}, {7,7,7,5,5,4}, {5,5,5,7,7,2}, {2,5,5,2,5,5}, {2,2,5,2,2,4}}, {{7,7,5,5,5,5}, {2,7,7,5,5,2}, {2,7,7,4,4,2}, {7,2,2,4,4,7}, {7,2,2,5,5,7}, {7,7,5,5,5,5}}, {{7,7,4,4}, {7,2,4,2}, {4,4,4,2}, {5,5,5,2}, {7,2,5,2}, {7,7,5,5}}, {{7,7,4,4}, {4,7,4,4}, {5,5,7,7}, {5,5,7,7}, {2,7,5,5}, {2,2,5,5}}, {{7,7,5,5,5}, {2,7,7,7,5}, {5,2,2,2,2}, {5,4,4,4,4}, {4,7,7,7,5}, {7,7,5,5,5}}, {{5,5,4}, {5,5,5}, {7,7,7}, {7,7,7}, {2,2,2}, {2,2,4}}, {{5,5,5,5}, {5,4,4,5}, {4,5,7,2}, {2,7,5,4}, {7,2,2,7}, {7,7,7,7}} } }; private static final double[][] DROP_PATTERNS_ATTACK_MULTIPLIERS = { {1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 0.7, 0.7, 1.0}, {1.0, 1.2, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 0.85, 1.0}, {1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0}, {1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0} }; private static final double[][] DROP_PATTERNS_DEFEND_MULTIPLIERS = { {1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0}, {1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.2, 1.0, 1.0}, {1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0}, {1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0} }; /** Names of rainbow power settings */ private static final String[] RAINBOW_POWER_NAMES = {"NONE", "50%", "80%", "100%", "50/100%"}; /** Each player's frame color */ private static final int[] PLAYER_COLOR_FRAME = {GameEngine.FRAME_COLOR_RED, GameEngine.FRAME_COLOR_BLUE}; /** GameManager that owns this mode */ private GameManager owner; /** Drawing and event handling EventReceiver */ private EventReceiver receiver; /** 溜まっている邪魔Blockのcount */ private int[] ojama; /** 送った邪魔Blockのcount */ private int[] ojamaSent; /** Time to display the most recent increase in score */ private int[] scgettime; /** 使用するBGM */ private int bgmno; /** Big */ //private boolean[] big; /** 効果音ON/OFF */ private boolean[] enableSE; /** マップ使用 flag */ private boolean[] useMap; /** 使用するマップセット number */ private int[] mapSet; /** マップ number(-1でランダム) */ private int[] mapNumber; /** Last preset number used */ private int[] presetNumber; /** 勝者 */ private int winnerID; /** マップセットのProperty file */ private CustomProperties[] propMap; /** 最大マップ number */ private int[] mapMaxNo; /** バックアップ用フィールド(マップをリプレイに保存するときに使用) */ private Field[] fldBackup; /** マップ選択用乱count */ private Random randMap; /** Version */ private int version; /** Amount of points earned from most recent clear */ private int[] lastscore; /** Score */ private int[] score; /** Settings for hard ojama blocks */ private int[] ojamaHard; /** Hurryup開始までの秒count(0でHurryupなし) */ private int[] hurryupSeconds; /** Time to display "ZENKESHI!" */ private int[] zenKeshiDisplay; /** Time to display "TECH BONUS" */ private int[] techBonusDisplay; /** Drop patterns */ private int[][][] dropPattern; /** Drop map set selected */ private int[] dropSet; /** Drop map selected */ private int[] dropMap; /** Drop multipliers */ private double[] attackMultiplier, defendMultiplier; /** Rainbow power settings for each player */ private int[] diamondPower; /** Frame when squares were last checked */ private int[] lastSquareCheck; /** Flag set when counters have been decremented */ private boolean[] hardDecremented; /* * Mode name */ @Override public String getName() { return "SPF VS-BATTLE (BETA)"; } /* * Number of players */ @Override public int getPlayers() { return MAX_PLAYERS; } /* * Mode initialization */ @Override public void modeInit(GameManager manager) { owner = manager; receiver = owner.receiver; ojama = new int[MAX_PLAYERS]; ojamaSent = new int[MAX_PLAYERS]; scgettime = new int[MAX_PLAYERS]; bgmno = 0; //big = new boolean[MAX_PLAYERS]; enableSE = new boolean[MAX_PLAYERS]; hurryupSeconds = new int[MAX_PLAYERS]; useMap = new boolean[MAX_PLAYERS]; mapSet = new int[MAX_PLAYERS]; mapNumber = new int[MAX_PLAYERS]; presetNumber = new int[MAX_PLAYERS]; propMap = new CustomProperties[MAX_PLAYERS]; mapMaxNo = new int[MAX_PLAYERS]; fldBackup = new Field[MAX_PLAYERS]; randMap = new Random(); lastscore = new int[MAX_PLAYERS]; score = new int[MAX_PLAYERS]; ojamaHard = new int[MAX_PLAYERS]; zenKeshiDisplay = new int[MAX_PLAYERS]; techBonusDisplay = new int[MAX_PLAYERS]; dropSet = new int[MAX_PLAYERS]; dropMap = new int[MAX_PLAYERS]; dropPattern = new int[MAX_PLAYERS][][]; attackMultiplier = new double[MAX_PLAYERS]; defendMultiplier = new double[MAX_PLAYERS]; diamondPower = new int[MAX_PLAYERS]; lastSquareCheck = new int[MAX_PLAYERS]; hardDecremented = new boolean[MAX_PLAYERS]; winnerID = -1; } /** * Read speed presets * @param engine GameEngine * @param prop Property file to read from * @param preset Preset number */ private void loadPreset(GameEngine engine, CustomProperties prop, int preset) { engine.speed.gravity = prop.getProperty("spfvs.gravity." + preset, 4); engine.speed.denominator = prop.getProperty("spfvs.denominator." + preset, 256); engine.speed.are = prop.getProperty("spfvs.are." + preset, 24); engine.speed.areLine = prop.getProperty("spfvs.areLine." + preset, 24); engine.speed.lineDelay = prop.getProperty("spfvs.lineDelay." + preset, 10); engine.speed.lockDelay = prop.getProperty("spfvs.lockDelay." + preset, 30); engine.speed.das = prop.getProperty("spfvs.das." + preset, 14); } /** * Save speed presets * @param engine GameEngine * @param prop Property file to save to * @param preset Preset number */ private void savePreset(GameEngine engine, CustomProperties prop, int preset) { prop.setProperty("spfvs.gravity." + preset, engine.speed.gravity); prop.setProperty("spfvs.denominator." + preset, engine.speed.denominator); prop.setProperty("spfvs.are." + preset, engine.speed.are); prop.setProperty("spfvs.areLine." + preset, engine.speed.areLine); prop.setProperty("spfvs.lineDelay." + preset, engine.speed.lineDelay); prop.setProperty("spfvs.lockDelay." + preset, engine.speed.lockDelay); prop.setProperty("spfvs.das." + preset, engine.speed.das); } /** * スピード以外の設定を読み込み * @param engine GameEngine * @param prop Property file to read from */ private void loadOtherSetting(GameEngine engine, CustomProperties prop) { int playerID = engine.playerID; bgmno = prop.getProperty("spfvs.bgmno", 0); //big[playerID] = prop.getProperty("spfvs.big.p" + playerID, false); enableSE[playerID] = prop.getProperty("spfvs.enableSE.p" + playerID, true); hurryupSeconds[playerID] = prop.getProperty("vsbattle.hurryupSeconds.p" + playerID, 0); useMap[playerID] = prop.getProperty("spfvs.useMap.p" + playerID, false); mapSet[playerID] = prop.getProperty("spfvs.mapSet.p" + playerID, 0); mapNumber[playerID] = prop.getProperty("spfvs.mapNumber.p" + playerID, -1); presetNumber[playerID] = prop.getProperty("spfvs.presetNumber.p" + playerID, 0); ojamaHard[playerID] = prop.getProperty("spfvs.ojamaHard.p" + playerID, 5); dropSet[playerID] = prop.getProperty("spfvs.dropSet.p" + playerID, 0); dropMap[playerID] = prop.getProperty("spfvs.dropMap.p" + playerID, 0); diamondPower[playerID] = prop.getProperty("spfvs.rainbowPower.p" + playerID, 2); } /** * スピード以外の設定を保存 * @param engine GameEngine * @param prop Property file to save to */ private void saveOtherSetting(GameEngine engine, CustomProperties prop) { int playerID = engine.playerID; prop.setProperty("spfvs.bgmno", bgmno); //prop.setProperty("spfvs.big.p" + playerID, big[playerID]); prop.setProperty("spfvs.enableSE.p" + playerID, enableSE[playerID]); prop.setProperty("vsbattle.hurryupSeconds.p" + playerID, hurryupSeconds[playerID]); prop.setProperty("spfvs.useMap.p" + playerID, useMap[playerID]); prop.setProperty("spfvs.mapSet.p" + playerID, mapSet[playerID]); prop.setProperty("spfvs.mapNumber.p" + playerID, mapNumber[playerID]); prop.setProperty("spfvs.presetNumber.p" + playerID, presetNumber[playerID]); prop.setProperty("spfvs.ojamaHard.p" + playerID, ojamaHard[playerID]); prop.setProperty("spfvs.dropSet.p" + playerID, dropSet[playerID]); prop.setProperty("spfvs.dropMap.p" + playerID, dropMap[playerID]); prop.setProperty("spfvs.rainbowPower.p" + playerID, diamondPower[playerID]); } /** * マップ読み込み * @param field フィールド * @param prop Property file to read from * @param preset 任意のID */ private void loadMap(Field field, CustomProperties prop, int id) { field.reset(); //field.readProperty(prop, id); field.stringToField(prop.getProperty("map." + id, "")); field.setAllAttribute(Block.BLOCK_ATTRIBUTE_VISIBLE, true); field.setAllAttribute(Block.BLOCK_ATTRIBUTE_OUTLINE, true); field.setAllAttribute(Block.BLOCK_ATTRIBUTE_SELFPLACED, false); } /** * マップ保存 * @param field フィールド * @param prop Property file to save to * @param id 任意のID */ private void saveMap(Field field, CustomProperties prop, int id) { //field.writeProperty(prop, id); prop.setProperty("map." + id, field.fieldToString()); } /** * プレビュー用にマップを読み込み * @param engine GameEngine * @param playerID プレイヤー number * @param id マップID * @param forceReload trueにするとマップファイルを強制再読み込み */ private void loadMapPreview(GameEngine engine, int playerID, int id, boolean forceReload) { if((propMap[playerID] == null) || (forceReload)) { mapMaxNo[playerID] = 0; propMap[playerID] = receiver.loadProperties("config/map/spf/" + mapSet[playerID] + ".map"); } if((propMap[playerID] == null) && (engine.field != null)) { engine.field.reset(); } else if(propMap[playerID] != null) { mapMaxNo[playerID] = propMap[playerID].getProperty("map.maxMapNumber", 0); engine.createFieldIfNeeded(); loadMap(engine.field, propMap[playerID], id); engine.field.setAllSkin(engine.getSkin()); } } private void loadDropMapPreview(GameEngine engine, int playerID, int[][] pattern) { if((pattern == null) && (engine.field != null)) { engine.field.reset(); } else if(pattern != null) { log.debug("Loading drop map preview"); engine.createFieldIfNeeded(); engine.field.reset(); int patternCol = 0; int maxHeight = engine.field.getHeight()-1; for (int x = 0; x < engine.field.getWidth(); x++) { if (patternCol >= pattern.length) patternCol = 0; for (int patternRow = 0; patternRow < pattern[patternCol].length; patternRow++) { engine.field.setBlockColor(x, maxHeight-patternRow, pattern[patternCol][patternRow]); Block blk = engine.field.getBlock(x, maxHeight-patternRow); blk.setAttribute(Block.BLOCK_ATTRIBUTE_VISIBLE, true); blk.setAttribute(Block.BLOCK_ATTRIBUTE_OUTLINE, true); } patternCol++; } engine.field.setAllSkin(engine.getSkin()); } } /* * Initialization for each player */ @Override public void playerInit(GameEngine engine, int playerID) { if(playerID == 1) { engine.randSeed = owner.engine[0].randSeed; engine.random = new Random(owner.engine[0].randSeed); } engine.framecolor = PLAYER_COLOR_FRAME[playerID]; engine.clearMode = GameEngine.CLEAR_GEM_COLOR; engine.garbageColorClear = true; engine.lineGravityType = GameEngine.LINE_GRAVITY_CASCADE; for(int i = 0; i < Piece.PIECE_COUNT; i++) engine.nextPieceEnable[i] = (PIECE_ENABLE[i] == 1); engine.blockColors = BLOCK_COLORS; engine.randomBlockColor = true; engine.connectBlocks = false; ojama[playerID] = 0; ojamaSent[playerID] = 0; score[playerID] = 0; scgettime[playerID] = 0; zenKeshiDisplay[playerID] = 0; techBonusDisplay[playerID] = 0; lastSquareCheck[playerID] = -1; hardDecremented[playerID] = true; if(engine.owner.replayMode == false) { loadOtherSetting(engine, engine.owner.modeConfig); loadPreset(engine, engine.owner.modeConfig, -1 - playerID); version = CURRENT_VERSION; } else { loadOtherSetting(engine, engine.owner.replayProp); loadPreset(engine, engine.owner.replayProp, -1 - playerID); version = owner.replayProp.getProperty("spfvs.version", 0); } } /* * Called at settings screen */ @Override public boolean onSetting(GameEngine engine, int playerID) { // Menu if((engine.owner.replayMode == false) && (engine.statc[4] == 0)) { // Up if(engine.ctrl.isMenuRepeatKey(Controller.BUTTON_UP)) { engine.statc[2]--; if(engine.statc[2] < 0){ engine.statc[2] = 18; loadDropMapPreview(engine, playerID, DROP_PATTERNS[dropSet[playerID]][dropMap[playerID]]); } else if (engine.statc[2] == 16) engine.field = null; engine.playSE("cursor"); } // Down if(engine.ctrl.isMenuRepeatKey(Controller.BUTTON_DOWN)) { engine.statc[2]++; if(engine.statc[2] > 18) { engine.statc[2] = 0; engine.field = null; } else if (engine.statc[2] == 17) loadDropMapPreview(engine, playerID, DROP_PATTERNS[dropSet[playerID]][dropMap[playerID]]); engine.playSE("cursor"); } // Configuration changes int change = 0; if(engine.ctrl.isMenuRepeatKey(Controller.BUTTON_LEFT)) change = -1; if(engine.ctrl.isMenuRepeatKey(Controller.BUTTON_RIGHT)) change = 1; if(change != 0) { engine.playSE("change"); int m = 1; if(engine.ctrl.isPress(Controller.BUTTON_E)) m = 100; if(engine.ctrl.isPress(Controller.BUTTON_F)) m = 1000; switch(engine.statc[2]) { case 0: engine.speed.gravity += change * m; if(engine.speed.gravity < -1) engine.speed.gravity = 99999; if(engine.speed.gravity > 99999) engine.speed.gravity = -1; break; case 1: engine.speed.denominator += change * m; if(engine.speed.denominator < -1) engine.speed.denominator = 99999; if(engine.speed.denominator > 99999) engine.speed.denominator = -1; break; case 2: engine.speed.are += change; if(engine.speed.are < 0) engine.speed.are = 99; if(engine.speed.are > 99) engine.speed.are = 0; break; case 3: engine.speed.areLine += change; if(engine.speed.areLine < 0) engine.speed.areLine = 99; if(engine.speed.areLine > 99) engine.speed.areLine = 0; break; case 4: engine.speed.lineDelay += change; if(engine.speed.lineDelay < 0) engine.speed.lineDelay = 99; if(engine.speed.lineDelay > 99) engine.speed.lineDelay = 0; break; case 5: engine.speed.lockDelay += change; if(engine.speed.lockDelay < 0) engine.speed.lockDelay = 99; if(engine.speed.lockDelay > 99) engine.speed.lockDelay = 0; break; case 6: engine.speed.das += change; if(engine.speed.das < 0) engine.speed.das = 99; if(engine.speed.das > 99) engine.speed.das = 0; break; case 7: case 8: presetNumber[playerID] += change; if(presetNumber[playerID] < 0) presetNumber[playerID] = 99; if(presetNumber[playerID] > 99) presetNumber[playerID] = 0; break; case 9: bgmno += change; if(bgmno < 0) bgmno = BGMStatus.BGM_COUNT - 1; if(bgmno > BGMStatus.BGM_COUNT - 1) bgmno = 0; break; case 10: useMap[playerID] = !useMap[playerID]; if(!useMap[playerID]) { if(engine.field != null) engine.field.reset(); } else { loadMapPreview(engine, playerID, (mapNumber[playerID] < 0) ? 0 : mapNumber[playerID], true); } break; case 11: mapSet[playerID] += change; if(mapSet[playerID] < 0) mapSet[playerID] = 99; if(mapSet[playerID] > 99) mapSet[playerID] = 0; if(useMap[playerID]) { mapNumber[playerID] = -1; loadMapPreview(engine, playerID, (mapNumber[playerID] < 0) ? 0 : mapNumber[playerID], true); } break; case 12: if(useMap[playerID]) { mapNumber[playerID] += change; if(mapNumber[playerID] < -1) mapNumber[playerID] = mapMaxNo[playerID] - 1; if(mapNumber[playerID] > mapMaxNo[playerID] - 1) mapNumber[playerID] = -1; loadMapPreview(engine, playerID, (mapNumber[playerID] < 0) ? 0 : mapNumber[playerID], true); } else { mapNumber[playerID] = -1; } break; case 13: enableSE[playerID] = !enableSE[playerID]; break; case 14: if (m > 10) hurryupSeconds[playerID] += change*m/10; else hurryupSeconds[playerID] += change; if(hurryupSeconds[playerID] < 0) hurryupSeconds[playerID] = 300; if(hurryupSeconds[playerID] > 300) hurryupSeconds[playerID] = 0; break; case 15: ojamaHard[playerID] += change; if(ojamaHard[playerID] < 1) ojamaHard[playerID] = 9; if(ojamaHard[playerID] > 9) ojamaHard[playerID] = 1; break; case 16: diamondPower[playerID] += change; if(diamondPower[playerID] < 0) diamondPower[playerID] = 3; if(diamondPower[playerID] > 3) diamondPower[playerID] = 0; break; case 17: dropSet[playerID] += change; if(dropSet[playerID] < 0) dropSet[playerID] = 3; if(dropSet[playerID] > 3) dropSet[playerID] = 0; if(dropMap[playerID] >= DROP_PATTERNS[dropSet[playerID]].length) dropMap[playerID] = 0; loadDropMapPreview(engine, playerID, DROP_PATTERNS[dropSet[playerID]][dropMap[playerID]]); break; case 18: dropMap[playerID] += change; if(dropMap[playerID] < 0) dropMap[playerID] = DROP_PATTERNS[dropSet[playerID]].length-1; if(dropMap[playerID] >= DROP_PATTERNS[dropSet[playerID]].length) dropMap[playerID] = 0; loadDropMapPreview(engine, playerID, DROP_PATTERNS[dropSet[playerID]][dropMap[playerID]]); break; /* case 18: big[playerID] = !big[playerID]; break; */ } } // 決定 if(engine.ctrl.isPush(Controller.BUTTON_A) && (engine.statc[3] >= 5)) { engine.playSE("decide"); if(engine.statc[2] == 7) { loadPreset(engine, owner.modeConfig, presetNumber[playerID]); } else if(engine.statc[2] == 8) { savePreset(engine, owner.modeConfig, presetNumber[playerID]); receiver.saveModeConfig(owner.modeConfig); } else { saveOtherSetting(engine, owner.modeConfig); savePreset(engine, owner.modeConfig, -1 - playerID); receiver.saveModeConfig(owner.modeConfig); engine.statc[4] = 1; } } // Cancel if(engine.ctrl.isPush(Controller.BUTTON_B)) { engine.quitflag = true; } // プレビュー用マップ読み込み if(useMap[playerID] && (engine.statc[3] == 0)) { loadMapPreview(engine, playerID, (mapNumber[playerID] < 0) ? 0 : mapNumber[playerID], true); } // ランダムマッププレビュー if(useMap[playerID] && (propMap[playerID] != null) && (mapNumber[playerID] < 0)) { if(engine.statc[3] % 30 == 0) { engine.statc[5]++; if(engine.statc[5] >= mapMaxNo[playerID]) engine.statc[5] = 0; loadMapPreview(engine, playerID, engine.statc[5], false); } } engine.statc[3]++; } else if(engine.statc[4] == 0) { engine.statc[3]++; engine.statc[2] = 0; if(engine.statc[3] >= 180) engine.statc[4] = 1; else if(engine.statc[3] > 120) engine.statc[2] = 17; else if (engine.statc[3] == 120) { engine.statc[2] = 17; loadDropMapPreview(engine, playerID, DROP_PATTERNS[dropSet[playerID]][dropMap[playerID]]); } else if(engine.statc[3] >= 60) engine.statc[2] = 9; } else { // 開始 if((owner.engine[0].statc[4] == 1) && (owner.engine[1].statc[4] == 1) && (playerID == 1)) { owner.engine[0].stat = GameEngine.STAT_READY; owner.engine[1].stat = GameEngine.STAT_READY; owner.engine[0].resetStatc(); owner.engine[1].resetStatc(); } // Cancel else if(engine.ctrl.isPush(Controller.BUTTON_B)) { engine.statc[4] = 0; } } return true; } /* * 設定画面の描画 */ @Override public void renderSetting(GameEngine engine, int playerID) { if(engine.statc[4] == 0) { if(engine.statc[2] < 9) { if(owner.replayMode == false) { receiver.drawMenuFont(engine, playerID, 0, (engine.statc[2] * 2) + 1, "b", (playerID == 0) ? EventReceiver.COLOR_RED : EventReceiver.COLOR_BLUE); } receiver.drawMenuFont(engine, playerID, 0, 0, "GRAVITY", EventReceiver.COLOR_ORANGE); receiver.drawMenuFont(engine, playerID, 1, 1, String.valueOf(engine.speed.gravity), (engine.statc[2] == 0) && !owner.replayMode); receiver.drawMenuFont(engine, playerID, 0, 2, "G-MAX", EventReceiver.COLOR_ORANGE); receiver.drawMenuFont(engine, playerID, 1, 3, String.valueOf(engine.speed.denominator), (engine.statc[2] == 1)); receiver.drawMenuFont(engine, playerID, 0, 4, "ARE", EventReceiver.COLOR_ORANGE); receiver.drawMenuFont(engine, playerID, 1, 5, String.valueOf(engine.speed.are), (engine.statc[2] == 2)); receiver.drawMenuFont(engine, playerID, 0, 6, "ARE LINE", EventReceiver.COLOR_ORANGE); receiver.drawMenuFont(engine, playerID, 1, 7, String.valueOf(engine.speed.areLine), (engine.statc[2] == 3)); receiver.drawMenuFont(engine, playerID, 0, 8, "LINE DELAY", EventReceiver.COLOR_ORANGE); receiver.drawMenuFont(engine, playerID, 1, 9, String.valueOf(engine.speed.lineDelay), (engine.statc[2] == 4)); receiver.drawMenuFont(engine, playerID, 0, 10, "LOCK DELAY", EventReceiver.COLOR_ORANGE); receiver.drawMenuFont(engine, playerID, 1, 11, String.valueOf(engine.speed.lockDelay), (engine.statc[2] == 5)); receiver.drawMenuFont(engine, playerID, 0, 12, "DAS", EventReceiver.COLOR_ORANGE); receiver.drawMenuFont(engine, playerID, 1, 13, String.valueOf(engine.speed.das), (engine.statc[2] == 6)); receiver.drawMenuFont(engine, playerID, 0, 14, "LOAD", EventReceiver.COLOR_GREEN); receiver.drawMenuFont(engine, playerID, 1, 15, String.valueOf(presetNumber[playerID]), (engine.statc[2] == 7)); receiver.drawMenuFont(engine, playerID, 0, 16, "SAVE", EventReceiver.COLOR_GREEN); receiver.drawMenuFont(engine, playerID, 1, 17, String.valueOf(presetNumber[playerID]), (engine.statc[2] == 8)); receiver.drawMenuFont(engine, playerID, 0, 19, "PAGE 1/3", EventReceiver.COLOR_YELLOW); } else if (engine.statc[2] < 17){ if(owner.replayMode == false) { receiver.drawMenuFont(engine, playerID, 0, ((engine.statc[2] - 9) * 2) + (engine.statc[2] == 16 ? 2 : 1), "b", (playerID == 0) ? EventReceiver.COLOR_RED : EventReceiver.COLOR_BLUE); } receiver.drawMenuFont(engine, playerID, 0, 0, "BGM", EventReceiver.COLOR_PINK); receiver.drawMenuFont(engine, playerID, 1, 1, String.valueOf(bgmno), (engine.statc[2] == 9) && !owner.replayMode); receiver.drawMenuFont(engine, playerID, 0, 2, "USE MAP", EventReceiver.COLOR_CYAN); receiver.drawMenuFont(engine, playerID, 1, 3, GeneralUtil.getONorOFF(useMap[playerID]), (engine.statc[2] == 10)); receiver.drawMenuFont(engine, playerID, 0, 4, "MAP SET", EventReceiver.COLOR_CYAN); receiver.drawMenuFont(engine, playerID, 1, 5, String.valueOf(mapSet[playerID]), (engine.statc[2] == 11)); receiver.drawMenuFont(engine, playerID, 0, 6, "MAP NO.", EventReceiver.COLOR_CYAN); receiver.drawMenuFont(engine, playerID, 1, 7, (mapNumber[playerID] < 0) ? "RANDOM" : mapNumber[playerID]+"/"+(mapMaxNo[playerID]-1), (engine.statc[2] == 12)); receiver.drawMenuFont(engine, playerID, 0, 8, "SE", EventReceiver.COLOR_CYAN); receiver.drawMenuFont(engine, playerID, 1, 9, GeneralUtil.getONorOFF(enableSE[playerID]), (engine.statc[2] == 13)); receiver.drawMenuFont(engine, playerID, 0, 10, "HURRYUP", EventReceiver.COLOR_CYAN); receiver.drawMenuFont(engine, playerID, 1, 11, (hurryupSeconds[playerID] == 0) ? "NONE" : hurryupSeconds[playerID]+"SEC", (engine.statc[2] == 14)); receiver.drawMenuFont(engine, playerID, 0, 12, "COUNTER", EventReceiver.COLOR_CYAN); receiver.drawMenuFont(engine, playerID, 1, 13, String.valueOf(ojamaHard[playerID]), (engine.statc[2] == 15)); receiver.drawMenuFont(engine, playerID, 0, 14, "RAINBOW", EventReceiver.COLOR_CYAN); receiver.drawMenuFont(engine, playerID, 0, 15, "GEM POWER", EventReceiver.COLOR_CYAN); receiver.drawMenuFont(engine, playerID, 1, 16, RAINBOW_POWER_NAMES[diamondPower[playerID]], (engine.statc[2] == 16)); receiver.drawMenuFont(engine, playerID, 0, 19, "PAGE 2/3", EventReceiver.COLOR_YELLOW); } else { if(owner.replayMode == false) { receiver.drawMenuFont(engine, playerID, 0, ((engine.statc[2] - 10) * 2 + 1), "b", (playerID == 0) ? EventReceiver.COLOR_RED : EventReceiver.COLOR_BLUE); } receiver.drawMenuFont(engine, playerID, 0, 0, "ATTACK", EventReceiver.COLOR_CYAN); int multiplier = (int) (100 * DROP_PATTERNS_ATTACK_MULTIPLIERS[dropSet[playerID]][dropMap[playerID]]); if (multiplier >= 100) receiver.drawMenuFont(engine, playerID, 2, 1, multiplier + "%", multiplier == 100 ? EventReceiver.COLOR_YELLOW : EventReceiver.COLOR_GREEN); else receiver.drawMenuFont(engine, playerID, 3, 1, multiplier + "%", EventReceiver.COLOR_RED); receiver.drawMenuFont(engine, playerID, 0, 2, "DEFEND", EventReceiver.COLOR_CYAN); multiplier = (int) (100 * DROP_PATTERNS_DEFEND_MULTIPLIERS[dropSet[playerID]][dropMap[playerID]]); if (multiplier >= 100) receiver.drawMenuFont(engine, playerID, 2, 3, multiplier + "%", multiplier == 100 ? EventReceiver.COLOR_YELLOW : EventReceiver.COLOR_RED); else receiver.drawMenuFont(engine, playerID, 3, 3, multiplier + "%", EventReceiver.COLOR_GREEN); receiver.drawMenuFont(engine, playerID, 0, 14, "DROP SET", EventReceiver.COLOR_CYAN); receiver.drawMenuFont(engine, playerID, 1, 15, DROP_SET_NAMES[dropSet[playerID]], (engine.statc[2] == 17 && !owner.replayMode)); receiver.drawMenuFont(engine, playerID, 0, 16, "DROP MAP", EventReceiver.COLOR_CYAN); String dropMapStr = String.valueOf(DROP_PATTERNS[dropSet[playerID]].length); if (dropMapStr.length() == 1) dropMapStr = "0" + dropMapStr; dropMapStr = String.valueOf(dropMap[playerID]+1) + "/" + dropMapStr; if (dropMapStr.length() == 4) dropMapStr = "0" + dropMapStr; receiver.drawMenuFont(engine, playerID, 1, 17, dropMapStr, (engine.statc[2] == 18)); receiver.drawMenuFont(engine, playerID, 0, 19, "PAGE 3/3", EventReceiver.COLOR_YELLOW); //receiver.drawMenuFont(engine, playerID, 0, 10, "BIG", EventReceiver.COLOR_CYAN); //receiver.drawMenuFont(engine, playerID, 1, 11, GeneralUtil.getONorOFF(big[playerID]), (engine.statc[2] == 18)); } } else { receiver.drawMenuFont(engine, playerID, 3, 10, "WAIT", EventReceiver.COLOR_YELLOW); } } /* * Readyの時のInitialization処理(Initialization前) */ @Override public boolean onReady(GameEngine engine, int playerID) { if(engine.statc[0] == 0) { engine.numColors = BLOCK_COLORS.length; engine.rainbowAnimate = (playerID == 0); engine.blockOutlineType = GameEngine.BLOCK_OUTLINE_CONNECT; dropPattern[playerID] = DROP_PATTERNS[dropSet[playerID]][dropMap[playerID]]; attackMultiplier[playerID] = DROP_PATTERNS_ATTACK_MULTIPLIERS[dropSet[playerID]][dropMap[playerID]]; defendMultiplier[playerID] = DROP_PATTERNS_DEFEND_MULTIPLIERS[dropSet[playerID]][dropMap[playerID]]; // マップ読み込み・リプレイ保存用にバックアップ if(useMap[playerID]) { if(owner.replayMode) { engine.createFieldIfNeeded(); loadMap(engine.field, owner.replayProp, playerID); engine.field.setAllSkin(engine.getSkin()); } else { if(propMap[playerID] == null) { propMap[playerID] = receiver.loadProperties("config/map/spf/" + mapSet[playerID] + ".map"); } if(propMap[playerID] != null) { engine.createFieldIfNeeded(); if(mapNumber[playerID] < 0) { if((playerID == 1) && (useMap[0]) && (mapNumber[0] < 0)) { engine.field.copy(owner.engine[0].field); } else { int no = (mapMaxNo[playerID] < 1) ? 0 : randMap.nextInt(mapMaxNo[playerID]); loadMap(engine.field, propMap[playerID], no); } } else { loadMap(engine.field, propMap[playerID], mapNumber[playerID]); } engine.field.setAllSkin(engine.getSkin()); fldBackup[playerID] = new Field(engine.field); } } } else if(engine.field != null) { engine.field.reset(); } } else if (engine.statc[0] == 1 && diamondPower[playerID] > 0) for (int x = 24; x < engine.nextPieceArraySize; x += 25) engine.nextPieceArrayObject[x].block[1].color = DIAMOND_COLOR; return false; } /* * ゲーム開始時の処理 */ @Override public void startGame(GameEngine engine, int playerID) { engine.b2bEnable = false; engine.comboType = GameEngine.COMBO_TYPE_DISABLE; //engine.big = big[playerID]; engine.enableSE = enableSE[playerID]; if(playerID == 1) owner.bgmStatus.bgm = bgmno; //engine.colorClearSize = big[playerID] ? 8 : 2; engine.colorClearSize = 2; engine.ignoreHidden = false; engine.tspinAllowKick = false; engine.tspinEnable = false; engine.useAllSpinBonus = false; } /* * Render score */ @Override public void renderLast(GameEngine engine, int playerID) { // ステータス表示 if(playerID == 0) { receiver.drawScoreFont(engine, playerID, -1, 0, "SPF VS", EventReceiver.COLOR_GREEN); receiver.drawScoreFont(engine, playerID, -1, 2, "OJAMA", EventReceiver.COLOR_PURPLE); receiver.drawScoreFont(engine, playerID, -1, 3, "1P:", EventReceiver.COLOR_RED); receiver.drawScoreFont(engine, playerID, 3, 3, String.valueOf(ojama[0]), (ojama[0] > 0)); receiver.drawScoreFont(engine, playerID, -1, 4, "2P:", EventReceiver.COLOR_BLUE); receiver.drawScoreFont(engine, playerID, 3, 4, String.valueOf(ojama[1]), (ojama[1] > 0)); receiver.drawScoreFont(engine, playerID, -1, 6, "ATTACK", EventReceiver.COLOR_GREEN); receiver.drawScoreFont(engine, playerID, -1, 7, "1P: " + String.valueOf(ojamaSent[0]), EventReceiver.COLOR_RED); receiver.drawScoreFont(engine, playerID, -1, 8, "2P: " + String.valueOf(ojamaSent[1]), EventReceiver.COLOR_BLUE); receiver.drawScoreFont(engine, playerID, -1, 10, "SCORE", EventReceiver.COLOR_PURPLE); receiver.drawScoreFont(engine, playerID, -1, 11, "1P: " + String.valueOf(score[0]), EventReceiver.COLOR_RED); receiver.drawScoreFont(engine, playerID, -1, 12, "2P: " + String.valueOf(score[1]), EventReceiver.COLOR_BLUE); receiver.drawScoreFont(engine, playerID, -1, 14, "TIME", EventReceiver.COLOR_GREEN); receiver.drawScoreFont(engine, playerID, -1, 15, GeneralUtil.getTime(engine.statistics.time)); } if (!owner.engine[playerID].gameActive) return; if(techBonusDisplay[playerID] > 0) receiver.drawMenuFont(engine, playerID, 0, 20, "TECH BONUS", EventReceiver.COLOR_YELLOW); if(zenKeshiDisplay[playerID] > 0) receiver.drawMenuFont(engine, playerID, 1, 21, "ZENKESHI!", EventReceiver.COLOR_YELLOW); Block b; int blockColor, textColor; if (ojamaHard[playerID] > 0 && engine.field != null) for (int x = 0; x < engine.field.getWidth(); x++) for (int y = 0; y < engine.field.getHeight(); y++) { b = engine.field.getBlock(x, y); if (!b.isEmpty() && b.hard > 0) { blockColor = b.secondaryColor; textColor = EventReceiver.COLOR_WHITE; if (blockColor == Block.BLOCK_COLOR_BLUE) textColor = EventReceiver.COLOR_BLUE; else if (blockColor == Block.BLOCK_COLOR_GREEN) textColor = EventReceiver.COLOR_GREEN; else if (blockColor == Block.BLOCK_COLOR_RED) textColor = EventReceiver.COLOR_RED; else if (blockColor == Block.BLOCK_COLOR_YELLOW) textColor = EventReceiver.COLOR_YELLOW; receiver.drawMenuFont(engine, playerID, x, y, String.valueOf(b.hard), textColor); } } } @Override public boolean onMove (GameEngine engine, int playerID) { hardDecremented[playerID] = false; return false; } @Override public void pieceLocked(GameEngine engine, int playerID, int avalanche) { if (engine.field == null) return; checkAll(engine, playerID); } /* * Calculate score */ @Override public void calcScore(GameEngine engine, int playerID, int avalanche) { if (engine.field == null) return; checkAll(engine, playerID); if (engine.field.canCascade()) return; int enemyID = 0; if(playerID == 0) enemyID = 1; int width = engine.field.getWidth(); int height = engine.field.getHeight(); int hiddenHeight = engine.field.getHiddenHeight(); int diamondBreakColor = Block.BLOCK_COLOR_INVALID; if (diamondPower[playerID] > 0) for (int y = (-1*hiddenHeight); y < height && diamondBreakColor == Block.BLOCK_COLOR_INVALID; y++) for (int x = 0; x < width && diamondBreakColor == Block.BLOCK_COLOR_INVALID; x++) if (engine.field.getBlockColor(x, y) == DIAMOND_COLOR) { receiver.blockBreak(engine, playerID, x, y, engine.field.getBlock(x, y)); engine.field.setBlockColor(x, y, Block.BLOCK_COLOR_NONE); if (y+1 >= height) { techBonusDisplay[playerID] = 120; engine.statistics.score += 10000; score[playerID] += 10000; } else diamondBreakColor = engine.field.getBlockColor(x, y+1, true); } double pts = 0; double add, multiplier; Block b; //Clear blocks from diamond if (diamondBreakColor > Block.BLOCK_COLOR_NONE) { engine.field.allClearColor(diamondBreakColor, true, true); for (int y = (-1*hiddenHeight); y < height; y++) { multiplier = getRowValue(y); for (int x = 0; x < width; x++) if (engine.field.getBlockColor(x, y, true) == diamondBreakColor) { pts += multiplier * 7; receiver.blockBreak(engine, playerID, x, y, engine.field.getBlock(x, y)); engine.field.setBlockColor(x, y, Block.BLOCK_COLOR_NONE); } } } if (diamondPower[playerID] == 1) pts *= 0.5; else if (diamondPower[playerID] == 2) pts *= 0.8; //TODO: Add diamond glitch //Clear blocks //engine.field.gemColorCheck(engine.colorClearSize, true, engine.garbageColorClear, engine.ignoreHidden); for (int y = (-1*hiddenHeight); y < height; y++) { multiplier = getRowValue(y); for (int x = 0; x < width; x++) { b = engine.field.getBlock(x, y); if (b == null) continue; if (!b.getAttribute(Block.BLOCK_ATTRIBUTE_ERASE) || b.isEmpty()) continue; add = multiplier * 7; if (b.bonusValue > 1) add *= b.bonusValue; if (b.getAttribute(Block.BLOCK_ATTRIBUTE_GARBAGE)) { add /= 2.0; b.secondaryColor = 0; b.hard = 0; } receiver.blockBreak(engine, playerID, x, y, b); engine.field.setBlockColor(x, y, Block.BLOCK_COLOR_NONE); pts += add; } } if (engine.chain > 1) pts += (engine.chain-1)*20.0; engine.playSE("combo" + Math.min(engine.chain, 20)); double ojamaNew = (int) (pts*attackMultiplier[playerID]/7.0); if (engine.field.isEmpty()) { engine.playSE("bravo"); zenKeshiDisplay[playerID] = 120; ojamaNew += 12; engine.statistics.score += 1000; score[playerID] += 1000; } lastscore[playerID] = ((int) pts) * 10; scgettime[playerID] = 120; score[playerID] += lastscore[playerID]; if (hurryupSeconds[playerID] > 0 && engine.statistics.time > hurryupSeconds[playerID]) ojamaNew *= 1 << (engine.statistics.time / (hurryupSeconds[playerID] * 60)); if (ojama[playerID] > 0 && ojamaNew > 0.0) { int delta = Math.min(ojama[playerID] << 1, (int) ojamaNew); ojama[playerID] -= delta >> 1; ojamaNew -= delta; } int ojamaSend = (int) (ojamaNew * defendMultiplier[enemyID]); if (ojamaSend > 0) ojama[enemyID] += ojamaSend; } public static double getRowValue(int row) { return ROW_VALUES[Math.min(Math.max(row, 0), ROW_VALUES.length-1)]; } public void checkAll(GameEngine engine, int playerID) { boolean recheck = checkHardDecrement(engine, playerID); if (recheck) log.debug("Converted garbage blocks to regular blocks. Rechecking squares."); checkSquares(engine, playerID, recheck); } public boolean checkHardDecrement (GameEngine engine, int playerID) { if (hardDecremented[playerID]) return false; hardDecremented[playerID] = true; boolean result = false; for (int y = (engine.field.getHiddenHeight() * -1); y < engine.field.getHeight(); y++) for (int x = 0; x < engine.field.getWidth(); x++) { Block b = engine.field.getBlock(x, y); if (b == null) continue; if (b.hard > 1) b.hard--; else if (b.hard == 1) { b.hard = 0; b.setAttribute(Block.BLOCK_ATTRIBUTE_GARBAGE, false); b.color = b.secondaryColor; result = true; } } return result; } public void checkSquares (GameEngine engine, int playerID, boolean forceRecheck) { if (engine.field == null) return; if (engine.statistics.time == lastSquareCheck[playerID] && !forceRecheck) return; lastSquareCheck[playerID] = engine.statistics.time; log.debug("Checking squares."); int width = engine.field.getWidth(); int height = engine.field.getHeight(); int hiddenHeight = engine.field.getHiddenHeight(); int color; Block b; int minX, minY, maxX, maxY; for (int x = 0; x < width; x++) for (int y = (-1*hiddenHeight); y < height; y++) { color = engine.field.getBlockColor(x, y); if (color < Block.BLOCK_COLOR_RED || color > Block.BLOCK_COLOR_PURPLE) continue; minX = x; minY = y; maxX = x; maxY = y; boolean expanded = false; b = engine.field.getBlock(x, y); if (!b.getAttribute(Block.BLOCK_ATTRIBUTE_BROKEN) && b.getAttribute(Block.BLOCK_ATTRIBUTE_CONNECT_RIGHT) && b.getAttribute(Block.BLOCK_ATTRIBUTE_CONNECT_DOWN) && !b.getAttribute(Block.BLOCK_ATTRIBUTE_CONNECT_UP) && !b.getAttribute(Block.BLOCK_ATTRIBUTE_CONNECT_LEFT)) { //Find boundaries of existing gem block maxX++; maxY++; Block test; while (maxX < width) { test = engine.field.getBlock(maxX, y); if (test == null) { maxX--; break; } if (test.color != color) { maxX--; break; } if (!test.getAttribute(Block.BLOCK_ATTRIBUTE_CONNECT_RIGHT)) break; maxX++; } while (maxY < height) { test = engine.field.getBlock(x, maxY); if (test == null) { maxY--; break; } if (test.color != color) { maxY--; break; } if (!test.getAttribute(Block.BLOCK_ATTRIBUTE_CONNECT_DOWN)) break; maxY++; } log.debug("Pre-existing square found: (" + minX + ", " + minY + ") to (" + maxX + ", " + maxY + ")"); } else if (b.getAttribute(Block.BLOCK_ATTRIBUTE_BROKEN) && color == engine.field.getBlockColor(x+1, y) && color == engine.field.getBlockColor(x, y+1) && color == engine.field.getBlockColor(x+1, y+1)) { Block bR = engine.field.getBlock(x+1, y); Block bD = engine.field.getBlock(x, y+1); Block bDR = engine.field.getBlock(x+1, y+1); if ( bR.getAttribute(Block.BLOCK_ATTRIBUTE_BROKEN) && bD.getAttribute(Block.BLOCK_ATTRIBUTE_BROKEN) && bDR.getAttribute(Block.BLOCK_ATTRIBUTE_BROKEN)) { //Form new gem block maxX = x+1; maxY = y+1; b.setAttribute(Block.BLOCK_ATTRIBUTE_BROKEN, false); bR.setAttribute(Block.BLOCK_ATTRIBUTE_BROKEN, false); bD.setAttribute(Block.BLOCK_ATTRIBUTE_BROKEN, false); bDR.setAttribute(Block.BLOCK_ATTRIBUTE_BROKEN, false); expanded = true; } log.debug("New square formed: (" + minX + ", " + minY + ") to (" + maxX + ", " + maxY + ")"); } if (maxX <= minX || maxY <= minY) continue; //No gem block, skip to next block boolean expandHere, done; int testX, testY; Block bTest; log.debug("Testing square for expansion. Coordinates before: (" + minX + ", " + minY + ") to (" + maxX + ", " + maxY + ")"); //Expand up for (testY = minY-1, done = false; testY >= (-1 * hiddenHeight) && !done; testY--) { log.debug("Testing to expand up. testY = " + testY); if (color != engine.field.getBlockColor(minX, testY) || color != engine.field.getBlockColor(maxX, testY)) break; if (engine.field.getBlock(minX, testY).getAttribute(Block.BLOCK_ATTRIBUTE_CONNECT_LEFT) || engine.field.getBlock(maxX, testY).getAttribute(Block.BLOCK_ATTRIBUTE_CONNECT_RIGHT)) break; expandHere = true; for (testX = minX; testX <= maxX && !done; testX++) { if (engine.field.getBlockColor(testX, testY) != color) { done = true; expandHere = false; } else if (engine.field.getBlock(testX, testY).getAttribute(Block.BLOCK_ATTRIBUTE_CONNECT_UP)) expandHere = false; } if (expandHere) { minY = testY; expanded = true; } } //Expand left for (testX = minX-1, done = false; testX >= 0 && !done; testX--) { if (color != engine.field.getBlockColor(testX, minY) || color != engine.field.getBlockColor(testX, maxY)) break; if (engine.field.getBlock(testX, minY).getAttribute(Block.BLOCK_ATTRIBUTE_CONNECT_UP) || engine.field.getBlock(testX, maxY).getAttribute(Block.BLOCK_ATTRIBUTE_CONNECT_DOWN)) break; expandHere = true; for (testY = minY; testY <= maxY && !done; testY++) { if (engine.field.getBlockColor(testX, testY) != color) { done = true; expandHere = false; } else if (engine.field.getBlock(testX, testY).getAttribute(Block.BLOCK_ATTRIBUTE_CONNECT_LEFT)) expandHere = false; } if (expandHere) { minX = testX; expanded = true; } } //Expand right for (testX = maxX+1, done = false; testX < width && !done; testX++) { if (color != engine.field.getBlockColor(testX, minY) || color != engine.field.getBlockColor(testX, maxY)) break; if (engine.field.getBlock(testX, minY).getAttribute(Block.BLOCK_ATTRIBUTE_CONNECT_UP) || engine.field.getBlock(testX, maxY).getAttribute(Block.BLOCK_ATTRIBUTE_CONNECT_DOWN)) break; expandHere = true; for (testY = minY; testY <= maxY && !done; testY++) { if (engine.field.getBlockColor(testX, testY) != color) { done = true; expandHere = false; } else if (engine.field.getBlock(testX, testY).getAttribute(Block.BLOCK_ATTRIBUTE_CONNECT_RIGHT)) expandHere = false; } if (expandHere) { maxX = testX; expanded = true; } } //Expand down for (testY = maxY+1, done = false; testY < height && !done; testY++) { if (color != engine.field.getBlockColor(minX, testY) || color != engine.field.getBlockColor(maxX, testY)) break; if (engine.field.getBlock(minX, testY).getAttribute(Block.BLOCK_ATTRIBUTE_CONNECT_LEFT) || engine.field.getBlock(maxX, testY).getAttribute(Block.BLOCK_ATTRIBUTE_CONNECT_RIGHT)) break; expandHere = true; for (testX = minX; testX <= maxX && !done; testX++) { if (engine.field.getBlockColor(testX, testY) != color) { done = true; expandHere = false; } else if (engine.field.getBlock(testX, testY).getAttribute(Block.BLOCK_ATTRIBUTE_CONNECT_DOWN)) expandHere = false; } if (expandHere) { maxY = testY; expanded = true; } } log.debug("expanded = " + expanded); if (expanded) { log.debug("Expanding square. Coordinates after: (" + minX + ", " + minY + ") to (" + maxX + ", " + maxY + ")"); int size = Math.min(maxX - minX + 1, maxY - minY + 1); for (testX = minX; testX <= maxX; testX++) for (testY = minY; testY <= maxY; testY++) { bTest = engine.field.getBlock(testX, testY); bTest.setAttribute(Block.BLOCK_ATTRIBUTE_BROKEN, false); bTest.setAttribute(Block.BLOCK_ATTRIBUTE_CONNECT_LEFT, testX != minX); bTest.setAttribute(Block.BLOCK_ATTRIBUTE_CONNECT_DOWN, testY != maxY); bTest.setAttribute(Block.BLOCK_ATTRIBUTE_CONNECT_UP, testY != minY); bTest.setAttribute(Block.BLOCK_ATTRIBUTE_CONNECT_RIGHT, testX != maxX); bTest.bonusValue = size; } } } } public boolean lineClearEnd(GameEngine engine, int playerID) { if (engine.field == null) return false; int width = engine.field.getWidth(); int height = engine.field.getHeight(); int hiddenHeight = engine.field.getHiddenHeight(); for (int y = (-1*hiddenHeight); y < height; y++) for (int x = 0; x < width; x++) if (engine.field.getBlockColor(x, y) == DIAMOND_COLOR) { calcScore(engine, playerID, 0); return true; } checkAll(engine, playerID); //Drop garbage if needed. if (ojama[playerID] > 0) { int enemyID = 0; if(playerID == 0) enemyID = 1; int dropRows = Math.min((ojama[playerID] + width - 1) / width, engine.field.getHighestBlockY(3)); if (dropRows <= 0) return false; int drop = Math.min(ojama[playerID], width * dropRows); ojama[playerID] -= drop; //engine.field.garbageDrop(engine, drop, big[playerID], ojamaHard[playerID], 3); engine.field.garbageDrop(engine, drop, false, ojamaHard[playerID], 3); engine.field.setAllSkin(engine.getSkin()); int patternCol = 0; for (int x = 0; x < engine.field.getWidth(); x++) { if (patternCol >= dropPattern[enemyID].length) patternCol = 0; int patternRow = 0; for (int y = dropRows - hiddenHeight; y >= (-1 * hiddenHeight); y--) { Block b = engine.field.getBlock(x, y); if (b.getAttribute(Block.BLOCK_ATTRIBUTE_GARBAGE) && b.secondaryColor == 0) { if (patternRow >= dropPattern[enemyID][patternCol].length) patternRow = 0; b.secondaryColor = dropPattern[enemyID][patternCol][patternRow]; patternRow++; } } patternCol++; } return true; } return false; } /* * Called after every frame */ @Override public void onLast(GameEngine engine, int playerID) { scgettime[playerID]++; if (zenKeshiDisplay[playerID] > 0) zenKeshiDisplay[playerID]--; int width = 1; if (engine.field != null) width = engine.field.getWidth(); int blockHeight = receiver.getBlockGraphicsHeight(engine, playerID); // せり上がりMeter if(ojama[playerID] * blockHeight / width > engine.meterValue) { engine.meterValue++; } else if(ojama[playerID] * blockHeight / width < engine.meterValue) { engine.meterValue--; } if(ojama[playerID] > 30) engine.meterColor = GameEngine.METER_COLOR_RED; else if(ojama[playerID] > 10) engine.meterColor = GameEngine.METER_COLOR_YELLOW; else engine.meterColor = GameEngine.METER_COLOR_GREEN; // 決着 if((playerID == 1) && (owner.engine[0].gameActive)) { if((owner.engine[0].stat == GameEngine.STAT_GAMEOVER) && (owner.engine[1].stat == GameEngine.STAT_GAMEOVER)) { // 引き分け winnerID = -1; owner.engine[0].gameActive = false; owner.engine[1].gameActive = false; owner.bgmStatus.bgm = BGMStatus.BGM_NOTHING; } else if((owner.engine[0].stat != GameEngine.STAT_GAMEOVER) && (owner.engine[1].stat == GameEngine.STAT_GAMEOVER)) { // 1P勝利 winnerID = 0; owner.engine[0].gameActive = false; owner.engine[1].gameActive = false; owner.engine[0].stat = GameEngine.STAT_EXCELLENT; owner.engine[0].resetStatc(); owner.engine[0].statc[1] = 1; owner.bgmStatus.bgm = BGMStatus.BGM_NOTHING; } else if((owner.engine[0].stat == GameEngine.STAT_GAMEOVER) && (owner.engine[1].stat != GameEngine.STAT_GAMEOVER)) { // 2P勝利 winnerID = 1; owner.engine[0].gameActive = false; owner.engine[1].gameActive = false; owner.engine[1].stat = GameEngine.STAT_EXCELLENT; owner.engine[1].resetStatc(); owner.engine[1].statc[1] = 1; owner.bgmStatus.bgm = BGMStatus.BGM_NOTHING; } } } /* * Render results screen */ @Override public void renderResult(GameEngine engine, int playerID) { receiver.drawMenuFont(engine, playerID, 0, 1, "RESULT", EventReceiver.COLOR_ORANGE); if(winnerID == -1) { receiver.drawMenuFont(engine, playerID, 6, 2, "DRAW", EventReceiver.COLOR_GREEN); } else if(winnerID == playerID) { receiver.drawMenuFont(engine, playerID, 6, 2, "WIN!", EventReceiver.COLOR_YELLOW); } else { receiver.drawMenuFont(engine, playerID, 6, 2, "LOSE", EventReceiver.COLOR_WHITE); } receiver.drawMenuFont(engine, playerID, 0, 3, "ATTACK", EventReceiver.COLOR_ORANGE); String strScore = String.format("%10d", ojamaSent[playerID]); receiver.drawMenuFont(engine, playerID, 0, 4, strScore); receiver.drawMenuFont(engine, playerID, 0, 5, "LINE", EventReceiver.COLOR_ORANGE); String strLines = String.format("%10d", engine.statistics.lines); receiver.drawMenuFont(engine, playerID, 0, 6, strLines); receiver.drawMenuFont(engine, playerID, 0, 7, "PIECE", EventReceiver.COLOR_ORANGE); String strPiece = String.format("%10d", engine.statistics.totalPieceLocked); receiver.drawMenuFont(engine, playerID, 0, 8, strPiece); receiver.drawMenuFont(engine, playerID, 0, 9, "ATTACK/MIN", EventReceiver.COLOR_ORANGE); float apm = (float)(ojamaSent[playerID] * 3600) / (float)(engine.statistics.time); String strAPM = String.format("%10g", apm); receiver.drawMenuFont(engine, playerID, 0, 10, strAPM); receiver.drawMenuFont(engine, playerID, 0, 11, "LINE/MIN", EventReceiver.COLOR_ORANGE); String strLPM = String.format("%10g", engine.statistics.lpm); receiver.drawMenuFont(engine, playerID, 0, 12, strLPM); receiver.drawMenuFont(engine, playerID, 0, 13, "PIECE/SEC", EventReceiver.COLOR_ORANGE); String strPPS = String.format("%10g", engine.statistics.pps); receiver.drawMenuFont(engine, playerID, 0, 14, strPPS); receiver.drawMenuFont(engine, playerID, 0, 15, "TIME", EventReceiver.COLOR_ORANGE); String strTime = String.format("%10s", GeneralUtil.getTime(owner.engine[0].statistics.time)); receiver.drawMenuFont(engine, playerID, 0, 16, strTime); } /* * Called when saving replay */ @Override public void saveReplay(GameEngine engine, int playerID, CustomProperties prop) { saveOtherSetting(engine, owner.replayProp); savePreset(engine, owner.replayProp, -1 - playerID); if(useMap[playerID] && (fldBackup[playerID] != null)) { saveMap(fldBackup[playerID], owner.replayProp, playerID); } owner.replayProp.setProperty("spfvs.version", version); } }
src/mu/nu/nullpo/game/subsystem/mode/SPFMode.java
/* Copyright (c) 2010, NullNoname All rights reserved. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: * Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. * Neither the name of NullNoname nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ package mu.nu.nullpo.game.subsystem.mode; import java.util.Random; import mu.nu.nullpo.game.component.BGMStatus; import mu.nu.nullpo.game.component.Block; import mu.nu.nullpo.game.component.Controller; import mu.nu.nullpo.game.component.Field; import mu.nu.nullpo.game.component.Piece; import mu.nu.nullpo.game.event.EventReceiver; import mu.nu.nullpo.game.play.GameEngine; import mu.nu.nullpo.game.play.GameManager; import mu.nu.nullpo.util.CustomProperties; import mu.nu.nullpo.util.GeneralUtil; import org.apache.log4j.Logger; /** * SPF VS-BATTLE mode (Beta) */ public class SPFMode extends DummyMode { /** Log (Apache log4j) */ static Logger log = Logger.getLogger(SPFMode.class); /** Current version */ private static final int CURRENT_VERSION = 0; /** Enabled piece types */ private static final int[] PIECE_ENABLE = {0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0}; /** Block colors */ private static final int[] BLOCK_COLORS = { Block.BLOCK_COLOR_RED, Block.BLOCK_COLOR_RED, Block.BLOCK_COLOR_RED, Block.BLOCK_COLOR_RED, Block.BLOCK_COLOR_GEM_RED, Block.BLOCK_COLOR_GREEN, Block.BLOCK_COLOR_GREEN, Block.BLOCK_COLOR_GREEN, Block.BLOCK_COLOR_GREEN, Block.BLOCK_COLOR_GEM_GREEN, Block.BLOCK_COLOR_BLUE, Block.BLOCK_COLOR_BLUE, Block.BLOCK_COLOR_BLUE, Block.BLOCK_COLOR_BLUE, Block.BLOCK_COLOR_GEM_BLUE, Block.BLOCK_COLOR_YELLOW, Block.BLOCK_COLOR_YELLOW, Block.BLOCK_COLOR_YELLOW, Block.BLOCK_COLOR_YELLOW, Block.BLOCK_COLOR_GEM_YELLOW }; private static final double[] ROW_VALUES = { 2.3, 2.2, 2.1, 2.0, 1.9, 1.8, 1.7, 1.6, 1.5, 1.4, 1.3, 1.2, 1.1, 1.0 }; private static final int DIAMOND_COLOR = Block.BLOCK_COLOR_GEM_RAINBOW; /** Number of players */ private static final int MAX_PLAYERS = 2; /** Names of drop map sets */ private static final String[] DROP_SET_NAMES = {"CLASSIC", "REMIX", "SWORD", "S-MIRROR"}; private static final int[][][][] DROP_PATTERNS = { { {{2,2,2,2}, {5,5,5,5}, {7,7,7,7}, {4,4,4,4}}, {{2,2,4,4}, {2,2,4,4}, {5,5,2,2}, {5,5,2,2}, {7,7,5,5}, {7,7,5,5}}, {{5,5,5,5}, {2,7,2,7}, {2,7,2,7}, {2,7,2,7}, {2,7,2,7}, {4,4,4,4}}, {{2,5,7,4}}, {{7,7,4,4}, {4,4,7,7}, {2,2,5,5}, {2,2,5,5}, {4,4,7,7}, {7,7,4,4}}, {{4,7,7,5}, {7,7,5,5}, {7,5,5,2}, {5,5,2,2}, {5,2,2,4}, {2,2,4,4}}, {{2,2,5,5}, {4,4,5,5}, {2,2,5,5}, {4,4,7,7}, {2,2,7,7}, {4,4,7,7}}, {{5,5,5,5}, {2,2,7,7}, {2,2,7,7}, {7,7,2,2}, {7,7,2,2}, {4,4,4,4}}, {{5,7,4,2}, {2,5,7,4}, {4,2,5,7}, {7,4,2,5}}, {{2,5,7,4}, {5,7,4,2}, {7,4,2,5}, {4,2,5,7}}, {{2,2,2,2}} }, { {{2,2,7,2}, {5,5,4,5}, {7,7,5,7}, {4,4,2,4}}, {{2,2,4,4}, {2,2,4,4}, {5,5,2,2}, {5,5,2,2}, {7,7,5,5}, {7,7,5,5}}, {{5,5,4,4}, {2,7,2,7}, {2,7,2,7}, {2,7,2,7}, {2,7,2,7}, {4,4,5,5}}, {{2,5,7,4}}, {{7,7,4,4}, {4,4,7,7}, {2,5,5,5}, {2,2,2,5}, {4,4,7,7}, {7,7,4,4}}, {{7,7,7,7}, {5,7,4,2}, {7,4,2,5}, {4,2,5,7}, {2,5,7,4}, {5,5,5,5}}, {{2,2,5,5}, {4,4,5,5}, {2,2,5,5}, {4,4,7,7}, {2,2,7,7}, {4,4,7,7}}, {{5,4,5,4}, {2,2,2,7}, {2,7,7,7}, {7,2,2,2}, {7,7,7,2}, {4,5,4,5}}, {{5,7,4,2}, {2,5,7,4}, {4,2,5,7}, {7,4,2,5}}, {{2,5,7,4}, {5,7,4,2}, {7,4,2,5}, {4,2,5,7}}, {{2,2,2,2}} }, { {{2,5,5,5}, {5,2,2,5}, {5,5,2,2}, {4,4,7,7}, {4,7,7,4}, {7,4,4,4}}, {{2,2,2,5,5,5}, {5,3,7,5,4,5}, {5,5,7,7,4,4}, {4,4,2,4,4,7}, {4,2,4,4,7,4}, {2,4,4,7,4,4}}, {{4,4,5,5,7,2}, {4,4,5,5,7,2}, {5,5,7,7,7,5}, {5,7,7,7,4,5}, {7,7,2,2,5,4}, {7,2,2,2,5,4}}, {{2,2,5,4,2,7}, {2,7,4,5,7,2}, {2,7,4,4,7,7}, {2,7,5,5,2,2}, {2,7,5,4,2,7}, {7,7,4,5,7,2}}, {{2,7,7,7,7}, {2,7,5,7,7}, {2,2,5,5,5}, {2,2,2,5,5}, {2,4,2,4,4}, {4,4,4,4,4}}, {{2,2,5,5}, {2,7,7,5}, {5,7,4,4}, {5,5,2,4}, {4,2,2,7}, {4,4,7,7}}, {{2,2,5,5}, {2,2,5,5}, {5,5,7,7}, {5,5,7,7}, {7,7,4,4}, {7,7,4,4}}, {{2,2,5,4,2,7}, {2,2,4,5,7,2}, {7,7,4,5,7,2}, {7,7,5,4,2,7}, {2,2,5,4,2,7}, {2,2,4,5,7,2}}, {{7,7,4,4,7,7}, {7,7,7,7,5,7}, {2,5,2,2,5,2}, {2,5,2,2,5,2}, {4,4,4,4,5,4}, {4,4,7,7,4,4}}, {{2,5,5,5,5,4}, {5,2,5,5,4,4}, {2,2,2,2,2,2}, {7,7,7,7,7,7}, {4,7,4,4,5,5}, {7,4,4,4,4,5}}, {{2,2,5,2,2,4}, {2,5,5,2,5,5}, {5,5,5,7,7,2}, {7,7,7,5,5,4}, {4,7,7,4,7,7}, {4,4,7,4,4,2}}, {{7,7,5,5,5,5}, {7,2,2,5,5,7}, {7,2,2,4,4,7}, {2,7,7,4,4,2}, {2,7,7,5,5,2}, {7,7,5,5,5,5}}, {{7,7,5,5}, {7,2,5,2}, {5,5,5,2}, {4,4,4,2}, {7,2,4,2}, {7,7,4,4}}, {{2,2,5,5}, {2,7,5,5}, {5,5,7,7}, {5,5,7,7}, {4,7,4,4}, {7,7,4,4}}, {{7,7,5,5,5}, {4,7,7,7,5}, {5,4,4,4,4}, {5,2,2,2,2}, {2,7,7,7,5}, {7,7,5,5,5}}, {{2,2,4}, {2,2,2}, {7,7,7}, {7,7,7}, {5,5,5}, {5,5,4}}, {{7,7,7,7}, {7,2,2,7}, {2,7,5,4}, {4,5,7,2}, {5,4,4,5}, {5,5,5,5}} }, { {{7,4,4,4}, {4,7,7,4}, {4,4,7,7}, {5,5,2,2}, {5,2,2,5}, {2,5,5,5}}, {{2,4,4,7,4,4}, {4,2,4,4,7,4}, {4,4,2,4,4,7}, {5,5,7,7,4,4}, {5,3,7,5,4,5}, {2,2,2,5,5,5}}, {{7,2,2,2,5,4}, {7,7,2,2,5,4}, {5,7,7,7,4,5}, {5,5,7,7,7,5}, {4,4,5,5,7,2}, {4,4,5,5,7,2}}, {{7,7,4,5,7,2}, {2,7,5,4,2,7}, {2,7,5,5,2,2}, {2,7,4,4,7,7}, {2,7,4,5,7,2}, {2,2,5,4,2,7}}, {{4,4,4,4,4}, {2,4,2,4,4}, {2,2,2,5,5}, {2,2,5,5,5}, {2,7,5,7,7}, {2,7,7,7,7}}, {{4,4,7,7}, {4,2,2,7}, {5,5,2,4}, {5,7,4,4}, {2,7,7,5}, {2,2,5,5}}, {{7,7,4,4}, {7,7,4,4}, {5,5,7,7}, {5,5,7,7}, {2,2,5,5}, {2,2,5,5}}, {{2,2,4,5,7,2}, {2,2,5,4,2,7}, {7,7,5,4,2,7}, {7,7,4,5,7,2}, {2,2,4,5,7,2}, {2,2,5,4,2,7}}, {{4,4,7,7,4,4}, {4,4,4,4,5,4}, {2,5,2,2,5,2}, {2,5,2,2,5,2}, {7,7,7,7,5,7}, {7,7,4,4,7,7}}, {{7,4,4,4,4,5}, {4,7,4,4,5,5}, {7,7,7,7,7,7}, {2,2,2,2,2,2}, {5,2,5,5,4,4}, {2,5,5,5,5,4}}, {{4,4,7,4,4,2}, {4,7,7,4,7,7}, {7,7,7,5,5,4}, {5,5,5,7,7,2}, {2,5,5,2,5,5}, {2,2,5,2,2,4}}, {{7,7,5,5,5,5}, {2,7,7,5,5,2}, {2,7,7,4,4,2}, {7,2,2,4,4,7}, {7,2,2,5,5,7}, {7,7,5,5,5,5}}, {{7,7,4,4}, {7,2,4,2}, {4,4,4,2}, {5,5,5,2}, {7,2,5,2}, {7,7,5,5}}, {{7,7,4,4}, {4,7,4,4}, {5,5,7,7}, {5,5,7,7}, {2,7,5,5}, {2,2,5,5}}, {{7,7,5,5,5}, {2,7,7,7,5}, {5,2,2,2,2}, {5,4,4,4,4}, {4,7,7,7,5}, {7,7,5,5,5}}, {{5,5,4}, {5,5,5}, {7,7,7}, {7,7,7}, {2,2,2}, {2,2,4}}, {{5,5,5,5}, {5,4,4,5}, {4,5,7,2}, {2,7,5,4}, {7,2,2,7}, {7,7,7,7}} } }; private static final double[][] DROP_PATTERNS_ATTACK_MULTIPLIERS = { {1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 0.7, 0.7, 1.0}, {1.0, 1.2, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 0.85, 1.0}, {1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0}, {1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0} }; private static final double[][] DROP_PATTERNS_DEFEND_MULTIPLIERS = { {1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0}, {1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.2, 1.0, 1.0}, {1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0}, {1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0} }; /** Names of rainbow power settings */ private static final String[] RAINBOW_POWER_NAMES = {"NONE", "50%", "80%", "100%", "50/100%"}; /** Each player's frame color */ private static final int[] PLAYER_COLOR_FRAME = {GameEngine.FRAME_COLOR_RED, GameEngine.FRAME_COLOR_BLUE}; /** GameManager that owns this mode */ private GameManager owner; /** Drawing and event handling EventReceiver */ private EventReceiver receiver; /** 溜まっている邪魔Blockのcount */ private int[] ojama; /** 送った邪魔Blockのcount */ private int[] ojamaSent; /** Time to display the most recent increase in score */ private int[] scgettime; /** 使用するBGM */ private int bgmno; /** Big */ //private boolean[] big; /** 効果音ON/OFF */ private boolean[] enableSE; /** マップ使用 flag */ private boolean[] useMap; /** 使用するマップセット number */ private int[] mapSet; /** マップ number(-1でランダム) */ private int[] mapNumber; /** Last preset number used */ private int[] presetNumber; /** 勝者 */ private int winnerID; /** マップセットのProperty file */ private CustomProperties[] propMap; /** 最大マップ number */ private int[] mapMaxNo; /** バックアップ用フィールド(マップをリプレイに保存するときに使用) */ private Field[] fldBackup; /** マップ選択用乱count */ private Random randMap; /** Version */ private int version; /** Amount of points earned from most recent clear */ private int[] lastscore; /** Score */ private int[] score; /** Settings for hard ojama blocks */ private int[] ojamaHard; /** Hurryup開始までの秒count(0でHurryupなし) */ private int[] hurryupSeconds; /** Time to display "ZENKESHI!" */ private int[] zenKeshiDisplay; /** Time to display "TECH BONUS" */ private int[] techBonusDisplay; /** Drop patterns */ private int[][][] dropPattern; /** Drop map set selected */ private int[] dropSet; /** Drop map selected */ private int[] dropMap; /** Drop multipliers */ private double[] attackMultiplier, defendMultiplier; /** Rainbow power settings for each player */ private int[] diamondPower; /** Frame when squares were last checked */ private int[] lastSquareCheck; /** Flag set when counters have been decremented */ private boolean[] hardDecremented; /* * Mode name */ @Override public String getName() { return "SPF VS-BATTLE (BETA)"; } /* * Number of players */ @Override public int getPlayers() { return MAX_PLAYERS; } /* * Mode initialization */ @Override public void modeInit(GameManager manager) { owner = manager; receiver = owner.receiver; ojama = new int[MAX_PLAYERS]; ojamaSent = new int[MAX_PLAYERS]; scgettime = new int[MAX_PLAYERS]; bgmno = 0; //big = new boolean[MAX_PLAYERS]; enableSE = new boolean[MAX_PLAYERS]; hurryupSeconds = new int[MAX_PLAYERS]; useMap = new boolean[MAX_PLAYERS]; mapSet = new int[MAX_PLAYERS]; mapNumber = new int[MAX_PLAYERS]; presetNumber = new int[MAX_PLAYERS]; propMap = new CustomProperties[MAX_PLAYERS]; mapMaxNo = new int[MAX_PLAYERS]; fldBackup = new Field[MAX_PLAYERS]; randMap = new Random(); lastscore = new int[MAX_PLAYERS]; score = new int[MAX_PLAYERS]; ojamaHard = new int[MAX_PLAYERS]; zenKeshiDisplay = new int[MAX_PLAYERS]; techBonusDisplay = new int[MAX_PLAYERS]; dropSet = new int[MAX_PLAYERS]; dropMap = new int[MAX_PLAYERS]; dropPattern = new int[MAX_PLAYERS][][]; attackMultiplier = new double[MAX_PLAYERS]; defendMultiplier = new double[MAX_PLAYERS]; diamondPower = new int[MAX_PLAYERS]; lastSquareCheck = new int[MAX_PLAYERS]; hardDecremented = new boolean[MAX_PLAYERS]; winnerID = -1; } /** * Read speed presets * @param engine GameEngine * @param prop Property file to read from * @param preset Preset number */ private void loadPreset(GameEngine engine, CustomProperties prop, int preset) { engine.speed.gravity = prop.getProperty("spfvs.gravity." + preset, 4); engine.speed.denominator = prop.getProperty("spfvs.denominator." + preset, 256); engine.speed.are = prop.getProperty("spfvs.are." + preset, 24); engine.speed.areLine = prop.getProperty("spfvs.areLine." + preset, 24); engine.speed.lineDelay = prop.getProperty("spfvs.lineDelay." + preset, 10); engine.speed.lockDelay = prop.getProperty("spfvs.lockDelay." + preset, 30); engine.speed.das = prop.getProperty("spfvs.das." + preset, 14); } /** * Save speed presets * @param engine GameEngine * @param prop Property file to save to * @param preset Preset number */ private void savePreset(GameEngine engine, CustomProperties prop, int preset) { prop.setProperty("spfvs.gravity." + preset, engine.speed.gravity); prop.setProperty("spfvs.denominator." + preset, engine.speed.denominator); prop.setProperty("spfvs.are." + preset, engine.speed.are); prop.setProperty("spfvs.areLine." + preset, engine.speed.areLine); prop.setProperty("spfvs.lineDelay." + preset, engine.speed.lineDelay); prop.setProperty("spfvs.lockDelay." + preset, engine.speed.lockDelay); prop.setProperty("spfvs.das." + preset, engine.speed.das); } /** * スピード以外の設定を読み込み * @param engine GameEngine * @param prop Property file to read from */ private void loadOtherSetting(GameEngine engine, CustomProperties prop) { int playerID = engine.playerID; bgmno = prop.getProperty("spfvs.bgmno", 0); //big[playerID] = prop.getProperty("spfvs.big.p" + playerID, false); enableSE[playerID] = prop.getProperty("spfvs.enableSE.p" + playerID, true); hurryupSeconds[playerID] = prop.getProperty("vsbattle.hurryupSeconds.p" + playerID, 0); useMap[playerID] = prop.getProperty("spfvs.useMap.p" + playerID, false); mapSet[playerID] = prop.getProperty("spfvs.mapSet.p" + playerID, 0); mapNumber[playerID] = prop.getProperty("spfvs.mapNumber.p" + playerID, -1); presetNumber[playerID] = prop.getProperty("spfvs.presetNumber.p" + playerID, 0); ojamaHard[playerID] = prop.getProperty("spfvs.ojamaHard.p" + playerID, 5); dropSet[playerID] = prop.getProperty("spfvs.dropSet.p" + playerID, 0); dropMap[playerID] = prop.getProperty("spfvs.dropMap.p" + playerID, 0); diamondPower[playerID] = prop.getProperty("spfvs.rainbowPower.p" + playerID, 2); } /** * スピード以外の設定を保存 * @param engine GameEngine * @param prop Property file to save to */ private void saveOtherSetting(GameEngine engine, CustomProperties prop) { int playerID = engine.playerID; prop.setProperty("spfvs.bgmno", bgmno); //prop.setProperty("spfvs.big.p" + playerID, big[playerID]); prop.setProperty("spfvs.enableSE.p" + playerID, enableSE[playerID]); prop.setProperty("vsbattle.hurryupSeconds.p" + playerID, hurryupSeconds[playerID]); prop.setProperty("spfvs.useMap.p" + playerID, useMap[playerID]); prop.setProperty("spfvs.mapSet.p" + playerID, mapSet[playerID]); prop.setProperty("spfvs.mapNumber.p" + playerID, mapNumber[playerID]); prop.setProperty("spfvs.presetNumber.p" + playerID, presetNumber[playerID]); prop.setProperty("spfvs.ojamaHard.p" + playerID, ojamaHard[playerID]); prop.setProperty("spfvs.dropSet.p" + playerID, dropSet[playerID]); prop.setProperty("spfvs.dropMap.p" + playerID, dropMap[playerID]); prop.setProperty("spfvs.rainbowPower.p" + playerID, diamondPower[playerID]); } /** * マップ読み込み * @param field フィールド * @param prop Property file to read from * @param preset 任意のID */ private void loadMap(Field field, CustomProperties prop, int id) { field.reset(); //field.readProperty(prop, id); field.stringToField(prop.getProperty("map." + id, "")); field.setAllAttribute(Block.BLOCK_ATTRIBUTE_VISIBLE, true); field.setAllAttribute(Block.BLOCK_ATTRIBUTE_OUTLINE, true); field.setAllAttribute(Block.BLOCK_ATTRIBUTE_SELFPLACED, false); } /** * マップ保存 * @param field フィールド * @param prop Property file to save to * @param id 任意のID */ private void saveMap(Field field, CustomProperties prop, int id) { //field.writeProperty(prop, id); prop.setProperty("map." + id, field.fieldToString()); } /** * プレビュー用にマップを読み込み * @param engine GameEngine * @param playerID プレイヤー number * @param id マップID * @param forceReload trueにするとマップファイルを強制再読み込み */ private void loadMapPreview(GameEngine engine, int playerID, int id, boolean forceReload) { if((propMap[playerID] == null) || (forceReload)) { mapMaxNo[playerID] = 0; propMap[playerID] = receiver.loadProperties("config/map/spf/" + mapSet[playerID] + ".map"); } if((propMap[playerID] == null) && (engine.field != null)) { engine.field.reset(); } else if(propMap[playerID] != null) { mapMaxNo[playerID] = propMap[playerID].getProperty("map.maxMapNumber", 0); engine.createFieldIfNeeded(); loadMap(engine.field, propMap[playerID], id); engine.field.setAllSkin(engine.getSkin()); } } private void loadDropMapPreview(GameEngine engine, int playerID, int[][] pattern) { if((pattern == null) && (engine.field != null)) { engine.field.reset(); } else if(pattern != null) { log.debug("Loading drop map preview"); engine.createFieldIfNeeded(); engine.field.reset(); int patternCol = 0; int maxHeight = engine.field.getHeight()-1; for (int x = 0; x < engine.field.getWidth(); x++) { if (patternCol >= pattern.length) patternCol = 0; for (int patternRow = 0; patternRow < pattern[patternCol].length; patternRow++) { engine.field.setBlockColor(x, maxHeight-patternRow, pattern[patternCol][patternRow]); Block blk = engine.field.getBlock(x, maxHeight-patternRow); blk.setAttribute(Block.BLOCK_ATTRIBUTE_VISIBLE, true); blk.setAttribute(Block.BLOCK_ATTRIBUTE_OUTLINE, true); } patternCol++; } engine.field.setAllSkin(engine.getSkin()); } } /* * Initialization for each player */ @Override public void playerInit(GameEngine engine, int playerID) { if(playerID == 1) { engine.randSeed = owner.engine[0].randSeed; engine.random = new Random(owner.engine[0].randSeed); } engine.framecolor = PLAYER_COLOR_FRAME[playerID]; engine.clearMode = GameEngine.CLEAR_GEM_COLOR; engine.garbageColorClear = true; engine.lineGravityType = GameEngine.LINE_GRAVITY_CASCADE; for(int i = 0; i < Piece.PIECE_COUNT; i++) engine.nextPieceEnable[i] = (PIECE_ENABLE[i] == 1); engine.blockColors = BLOCK_COLORS; engine.randomBlockColor = true; engine.connectBlocks = false; ojama[playerID] = 0; ojamaSent[playerID] = 0; score[playerID] = 0; scgettime[playerID] = 0; zenKeshiDisplay[playerID] = 0; techBonusDisplay[playerID] = 0; lastSquareCheck[playerID] = -1; hardDecremented[playerID] = true; if(engine.owner.replayMode == false) { loadOtherSetting(engine, engine.owner.modeConfig); loadPreset(engine, engine.owner.modeConfig, -1 - playerID); version = CURRENT_VERSION; } else { loadOtherSetting(engine, engine.owner.replayProp); loadPreset(engine, engine.owner.replayProp, -1 - playerID); version = owner.replayProp.getProperty("spfvs.version", 0); } } /* * Called at settings screen */ @Override public boolean onSetting(GameEngine engine, int playerID) { // Menu if((engine.owner.replayMode == false) && (engine.statc[4] == 0)) { // Up if(engine.ctrl.isMenuRepeatKey(Controller.BUTTON_UP)) { engine.statc[2]--; if(engine.statc[2] < 0){ engine.statc[2] = 18; loadDropMapPreview(engine, playerID, DROP_PATTERNS[dropSet[playerID]][dropMap[playerID]]); } else if (engine.statc[2] == 16) engine.field = null; engine.playSE("cursor"); } // Down if(engine.ctrl.isMenuRepeatKey(Controller.BUTTON_DOWN)) { engine.statc[2]++; if(engine.statc[2] > 18) { engine.statc[2] = 0; engine.field = null; } else if (engine.statc[2] == 17) loadDropMapPreview(engine, playerID, DROP_PATTERNS[dropSet[playerID]][dropMap[playerID]]); engine.playSE("cursor"); } // Configuration changes int change = 0; if(engine.ctrl.isMenuRepeatKey(Controller.BUTTON_LEFT)) change = -1; if(engine.ctrl.isMenuRepeatKey(Controller.BUTTON_RIGHT)) change = 1; if(change != 0) { engine.playSE("change"); int m = 1; if(engine.ctrl.isPress(Controller.BUTTON_E)) m = 100; if(engine.ctrl.isPress(Controller.BUTTON_F)) m = 1000; switch(engine.statc[2]) { case 0: engine.speed.gravity += change * m; if(engine.speed.gravity < -1) engine.speed.gravity = 99999; if(engine.speed.gravity > 99999) engine.speed.gravity = -1; break; case 1: engine.speed.denominator += change * m; if(engine.speed.denominator < -1) engine.speed.denominator = 99999; if(engine.speed.denominator > 99999) engine.speed.denominator = -1; break; case 2: engine.speed.are += change; if(engine.speed.are < 0) engine.speed.are = 99; if(engine.speed.are > 99) engine.speed.are = 0; break; case 3: engine.speed.areLine += change; if(engine.speed.areLine < 0) engine.speed.areLine = 99; if(engine.speed.areLine > 99) engine.speed.areLine = 0; break; case 4: engine.speed.lineDelay += change; if(engine.speed.lineDelay < 0) engine.speed.lineDelay = 99; if(engine.speed.lineDelay > 99) engine.speed.lineDelay = 0; break; case 5: engine.speed.lockDelay += change; if(engine.speed.lockDelay < 0) engine.speed.lockDelay = 99; if(engine.speed.lockDelay > 99) engine.speed.lockDelay = 0; break; case 6: engine.speed.das += change; if(engine.speed.das < 0) engine.speed.das = 99; if(engine.speed.das > 99) engine.speed.das = 0; break; case 7: case 8: presetNumber[playerID] += change; if(presetNumber[playerID] < 0) presetNumber[playerID] = 99; if(presetNumber[playerID] > 99) presetNumber[playerID] = 0; break; case 9: bgmno += change; if(bgmno < 0) bgmno = BGMStatus.BGM_COUNT - 1; if(bgmno > BGMStatus.BGM_COUNT - 1) bgmno = 0; break; case 10: useMap[playerID] = !useMap[playerID]; if(!useMap[playerID]) { if(engine.field != null) engine.field.reset(); } else { loadMapPreview(engine, playerID, (mapNumber[playerID] < 0) ? 0 : mapNumber[playerID], true); } break; case 11: mapSet[playerID] += change; if(mapSet[playerID] < 0) mapSet[playerID] = 99; if(mapSet[playerID] > 99) mapSet[playerID] = 0; if(useMap[playerID]) { mapNumber[playerID] = -1; loadMapPreview(engine, playerID, (mapNumber[playerID] < 0) ? 0 : mapNumber[playerID], true); } break; case 12: if(useMap[playerID]) { mapNumber[playerID] += change; if(mapNumber[playerID] < -1) mapNumber[playerID] = mapMaxNo[playerID] - 1; if(mapNumber[playerID] > mapMaxNo[playerID] - 1) mapNumber[playerID] = -1; loadMapPreview(engine, playerID, (mapNumber[playerID] < 0) ? 0 : mapNumber[playerID], true); } else { mapNumber[playerID] = -1; } break; case 13: enableSE[playerID] = !enableSE[playerID]; break; case 14: if (m > 10) hurryupSeconds[playerID] += change*m/10; else hurryupSeconds[playerID] += change; if(hurryupSeconds[playerID] < 0) hurryupSeconds[playerID] = 300; if(hurryupSeconds[playerID] > 300) hurryupSeconds[playerID] = 0; break; case 15: ojamaHard[playerID] += change; if(ojamaHard[playerID] < 1) ojamaHard[playerID] = 9; if(ojamaHard[playerID] > 9) ojamaHard[playerID] = 1; break; case 16: diamondPower[playerID] += change; if(diamondPower[playerID] < 0) diamondPower[playerID] = 3; if(diamondPower[playerID] > 3) diamondPower[playerID] = 0; break; case 17: dropSet[playerID] += change; if(dropSet[playerID] < 0) dropSet[playerID] = 3; if(dropSet[playerID] > 3) dropSet[playerID] = 0; if(dropMap[playerID] >= DROP_PATTERNS[dropSet[playerID]].length) dropMap[playerID] = 0; loadDropMapPreview(engine, playerID, DROP_PATTERNS[dropSet[playerID]][dropMap[playerID]]); break; case 18: dropMap[playerID] += change; if(dropMap[playerID] < 0) dropMap[playerID] = DROP_PATTERNS[dropSet[playerID]].length-1; if(dropMap[playerID] >= DROP_PATTERNS[dropSet[playerID]].length) dropMap[playerID] = 0; loadDropMapPreview(engine, playerID, DROP_PATTERNS[dropSet[playerID]][dropMap[playerID]]); break; /* case 18: big[playerID] = !big[playerID]; break; */ } } // 決定 if(engine.ctrl.isPush(Controller.BUTTON_A) && (engine.statc[3] >= 5)) { engine.playSE("decide"); if(engine.statc[2] == 7) { loadPreset(engine, owner.modeConfig, presetNumber[playerID]); } else if(engine.statc[2] == 8) { savePreset(engine, owner.modeConfig, presetNumber[playerID]); receiver.saveModeConfig(owner.modeConfig); } else { saveOtherSetting(engine, owner.modeConfig); savePreset(engine, owner.modeConfig, -1 - playerID); receiver.saveModeConfig(owner.modeConfig); engine.statc[4] = 1; } } // Cancel if(engine.ctrl.isPush(Controller.BUTTON_B)) { engine.quitflag = true; } // プレビュー用マップ読み込み if(useMap[playerID] && (engine.statc[3] == 0)) { loadMapPreview(engine, playerID, (mapNumber[playerID] < 0) ? 0 : mapNumber[playerID], true); } // ランダムマッププレビュー if(useMap[playerID] && (propMap[playerID] != null) && (mapNumber[playerID] < 0)) { if(engine.statc[3] % 30 == 0) { engine.statc[5]++; if(engine.statc[5] >= mapMaxNo[playerID]) engine.statc[5] = 0; loadMapPreview(engine, playerID, engine.statc[5], false); } } engine.statc[3]++; } else if(engine.statc[4] == 0) { engine.statc[3]++; engine.statc[2] = 0; if(engine.statc[3] >= 180) engine.statc[4] = 1; else if(engine.statc[3] > 120) engine.statc[2] = 17; else if (engine.statc[3] == 120) { engine.statc[2] = 17; loadDropMapPreview(engine, playerID, DROP_PATTERNS[dropSet[playerID]][dropMap[playerID]]); } else if(engine.statc[3] >= 60) engine.statc[2] = 9; } else { // 開始 if((owner.engine[0].statc[4] == 1) && (owner.engine[1].statc[4] == 1) && (playerID == 1)) { owner.engine[0].stat = GameEngine.STAT_READY; owner.engine[1].stat = GameEngine.STAT_READY; owner.engine[0].resetStatc(); owner.engine[1].resetStatc(); } // Cancel else if(engine.ctrl.isPush(Controller.BUTTON_B)) { engine.statc[4] = 0; } } return true; } /* * 設定画面の描画 */ @Override public void renderSetting(GameEngine engine, int playerID) { if(engine.statc[4] == 0) { if(engine.statc[2] < 9) { if(owner.replayMode == false) { receiver.drawMenuFont(engine, playerID, 0, (engine.statc[2] * 2) + 1, "b", (playerID == 0) ? EventReceiver.COLOR_RED : EventReceiver.COLOR_BLUE); } receiver.drawMenuFont(engine, playerID, 0, 0, "GRAVITY", EventReceiver.COLOR_ORANGE); receiver.drawMenuFont(engine, playerID, 1, 1, String.valueOf(engine.speed.gravity), (engine.statc[2] == 0) && !owner.replayMode); receiver.drawMenuFont(engine, playerID, 0, 2, "G-MAX", EventReceiver.COLOR_ORANGE); receiver.drawMenuFont(engine, playerID, 1, 3, String.valueOf(engine.speed.denominator), (engine.statc[2] == 1)); receiver.drawMenuFont(engine, playerID, 0, 4, "ARE", EventReceiver.COLOR_ORANGE); receiver.drawMenuFont(engine, playerID, 1, 5, String.valueOf(engine.speed.are), (engine.statc[2] == 2)); receiver.drawMenuFont(engine, playerID, 0, 6, "ARE LINE", EventReceiver.COLOR_ORANGE); receiver.drawMenuFont(engine, playerID, 1, 7, String.valueOf(engine.speed.areLine), (engine.statc[2] == 3)); receiver.drawMenuFont(engine, playerID, 0, 8, "LINE DELAY", EventReceiver.COLOR_ORANGE); receiver.drawMenuFont(engine, playerID, 1, 9, String.valueOf(engine.speed.lineDelay), (engine.statc[2] == 4)); receiver.drawMenuFont(engine, playerID, 0, 10, "LOCK DELAY", EventReceiver.COLOR_ORANGE); receiver.drawMenuFont(engine, playerID, 1, 11, String.valueOf(engine.speed.lockDelay), (engine.statc[2] == 5)); receiver.drawMenuFont(engine, playerID, 0, 12, "DAS", EventReceiver.COLOR_ORANGE); receiver.drawMenuFont(engine, playerID, 1, 13, String.valueOf(engine.speed.das), (engine.statc[2] == 6)); receiver.drawMenuFont(engine, playerID, 0, 14, "LOAD", EventReceiver.COLOR_GREEN); receiver.drawMenuFont(engine, playerID, 1, 15, String.valueOf(presetNumber[playerID]), (engine.statc[2] == 7)); receiver.drawMenuFont(engine, playerID, 0, 16, "SAVE", EventReceiver.COLOR_GREEN); receiver.drawMenuFont(engine, playerID, 1, 17, String.valueOf(presetNumber[playerID]), (engine.statc[2] == 8)); receiver.drawMenuFont(engine, playerID, 0, 19, "PAGE 1/3", EventReceiver.COLOR_YELLOW); } else if (engine.statc[2] < 17){ if(owner.replayMode == false) { receiver.drawMenuFont(engine, playerID, 0, ((engine.statc[2] - 9) * 2) + (engine.statc[2] == 16 ? 2 : 1), "b", (playerID == 0) ? EventReceiver.COLOR_RED : EventReceiver.COLOR_BLUE); } receiver.drawMenuFont(engine, playerID, 0, 0, "BGM", EventReceiver.COLOR_PINK); receiver.drawMenuFont(engine, playerID, 1, 1, String.valueOf(bgmno), (engine.statc[2] == 9) && !owner.replayMode); receiver.drawMenuFont(engine, playerID, 0, 2, "USE MAP", EventReceiver.COLOR_CYAN); receiver.drawMenuFont(engine, playerID, 1, 3, GeneralUtil.getONorOFF(useMap[playerID]), (engine.statc[2] == 10)); receiver.drawMenuFont(engine, playerID, 0, 4, "MAP SET", EventReceiver.COLOR_CYAN); receiver.drawMenuFont(engine, playerID, 1, 5, String.valueOf(mapSet[playerID]), (engine.statc[2] == 11)); receiver.drawMenuFont(engine, playerID, 0, 6, "MAP NO.", EventReceiver.COLOR_CYAN); receiver.drawMenuFont(engine, playerID, 1, 7, (mapNumber[playerID] < 0) ? "RANDOM" : mapNumber[playerID]+"/"+(mapMaxNo[playerID]-1), (engine.statc[2] == 12)); receiver.drawMenuFont(engine, playerID, 0, 8, "SE", EventReceiver.COLOR_CYAN); receiver.drawMenuFont(engine, playerID, 1, 9, GeneralUtil.getONorOFF(enableSE[playerID]), (engine.statc[2] == 13)); receiver.drawMenuFont(engine, playerID, 0, 10, "HURRYUP", EventReceiver.COLOR_CYAN); receiver.drawMenuFont(engine, playerID, 1, 11, (hurryupSeconds[playerID] == 0) ? "NONE" : hurryupSeconds[playerID]+"SEC", (engine.statc[2] == 14)); receiver.drawMenuFont(engine, playerID, 0, 12, "COUNTER", EventReceiver.COLOR_CYAN); receiver.drawMenuFont(engine, playerID, 1, 13, String.valueOf(ojamaHard[playerID]), (engine.statc[2] == 15)); receiver.drawMenuFont(engine, playerID, 0, 14, "RAINBOW", EventReceiver.COLOR_CYAN); receiver.drawMenuFont(engine, playerID, 0, 15, "GEM POWER", EventReceiver.COLOR_CYAN); receiver.drawMenuFont(engine, playerID, 1, 16, RAINBOW_POWER_NAMES[diamondPower[playerID]], (engine.statc[2] == 16)); receiver.drawMenuFont(engine, playerID, 0, 19, "PAGE 2/3", EventReceiver.COLOR_YELLOW); } else { if(owner.replayMode == false) { receiver.drawMenuFont(engine, playerID, 0, ((engine.statc[2] - 10) * 2 + 1), "b", (playerID == 0) ? EventReceiver.COLOR_RED : EventReceiver.COLOR_BLUE); } receiver.drawMenuFont(engine, playerID, 0, 0, "ATTACK", EventReceiver.COLOR_CYAN); int multiplier = (int) (100 * DROP_PATTERNS_ATTACK_MULTIPLIERS[dropSet[playerID]][dropMap[playerID]]); if (multiplier >= 100) receiver.drawMenuFont(engine, playerID, 2, 1, multiplier + "%", multiplier == 100 ? EventReceiver.COLOR_YELLOW : EventReceiver.COLOR_GREEN); else receiver.drawMenuFont(engine, playerID, 3, 1, multiplier + "%", EventReceiver.COLOR_RED); receiver.drawMenuFont(engine, playerID, 0, 2, "DEFEND", EventReceiver.COLOR_CYAN); multiplier = (int) (100 * DROP_PATTERNS_DEFEND_MULTIPLIERS[dropSet[playerID]][dropMap[playerID]]); if (multiplier >= 100) receiver.drawMenuFont(engine, playerID, 2, 3, multiplier + "%", multiplier == 100 ? EventReceiver.COLOR_YELLOW : EventReceiver.COLOR_RED); else receiver.drawMenuFont(engine, playerID, 3, 3, multiplier + "%", EventReceiver.COLOR_GREEN); receiver.drawMenuFont(engine, playerID, 0, 14, "DROP SET", EventReceiver.COLOR_CYAN); receiver.drawMenuFont(engine, playerID, 1, 15, DROP_SET_NAMES[dropSet[playerID]], (engine.statc[2] == 17 && !owner.replayMode)); receiver.drawMenuFont(engine, playerID, 0, 16, "DROP MAP", EventReceiver.COLOR_CYAN); String dropMapStr = String.valueOf(DROP_PATTERNS[dropSet[playerID]].length); if (dropMapStr.length() == 1) dropMapStr = "0" + dropMapStr; dropMapStr = String.valueOf(dropMap[playerID]+1) + "/" + dropMapStr; if (dropMapStr.length() == 4) dropMapStr = "0" + dropMapStr; receiver.drawMenuFont(engine, playerID, 1, 17, dropMapStr, (engine.statc[2] == 18)); receiver.drawMenuFont(engine, playerID, 0, 19, "PAGE 3/3", EventReceiver.COLOR_YELLOW); //receiver.drawMenuFont(engine, playerID, 0, 10, "BIG", EventReceiver.COLOR_CYAN); //receiver.drawMenuFont(engine, playerID, 1, 11, GeneralUtil.getONorOFF(big[playerID]), (engine.statc[2] == 18)); } } else { receiver.drawMenuFont(engine, playerID, 3, 10, "WAIT", EventReceiver.COLOR_YELLOW); } } /* * Readyの時のInitialization処理(Initialization前) */ @Override public boolean onReady(GameEngine engine, int playerID) { if(engine.statc[0] == 0) { engine.numColors = BLOCK_COLORS.length; engine.rainbowAnimate = (playerID == 0); engine.blockOutlineType = GameEngine.BLOCK_OUTLINE_CONNECT; dropPattern[playerID] = DROP_PATTERNS[dropSet[playerID]][dropMap[playerID]]; attackMultiplier[playerID] = DROP_PATTERNS_ATTACK_MULTIPLIERS[dropSet[playerID]][dropMap[playerID]]; defendMultiplier[playerID] = DROP_PATTERNS_DEFEND_MULTIPLIERS[dropSet[playerID]][dropMap[playerID]]; // マップ読み込み・リプレイ保存用にバックアップ if(useMap[playerID]) { if(owner.replayMode) { engine.createFieldIfNeeded(); loadMap(engine.field, owner.replayProp, playerID); engine.field.setAllSkin(engine.getSkin()); } else { if(propMap[playerID] == null) { propMap[playerID] = receiver.loadProperties("config/map/spf/" + mapSet[playerID] + ".map"); } if(propMap[playerID] != null) { engine.createFieldIfNeeded(); if(mapNumber[playerID] < 0) { if((playerID == 1) && (useMap[0]) && (mapNumber[0] < 0)) { engine.field.copy(owner.engine[0].field); } else { int no = (mapMaxNo[playerID] < 1) ? 0 : randMap.nextInt(mapMaxNo[playerID]); loadMap(engine.field, propMap[playerID], no); } } else { loadMap(engine.field, propMap[playerID], mapNumber[playerID]); } engine.field.setAllSkin(engine.getSkin()); fldBackup[playerID] = new Field(engine.field); } } } else if(engine.field != null) { engine.field.reset(); } } else if (engine.statc[0] == 1 && diamondPower[playerID] > 0) for (int x = 24; x < engine.nextPieceArraySize; x += 25) engine.nextPieceArrayObject[x].block[1].color = DIAMOND_COLOR; return false; } /* * ゲーム開始時の処理 */ @Override public void startGame(GameEngine engine, int playerID) { engine.b2bEnable = false; engine.comboType = GameEngine.COMBO_TYPE_DISABLE; //engine.big = big[playerID]; engine.enableSE = enableSE[playerID]; if(playerID == 1) owner.bgmStatus.bgm = bgmno; //engine.colorClearSize = big[playerID] ? 8 : 2; engine.colorClearSize = 2; engine.ignoreHidden = false; engine.tspinAllowKick = false; engine.tspinEnable = false; engine.useAllSpinBonus = false; } /* * Render score */ @Override public void renderLast(GameEngine engine, int playerID) { // ステータス表示 if(playerID == 0) { receiver.drawScoreFont(engine, playerID, -1, 0, "SPF VS", EventReceiver.COLOR_GREEN); receiver.drawScoreFont(engine, playerID, -1, 2, "OJAMA", EventReceiver.COLOR_PURPLE); receiver.drawScoreFont(engine, playerID, -1, 3, "1P:", EventReceiver.COLOR_RED); receiver.drawScoreFont(engine, playerID, 3, 3, String.valueOf(ojama[0]), (ojama[0] > 0)); receiver.drawScoreFont(engine, playerID, -1, 4, "2P:", EventReceiver.COLOR_BLUE); receiver.drawScoreFont(engine, playerID, 3, 4, String.valueOf(ojama[1]), (ojama[1] > 0)); receiver.drawScoreFont(engine, playerID, -1, 6, "ATTACK", EventReceiver.COLOR_GREEN); receiver.drawScoreFont(engine, playerID, -1, 7, "1P: " + String.valueOf(ojamaSent[0]), EventReceiver.COLOR_RED); receiver.drawScoreFont(engine, playerID, -1, 8, "2P: " + String.valueOf(ojamaSent[1]), EventReceiver.COLOR_BLUE); receiver.drawScoreFont(engine, playerID, -1, 10, "SCORE", EventReceiver.COLOR_PURPLE); receiver.drawScoreFont(engine, playerID, -1, 11, "1P: " + String.valueOf(score[0]), EventReceiver.COLOR_RED); receiver.drawScoreFont(engine, playerID, -1, 12, "2P: " + String.valueOf(score[1]), EventReceiver.COLOR_BLUE); receiver.drawScoreFont(engine, playerID, -1, 14, "TIME", EventReceiver.COLOR_GREEN); receiver.drawScoreFont(engine, playerID, -1, 15, GeneralUtil.getTime(engine.statistics.time)); } if (!owner.engine[playerID].gameActive) return; if(techBonusDisplay[playerID] > 0) receiver.drawMenuFont(engine, playerID, 0, 20, "TECH BONUS", EventReceiver.COLOR_YELLOW); if(zenKeshiDisplay[playerID] > 0) receiver.drawMenuFont(engine, playerID, 1, 21, "ZENKESHI!", EventReceiver.COLOR_YELLOW); Block b; int blockColor, textColor; if (ojamaHard[playerID] > 0 && engine.field != null) for (int x = 0; x < engine.field.getWidth(); x++) for (int y = 0; y < engine.field.getHeight(); y++) { b = engine.field.getBlock(x, y); if (!b.isEmpty() && b.hard > 0) { blockColor = b.secondaryColor; textColor = EventReceiver.COLOR_WHITE; if (blockColor == Block.BLOCK_COLOR_BLUE) textColor = EventReceiver.COLOR_BLUE; else if (blockColor == Block.BLOCK_COLOR_GREEN) textColor = EventReceiver.COLOR_GREEN; else if (blockColor == Block.BLOCK_COLOR_RED) textColor = EventReceiver.COLOR_RED; else if (blockColor == Block.BLOCK_COLOR_YELLOW) textColor = EventReceiver.COLOR_YELLOW; receiver.drawMenuFont(engine, playerID, x, y, String.valueOf(b.hard), textColor); } } } @Override public boolean onMove (GameEngine engine, int playerID) { hardDecremented[playerID] = false; return false; } @Override public void pieceLocked(GameEngine engine, int playerID, int avalanche) { if (engine.field == null) return; checkAll(engine, playerID); } /* * Calculate score */ @Override public void calcScore(GameEngine engine, int playerID, int avalanche) { if (engine.field == null) return; checkAll(engine, playerID); if (engine.field.canCascade()) return; int enemyID = 0; if(playerID == 0) enemyID = 1; int width = engine.field.getWidth(); int height = engine.field.getHeight(); int hiddenHeight = engine.field.getHiddenHeight(); int diamondBreakColor = Block.BLOCK_COLOR_INVALID; if (diamondPower[playerID] > 0) for (int y = (-1*hiddenHeight); y < height && diamondBreakColor == Block.BLOCK_COLOR_INVALID; y++) for (int x = 0; x < width && diamondBreakColor == Block.BLOCK_COLOR_INVALID; x++) if (engine.field.getBlockColor(x, y) == DIAMOND_COLOR) { receiver.blockBreak(engine, playerID, x, y, engine.field.getBlock(x, y)); engine.field.setBlockColor(x, y, Block.BLOCK_COLOR_NONE); if (y+1 >= height) { techBonusDisplay[playerID] = 120; engine.statistics.score += 10000; score[playerID] += 10000; } else diamondBreakColor = engine.field.getBlockColor(x, y+1, true); } double pts = 0; double add, multiplier; Block b; //Clear blocks from diamond if (diamondBreakColor > Block.BLOCK_COLOR_NONE) { engine.field.allClearColor(diamondBreakColor, true, true); for (int y = (-1*hiddenHeight); y < height; y++) { multiplier = getRowValue(y); for (int x = 0; x < width; x++) if (engine.field.getBlockColor(x, y, true) == diamondBreakColor) { pts += multiplier * 7; receiver.blockBreak(engine, playerID, x, y, engine.field.getBlock(x, y)); engine.field.setBlockColor(x, y, Block.BLOCK_COLOR_NONE); } } } if (diamondPower[playerID] == 1) pts *= 0.5; else if (diamondPower[playerID] == 2) pts *= 0.8; //TODO: Add diamond glitch //Clear blocks //engine.field.gemColorCheck(engine.colorClearSize, true, engine.garbageColorClear, engine.ignoreHidden); for (int y = (-1*hiddenHeight); y < height; y++) { multiplier = getRowValue(y); for (int x = 0; x < width; x++) { b = engine.field.getBlock(x, y); if (b == null) continue; if (!b.getAttribute(Block.BLOCK_ATTRIBUTE_ERASE) || b.isEmpty()) continue; add = multiplier * 7; if (b.bonusValue > 1) add *= b.bonusValue; if (b.getAttribute(Block.BLOCK_ATTRIBUTE_GARBAGE)) { add /= 2.0; b.secondaryColor = 0; b.hard = 0; } receiver.blockBreak(engine, playerID, x, y, b); engine.field.setBlockColor(x, y, Block.BLOCK_COLOR_NONE); pts += add; } } if (engine.chain > 1) pts += (engine.chain-1)*20.0; engine.playSE("combo" + Math.min(engine.chain, 20)); double ojamaNew = (int) (pts*attackMultiplier[playerID]/7.0); if (engine.field.isEmpty()) { engine.playSE("bravo"); zenKeshiDisplay[playerID] = 120; ojamaNew += 12; engine.statistics.score += 1000; score[playerID] += 1000; } lastscore[playerID] = ((int) pts) * 10; scgettime[playerID] = 120; score[playerID] += lastscore[playerID]; if (hurryupSeconds[playerID] > 0 && engine.statistics.time > hurryupSeconds[playerID]) ojamaNew *= 1 << (engine.statistics.time / (hurryupSeconds[playerID] * 60)); if (ojama[playerID] > 0 && ojamaNew > 0.0) { int delta = Math.min(ojama[playerID] << 1, (int) ojamaNew); ojama[playerID] -= delta >> 1; ojamaNew -= delta; } int ojamaSend = (int) (ojamaNew * defendMultiplier[enemyID]); if (ojamaSend > 0) ojama[enemyID] += ojamaSend; } public static double getRowValue(int row) { return ROW_VALUES[Math.min(Math.max(row, 0), ROW_VALUES.length-1)]; } public void checkAll(GameEngine engine, int playerID) { boolean recheck = checkHardDecrement(engine, playerID); if (recheck) log.debug("Converted garbage blocks to regular blocks. Rechecking squares."); checkSquares(engine, playerID, recheck); } public boolean checkHardDecrement (GameEngine engine, int playerID) { if (hardDecremented[playerID]) return false; hardDecremented[playerID] = true; boolean result = false; for (int y = (engine.field.getHiddenHeight() * -1); y < engine.field.getHeight(); y++) for (int x = 0; x < engine.field.getWidth(); x++) { Block b = engine.field.getBlock(x, y); if (b == null) continue; if (b.hard > 1) b.hard--; else if (b.hard == 1) { b.hard = 0; b.setAttribute(Block.BLOCK_ATTRIBUTE_GARBAGE, false); b.color = b.secondaryColor; result = true; } } return result; } public void checkSquares (GameEngine engine, int playerID, boolean forceRecheck) { if (engine.field == null) return; if (engine.statistics.time == lastSquareCheck[playerID] && !forceRecheck) return; lastSquareCheck[playerID] = engine.statistics.time; log.debug("Checking squares."); int width = engine.field.getWidth(); int height = engine.field.getHeight(); int hiddenHeight = engine.field.getHiddenHeight(); int color; Block b; int minX, minY, maxX, maxY; for (int x = 0; x < width; x++) for (int y = (-1*hiddenHeight); y < height; y++) { color = engine.field.getBlockColor(x, y); if (color < Block.BLOCK_COLOR_RED || color > Block.BLOCK_COLOR_PURPLE) continue; minX = x; minY = y; maxX = x; maxY = y; boolean expanded = false; b = engine.field.getBlock(x, y); if (!b.getAttribute(Block.BLOCK_ATTRIBUTE_BROKEN) && b.getAttribute(Block.BLOCK_ATTRIBUTE_CONNECT_RIGHT) && b.getAttribute(Block.BLOCK_ATTRIBUTE_CONNECT_DOWN) && !b.getAttribute(Block.BLOCK_ATTRIBUTE_CONNECT_UP) && !b.getAttribute(Block.BLOCK_ATTRIBUTE_CONNECT_LEFT)) { //Find boundaries of existing gem block maxX++; maxY++; Block test; while (maxX < width) { test = engine.field.getBlock(maxX, y); if (test == null) { maxX--; break; } if (test.color != color) { maxX--; break; } if (!test.getAttribute(Block.BLOCK_ATTRIBUTE_CONNECT_RIGHT)) break; maxX++; } while (maxY < height) { test = engine.field.getBlock(x, maxY); if (test == null) { maxY--; break; } if (test.color != color) { maxY--; break; } if (!test.getAttribute(Block.BLOCK_ATTRIBUTE_CONNECT_DOWN)) break; maxY++; } log.debug("Pre-existing square found: (" + minX + ", " + minY + ") to (" + maxX + ", " + maxY + ")"); } else if (b.getAttribute(Block.BLOCK_ATTRIBUTE_BROKEN) && color == engine.field.getBlockColor(x+1, y) && color == engine.field.getBlockColor(x, y+1) && color == engine.field.getBlockColor(x+1, y+1)) { Block bR = engine.field.getBlock(x+1, y); Block bD = engine.field.getBlock(x, y+1); Block bDR = engine.field.getBlock(x+1, y+1); if ( bR.getAttribute(Block.BLOCK_ATTRIBUTE_BROKEN) && bD.getAttribute(Block.BLOCK_ATTRIBUTE_BROKEN) && bDR.getAttribute(Block.BLOCK_ATTRIBUTE_BROKEN)) { //Form new gem block maxX = x+1; maxY = y+1; b.setAttribute(Block.BLOCK_ATTRIBUTE_BROKEN, false); bR.setAttribute(Block.BLOCK_ATTRIBUTE_BROKEN, false); bD.setAttribute(Block.BLOCK_ATTRIBUTE_BROKEN, false); bDR.setAttribute(Block.BLOCK_ATTRIBUTE_BROKEN, false); expanded = true; } log.debug("New square formed: (" + minX + ", " + minY + ") to (" + maxX + ", " + maxY + ")"); } if (maxX <= minX || maxY <= minY) continue; //No gem block, skip to next block boolean expandHere, done; int testX, testY; Block bTest; log.debug("Testing square for expansion. Coordinates before: (" + minX + ", " + minY + ") to (" + maxX + ", " + maxY + ")"); //Expand up for (testY = minY-1, done = false; testY >= (-1 * hiddenHeight) && !done; testY--) { log.debug("Testing to expand up. testY = " + testY); if (color != engine.field.getBlockColor(minX, testY) || color != engine.field.getBlockColor(maxX, testY)) break; if (engine.field.getBlock(minX, testY).getAttribute(Block.BLOCK_ATTRIBUTE_CONNECT_LEFT) || engine.field.getBlock(maxX, testY).getAttribute(Block.BLOCK_ATTRIBUTE_CONNECT_RIGHT)) break; expandHere = true; for (testX = minX; testX <= maxX && !done; testX++) { if (engine.field.getBlockColor(testX, testY) != color) { done = true; expandHere = false; } else if (engine.field.getBlock(testX, testY).getAttribute(Block.BLOCK_ATTRIBUTE_CONNECT_UP)) expandHere = false; } if (expandHere) { minY = testY; expanded = true; } } //Expand left for (testX = minX-1, done = false; testX >= 0 && !done; testX--) { if (color != engine.field.getBlockColor(testX, minY) || color != engine.field.getBlockColor(testX, maxY)) break; if (engine.field.getBlock(testX, minY).getAttribute(Block.BLOCK_ATTRIBUTE_CONNECT_UP) || engine.field.getBlock(testX, maxY).getAttribute(Block.BLOCK_ATTRIBUTE_CONNECT_DOWN)) break; expandHere = true; for (testY = minY; testY <= maxY && !done; testY++) { if (engine.field.getBlockColor(testX, testY) != color) { done = true; expandHere = false; } else if (engine.field.getBlock(testX, testY).getAttribute(Block.BLOCK_ATTRIBUTE_CONNECT_LEFT)) expandHere = false; } if (expandHere) { minX = testX; expanded = true; } } //Expand right for (testX = maxX+1, done = false; testX < width && !done; testX++) { if (color != engine.field.getBlockColor(testX, minY) || color != engine.field.getBlockColor(testX, maxY)) break; if (engine.field.getBlock(testX, minY).getAttribute(Block.BLOCK_ATTRIBUTE_CONNECT_UP) || engine.field.getBlock(testX, maxY).getAttribute(Block.BLOCK_ATTRIBUTE_CONNECT_DOWN)) break; expandHere = true; for (testY = minY; testY <= maxY && !done; testY++) { if (engine.field.getBlockColor(testX, testY) != color) { done = true; expandHere = false; } else if (engine.field.getBlock(testX, testY).getAttribute(Block.BLOCK_ATTRIBUTE_CONNECT_RIGHT)) expandHere = false; } if (expandHere) { maxX = testX; expanded = true; } } //Expand down for (testY = maxY+1, done = false; testY < height && !done; testY++) { if (color != engine.field.getBlockColor(minX, testY) || color != engine.field.getBlockColor(maxX, testY)) break; if (engine.field.getBlock(minX, testY).getAttribute(Block.BLOCK_ATTRIBUTE_CONNECT_LEFT) || engine.field.getBlock(maxX, testY).getAttribute(Block.BLOCK_ATTRIBUTE_CONNECT_RIGHT)) break; expandHere = true; for (testX = minX; testX <= maxX && !done; testX++) { if (engine.field.getBlockColor(testX, testY) != color) { done = true; expandHere = false; } else if (engine.field.getBlock(testX, testY).getAttribute(Block.BLOCK_ATTRIBUTE_CONNECT_DOWN)) expandHere = false; } if (expandHere) { maxY = testY; expanded = true; } } log.debug("expanded = " + expanded); if (expanded) { log.debug("Expanding square. Coordinates after: (" + minX + ", " + minY + ") to (" + maxX + ", " + maxY + ")"); int size = Math.min(maxX - minX + 1, maxY - minY + 1); for (testX = minX; testX <= maxX; testX++) for (testY = minY; testY <= maxY; testY++) { bTest = engine.field.getBlock(testX, testY); bTest.setAttribute(Block.BLOCK_ATTRIBUTE_BROKEN, false); bTest.setAttribute(Block.BLOCK_ATTRIBUTE_CONNECT_LEFT, testX != minX); bTest.setAttribute(Block.BLOCK_ATTRIBUTE_CONNECT_DOWN, testY != maxY); bTest.setAttribute(Block.BLOCK_ATTRIBUTE_CONNECT_UP, testY != minY); bTest.setAttribute(Block.BLOCK_ATTRIBUTE_CONNECT_RIGHT, testX != maxX); bTest.bonusValue = size; } } } } public boolean lineClearEnd(GameEngine engine, int playerID) { if (engine.field == null) return false; int width = engine.field.getWidth(); int height = engine.field.getHeight(); int hiddenHeight = engine.field.getHiddenHeight(); for (int y = (-1*hiddenHeight); y < height; y++) for (int x = 0; x < width; x++) if (engine.field.getBlockColor(x, y) == DIAMOND_COLOR) { calcScore(engine, playerID, 0); return true; } checkAll(engine, playerID); //Drop garbage if needed. if (ojama[playerID] > 0) { int enemyID = 0; if(playerID == 0) enemyID = 1; int dropRows = Math.min((ojama[playerID] + width - 1) / width, engine.field.getHighestBlockY(3)); if (dropRows <= 0) return false; int drop = Math.min(ojama[playerID], width * dropRows); ojama[playerID] -= drop; //engine.field.garbageDrop(engine, drop, big[playerID], ojamaHard[playerID], 3); engine.field.garbageDrop(engine, drop, false, ojamaHard[playerID], 3); engine.field.setAllSkin(engine.getSkin()); int patternCol = 0; for (int x = 0; x < engine.field.getWidth(); x++) { if (patternCol >= dropPattern[enemyID].length) patternCol = 0; int patternRow = 0; for (int y = dropRows - hiddenHeight; y >= (-1 * hiddenHeight); y--) { Block b = engine.field.getBlock(x, y); if (b.getAttribute(Block.BLOCK_ATTRIBUTE_GARBAGE) && b.secondaryColor == 0) { if (patternRow >= dropPattern[enemyID][patternCol].length) patternRow = 0; b.secondaryColor = dropPattern[enemyID][patternCol][patternRow]; patternRow++; } } patternCol++; } return true; } return false; } /* * Called after every frame */ @Override public void onLast(GameEngine engine, int playerID) { scgettime[playerID]++; if (zenKeshiDisplay[playerID] > 0) zenKeshiDisplay[playerID]--; int width = 1; if (engine.field != null) width = engine.field.getWidth(); int blockHeight = receiver.getBlockGraphicsHeight(engine, playerID); // せり上がりMeter if(ojama[playerID] * blockHeight / width > engine.meterValue) { engine.meterValue++; } else if(ojama[playerID] * blockHeight / width < engine.meterValue) { engine.meterValue--; } if(ojama[playerID] > 30) engine.meterColor = GameEngine.METER_COLOR_RED; else if(ojama[playerID] > 10) engine.meterColor = GameEngine.METER_COLOR_YELLOW; else engine.meterColor = GameEngine.METER_COLOR_GREEN; // 決着 if((playerID == 1) && (owner.engine[0].gameActive)) { if((owner.engine[0].stat == GameEngine.STAT_GAMEOVER) && (owner.engine[1].stat == GameEngine.STAT_GAMEOVER)) { // 引き分け winnerID = -1; owner.engine[0].gameActive = false; owner.engine[1].gameActive = false; owner.bgmStatus.bgm = BGMStatus.BGM_NOTHING; } else if((owner.engine[0].stat != GameEngine.STAT_GAMEOVER) && (owner.engine[1].stat == GameEngine.STAT_GAMEOVER)) { // 1P勝利 winnerID = 0; owner.engine[0].gameActive = false; owner.engine[1].gameActive = false; owner.engine[0].stat = GameEngine.STAT_EXCELLENT; owner.engine[0].resetStatc(); owner.engine[0].statc[1] = 1; owner.bgmStatus.bgm = BGMStatus.BGM_NOTHING; } else if((owner.engine[0].stat == GameEngine.STAT_GAMEOVER) && (owner.engine[1].stat != GameEngine.STAT_GAMEOVER)) { // 2P勝利 winnerID = 1; owner.engine[0].gameActive = false; owner.engine[1].gameActive = false; owner.engine[1].stat = GameEngine.STAT_EXCELLENT; owner.engine[1].resetStatc(); owner.engine[1].statc[1] = 1; owner.bgmStatus.bgm = BGMStatus.BGM_NOTHING; } } } /* * Render results screen */ @Override public void renderResult(GameEngine engine, int playerID) { receiver.drawMenuFont(engine, playerID, 0, 1, "RESULT", EventReceiver.COLOR_ORANGE); if(winnerID == -1) { receiver.drawMenuFont(engine, playerID, 6, 2, "DRAW", EventReceiver.COLOR_GREEN); } else if(winnerID == playerID) { receiver.drawMenuFont(engine, playerID, 6, 2, "WIN!", EventReceiver.COLOR_YELLOW); } else { receiver.drawMenuFont(engine, playerID, 6, 2, "LOSE", EventReceiver.COLOR_WHITE); } receiver.drawMenuFont(engine, playerID, 0, 3, "ATTACK", EventReceiver.COLOR_ORANGE); String strScore = String.format("%10d", ojamaSent[playerID]); receiver.drawMenuFont(engine, playerID, 0, 4, strScore); receiver.drawMenuFont(engine, playerID, 0, 5, "LINE", EventReceiver.COLOR_ORANGE); String strLines = String.format("%10d", engine.statistics.lines); receiver.drawMenuFont(engine, playerID, 0, 6, strLines); receiver.drawMenuFont(engine, playerID, 0, 7, "PIECE", EventReceiver.COLOR_ORANGE); String strPiece = String.format("%10d", engine.statistics.totalPieceLocked); receiver.drawMenuFont(engine, playerID, 0, 8, strPiece); receiver.drawMenuFont(engine, playerID, 0, 9, "ATTACK/MIN", EventReceiver.COLOR_ORANGE); float apm = (float)(ojamaSent[playerID] * 3600) / (float)(engine.statistics.time); String strAPM = String.format("%10g", apm); receiver.drawMenuFont(engine, playerID, 0, 10, strAPM); receiver.drawMenuFont(engine, playerID, 0, 11, "LINE/MIN", EventReceiver.COLOR_ORANGE); String strLPM = String.format("%10g", engine.statistics.lpm); receiver.drawMenuFont(engine, playerID, 0, 12, strLPM); receiver.drawMenuFont(engine, playerID, 0, 13, "PIECE/SEC", EventReceiver.COLOR_ORANGE); String strPPS = String.format("%10g", engine.statistics.pps); receiver.drawMenuFont(engine, playerID, 0, 14, strPPS); receiver.drawMenuFont(engine, playerID, 0, 15, "TIME", EventReceiver.COLOR_ORANGE); String strTime = String.format("%10s", GeneralUtil.getTime(owner.engine[0].statistics.time)); receiver.drawMenuFont(engine, playerID, 0, 16, strTime); } /* * Called when saving replay */ @Override public void saveReplay(GameEngine engine, int playerID, CustomProperties prop) { saveOtherSetting(engine, owner.replayProp); savePreset(engine, owner.replayProp, -1 - playerID); if(useMap[playerID] && (fldBackup[playerID] != null)) { saveMap(fldBackup[playerID], owner.replayProp, playerID); } owner.replayProp.setProperty("spfvs.version", version); } }
Minor indentation fix
src/mu/nu/nullpo/game/subsystem/mode/SPFMode.java
Minor indentation fix
<ide><path>rc/mu/nu/nullpo/game/subsystem/mode/SPFMode.java <ide> } <ide> } <ide> else if (engine.statc[0] == 1 && diamondPower[playerID] > 0) <del> for (int x = 24; x < engine.nextPieceArraySize; x += 25) <del> engine.nextPieceArrayObject[x].block[1].color = DIAMOND_COLOR; <add> for (int x = 24; x < engine.nextPieceArraySize; x += 25) <add> engine.nextPieceArrayObject[x].block[1].color = DIAMOND_COLOR; <ide> return false; <ide> } <ide>
Java
mpl-2.0
462cece166da82c71f32223d2a5dd9591a04fa59
0
Wurst-Imperium/Wurst-MC-1.9,Wurst-Imperium/Wurst-Client-for-MC-1.9.X,Wurst-Imperium/Wurst-Client-for-MC-1.9.X
src/net/wurstclient/features/mods/HighJumpMod.java
/* * Copyright 2014 - 2017 | Wurst-Imperium | All rights reserved. * * This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ package net.wurstclient.features.mods; import net.wurstclient.settings.SliderSetting; import net.wurstclient.settings.SliderSetting.ValueDisplay; @Mod.Info(description = "Makes you jump much higher.", name = "HighJump", tags = "high jump", help = "Mods/HighJump") @Mod.Bypasses(ghostMode = false, latestNCP = false, olderNCP = false, antiCheat = false, mineplex = false) public final class HighJumpMod extends Mod { public final SliderSetting height = new SliderSetting("Height", 6, 1, 100, 1, ValueDisplay.INTEGER); @Override public void initSettings() { settings.add(height); } }
Move HighJumpMod
src/net/wurstclient/features/mods/HighJumpMod.java
Move HighJumpMod
<ide><path>rc/net/wurstclient/features/mods/HighJumpMod.java <del>/* <del> * Copyright 2014 - 2017 | Wurst-Imperium | All rights reserved. <del> * <del> * This Source Code Form is subject to the terms of the Mozilla Public <del> * License, v. 2.0. If a copy of the MPL was not distributed with this <del> * file, You can obtain one at http://mozilla.org/MPL/2.0/. <del> */ <del>package net.wurstclient.features.mods; <del> <del>import net.wurstclient.settings.SliderSetting; <del>import net.wurstclient.settings.SliderSetting.ValueDisplay; <del> <del>@Mod.Info(description = "Makes you jump much higher.", <del> name = "HighJump", <del> tags = "high jump", <del> help = "Mods/HighJump") <del>@Mod.Bypasses(ghostMode = false, <del> latestNCP = false, <del> olderNCP = false, <del> antiCheat = false, <del> mineplex = false) <del>public final class HighJumpMod extends Mod <del>{ <del> public final SliderSetting height = <del> new SliderSetting("Height", 6, 1, 100, 1, ValueDisplay.INTEGER); <del> <del> @Override <del> public void initSettings() <del> { <del> settings.add(height); <del> } <del>}
JavaScript
mit
1b8e847d639d2a4a8905d94c6721a2f497f08f14
0
ktheory/juicer-rails
public/js/app.js
// @depend pkg var myApp = ;
Removed unused public directory
public/js/app.js
Removed unused public directory
<ide><path>ublic/js/app.js <del>// @depend pkg <del>var myApp = ;
Java
mit
d97ec15fdb880d9252bfec0a787ec907e03d3c0a
0
mercari/siberi-android
package com.mercari.siberi; import android.os.Build; import com.mercari.siberi.db.SiberiSQLStorage; import org.json.JSONException; import org.json.JSONObject; import org.junit.After; import org.junit.Before; import org.junit.Test; import org.junit.runner.RunWith; import org.robolectric.RobolectricGradleTestRunner; import org.robolectric.RuntimeEnvironment; import org.robolectric.annotation.Config; import java.lang.reflect.Field; import java.util.concurrent.CountDownLatch; import static junit.framework.Assert.assertFalse; import static org.hamcrest.MatcherAssert.assertThat; import static org.hamcrest.Matchers.is; @RunWith(RobolectricGradleTestRunner.class) @Config(constants = BuildConfig.class, sdk = Build.VERSION_CODES.KITKAT) public class SiberiUnitTest { SiberiSQLStorage siberiStorage; @Before public void setup(){ siberiStorage = new SiberiSQLStorage(RuntimeEnvironment.application); Siberi.setUpCustomStorage(siberiStorage); } @After public void teardown() { resetDB(); } //FIX: test fails when test1SetExperimentContents runs after test3ClearExperimentTest @Test public void test1SetExperimentContents() throws JSONException{ siberiStorage.clear(); JSONObject object = createExperimentData(); Siberi.setExperimentContents(object.optJSONArray("experiment_results")); ExperimentContent result = siberiStorage.select("test_001_change_button_color"); assertThat(result.getTestName(),is("test_001_change_button_color")); } @Test public void test2RunTest() throws InterruptedException, JSONException { siberiStorage.clear(); siberiStorage.insert("test_001_change_button_color", 2, createMetaData()); final CountDownLatch latch = new CountDownLatch(1); final ExperimentContent result = new ExperimentContent("test"); Siberi.runTest("test_001_change_button_color", new Siberi.ExperimentRunner() { @Override public void run(ExperimentContent content) { result.setTestName(content.testName); result.setVariant(content.variant); result.setMetaData(content.metaData); latch.countDown(); } }); latch.await(); assertThat(result.getTestName(),is("test_001_change_button_color")); assertThat(result.getVariant(), is(2)); } @Test public void test3ClearExperimentTest() throws InterruptedException, JSONException { siberiStorage.insert("test_001_change_button_color", 2, createMetaData()); final CountDownLatch latch = new CountDownLatch(1); final ExperimentContent result = new ExperimentContent("test"); Siberi.clearExperimentContent(); Thread.sleep(1000); //wait for clear content task to end Siberi.runTest("test_001_change_button_color", new Siberi.ExperimentRunner() { @Override public void run(ExperimentContent content) { result.setTestName(content.testName); result.setVariant(content.variant); result.setMetaData(content.metaData); latch.countDown(); } }); latch.await(); assertThat(result.getTestName(),is("test_001_change_button_color")); assertFalse(result.containsVariant()); } private void resetDB(){ Field storage; try { storage = Siberi.class.getDeclaredField("sStorage"); storage.setAccessible(true); storage.set(null, null); } catch (Exception e) { throw new RuntimeException("Error! "+ e); } siberiStorage.close(); } private JSONObject createExperimentData() throws JSONException { String str = "{\n" + " \"experiment_results\":[\n" + " {\n" + " \"name\" : \"test_001_change_button_color\",\n" + " \"variant\" : 2,\n" + " \"metadata\" : {\n" + "\n" + " }\n" + " },\n" + " {\n" + " \"name\" : \"test_002_change_text\",\n" + " \"variant\" : 2,\n" + " \"metadata\" : {\n" + " \"text\": \"Share your thought about curry!!\"\n" + " }\n" + " }\n" + " ]\n" + "}"; return new JSONObject(str); } private JSONObject createMetaData() throws JSONException { String str = " {\n" + " \"metadata\" : {\n" + " \"text\": \"Share your thought about curry!!\"\n" + " }\n" + " }\n"; return new JSONObject(str); } }
siberi-library/src/test/java/com/mercari/siberi/SiberiUnitTest.java
package com.mercari.siberi; import android.os.Build; import com.mercari.siberi.db.SiberiSQLStorage; import org.json.JSONException; import org.json.JSONObject; import org.junit.After; import org.junit.Before; import org.junit.Test; import org.junit.runner.RunWith; import org.robolectric.RobolectricGradleTestRunner; import org.robolectric.RuntimeEnvironment; import org.robolectric.annotation.Config; import java.lang.reflect.Field; import java.util.concurrent.CountDownLatch; import static junit.framework.Assert.assertFalse; import static org.hamcrest.MatcherAssert.assertThat; import static org.hamcrest.Matchers.is; @RunWith(RobolectricGradleTestRunner.class) @Config(constants = BuildConfig.class, sdk = Build.VERSION_CODES.KITKAT) public class SiberiUnitTest { SiberiSQLStorage siberiStorage; @Before public void setup(){ siberiStorage = new SiberiSQLStorage(RuntimeEnvironment.application); Siberi.setUpCustomStorage(siberiStorage); } @After public void teardown() { resetDB(); } //FIX: test fails when test1SetExperimentContents runs after test3ClearExperimentTest @Test public void test1SetExperimentContents() throws JSONException{ siberiStorage.clear(); JSONObject object = createExperimentData(); Siberi.setExperimentContents(object.optJSONArray("experiment_results")); ExperimentContent result = siberiStorage.select("test_001_change_button_color"); assertThat(result.getTestName(),is("test_001_change_button_color")); } @Test public void test2RunTest() throws InterruptedException, JSONException { siberiStorage.clear(); siberiStorage.insert("test_001_change_button_color", 2, createMetaData()); final CountDownLatch latch = new CountDownLatch(1); final ExperimentContent result = new ExperimentContent("test"); Siberi.runTest("test_001_change_button_color", new Siberi.ExperimentRunner() { @Override public void run(ExperimentContent content) { result.setTestName(content.testName); result.setVariant(content.variant); result.setMetaData(content.metaData); latch.countDown(); } }); latch.await(); assertThat(result.getTestName(),is("test_001_change_button_color")); assertThat(result.getVariant(), is(2)); } @Test public void test3ClearExperimentTest() throws InterruptedException, JSONException { siberiStorage.insert("test_001_change_button_color", 2, createMetaData()); final CountDownLatch latch = new CountDownLatch(1); final ExperimentContent result = new ExperimentContent("test"); Siberi.clearExperimentContent(); Siberi.runTest("test_001_change_button_color", new Siberi.ExperimentRunner() { @Override public void run(ExperimentContent content) { result.setTestName(content.testName); result.setVariant(content.variant); result.setMetaData(content.metaData); latch.countDown(); } }); latch.await(); assertThat(result.getTestName(),is("test_001_change_button_color")); assertFalse(result.containsVariant()); } private void resetDB(){ Field storage; try { storage = Siberi.class.getDeclaredField("sStorage"); storage.setAccessible(true); storage.set(null, null); } catch (Exception e) { throw new RuntimeException("Error! "+ e); } siberiStorage.close(); } private JSONObject createExperimentData() throws JSONException { String str = "{\n" + " \"experiment_results\":[\n" + " {\n" + " \"name\" : \"test_001_change_button_color\",\n" + " \"variant\" : 2,\n" + " \"metadata\" : {\n" + "\n" + " }\n" + " },\n" + " {\n" + " \"name\" : \"test_002_change_text\",\n" + " \"variant\" : 2,\n" + " \"metadata\" : {\n" + " \"text\": \"Share your thought about curry!!\"\n" + " }\n" + " }\n" + " ]\n" + "}"; return new JSONObject(str); } private JSONObject createMetaData() throws JSONException { String str = " {\n" + " \"metadata\" : {\n" + " \"text\": \"Share your thought about curry!!\"\n" + " }\n" + " }\n"; return new JSONObject(str); } }
Fix test
siberi-library/src/test/java/com/mercari/siberi/SiberiUnitTest.java
Fix test
<ide><path>iberi-library/src/test/java/com/mercari/siberi/SiberiUnitTest.java <ide> public void test3ClearExperimentTest() throws InterruptedException, JSONException { <ide> siberiStorage.insert("test_001_change_button_color", 2, createMetaData()); <ide> final CountDownLatch latch = new CountDownLatch(1); <add> <ide> final ExperimentContent result = new ExperimentContent("test"); <ide> Siberi.clearExperimentContent(); <add> Thread.sleep(1000); //wait for clear content task to end <ide> Siberi.runTest("test_001_change_button_color", new Siberi.ExperimentRunner() { <ide> @Override <ide> public void run(ExperimentContent content) {
Java
apache-2.0
b4e0d827f273ca363878d6238fd1a30ff2091757
0
openbaton/NFVO,openbaton/NFVO
/* * Copyright (c) 2016 Open Baton (http://www.openbaton.org) * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ package org.openbaton.nfvo.core.test; import org.junit.After; import org.junit.Test; import org.junit.runner.RunWith; import org.openbaton.nfvo.main.Application; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.test.context.SpringBootTest; import org.springframework.context.ConfigurableApplicationContext; import org.springframework.test.context.TestExecutionListeners; import org.springframework.test.context.TestPropertySource; import org.springframework.test.context.junit4.SpringRunner; import org.springframework.test.context.support.DependencyInjectionTestExecutionListener; /** Created by lto on 20/04/15. */ @RunWith(SpringRunner.class) @SpringBootTest(classes = {Application.class}) @TestExecutionListeners({DependencyInjectionTestExecutionListener.class}) @TestPropertySource(properties = {"timezone = GMT", "port: 4242"}) public class IntegrationClassSuiteTest { @Autowired ConfigurableApplicationContext context; private Logger log = LoggerFactory.getLogger(this.getClass()); @Test public void method1() { log.info("Here the context"); for (String s : context.getBeanDefinitionNames()) { log.info(s); } } @After public void shutdown() { context.close(); } }
main/src/test/java/org/openbaton/nfvo/core/test/IntegrationClassSuiteTest.java
/* * Copyright (c) 2016 Open Baton (http://www.openbaton.org) * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ package org.openbaton.nfvo.core.test; import org.junit.After; import org.junit.Test; import org.junit.runner.RunWith; import org.openbaton.nfvo.main.Application; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.context.ConfigurableApplicationContext; import org.springframework.test.context.ContextConfiguration; import org.springframework.test.context.TestExecutionListeners; import org.springframework.test.context.TestPropertySource; import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; import org.springframework.test.context.support.DependencyInjectionTestExecutionListener; /** Created by lto on 20/04/15. */ @RunWith(SpringJUnit4ClassRunner.class) @TestExecutionListeners({DependencyInjectionTestExecutionListener.class}) @ContextConfiguration(classes = {Application.class}) @TestPropertySource(properties = {"timezone = GMT", "port: 4242"}) public class IntegrationClassSuiteTest { @Autowired ConfigurableApplicationContext context; private Logger log = LoggerFactory.getLogger(this.getClass()); @Test public void method1() { log.info("Here the context"); for (String s : context.getBeanDefinitionNames()) { log.info(s); } } @After public void shutdown() { context.close(); } }
fix: fix test with correct dependencies
main/src/test/java/org/openbaton/nfvo/core/test/IntegrationClassSuiteTest.java
fix: fix test with correct dependencies
<ide><path>ain/src/test/java/org/openbaton/nfvo/core/test/IntegrationClassSuiteTest.java <ide> import org.slf4j.Logger; <ide> import org.slf4j.LoggerFactory; <ide> import org.springframework.beans.factory.annotation.Autowired; <add>import org.springframework.boot.test.context.SpringBootTest; <ide> import org.springframework.context.ConfigurableApplicationContext; <del>import org.springframework.test.context.ContextConfiguration; <ide> import org.springframework.test.context.TestExecutionListeners; <ide> import org.springframework.test.context.TestPropertySource; <del>import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; <add>import org.springframework.test.context.junit4.SpringRunner; <ide> import org.springframework.test.context.support.DependencyInjectionTestExecutionListener; <ide> <ide> /** Created by lto on 20/04/15. */ <del>@RunWith(SpringJUnit4ClassRunner.class) <add>@RunWith(SpringRunner.class) <add>@SpringBootTest(classes = {Application.class}) <ide> @TestExecutionListeners({DependencyInjectionTestExecutionListener.class}) <del>@ContextConfiguration(classes = {Application.class}) <ide> @TestPropertySource(properties = {"timezone = GMT", "port: 4242"}) <ide> public class IntegrationClassSuiteTest { <ide>
Java
epl-1.0
2df88ffca71ded5c77df877502702ddccd2727c7
0
parzonka/prm4j
/* * Copyright (c) 2012 Mateusz Parzonka, Eric Bodden * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/epl-v10.html * * Contributors: * Mateusz Parzonka - initial API and implementation */ package prm4j.indexing.realtime; import prm4j.api.BaseEvent; import prm4j.api.Event; import prm4j.api.ParametricMonitor; import prm4j.indexing.BaseMonitor; import prm4j.indexing.staticdata.ChainData; import prm4j.indexing.staticdata.EventContext; import prm4j.indexing.staticdata.JoinData; import prm4j.indexing.staticdata.MaxData; import prm4j.indexing.staticdata.MetaNode; import prm4j.spec.Spec; public class DefaultParametricMonitor implements ParametricMonitor { private final BaseMonitor monitorPrototype; private BindingStore bindingStore; private NodeStore nodeStore; private final EventContext eventContext; private long timestamp = 0L; private MetaNode metaTree; private Spec spec; /** * Creates a DefaultParametricMonitor using default {@link BindingStore} and {@link NodeStore} implementations (and * configurations). * * @param metaTree * @param eventContext * @param spec */ public DefaultParametricMonitor(MetaNode metaTree, EventContext eventContext, Spec spec) { this.eventContext = eventContext; this.metaTree = metaTree; this.spec = spec; bindingStore = new DefaultBindingStore(spec.getFullParameterSet()); nodeStore = new DefaultNodeStore(metaTree); monitorPrototype = spec.getInitialMonitor(); } /** * Creates a DefaultParametricMonitor which externally configurable BindingStore and NodeStore. Please note, that a * {@link DefaultParametricMonitor} created this way is currently not resettable. * * @param bindingStore * @param nodeStore * @param monitorPrototype * @param eventContext */ public DefaultParametricMonitor(BindingStore bindingStore, NodeStore nodeStore, BaseMonitor monitorPrototype, EventContext eventContext) { this.bindingStore = bindingStore; this.nodeStore = nodeStore; this.monitorPrototype = monitorPrototype; this.eventContext = eventContext; } @Override public synchronized void processEvent(Event event) { final BaseEvent baseEvent = event.getBaseEvent(); // selects all bindings from 'bindings' which are not null final int[] parameterMask = baseEvent.getParameterMask(); // uncompressed representation of bindings final LowLevelBinding[] bindings = bindingStore.getBindings(event.getBoundObjects()); // node associated to the current bindings. May be NullNode if binding is encountered the first time Node instanceNode = nodeStore.getNode(bindings, parameterMask); // monitor associated with the instance node. May be null if the instance node is a NullNode BaseMonitor instanceMonitor = instanceNode.getMonitor(); // disable all bindings which are if (eventContext.isDisablingEvent(baseEvent)) { // 2 for (int i = 0; i < parameterMask.length; i++) { // 3 bindings[parameterMask[i]].setDisabled(true); // 4 } // 5 } // 6 if (instanceMonitor == null) { // 7 // direct update phase for (MonitorSet monitorSet : instanceNode.getMonitorSets()) { // (30 - 32) new if (monitorSet != null) { monitorSet.processEvent(event); } } findMaxPhase: for (MaxData maxData : eventContext.getMaxData(baseEvent)) { // 8 BaseMonitor maxMonitor = nodeStore.getNode(bindings, maxData.getNodeMask()).getMonitor(); // 9 if (maxMonitor != null) { // 10 for (int i : maxData.getDiffMask()) { // 11 LowLevelBinding b = bindings[i]; if (b.getTimestamp() < timestamp && (b.getTimestamp() > maxMonitor.getCreationTime() || b.isDisabled())) { // 12 continue findMaxPhase; // 13 } } if (instanceNode == NullNode.instance) { instanceNode = nodeStore.getOrCreateNode(bindings, parameterMask); // get real // instance node } // inlined DefineTo from 73 instanceMonitor = maxMonitor.copy(toCompressedBindings(bindings, parameterMask)); // 102-105 instanceMonitor.processEvent(event); // 103 instanceNode.setMonitor(instanceMonitor); // 106 // inlined chain-method for (ChainData chainData : instanceNode.getMetaNode().getChainDataArray()) { // 110 nodeStore.getOrCreateNode(bindings, chainData.getNodeMask()) .getMonitorSet(chainData.getMonitorSetId()).add(instanceMonitor); // 111 } // 107 break findMaxPhase; } } Node node = null; monitorCreation: if (instanceMonitor == null) { if (eventContext.isCreationEvent(baseEvent)) { // 20 for (int i = 0; i < parameterMask.length; i++) { // 21 if (bindings[i].isDisabled()) // 22 break monitorCreation; // 23 } // inlined DefineNew from 93 instanceMonitor = monitorPrototype.copy(toCompressedBindings(bindings, parameterMask), timestamp); // 94 // - // 97 instanceMonitor.processEvent(event); // 95 if (instanceNode == NullNode.instance) { instanceNode = nodeStore.getOrCreateNode(bindings, parameterMask); // get real // instance node } instanceNode.setMonitor(instanceMonitor); // 98 // inlined chain-method for (ChainData chainData : instanceNode.getMetaNode().getChainDataArray()) { // 110 node = nodeStore.getOrCreateNode(bindings, chainData.getNodeMask()); node.getMonitorSet(chainData.getMonitorSetId()).add(instanceMonitor); // 111 } // 99 } } // inlined Join from 42 joinPhase: for (JoinData joinData : eventContext.getJoinData(baseEvent)) { // 43 // if node does not exist there can't be any joinable monitors final Node compatibleNode = nodeStore.getNode(bindings, joinData.getNodeMask()); if (compatibleNode == NullNode.instance) { continue joinPhase; } // if bindings are disabled, the binding will not add to a valid trace long tmax = 0L; // 44 final int[] diffMask = joinData.getDiffMask(); for (int i = 0; i < diffMask.length; i++) { // 45 final LowLevelBinding b = bindings[diffMask[i]]; final long bTimestamp = b.getTimestamp(); if (bTimestamp < timestamp) { // 46 if (b.isDisabled()) { // 47 continue joinPhase; // 48 } else if (tmax < bTimestamp) { // 49 tmax = bTimestamp; // 50 } // 51 } // 52 } // 53 final boolean someBindingsAreKnown = tmax < timestamp; // calculate once the bindings to be joined with the whole monitor set final LowLevelBinding[] joinableBindings = createJoinableBindings(bindings, joinData.getExtensionPattern()); // 56 - 61 // join is performed in monitor set compatibleNode.getMonitorSet(joinData.getMonitorSetId()).join(nodeStore, event, joinableBindings, someBindingsAreKnown, tmax, joinData.getCopyPattern()); } } else { // update phase instanceMonitor.processEvent(event); // 30 for (MonitorSet monitorSet : instanceNode.getMonitorSets()) { // 30 - 32 if (monitorSet != null) { monitorSet.processEvent(event); } } } for (int i = 0; i < parameterMask.length; i++) { // 37 bindings[parameterMask[i]].setTimestamp(timestamp); } timestamp++; // 40 } private static LowLevelBinding[] toCompressedBindings(LowLevelBinding[] uncompressedBindings, int[] parameterMask) { LowLevelBinding[] result = new LowLevelBinding[parameterMask.length]; int j = 0; for (int i = 0; i < parameterMask.length; i++) { result[j++] = uncompressedBindings[parameterMask[i]]; } return result; } /** * Returns an array of bindings containing "gaps" enabling efficient joins by filling these gaps. * * @param bindings * @param extensionPattern * allows transformation of the bindings to joinable bindings * @return joinable bindings */ static LowLevelBinding[] createJoinableBindings(LowLevelBinding[] bindings, int[] extensionPattern) { final LowLevelBinding[] joinableBindings = new LowLevelBinding[extensionPattern.length]; for (int i = 0; i < extensionPattern.length; i++) { final int e = extensionPattern[i]; if (e >= 0) { joinableBindings[i] = bindings[e]; } } return joinableBindings; } @Override public void reset() { if (metaTree == null || spec == null) { throw new UnsupportedOperationException( "ParametricMonitor can not be resetted when created from externally configured components."); } timestamp = 0L; bindingStore = new DefaultBindingStore(spec.getFullParameterSet()); nodeStore = new DefaultNodeStore(metaTree); } }
src/main/java/prm4j/indexing/realtime/DefaultParametricMonitor.java
/* * Copyright (c) 2012 Mateusz Parzonka, Eric Bodden * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/epl-v10.html * * Contributors: * Mateusz Parzonka - initial API and implementation */ package prm4j.indexing.realtime; import prm4j.api.BaseEvent; import prm4j.api.Event; import prm4j.api.ParametricMonitor; import prm4j.indexing.BaseMonitor; import prm4j.indexing.staticdata.ChainData; import prm4j.indexing.staticdata.EventContext; import prm4j.indexing.staticdata.JoinData; import prm4j.indexing.staticdata.MaxData; import prm4j.indexing.staticdata.MetaNode; import prm4j.spec.Spec; public class DefaultParametricMonitor implements ParametricMonitor { private final BaseMonitor monitorPrototype; private final BindingStore bindingStore; private final NodeStore nodeStore; private final EventContext eventContext; private long timestamp = 0L; /** * Creates a DefaultParametricMonitor using default {@link BindingStore} and {@link NodeStore} implementations (and * configurations). * * @param metaTree * @param eventContext * @param spec */ public DefaultParametricMonitor(MetaNode metaTree, EventContext eventContext, Spec spec) { this.eventContext = eventContext; bindingStore = new DefaultBindingStore(spec.getFullParameterSet()); nodeStore = new DefaultNodeStore(metaTree); monitorPrototype = spec.getInitialMonitor(); } /** * Creates a DefaultParametricMonitor which externally configurable BindingStore and NodeStore. * * @param bindingStore * @param nodeStore * @param monitorPrototype * @param eventContext */ public DefaultParametricMonitor(BindingStore bindingStore, NodeStore nodeStore, BaseMonitor monitorPrototype, EventContext eventContext) { this.bindingStore = bindingStore; this.nodeStore = nodeStore; this.monitorPrototype = monitorPrototype; this.eventContext = eventContext; } @Override public synchronized void processEvent(Event event) { final BaseEvent baseEvent = event.getBaseEvent(); // selects all bindings from 'bindings' which are not null final int[] parameterMask = baseEvent.getParameterMask(); // uncompressed representation of bindings final LowLevelBinding[] bindings = bindingStore.getBindings(event.getBoundObjects()); // node associated to the current bindings. May be NullNode if binding is encountered the first time Node instanceNode = nodeStore.getNode(bindings, parameterMask); // monitor associated with the instance node. May be null if the instance node is a NullNode BaseMonitor instanceMonitor = instanceNode.getMonitor(); // disable all bindings which are if (eventContext.isDisablingEvent(baseEvent)) { // 2 for (int i = 0; i < parameterMask.length; i++) { // 3 bindings[parameterMask[i]].setDisabled(true); // 4 } // 5 } // 6 if (instanceMonitor == null) { // 7 // direct update phase for (MonitorSet monitorSet : instanceNode.getMonitorSets()) { // (30 - 32) new if (monitorSet != null) { monitorSet.processEvent(event); } } findMaxPhase: for (MaxData maxData : eventContext.getMaxData(baseEvent)) { // 8 BaseMonitor maxMonitor = nodeStore.getNode(bindings, maxData.getNodeMask()).getMonitor(); // 9 if (maxMonitor != null) { // 10 for (int i : maxData.getDiffMask()) { // 11 LowLevelBinding b = bindings[i]; if (b.getTimestamp() < timestamp && (b.getTimestamp() > maxMonitor.getCreationTime() || b.isDisabled())) { // 12 continue findMaxPhase; // 13 } } if (instanceNode == NullNode.instance) { instanceNode = nodeStore.getOrCreateNode(bindings, parameterMask); // get real // instance node } // inlined DefineTo from 73 instanceMonitor = maxMonitor.copy(toCompressedBindings(bindings, parameterMask)); // 102-105 instanceMonitor.processEvent(event); // 103 instanceNode.setMonitor(instanceMonitor); // 106 // inlined chain-method for (ChainData chainData : instanceNode.getMetaNode().getChainDataArray()) { // 110 nodeStore.getOrCreateNode(bindings, chainData.getNodeMask()) .getMonitorSet(chainData.getMonitorSetId()).add(instanceMonitor); // 111 } // 107 break findMaxPhase; } } Node node = null; monitorCreation: if (instanceMonitor == null) { if (eventContext.isCreationEvent(baseEvent)) { // 20 for (int i = 0; i < parameterMask.length; i++) { // 21 if (bindings[i].isDisabled()) // 22 break monitorCreation; // 23 } // inlined DefineNew from 93 instanceMonitor = monitorPrototype.copy(toCompressedBindings(bindings, parameterMask), timestamp); // 94 - 97 instanceMonitor.processEvent(event); // 95 if (instanceNode == NullNode.instance) { instanceNode = nodeStore.getOrCreateNode(bindings, parameterMask); // get real // instance node } instanceNode.setMonitor(instanceMonitor); // 98 // inlined chain-method for (ChainData chainData : instanceNode.getMetaNode().getChainDataArray()) { // 110 node = nodeStore.getOrCreateNode(bindings, chainData.getNodeMask()); node.getMonitorSet(chainData.getMonitorSetId()).add(instanceMonitor); // 111 } // 99 } } // inlined Join from 42 joinPhase: for (JoinData joinData : eventContext.getJoinData(baseEvent)) { // 43 // if node does not exist there can't be any joinable monitors final Node compatibleNode = nodeStore.getNode(bindings, joinData.getNodeMask()); if (compatibleNode == NullNode.instance) { continue joinPhase; } // if bindings are disabled, the binding will not add to a valid trace long tmax = 0L; // 44 final int[] diffMask = joinData.getDiffMask(); for (int i = 0; i < diffMask.length; i++) { // 45 final LowLevelBinding b = bindings[diffMask[i]]; final long bTimestamp = b.getTimestamp(); if (bTimestamp < timestamp) { // 46 if (b.isDisabled()) { // 47 continue joinPhase; // 48 } else if (tmax < bTimestamp) { // 49 tmax = bTimestamp; // 50 } // 51 } // 52 } // 53 final boolean someBindingsAreKnown = tmax < timestamp; // calculate once the bindings to be joined with the whole monitor set final LowLevelBinding[] joinableBindings = createJoinableBindings(bindings, joinData.getExtensionPattern()); // 56 - 61 // join is performed in monitor set compatibleNode.getMonitorSet(joinData.getMonitorSetId()).join(nodeStore, event, joinableBindings, someBindingsAreKnown, tmax, joinData.getCopyPattern()); } } else { // update phase instanceMonitor.processEvent(event); // 30 for (MonitorSet monitorSet : instanceNode.getMonitorSets()) { // 30 - 32 if (monitorSet != null) { monitorSet.processEvent(event); } } } for (int i = 0; i < parameterMask.length; i++) { // 37 bindings[parameterMask[i]].setTimestamp(timestamp); } timestamp++; // 40 } private static LowLevelBinding[] toCompressedBindings(LowLevelBinding[] uncompressedBindings, int[] parameterMask) { LowLevelBinding[] result = new LowLevelBinding[parameterMask.length]; int j = 0; for (int i = 0; i < parameterMask.length; i++) { result[j++] = uncompressedBindings[parameterMask[i]]; } return result; } /** * Returns an array of bindings containing "gaps" enabling efficient joins by filling these gaps. * * @param bindings * @param extensionPattern * allows transformation of the bindings to joinable bindings * @return joinable bindings */ static LowLevelBinding[] createJoinableBindings(LowLevelBinding[] bindings, int[] extensionPattern) { final LowLevelBinding[] joinableBindings = new LowLevelBinding[extensionPattern.length]; for (int i = 0; i < extensionPattern.length; i++) { final int e = extensionPattern[i]; if (e >= 0) { joinableBindings[i] = bindings[e]; } } return joinableBindings; } @Override public void reset() { // TODO Auto-generated method stub } }
Let DefaultParametricMonitor be resettable
src/main/java/prm4j/indexing/realtime/DefaultParametricMonitor.java
Let DefaultParametricMonitor be resettable
<ide><path>rc/main/java/prm4j/indexing/realtime/DefaultParametricMonitor.java <ide> public class DefaultParametricMonitor implements ParametricMonitor { <ide> <ide> private final BaseMonitor monitorPrototype; <del> private final BindingStore bindingStore; <del> private final NodeStore nodeStore; <add> private BindingStore bindingStore; <add> private NodeStore nodeStore; <ide> private final EventContext eventContext; <ide> private long timestamp = 0L; <add> private MetaNode metaTree; <add> private Spec spec; <ide> <ide> /** <ide> * Creates a DefaultParametricMonitor using default {@link BindingStore} and {@link NodeStore} implementations (and <ide> */ <ide> public DefaultParametricMonitor(MetaNode metaTree, EventContext eventContext, Spec spec) { <ide> this.eventContext = eventContext; <add> this.metaTree = metaTree; <add> this.spec = spec; <ide> bindingStore = new DefaultBindingStore(spec.getFullParameterSet()); <ide> nodeStore = new DefaultNodeStore(metaTree); <ide> monitorPrototype = spec.getInitialMonitor(); <ide> } <ide> <ide> /** <del> * Creates a DefaultParametricMonitor which externally configurable BindingStore and NodeStore. <add> * Creates a DefaultParametricMonitor which externally configurable BindingStore and NodeStore. Please note, that a <add> * {@link DefaultParametricMonitor} created this way is currently not resettable. <ide> * <ide> * @param bindingStore <ide> * @param nodeStore <ide> } <ide> if (instanceNode == NullNode.instance) { <ide> instanceNode = nodeStore.getOrCreateNode(bindings, parameterMask); // get real <del> // instance node <add> // instance node <ide> } <ide> // inlined DefineTo from 73 <ide> instanceMonitor = maxMonitor.copy(toCompressedBindings(bindings, parameterMask)); // 102-105 <ide> } <ide> <ide> // inlined DefineNew from 93 <del> instanceMonitor = monitorPrototype.copy(toCompressedBindings(bindings, parameterMask), <del> timestamp); // 94 - 97 <add> instanceMonitor = monitorPrototype.copy(toCompressedBindings(bindings, parameterMask), timestamp); // 94 <add> // - <add> // 97 <ide> instanceMonitor.processEvent(event); // 95 <ide> if (instanceNode == NullNode.instance) { <ide> instanceNode = nodeStore.getOrCreateNode(bindings, parameterMask); // get real <del> // instance node <add> // instance node <ide> } <ide> instanceNode.setMonitor(instanceMonitor); // 98 <ide> // inlined chain-method <ide> <ide> @Override <ide> public void reset() { <del> // TODO Auto-generated method stub <add> if (metaTree == null || spec == null) { <add> throw new UnsupportedOperationException( <add> "ParametricMonitor can not be resetted when created from externally configured components."); <add> } <add> timestamp = 0L; <add> bindingStore = new DefaultBindingStore(spec.getFullParameterSet()); <add> nodeStore = new DefaultNodeStore(metaTree); <ide> } <ide> <ide> }
JavaScript
mit
960093c40919e99edc0ea7770b0bb3c66046f7f3
0
juanmougan/reduxForecastApp,juanmougan/reduxForecastApp
import { combineReducers } from 'redux'; import WeatherReducer from './reducer_weather'; const rootReducer = combineReducers({ weather: WeatherReducer }); export default rootReducer;
src/reducers/index.js
import { combineReducers } from 'redux'; const rootReducer = combineReducers({ weather: WeatherReducer }); export default rootReducer;
Somewhere in between 59 and 60
src/reducers/index.js
Somewhere in between 59 and 60
<ide><path>rc/reducers/index.js <ide> import { combineReducers } from 'redux'; <add>import WeatherReducer from './reducer_weather'; <ide> <ide> const rootReducer = combineReducers({ <ide> weather: WeatherReducer
Java
apache-2.0
60bc2486a6bb7fa3a7ee4ea8079b7627e641a74c
0
tpalsulich/NYU-BusTracker-Android,SaikiranGoud/Rockingandroidworld
package com.nyubustracker.activities; import android.app.Activity; import android.app.AlertDialog; import android.app.Dialog; import android.app.ProgressDialog; import android.content.Context; import android.content.DialogInterface; import android.content.Intent; import android.content.SharedPreferences; import android.graphics.Bitmap; import android.graphics.BitmapFactory; import android.graphics.Matrix; import android.graphics.drawable.ColorDrawable; import android.location.Location; import android.location.LocationManager; import android.net.ConnectivityManager; import android.net.NetworkInfo; import android.net.Uri; import android.os.Bundle; import android.os.Handler; import android.os.Looper; import android.text.TextUtils; import android.util.Log; import android.util.TypedValue; import android.view.Gravity; import android.view.View; import android.view.ViewGroup; import android.view.animation.Animation; import android.view.animation.AnimationUtils; import android.widget.CompoundButton; import android.widget.LinearLayout; import android.widget.ListView; import android.widget.TextSwitcher; import android.widget.TextView; import android.widget.Toast; import android.widget.ViewSwitcher; import com.flurry.android.FlurryAgent; import com.google.android.gms.analytics.GoogleAnalytics; import com.google.android.gms.common.ConnectionResult; import com.google.android.gms.common.GooglePlayServicesUtil; import com.google.android.gms.maps.CameraUpdate; import com.google.android.gms.maps.CameraUpdateFactory; import com.google.android.gms.maps.GoogleMap; import com.google.android.gms.maps.MapFragment; import com.google.android.gms.maps.model.BitmapDescriptorFactory; import com.google.android.gms.maps.model.LatLng; import com.google.android.gms.maps.model.LatLngBounds; import com.google.android.gms.maps.model.Marker; import com.google.android.gms.maps.model.MarkerOptions; import com.google.android.gms.maps.model.PolylineOptions; import com.nyubustracker.NYUBusTrackerApplication; import com.nyubustracker.R; import com.nyubustracker.adapters.StopAdapter; import com.nyubustracker.adapters.TimeAdapter; import com.nyubustracker.helpers.BusDownloaderHelper; import com.nyubustracker.helpers.BusManager; import com.nyubustracker.helpers.Downloader; import com.nyubustracker.helpers.DownloaderHelper; import com.nyubustracker.helpers.MultipleOrientationSlidingDrawer; import com.nyubustracker.helpers.RouteDownloaderHelper; import com.nyubustracker.helpers.SegmentDownloaderHelper; import com.nyubustracker.helpers.StopDownloaderHelper; import com.nyubustracker.helpers.TimeDownloaderHelper; import com.nyubustracker.helpers.VersionDownloaderHelper; import com.nyubustracker.models.Bus; import com.nyubustracker.models.Route; import com.nyubustracker.models.Stop; import com.nyubustracker.models.Time; import org.json.JSONException; import org.json.JSONObject; import java.io.BufferedReader; import java.io.File; import java.io.FileInputStream; import java.io.IOException; import java.io.InputStreamReader; import java.util.ArrayList; import java.util.Calendar; import java.util.Collections; import java.util.HashMap; import java.util.List; import java.util.Timer; import java.util.TimerTask; import se.emilsjolander.stickylistheaders.StickyListHeadersListView; public class MainActivity extends Activity { public static final boolean LOCAL_LOGV = true; private static final String RUN_ONCE_PREF = "runOnce"; private static final String STOP_PREF = "stops"; private static final String START_STOP_PREF = "startStop"; private static final String END_STOP_PREF = "endStop"; private static final String FIRST_TIME = "firstTime"; public static final String REFACTOR_LOG_TAG = "refactor"; public static final String LOG_TAG = "nyu_log_tag"; private final CompoundButton.OnCheckedChangeListener cbListener = new CompoundButton.OnCheckedChangeListener() { @Override public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) { Stop s = (Stop) buttonView.getTag(); s.setFavorite(isChecked); getSharedPreferences(Stop.FAVORITES_PREF, MODE_PRIVATE).edit().putBoolean(s.getID(), isChecked).commit(); } }; static ProgressDialog progressDialog; private static SharedPreferences oncePreferences; double onStartTime; private Stop startStop; // Stop object to keep track of the start location of the desired route. private Stop endStop; // Keep track of the desired end location. private HashMap<String, Boolean> clickableMapMarkers; // Hash of all markers which are clickable (so we don't zoom in on buses). private ArrayList<Marker> busesOnMap = new ArrayList<Marker>(); private TextSwitcher mSwitcher; private String mSwitcherCurrentText; private TimeAdapter timesAdapter; private StickyListHeadersListView timesList; private Timer timeUntilTimer; // Timer used to refresh the "time until next bus" every minute, on the minute. private Timer busRefreshTimer; // Timer used to refresh the bus locations every few seconds. private GoogleMap mMap; // Map to display all stops, segments, and buses. private boolean offline = true; private MultipleOrientationSlidingDrawer drawer; public static int downloadsOnTheWire = 0; public static Handler UIHandler; static { UIHandler = new Handler(Looper.getMainLooper()); } public static void runOnUI(Runnable runnable) { UIHandler.post(runnable); } private static Bitmap rotateBitmap(Bitmap source, float angle) { Matrix matrix = new Matrix(); matrix.postRotate(angle); return Bitmap.createBitmap(source, 0, 0, source.getWidth(), source.getHeight(), matrix, true); } private void setUpMapIfNeeded() { // First check if GPS is available. final LatLng BROADWAY = new LatLng(40.729146, -73.993756); int retCode = GooglePlayServicesUtil.isGooglePlayServicesAvailable(getApplicationContext()); if (retCode != ConnectionResult.SUCCESS) { GooglePlayServicesUtil.getErrorDialog(retCode, this, 1).show(); } // Do a null check to confirm that we have not already instantiated the map. if (mMap == null) { MapFragment mFrag = ((MapFragment) getFragmentManager().findFragmentById(R.id.map)); if (mFrag != null) mMap = mFrag.getMap(); // Check if we were successful in obtaining the map. if (mMap != null) { // The Map is verified. It is now safe to manipulate the map. mMap.getUiSettings().setRotateGesturesEnabled(false); mMap.getUiSettings().setZoomControlsEnabled(false); mMap.setMyLocationEnabled(true); mMap.setOnMarkerClickListener(new GoogleMap.OnMarkerClickListener() { @Override public boolean onMarkerClick(Marker marker) { return !clickableMapMarkers.get(marker.getId()); // Return true to consume the event. } }); CameraUpdate center= CameraUpdateFactory.newLatLng(BROADWAY); CameraUpdate zoom=CameraUpdateFactory.zoomTo(15); mMap.moveCamera(center); mMap.animateCamera(zoom); } } } String readSavedData(String fileName) throws JSONException { if (LOCAL_LOGV) Log.v(REFACTOR_LOG_TAG, "Reading saved data from " + fileName); StringBuilder buffer = new StringBuilder(""); try { File path = new File(getFilesDir(), Downloader.CREATED_FILES_DIR); path.mkdir(); File file = new File(path, fileName); FileInputStream inputStream = new FileInputStream(file); InputStreamReader streamReader = new InputStreamReader(inputStream); BufferedReader bufferedReader = new BufferedReader(streamReader); String readString = bufferedReader.readLine(); while (readString != null) { buffer.append(readString); readString = bufferedReader.readLine(); } inputStream.close(); } catch (IOException e) { if (LOCAL_LOGV) Log.v(REFACTOR_LOG_TAG, "Failed to read " + fileName + "..."); throw new JSONException("Failed to read " + fileName); } return buffer.toString(); } private void downloadEverything(boolean block) { deleteEverythingInMemory(); ConnectivityManager connMgr = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE); NetworkInfo networkInfo = connMgr.getActiveNetworkInfo(); if (networkInfo != null && networkInfo.isConnected()) { offline = false; // Download and parse everything, put it all in persistent memory, continue. if (block) progressDialog = ProgressDialog.show(this, getString(R.string.downloading), getString(R.string.wait), true, false); else progressDialog = null; Context context = getApplicationContext(); downloadsOnTheWire += 4; new Downloader(new StopDownloaderHelper(), context).execute(DownloaderHelper.STOPS_URL); new Downloader(new RouteDownloaderHelper(), context).execute(DownloaderHelper.ROUTES_URL); new Downloader(new SegmentDownloaderHelper(), context).execute(DownloaderHelper.SEGMENTS_URL); new Downloader(new VersionDownloaderHelper(), context).execute(DownloaderHelper.VERSION_URL); } else if (!offline) { // Only show the offline dialog once. offline = true; Context context = getApplicationContext(); CharSequence text = getString(R.string.unable_to_connect); int duration = Toast.LENGTH_SHORT; if (context != null) { Toast.makeText(context, text, duration).show(); } } } public static void pieceDownloadsTogether(final Context context) { downloadsOnTheWire--; if (LOCAL_LOGV) Log.v(REFACTOR_LOG_TAG, "Downloads on the wire: " + downloadsOnTheWire); if (downloadsOnTheWire <= 0) { if (LOCAL_LOGV) Log.v(REFACTOR_LOG_TAG, "Downloading finished!"); oncePreferences.edit().putBoolean(FIRST_TIME, false).apply(); if (progressDialog != null) { runOnUI(new Runnable() { @Override public void run() { Stop broadway = BusManager.getBusManager().getStopByName("715 Broadway"); if (broadway != null) { context.getSharedPreferences(Stop.FAVORITES_PREF, MODE_PRIVATE).edit().putBoolean(broadway.getID(), true).apply(); broadway.setFavorite(true); } progressDialog.dismiss(); } }); } } // Else, we have nothing to do, since not all downloads are finished. } @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); if (LOCAL_LOGV) Log.v(REFACTOR_LOG_TAG, "onCreate!"); setContentView(R.layout.activity_main); ((NYUBusTrackerApplication) getApplication()).getTracker(); oncePreferences = getSharedPreferences(RUN_ONCE_PREF, MODE_PRIVATE); setUpMapIfNeeded(); // Instantiates mMap, if it needs to be. // Singleton BusManager to keep track of all stops, routes, etc. final BusManager sharedManager = BusManager.getBusManager(); mSwitcher = (TextSwitcher) findViewById(R.id.next_time); mSwitcherCurrentText = ""; // Set the ViewFactory of the TextSwitcher that will create TextView object when asked mSwitcher.setFactory(new ViewSwitcher.ViewFactory() { public View makeView() { TextView myText = new TextView(MainActivity.this); myText.setTextSize(TypedValue.COMPLEX_UNIT_PX, getResources().getDimensionPixelSize(R.dimen.time_until_text_size)); myText.setTextColor(getResources().getColor(R.color.main_text)); myText.setGravity(Gravity.CENTER_VERTICAL | Gravity.LEFT); myText.setEllipsize(TextUtils.TruncateAt.END); myText.setSingleLine(true); return myText; } }); // Declare the in and out animations and initialize them Animation in = AnimationUtils.loadAnimation(MainActivity.this, android.R.anim.slide_in_left); Animation out = AnimationUtils.loadAnimation(MainActivity.this, android.R.anim.slide_out_right); // set the animation type of textSwitcher mSwitcher.setInAnimation(in); mSwitcher.setOutAnimation(out); drawer = (MultipleOrientationSlidingDrawer) findViewById(R.id.sliding_drawer); drawer.setAllowSingleTap(false); drawer.lock(); timesList = (StickyListHeadersListView) findViewById(R.id.times_list); timesAdapter = new TimeAdapter(getApplicationContext(), new ArrayList<Time>()); timesList.setAdapter(timesAdapter); if (oncePreferences.getBoolean(FIRST_TIME, true)) { if (LOCAL_LOGV) Log.v(REFACTOR_LOG_TAG, "Downloading because of first time"); downloadEverything(true); } else { if (!sharedManager.hasRoutes() || !sharedManager.hasStops()) { if (LOCAL_LOGV) Log.v(REFACTOR_LOG_TAG, "Parsing cached files..."); try { JSONObject stopJson = new JSONObject(readSavedData(StopDownloaderHelper.STOP_JSON_FILE)); JSONObject routeJson = new JSONObject(readSavedData(RouteDownloaderHelper.ROUTE_JSON_FILE)); JSONObject segJson = new JSONObject(readSavedData(SegmentDownloaderHelper.SEGMENT_JSON_FILE)); JSONObject verJson = new JSONObject(readSavedData(VersionDownloaderHelper.VERSION_JSON_FILE)); Stop.parseJSON(stopJson); Route.parseJSON(routeJson); BusManager.parseSegments(segJson); BusManager.parseVersion(verJson); Context context = getApplicationContext(); for (String timeURL : sharedManager.getTimesToDownload()) { String timeFileName = timeURL.substring(timeURL.lastIndexOf("/") + 1, timeURL.indexOf(".json")); if (LOCAL_LOGV) Log.v(REFACTOR_LOG_TAG, "Trying to parse " + timeFileName); try { BusManager.parseTime(new JSONObject(readSavedData(timeFileName))); } catch (JSONException e) { if (LOCAL_LOGV) Log.v(REFACTOR_LOG_TAG, "Didn't find time file, so downloading it: " + timeURL); new Downloader(new TimeDownloaderHelper(), context).execute(timeURL); } } SharedPreferences favoritePreferences = getSharedPreferences(Stop.FAVORITES_PREF, MODE_PRIVATE); if (LOCAL_LOGV) Log.v(REFACTOR_LOG_TAG, "Done parsing..."); for (Stop s : sharedManager.getStops()) { boolean result = favoritePreferences.getBoolean(s.getID(), false); s.setFavorite(result); } new Downloader(new VersionDownloaderHelper(), context).execute(DownloaderHelper.VERSION_URL); setStartAndEndStops(); // Update the map to show the corresponding stops, buses, and segments. updateMapWithNewStartOrEnd(); // Get the location of the buses every 10 sec. renewBusRefreshTimer(); renewTimeUntilTimer(); setNextBusTime(); } catch (JSONException e) { if (LOCAL_LOGV) Log.v(REFACTOR_LOG_TAG, "Re-downloading because of an error."); e.printStackTrace(); downloadEverything(true); } } else { setStartAndEndStops(); updateMapWithNewStartOrEnd(); } } } @Override public void onStart() { super.onStart(); // if (LOCAL_LOGV) Log.v("General Debugging", "onStart!"); onStartTime = System.currentTimeMillis(); GoogleAnalytics.getInstance(this).reportActivityStart(this); FlurryAgent.onStartSession(this, getString(LOCAL_LOGV ? R.string.flurry_debug_api_key : R.string.flurry_api_key)); } @Override public void onResume() { super.onResume(); if (LOCAL_LOGV) Log.v(REFACTOR_LOG_TAG, "onResume!"); if (endStop != null && startStop != null) { renewTimeUntilTimer(); renewBusRefreshTimer(); setUpMapIfNeeded(); setStartAndEndStops(); } } @Override public void onPause() { super.onPause(); if (LOCAL_LOGV) Log.v(REFACTOR_LOG_TAG, "onPause!"); cacheStartAndEndStops(); if (timeUntilTimer != null) timeUntilTimer.cancel(); if (busRefreshTimer != null) busRefreshTimer.cancel(); } @Override public void onStop() { super.onStop(); // if (LOCAL_LOGV) Log.v("General Debugging", "onStop!"); GoogleAnalytics.getInstance(this).reportActivityStop(this); FlurryAgent.onEndSession(this); } @Override public void onDestroy() { super.onDestroy(); if (LOCAL_LOGV) Log.v(REFACTOR_LOG_TAG, "onDestroy!"); cacheStartAndEndStops(); // Remember user's preferences across lifetimes. if (timeUntilTimer != null) timeUntilTimer.cancel(); // Don't need a timer anymore -- must be recreated onResume. if (busRefreshTimer != null) busRefreshTimer.cancel(); } @Override public void onBackPressed() { if (drawer.isOpened()) drawer.animateClose(); else super.onBackPressed(); } void cacheStartAndEndStops() { if (endStop != null) getSharedPreferences(STOP_PREF, MODE_PRIVATE).edit().putString(END_STOP_PREF, endStop.getName()).apply(); // Creates or updates cache file. if (startStop != null) getSharedPreferences(STOP_PREF, MODE_PRIVATE).edit().putString(START_STOP_PREF, startStop.getName()).apply(); } void sayBusIsOffline() { updateNextTimeSwitcher(getString(R.string.offline)); ((TextView) findViewById(R.id.next_bus)).setText(""); ((TextView) findViewById(R.id.next_route)).setText(""); } /* renewTimeUntilTimer() creates a new timer that calls setNextBusTime() every minute on the minute. */ private void renewTimeUntilTimer() { Calendar rightNow = Calendar.getInstance(); if (timeUntilTimer != null) timeUntilTimer.cancel(); timeUntilTimer = new Timer(); timeUntilTimer.scheduleAtFixedRate(new TimerTask() { @Override public void run() { runOnUiThread(new Runnable() { @Override public void run() { if (startStop != null && endStop != null) setNextBusTime(); } }); } }, (60 - rightNow.get(Calendar.SECOND)) * 1000, 60000); } private void renewBusRefreshTimer() { if (busRefreshTimer != null) busRefreshTimer.cancel(); busRefreshTimer = new Timer(); busRefreshTimer.scheduleAtFixedRate(new TimerTask() { @Override public void run() { runOnUiThread(new Runnable() { @Override public void run() { ConnectivityManager connMgr = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE); NetworkInfo networkInfo = connMgr.getActiveNetworkInfo(); if (networkInfo != null && networkInfo.isConnected()) { offline = false; new Downloader(new BusDownloaderHelper(), getApplicationContext()).execute(DownloaderHelper.VEHICLES_URL); updateMapWithNewBusLocations(); if (LOCAL_LOGV) Log.v(REFACTOR_LOG_TAG, "Current start: " + startStop); if (LOCAL_LOGV) Log.v(REFACTOR_LOG_TAG, "Current end : " + endStop); } else if (!offline) { offline = true; Context context = getApplicationContext(); CharSequence text = getString(R.string.unable_to_connect); int duration = Toast.LENGTH_SHORT; if (context != null) { Toast.makeText(context, text, duration).show(); } } } }); } }, 0, 1500L); } /* Returns the best location we can, checking every available location provider. If no provider is available (e.g. all location services turned off), this will return null. */ public Location getLocation() { Location bestLocation = null; LocationManager locationManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE); for (String provider : locationManager.getProviders(true)) { Location l = locationManager.getLastKnownLocation(provider); if (l != null && (bestLocation == null || l.getAccuracy() < bestLocation.getAccuracy()) && (System.currentTimeMillis() - l.getTime()) < 120000) { bestLocation = l; } } return bestLocation; } void setStartAndEndStops() { String end = getSharedPreferences(STOP_PREF, MODE_PRIVATE).getString(END_STOP_PREF, "3rd Ave & 14th St"); // Creates or updates cache file. String start = getSharedPreferences(STOP_PREF, MODE_PRIVATE).getString(START_STOP_PREF, "715 Broadway"); if (startStop == null) setStartStop(BusManager.getBusManager().getStopByName(start)); if (endStop == null) setEndStop(BusManager.getBusManager().getStopByName(end)); Location l = getLocation(); if (l != null && System.currentTimeMillis() - onStartTime < 1000) { Location startLoc = new Location(""), endLoc = new Location(""); startLoc.setLatitude(startStop.getLocation().latitude); startLoc.setLongitude(startStop.getLocation().longitude); endLoc.setLatitude(endStop.getLocation().latitude); endLoc.setLongitude(endStop.getLocation().longitude); if (l.distanceTo(startLoc) > l.distanceTo(endLoc)) { setStartStop(endStop); } } } // Clear the map of all buses and put them all back on in their new locations. private void updateMapWithNewBusLocations() { if (startStop == null || endStop == null) { mMap.clear(); displayStopError(); return; } List<Route> routesBetweenStartAndEnd = startStop.getRoutesTo(endStop); BusManager sharedManager = BusManager.getBusManager(); for (Marker m : busesOnMap) { m.remove(); } busesOnMap = new ArrayList<Marker>(); if (clickableMapMarkers == null) clickableMapMarkers = new HashMap<String, Boolean>(); // New set of buses means new set of clickable markers! for (Route r : routesBetweenStartAndEnd) { for (Bus b : sharedManager.getBuses()) { //if (LOCAL_LOGV) Log.v("BusLocations", "bus id: " + b.getID() + ", bus route: " + b.getRoute() + " vs route: " + r.getID()); if (b.getRoute().equals(r.getID())) { Marker mMarker = mMap.addMarker(new MarkerOptions().position(b.getLocation()).icon(BitmapDescriptorFactory.fromBitmap(rotateBitmap(BitmapFactory.decodeResource(this.getResources(), R.drawable.ic_bus_arrow), b.getHeading()))).anchor(0.5f, 0.5f)); clickableMapMarkers.put(mMarker.getId(), false); // Unable to click on buses. busesOnMap.add(mMarker); } } } } // Clear the map, because we may have just changed what route we wish to display. Then, add everything back onto the map. private void updateMapWithNewStartOrEnd() { setUpMapIfNeeded(); mMap.clear(); if (startStop == null || endStop == null) return; List<Route> routesBetweenStartAndEnd = startStop.getRoutesTo(endStop); clickableMapMarkers = new HashMap<String, Boolean>(); LatLngBounds.Builder builder = new LatLngBounds.Builder(); boolean validBuilder = false; for (Route r : routesBetweenStartAndEnd) { if (!r.getSegments().isEmpty()) { if (LOCAL_LOGV) Log.v(REFACTOR_LOG_TAG, "Updating map with route: " + r.getLongName()); for (Stop s : r.getStops()) { for (Stop f : s.getFamily()) { if ((!f.isHidden() && !f.isRelatedTo(startStop) && !f.isRelatedTo(endStop)) || (f == startStop || f == endStop)) { // Only put one representative from a family of stops on the p Marker mMarker = mMap.addMarker(new MarkerOptions().position(f.getLocation()).title(f.getName()) .anchor(0.5f, 0.5f).icon(BitmapDescriptorFactory.fromBitmap( BitmapFactory.decodeResource(this.getResources(), R.drawable.ic_map_stop)))); clickableMapMarkers.put(mMarker.getId(), true); } } } // Adds the segments of every Route to the map. for (PolylineOptions p : r.getSegments()) { if (p != null) { for (LatLng loc : p.getPoints()) { validBuilder = true; builder.include(loc); } p.color(getResources().getColor(R.color.main_buttons)); mMap.addPolyline(p); } } } } if (validBuilder) { LatLngBounds bounds = builder.build(); try { mMap.animateCamera(CameraUpdateFactory.newLatLngBounds(bounds, 30)); } catch (IllegalStateException e) { // In case the view is not done being created. //e.printStackTrace(); mMap.moveCamera(CameraUpdateFactory.newLatLngBounds(bounds, this.getResources().getDisplayMetrics().widthPixels, this.getResources().getDisplayMetrics().heightPixels, 100)); } } } private void setEndStop(Stop stop) { if (stop == null || startStop == null || !startStop.isConnectedTo(stop)) { ((TextView) findViewById(R.id.end_stop)).setText(getString(R.string.default_end)); if (drawer.isOpened()) drawer.animateClose(); endStop = null; updateMapWithNewStartOrEnd(); drawer.lock(); drawer.setAllowSingleTap(false); sayBusIsOffline(); } else { if (startStop.getOppositeStop() != null && startStop.distanceTo(stop) > startStop.getOppositeStop().distanceTo(stop)) startStop = startStop.getOppositeStop(); ((TextView) findViewById(R.id.end_stop)).setText(stop.getUltimateName()); endStop = stop; } setNextBusTime(); } private void setStartStop(Stop stop) { if (stop == null) { startStop = null; ((TextView) findViewById(R.id.start_stop)).setText(getString(R.string.default_start)); setEndStop(null); displayStopError(); return; } else { stop = stop.getUltimateParent(); } if (endStop != null && endStop.getUltimateName().equals(stop.getUltimateName())) { // Swap the start and end stops. Stop temp = startStop; startStop = endStop.getUltimateParent(); ((TextView) findViewById(R.id.start_stop)).setText(startStop.getUltimateName()); setEndStop(temp); } else { // We have a new start. So, we must ensure the end is actually connected. If not, pick the first connected stop. startStop = stop; ((TextView) findViewById(R.id.start_stop)).setText(stop.getUltimateName()); if (!startStop.isConnectedTo(endStop)) { setEndStop(null); } } setNextBusTime(); } private void setNextBusTime() { if (timeUntilTimer != null) timeUntilTimer.cancel(); if (busRefreshTimer != null) busRefreshTimer.cancel(); if (startStop == null || endStop == null) return; List<Time> timesBetweenStartAndEnd = startStop.getTimesTo(endStop); timesAdapter.setDataSet(timesBetweenStartAndEnd); timesAdapter.notifyDataSetChanged(); drawer.setAllowSingleTap(true); drawer.unlock(); final Time currentTime = Time.getCurrentTime(); ArrayList<Time> tempTimesBetweenStartAndEnd = new ArrayList<Time>(timesBetweenStartAndEnd); tempTimesBetweenStartAndEnd.add(currentTime); Collections.sort(tempTimesBetweenStartAndEnd); int index = tempTimesBetweenStartAndEnd.indexOf(currentTime); int nextTimeTempIndex = (index + 1) % tempTimesBetweenStartAndEnd.size(); Time nextBusTime = tempTimesBetweenStartAndEnd.get(nextTimeTempIndex); final int nextTimeIndex = timesBetweenStartAndEnd.indexOf(nextBusTime); updateNextTimeSwitcher(currentTime.getTimeAsStringUntil(nextBusTime, getResources())); timesList.clearFocus(); if (!drawer.isOpened()) timesList.post(new Runnable() { @Override public void run() { timesList.setSelection(nextTimeIndex); } }); timesAdapter.setTime(currentTime); if (BusManager.getBusManager().isNotDuringSafeRide()) { String routeText; String route = nextBusTime.getRoute(); if (route == null) route = "Unknown"; String[] routeArray = route.split("\\s"); if (routeArray[0].length() == 1) { // We have the A, B, C, E, etc. So, prepend route. routeText = getString(R.string.route) + route; } else { routeText = route; } ((TextView) findViewById(R.id.next_route)).setText(getString(R.string.via) + routeText); ((TextView) findViewById(R.id.next_bus)).setText(getString(R.string.next_bus_in)); findViewById(R.id.safe_ride_button).setVisibility(View.GONE); } else showSafeRideInfoIfNeeded(currentTime); renewBusRefreshTimer(); renewTimeUntilTimer(); updateMapWithNewStartOrEnd(); } private void showSafeRideInfoIfNeeded(Time currentTime) { if (!BusManager.getBusManager().isNotDuringSafeRide()) { ((TextView) findViewById(R.id.next_route)).setText(""); ((TextView) findViewById(R.id.next_bus)).setText(""); if (currentTime.getHour() < 7) { findViewById(R.id.safe_ride_button).setVisibility(View.VISIBLE); } else { findViewById(R.id.safe_ride_button).setVisibility(View.GONE); } } } private void updateNextTimeSwitcher(final String newSwitcherText){ if (LOCAL_LOGV) Log.v(REFACTOR_LOG_TAG, "Updating switcher to [" + newSwitcherText + "]"); if (drawer != null && !drawer.isMoving() && !mSwitcherCurrentText.equals(newSwitcherText)) { mSwitcher.setText(newSwitcherText); // Pass resources so we return the proper string value. mSwitcherCurrentText = newSwitcherText; } // Handle a bug where the time until text disappears when the drawer is being moved. So, just wait for it to finish. // We don't know if the drawer will end up open or closed, though. So handle both cases. else if (drawer != null && !mSwitcherCurrentText.equals(newSwitcherText)) { drawer.setOnDrawerCloseListener(new MultipleOrientationSlidingDrawer.OnDrawerCloseListener() { @Override public void onDrawerClosed() { mSwitcher.setText(newSwitcherText); mSwitcherCurrentText = newSwitcherText; } }); drawer.setOnDrawerOpenListener(new MultipleOrientationSlidingDrawer.OnDrawerOpenListener() { @Override public void onDrawerOpened() { mSwitcher.setText(newSwitcherText); mSwitcherCurrentText = newSwitcherText; } }); } } @SuppressWarnings("UnusedParameters") public void callSafeRide(View view) { Intent callIntent = new Intent(Intent.ACTION_DIAL); callIntent.setData(Uri.parse("tel:12129928267")); startActivity(callIntent); } @SuppressWarnings("UnusedParameters") public void createEndDialog(View view) { // Get all stops connected to the start stop. if (startStop == null) return; final ArrayList<Stop> connectedStops = BusManager.getBusManager().getConnectedStops(startStop); if (connectedStops.size() > 0) { ListView listView = new ListView(this); // ListView to populate the dialog. listView.setId(R.id.end_stop_list); listView.setDivider(new ColorDrawable(getResources().getColor(R.color.time_list_background))); listView.setDividerHeight(2); AlertDialog.Builder builder = new AlertDialog.Builder(this); // Used to build the dialog with the list of connected Stops. builder.setView(listView); final Dialog dialog = builder.create(); // An adapter takes some data, then adapts it to fit into a view. The adapter supplies the individual view elements of // the list view. So, in this case, we supply the StopAdapter with a list of stops, and it gives us back the nice // views with a heart button to signify favorites and a TextView with the name of the stop. // We provide the onClickListeners to the adapter, which then attaches them to the respective views. StopAdapter adapter = new StopAdapter(getApplicationContext(), connectedStops, new View.OnClickListener() { @Override public void onClick(View view) { // Clicked on a Stop. So, make it the end and dismiss the dialog. Stop s = (Stop) view.getTag(); setEndStop(s); // Actually set the end stop. dialog.dismiss(); } }, cbListener); listView.setAdapter(adapter); dialog.setCanceledOnTouchOutside(true); dialog.show(); // Dismissed when a stop is clicked. } else if (startStop != null) { displayStopError(); } } @SuppressWarnings("UnusedParameters") public void createStartDialog(View view) { final ArrayList<Stop> stops = BusManager.getBusManager().getStops(); // Show every stop as an option to start. if (stops.size() > 0) { ListView listView = new ListView(this); listView.setId(R.id.start_stop); listView.setDivider(new ColorDrawable(getResources().getColor(R.color.time_list_background))); listView.setDividerHeight(1); AlertDialog.Builder builder = new AlertDialog.Builder(this); builder.setView(listView); final Dialog dialog = builder.create(); StopAdapter adapter = new StopAdapter(getApplicationContext(), stops, new View.OnClickListener() { @Override public void onClick(View view) { Stop s = (Stop) view.getTag(); setStartStop(s); // Actually set the start stop. dialog.dismiss(); } }, cbListener); listView.setAdapter(adapter); dialog.setCanceledOnTouchOutside(true); dialog.show(); } else { displayStopError(); } } public void displayStopError() { Context context = getApplicationContext(); CharSequence text = getString(R.string.no_stops_available); int duration = Toast.LENGTH_LONG; if (context != null) { Toast.makeText(context, text, duration).show(); } } @SuppressWarnings("UnusedParameters") public void createInfoDialog(View view) { AlertDialog.Builder builder = new AlertDialog.Builder(MainActivity.this); LinearLayout linearLayout = (LinearLayout) getLayoutInflater() .inflate( R.layout.information_layout, (ViewGroup) ((ViewGroup) this.findViewById(android.R.id.content)).getChildAt(0), false ); builder.setView(linearLayout); Dialog dialog = builder.create(); dialog.setCanceledOnTouchOutside(true); dialog.show(); } @SuppressWarnings("UnusedParameters") public void goToGitHub(View view) { String url = "https://github.com/tpalsulich/NYU-BusTracker-Android"; Intent i = new Intent(Intent.ACTION_VIEW); i.setData(Uri.parse(url)); startActivity(i); } @SuppressWarnings("UnusedParameters") public void goToWebsite(View view) { String url = "http://www.nyubustracker.com"; Intent i = new Intent(Intent.ACTION_VIEW); i.setData(Uri.parse(url)); startActivity(i); } private void deleteEverythingInMemory() { if (LOCAL_LOGV) Log.v(REFACTOR_LOG_TAG, "Trying to delete all files."); File directory = new File(getFilesDir(), Downloader.CREATED_FILES_DIR); File[] files = directory.listFiles(); if (files != null) { for (File f : files) { if (f.delete()) { if (LOCAL_LOGV) Log.v(REFACTOR_LOG_TAG, "Deleted " + f.toString()); } else if (LOCAL_LOGV) Log.v(REFACTOR_LOG_TAG, "Could not delete " + f.toString()); } } } private void showErrorAndFinish() { AlertDialog.Builder builder = new AlertDialog.Builder(this); builder.setMessage("Error downloading") .setCancelable(false) .setPositiveButton("Refresh", new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int id) { finish(); } }) .setNegativeButton("Try again later", new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialogInterface, int i) { downloadEverything(true); } }); AlertDialog alert = builder.create(); alert.show(); } }
NYUBusTracker/src/main/java/com/nyubustracker/activities/MainActivity.java
package com.nyubustracker.activities; import android.app.Activity; import android.app.AlertDialog; import android.app.Dialog; import android.app.ProgressDialog; import android.content.Context; import android.content.DialogInterface; import android.content.Intent; import android.content.SharedPreferences; import android.graphics.Bitmap; import android.graphics.BitmapFactory; import android.graphics.Matrix; import android.graphics.drawable.ColorDrawable; import android.location.Location; import android.location.LocationManager; import android.net.ConnectivityManager; import android.net.NetworkInfo; import android.net.Uri; import android.os.Bundle; import android.os.Handler; import android.os.Looper; import android.text.TextUtils; import android.util.Log; import android.util.TypedValue; import android.view.Gravity; import android.view.View; import android.view.ViewGroup; import android.view.animation.Animation; import android.view.animation.AnimationUtils; import android.widget.CompoundButton; import android.widget.LinearLayout; import android.widget.ListView; import android.widget.TextSwitcher; import android.widget.TextView; import android.widget.Toast; import android.widget.ViewSwitcher; import com.flurry.android.FlurryAgent; import com.google.android.gms.analytics.GoogleAnalytics; import com.google.android.gms.common.ConnectionResult; import com.google.android.gms.common.GooglePlayServicesUtil; import com.google.android.gms.maps.CameraUpdate; import com.google.android.gms.maps.CameraUpdateFactory; import com.google.android.gms.maps.GoogleMap; import com.google.android.gms.maps.MapFragment; import com.google.android.gms.maps.model.BitmapDescriptorFactory; import com.google.android.gms.maps.model.LatLng; import com.google.android.gms.maps.model.LatLngBounds; import com.google.android.gms.maps.model.Marker; import com.google.android.gms.maps.model.MarkerOptions; import com.google.android.gms.maps.model.PolylineOptions; import com.nyubustracker.NYUBusTrackerApplication; import com.nyubustracker.R; import com.nyubustracker.adapters.StopAdapter; import com.nyubustracker.adapters.TimeAdapter; import com.nyubustracker.helpers.BusDownloaderHelper; import com.nyubustracker.helpers.BusManager; import com.nyubustracker.helpers.Downloader; import com.nyubustracker.helpers.DownloaderHelper; import com.nyubustracker.helpers.MultipleOrientationSlidingDrawer; import com.nyubustracker.helpers.RouteDownloaderHelper; import com.nyubustracker.helpers.SegmentDownloaderHelper; import com.nyubustracker.helpers.StopDownloaderHelper; import com.nyubustracker.helpers.TimeDownloaderHelper; import com.nyubustracker.helpers.VersionDownloaderHelper; import com.nyubustracker.models.Bus; import com.nyubustracker.models.Route; import com.nyubustracker.models.Stop; import com.nyubustracker.models.Time; import org.json.JSONException; import org.json.JSONObject; import java.io.BufferedReader; import java.io.File; import java.io.FileInputStream; import java.io.IOException; import java.io.InputStreamReader; import java.util.ArrayList; import java.util.Calendar; import java.util.Collections; import java.util.HashMap; import java.util.List; import java.util.Timer; import java.util.TimerTask; import se.emilsjolander.stickylistheaders.StickyListHeadersListView; public class MainActivity extends Activity { public static final boolean LOCAL_LOGV = true; private static final String RUN_ONCE_PREF = "runOnce"; private static final String STOP_PREF = "stops"; private static final String START_STOP_PREF = "startStop"; private static final String END_STOP_PREF = "endStop"; private static final String FIRST_TIME = "firstTime"; public static final String REFACTOR_LOG_TAG = "refactor"; public static final String LOG_TAG = "nyu_log_tag"; private final CompoundButton.OnCheckedChangeListener cbListener = new CompoundButton.OnCheckedChangeListener() { @Override public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) { Stop s = (Stop) buttonView.getTag(); s.setFavorite(isChecked); getSharedPreferences(Stop.FAVORITES_PREF, MODE_PRIVATE).edit().putBoolean(s.getID(), isChecked).commit(); } }; static ProgressDialog progressDialog; private static SharedPreferences oncePreferences; double onStartTime; private Stop startStop; // Stop object to keep track of the start location of the desired route. private Stop endStop; // Keep track of the desired end location. private HashMap<String, Boolean> clickableMapMarkers; // Hash of all markers which are clickable (so we don't zoom in on buses). private ArrayList<Marker> busesOnMap = new ArrayList<Marker>(); private TextSwitcher mSwitcher; private String mSwitcherCurrentText; private TimeAdapter timesAdapter; private StickyListHeadersListView timesList; private Timer timeUntilTimer; // Timer used to refresh the "time until next bus" every minute, on the minute. private Timer busRefreshTimer; // Timer used to refresh the bus locations every few seconds. private GoogleMap mMap; // Map to display all stops, segments, and buses. private boolean offline = true; private MultipleOrientationSlidingDrawer drawer; public static int downloadsOnTheWire = 0; public static Handler UIHandler; static { UIHandler = new Handler(Looper.getMainLooper()); } public static void runOnUI(Runnable runnable) { UIHandler.post(runnable); } private static Bitmap rotateBitmap(Bitmap source, float angle) { Matrix matrix = new Matrix(); matrix.postRotate(angle); return Bitmap.createBitmap(source, 0, 0, source.getWidth(), source.getHeight(), matrix, true); } private void setUpMapIfNeeded() { // First check if GPS is available. final LatLng BROADWAY = new LatLng(40.729146, -73.993756); int retCode = GooglePlayServicesUtil.isGooglePlayServicesAvailable(getApplicationContext()); if (retCode != ConnectionResult.SUCCESS) { GooglePlayServicesUtil.getErrorDialog(retCode, this, 1).show(); } // Do a null check to confirm that we have not already instantiated the map. if (mMap == null) { MapFragment mFrag = ((MapFragment) getFragmentManager().findFragmentById(R.id.map)); if (mFrag != null) mMap = mFrag.getMap(); // Check if we were successful in obtaining the map. if (mMap != null) { // The Map is verified. It is now safe to manipulate the map. mMap.getUiSettings().setRotateGesturesEnabled(false); mMap.getUiSettings().setZoomControlsEnabled(false); mMap.setMyLocationEnabled(true); mMap.setOnMarkerClickListener(new GoogleMap.OnMarkerClickListener() { @Override public boolean onMarkerClick(Marker marker) { return !clickableMapMarkers.get(marker.getId()); // Return true to consume the event. } }); CameraUpdate center= CameraUpdateFactory.newLatLng(BROADWAY); CameraUpdate zoom=CameraUpdateFactory.zoomTo(15); mMap.moveCamera(center); mMap.animateCamera(zoom); } } } String readSavedData(String fileName) throws JSONException { if (LOCAL_LOGV) Log.v(REFACTOR_LOG_TAG, "Reading saved data from " + fileName); StringBuilder buffer = new StringBuilder(""); try { File path = new File(getFilesDir(), Downloader.CREATED_FILES_DIR); path.mkdir(); File file = new File(path, fileName); FileInputStream inputStream = new FileInputStream(file); InputStreamReader streamReader = new InputStreamReader(inputStream); BufferedReader bufferedReader = new BufferedReader(streamReader); String readString = bufferedReader.readLine(); while (readString != null) { buffer.append(readString); readString = bufferedReader.readLine(); } inputStream.close(); } catch (IOException e) { if (LOCAL_LOGV) Log.v(REFACTOR_LOG_TAG, "Failed to read " + fileName + "..."); throw new JSONException("Failed to read " + fileName); } return buffer.toString(); } private void downloadEverything(boolean block) { deleteEverythingInMemory(); ConnectivityManager connMgr = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE); NetworkInfo networkInfo = connMgr.getActiveNetworkInfo(); if (networkInfo != null && networkInfo.isConnected()) { offline = false; // Download and parse everything, put it all in persistent memory, continue. if (block) progressDialog = ProgressDialog.show(this, getString(R.string.downloading), getString(R.string.wait), true, false); else progressDialog = null; Context context = getApplicationContext(); downloadsOnTheWire += 4; new Downloader(new StopDownloaderHelper(), context).execute(DownloaderHelper.STOPS_URL); new Downloader(new RouteDownloaderHelper(), context).execute(DownloaderHelper.ROUTES_URL); new Downloader(new SegmentDownloaderHelper(), context).execute(DownloaderHelper.SEGMENTS_URL); new Downloader(new VersionDownloaderHelper(), context).execute(DownloaderHelper.VERSION_URL); } else if (!offline) { // Only show the offline dialog once. offline = true; Context context = getApplicationContext(); CharSequence text = getString(R.string.unable_to_connect); int duration = Toast.LENGTH_SHORT; if (context != null) { Toast.makeText(context, text, duration).show(); } } } public static void pieceDownloadsTogether(final Context context) { downloadsOnTheWire--; if (LOCAL_LOGV) Log.v(REFACTOR_LOG_TAG, "Downloads on the wire: " + downloadsOnTheWire); if (downloadsOnTheWire <= 0) { if (LOCAL_LOGV) Log.v(REFACTOR_LOG_TAG, "Downloading finished!"); oncePreferences.edit().putBoolean(FIRST_TIME, false).apply(); if (progressDialog != null) { runOnUI(new Runnable() { @Override public void run() { Stop broadway = BusManager.getBusManager().getStopByName("715 Broadway"); if (broadway != null) { context.getSharedPreferences(Stop.FAVORITES_PREF, MODE_PRIVATE).edit().putBoolean(broadway.getID(), true).apply(); broadway.setFavorite(true); } progressDialog.dismiss(); } }); } } // Else, we have nothing to do, since not all downloads are finished. } @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); if (LOCAL_LOGV) Log.v(REFACTOR_LOG_TAG, "onCreate!"); setContentView(R.layout.activity_main); ((NYUBusTrackerApplication) getApplication()).getTracker(); oncePreferences = getSharedPreferences(RUN_ONCE_PREF, MODE_PRIVATE); setUpMapIfNeeded(); // Instantiates mMap, if it needs to be. // Singleton BusManager to keep track of all stops, routes, etc. final BusManager sharedManager = BusManager.getBusManager(); mSwitcher = (TextSwitcher) findViewById(R.id.next_time); mSwitcherCurrentText = ""; // Set the ViewFactory of the TextSwitcher that will create TextView object when asked mSwitcher.setFactory(new ViewSwitcher.ViewFactory() { public View makeView() { TextView myText = new TextView(MainActivity.this); myText.setTextSize(TypedValue.COMPLEX_UNIT_PX, getResources().getDimensionPixelSize(R.dimen.time_until_text_size)); myText.setTextColor(getResources().getColor(R.color.main_text)); myText.setGravity(Gravity.CENTER_VERTICAL | Gravity.LEFT); myText.setEllipsize(TextUtils.TruncateAt.END); myText.setSingleLine(true); return myText; } }); // Declare the in and out animations and initialize them Animation in = AnimationUtils.loadAnimation(MainActivity.this, android.R.anim.slide_in_left); Animation out = AnimationUtils.loadAnimation(MainActivity.this, android.R.anim.slide_out_right); // set the animation type of textSwitcher mSwitcher.setInAnimation(in); mSwitcher.setOutAnimation(out); drawer = (MultipleOrientationSlidingDrawer) findViewById(R.id.sliding_drawer); drawer.setAllowSingleTap(false); drawer.lock(); timesList = (StickyListHeadersListView) findViewById(R.id.times_list); timesAdapter = new TimeAdapter(getApplicationContext(), new ArrayList<Time>()); timesList.setAdapter(timesAdapter); if (oncePreferences.getBoolean(FIRST_TIME, true)) { if (LOCAL_LOGV) Log.v(REFACTOR_LOG_TAG, "Downloading because of first time"); downloadEverything(true); } else { if (!sharedManager.hasRoutes() || !sharedManager.hasStops()) { if (LOCAL_LOGV) Log.v(REFACTOR_LOG_TAG, "Parsing cached files..."); try { JSONObject stopJson = new JSONObject(readSavedData(StopDownloaderHelper.STOP_JSON_FILE)); JSONObject routeJson = new JSONObject(readSavedData(RouteDownloaderHelper.ROUTE_JSON_FILE)); JSONObject segJson = new JSONObject(readSavedData(SegmentDownloaderHelper.SEGMENT_JSON_FILE)); JSONObject verJson = new JSONObject(readSavedData(VersionDownloaderHelper.VERSION_JSON_FILE)); Stop.parseJSON(stopJson); Route.parseJSON(routeJson); BusManager.parseSegments(segJson); BusManager.parseVersion(verJson); Context context = getApplicationContext(); for (String timeURL : sharedManager.getTimesToDownload()) { String timeFileName = timeURL.substring(timeURL.lastIndexOf("/") + 1, timeURL.indexOf(".json")); if (LOCAL_LOGV) Log.v(REFACTOR_LOG_TAG, "Trying to parse " + timeFileName); try { BusManager.parseTime(new JSONObject(readSavedData(timeFileName))); } catch (JSONException e) { if (LOCAL_LOGV) Log.v(REFACTOR_LOG_TAG, "Didn't find time file, so downloading it: " + timeURL); new Downloader(new TimeDownloaderHelper(), context).execute(timeURL); } } SharedPreferences favoritePreferences = getSharedPreferences(Stop.FAVORITES_PREF, MODE_PRIVATE); if (LOCAL_LOGV) Log.v(REFACTOR_LOG_TAG, "Done parsing..."); for (Stop s : sharedManager.getStops()) { boolean result = favoritePreferences.getBoolean(s.getID(), false); s.setFavorite(result); } new Downloader(new VersionDownloaderHelper(), context).execute(DownloaderHelper.VERSION_URL); setStartAndEndStops(); // Update the map to show the corresponding stops, buses, and segments. updateMapWithNewStartOrEnd(); // Get the location of the buses every 10 sec. renewBusRefreshTimer(); renewTimeUntilTimer(); setNextBusTime(); } catch (JSONException e) { if (LOCAL_LOGV) Log.v(REFACTOR_LOG_TAG, "Re-downloading because of an error."); e.printStackTrace(); downloadEverything(true); } } else { setStartAndEndStops(); updateMapWithNewStartOrEnd(); } } } @Override public void onStart() { super.onStart(); // if (LOCAL_LOGV) Log.v("General Debugging", "onStart!"); onStartTime = System.currentTimeMillis(); GoogleAnalytics.getInstance(this).reportActivityStart(this); FlurryAgent.onStartSession(this, getString(LOCAL_LOGV ? R.string.flurry_debug_api_key : R.string.flurry_api_key)); } @Override public void onResume() { super.onResume(); if (LOCAL_LOGV) Log.v(REFACTOR_LOG_TAG, "onResume!"); if (endStop != null && startStop != null) { renewTimeUntilTimer(); renewBusRefreshTimer(); setUpMapIfNeeded(); setStartAndEndStops(); } } @Override public void onPause() { super.onPause(); if (LOCAL_LOGV) Log.v(REFACTOR_LOG_TAG, "onPause!"); cacheStartAndEndStops(); if (timeUntilTimer != null) timeUntilTimer.cancel(); if (busRefreshTimer != null) busRefreshTimer.cancel(); } @Override public void onStop() { super.onStop(); // if (LOCAL_LOGV) Log.v("General Debugging", "onStop!"); GoogleAnalytics.getInstance(this).reportActivityStop(this); FlurryAgent.onEndSession(this); } @Override public void onDestroy() { super.onDestroy(); if (LOCAL_LOGV) Log.v(REFACTOR_LOG_TAG, "onDestroy!"); cacheStartAndEndStops(); // Remember user's preferences across lifetimes. if (timeUntilTimer != null) timeUntilTimer.cancel(); // Don't need a timer anymore -- must be recreated onResume. if (busRefreshTimer != null) busRefreshTimer.cancel(); } @Override public void onBackPressed() { if (drawer.isOpened()) drawer.animateClose(); else super.onBackPressed(); } void cacheStartAndEndStops() { if (endStop != null) getSharedPreferences(STOP_PREF, MODE_PRIVATE).edit().putString(END_STOP_PREF, endStop.getName()).apply(); // Creates or updates cache file. if (startStop != null) getSharedPreferences(STOP_PREF, MODE_PRIVATE).edit().putString(START_STOP_PREF, startStop.getName()).apply(); } void sayBusIsOffline() { updateNextTimeSwitcher(getString(R.string.offline)); ((TextView) findViewById(R.id.next_bus)).setText(""); ((TextView) findViewById(R.id.next_route)).setText(""); } /* renewTimeUntilTimer() creates a new timer that calls setNextBusTime() every minute on the minute. */ private void renewTimeUntilTimer() { Calendar rightNow = Calendar.getInstance(); if (timeUntilTimer != null) timeUntilTimer.cancel(); timeUntilTimer = new Timer(); timeUntilTimer.scheduleAtFixedRate(new TimerTask() { @Override public void run() { runOnUiThread(new Runnable() { @Override public void run() { if (startStop != null && endStop != null) setNextBusTime(); } }); } }, (60 - rightNow.get(Calendar.SECOND)) * 1000, 60000); } private void renewBusRefreshTimer() { if (busRefreshTimer != null) busRefreshTimer.cancel(); busRefreshTimer = new Timer(); busRefreshTimer.scheduleAtFixedRate(new TimerTask() { @Override public void run() { runOnUiThread(new Runnable() { @Override public void run() { ConnectivityManager connMgr = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE); NetworkInfo networkInfo = connMgr.getActiveNetworkInfo(); if (networkInfo != null && networkInfo.isConnected()) { offline = false; new Downloader(new BusDownloaderHelper(), getApplicationContext()).execute(DownloaderHelper.VEHICLES_URL); updateMapWithNewBusLocations(); if (LOCAL_LOGV) Log.v(REFACTOR_LOG_TAG, "Current start: " + startStop); if (LOCAL_LOGV) Log.v(REFACTOR_LOG_TAG, "Current end : " + endStop); } else if (!offline) { offline = true; Context context = getApplicationContext(); CharSequence text = getString(R.string.unable_to_connect); int duration = Toast.LENGTH_SHORT; if (context != null) { Toast.makeText(context, text, duration).show(); } } } }); } }, 0, 1500L); } /* Returns the best location we can, checking every available location provider. If no provider is available (e.g. all location services turned off), this will return null. */ public Location getLocation() { Location bestLocation = null; LocationManager locationManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE); for (String provider : locationManager.getProviders(true)) { Location l = locationManager.getLastKnownLocation(provider); if (l != null && (bestLocation == null || l.getAccuracy() < bestLocation.getAccuracy()) && (System.currentTimeMillis() - l.getTime()) < 120000) { bestLocation = l; } } return bestLocation; } void setStartAndEndStops() { String end = getSharedPreferences(STOP_PREF, MODE_PRIVATE).getString(END_STOP_PREF, "3rd Ave & 14th St"); // Creates or updates cache file. String start = getSharedPreferences(STOP_PREF, MODE_PRIVATE).getString(START_STOP_PREF, "715 Broadway"); if (startStop == null) setStartStop(BusManager.getBusManager().getStopByName(start)); if (endStop == null) setEndStop(BusManager.getBusManager().getStopByName(end)); Location l = getLocation(); if (l != null && System.currentTimeMillis() - onStartTime < 1000) { Location startLoc = new Location(""), endLoc = new Location(""); startLoc.setLatitude(startStop.getLocation().latitude); startLoc.setLongitude(startStop.getLocation().longitude); endLoc.setLatitude(endStop.getLocation().latitude); endLoc.setLongitude(endStop.getLocation().longitude); if (l.distanceTo(startLoc) > l.distanceTo(endLoc)) { setStartStop(endStop); } } } // Clear the map of all buses and put them all back on in their new locations. private void updateMapWithNewBusLocations() { if (startStop == null || endStop == null) { mMap.clear(); displayStopError(); return; } List<Route> routesBetweenStartAndEnd = startStop.getRoutesTo(endStop); BusManager sharedManager = BusManager.getBusManager(); for (Marker m : busesOnMap) { m.remove(); } busesOnMap = new ArrayList<Marker>(); if (clickableMapMarkers == null) clickableMapMarkers = new HashMap<String, Boolean>(); // New set of buses means new set of clickable markers! for (Route r : routesBetweenStartAndEnd) { for (Bus b : sharedManager.getBuses()) { //if (LOCAL_LOGV) Log.v("BusLocations", "bus id: " + b.getID() + ", bus route: " + b.getRoute() + " vs route: " + r.getID()); if (b.getRoute().equals(r.getID())) { Marker mMarker = mMap.addMarker(new MarkerOptions().position(b.getLocation()).icon(BitmapDescriptorFactory.fromBitmap(rotateBitmap(BitmapFactory.decodeResource(this.getResources(), R.drawable.ic_bus_arrow), b.getHeading()))).anchor(0.5f, 0.5f)); clickableMapMarkers.put(mMarker.getId(), false); // Unable to click on buses. busesOnMap.add(mMarker); } } } } // Clear the map, because we may have just changed what route we wish to display. Then, add everything back onto the map. private void updateMapWithNewStartOrEnd() { setUpMapIfNeeded(); mMap.clear(); if (startStop == null || endStop == null) return; List<Route> routesBetweenStartAndEnd = startStop.getRoutesTo(endStop); clickableMapMarkers = new HashMap<String, Boolean>(); LatLngBounds.Builder builder = new LatLngBounds.Builder(); boolean validBuilder = false; for (Route r : routesBetweenStartAndEnd) { if (!r.getSegments().isEmpty()) { if (LOCAL_LOGV) Log.v(REFACTOR_LOG_TAG, "Updating map with route: " + r.getLongName()); for (Stop s : r.getStops()) { for (Stop f : s.getFamily()) { if ((!f.isHidden() && !f.isRelatedTo(startStop) && !f.isRelatedTo(endStop)) || (f == startStop || f == endStop)) { // Only put one representative from a family of stops on the p Marker mMarker = mMap.addMarker(new MarkerOptions().position(f.getLocation()).title(f.getName()) .anchor(0.5f, 0.5f).icon(BitmapDescriptorFactory.fromBitmap( BitmapFactory.decodeResource(this.getResources(), R.drawable.ic_map_stop)))); clickableMapMarkers.put(mMarker.getId(), true); } } } // Adds the segments of every Route to the map. for (PolylineOptions p : r.getSegments()) { if (p != null) { for (LatLng loc : p.getPoints()) { validBuilder = true; builder.include(loc); } p.color(getResources().getColor(R.color.main_buttons)); mMap.addPolyline(p); } } } } if (validBuilder) { LatLngBounds bounds = builder.build(); try { mMap.animateCamera(CameraUpdateFactory.newLatLngBounds(bounds, 30)); } catch (IllegalStateException e) { // In case the view is not done being created. //e.printStackTrace(); mMap.moveCamera(CameraUpdateFactory.newLatLngBounds(bounds, this.getResources().getDisplayMetrics().widthPixels, this.getResources().getDisplayMetrics().heightPixels, 100)); } } } private void setEndStop(Stop stop) { if (stop == null || startStop == null || !startStop.isConnectedTo(stop)) { ((TextView) findViewById(R.id.end_stop)).setText(getString(R.string.default_end)); if (drawer.isOpened()) drawer.animateClose(); endStop = null; updateMapWithNewStartOrEnd(); drawer.lock(); drawer.setAllowSingleTap(false); sayBusIsOffline(); } else { if (startStop.getOppositeStop() != null && startStop.distanceTo(stop) > startStop.getOppositeStop().distanceTo(stop)) startStop = startStop.getOppositeStop(); ((TextView) findViewById(R.id.end_stop)).setText(stop.getUltimateName()); endStop = stop; } setNextBusTime(); } private void setStartStop(Stop stop) { if (stop == null) { startStop = null; ((TextView) findViewById(R.id.start_stop)).setText(getString(R.string.default_start)); setEndStop(null); displayStopError(); return; } else { stop = stop.getUltimateParent(); } if (endStop != null && endStop.getUltimateName().equals(stop.getUltimateName())) { // Swap the start and end stops. Stop temp = startStop; startStop = endStop.getUltimateParent(); ((TextView) findViewById(R.id.start_stop)).setText(startStop.getUltimateName()); setEndStop(temp); } else { // We have a new start. So, we must ensure the end is actually connected. If not, pick the first connected stop. startStop = stop; ((TextView) findViewById(R.id.start_stop)).setText(stop.getUltimateName()); if (!startStop.isConnectedTo(endStop)) { setEndStop(null); } } setNextBusTime(); } private void setNextBusTime() { if (timeUntilTimer != null) timeUntilTimer.cancel(); if (busRefreshTimer != null) busRefreshTimer.cancel(); if (startStop == null || endStop == null) return; List<Time> timesBetweenStartAndEnd = startStop.getTimesTo(endStop); timesAdapter.setDataSet(timesBetweenStartAndEnd); timesAdapter.notifyDataSetChanged(); drawer.setAllowSingleTap(true); drawer.unlock(); final Time currentTime = Time.getCurrentTime(); ArrayList<Time> tempTimesBetweenStartAndEnd = new ArrayList<Time>(timesBetweenStartAndEnd); tempTimesBetweenStartAndEnd.add(currentTime); Collections.sort(tempTimesBetweenStartAndEnd); int index = tempTimesBetweenStartAndEnd.indexOf(currentTime); int nextTimeTempIndex = (index + 1) % tempTimesBetweenStartAndEnd.size(); Time nextBusTime = tempTimesBetweenStartAndEnd.get(nextTimeTempIndex); final int nextTimeIndex = timesBetweenStartAndEnd.indexOf(nextBusTime); updateNextTimeSwitcher(currentTime.getTimeAsStringUntil(nextBusTime, getResources())); timesList.clearFocus(); if (!drawer.isOpened()) timesList.post(new Runnable() { @Override public void run() { timesList.setSelection(nextTimeIndex); } }); timesAdapter.setTime(currentTime); if (BusManager.getBusManager().isNotDuringSafeRide()) { String routeText; String[] routeArray = nextBusTime.getRoute().split("\\s"); String route = nextBusTime.getRoute(); if (routeArray[0].length() == 1) { // We have the A, B, C, E, etc. So, prepend route. routeText = getString(R.string.route) + route; } else { routeText = route; } ((TextView) findViewById(R.id.next_route)).setText(getString(R.string.via) + routeText); ((TextView) findViewById(R.id.next_bus)).setText(getString(R.string.next_bus_in)); findViewById(R.id.safe_ride_button).setVisibility(View.GONE); } else showSafeRideInfoIfNeeded(currentTime); renewBusRefreshTimer(); renewTimeUntilTimer(); updateMapWithNewStartOrEnd(); } private void showSafeRideInfoIfNeeded(Time currentTime) { if (!BusManager.getBusManager().isNotDuringSafeRide()) { ((TextView) findViewById(R.id.next_route)).setText(""); ((TextView) findViewById(R.id.next_bus)).setText(""); if (currentTime.getHour() < 7) { findViewById(R.id.safe_ride_button).setVisibility(View.VISIBLE); } else { findViewById(R.id.safe_ride_button).setVisibility(View.GONE); } } } private void updateNextTimeSwitcher(final String newSwitcherText){ if (LOCAL_LOGV) Log.v(REFACTOR_LOG_TAG, "Updating switcher to [" + newSwitcherText + "]"); if (drawer != null && !drawer.isMoving() && !mSwitcherCurrentText.equals(newSwitcherText)) { mSwitcher.setText(newSwitcherText); // Pass resources so we return the proper string value. mSwitcherCurrentText = newSwitcherText; } // Handle a bug where the time until text disappears when the drawer is being moved. So, just wait for it to finish. // We don't know if the drawer will end up open or closed, though. So handle both cases. else if (drawer != null && !mSwitcherCurrentText.equals(newSwitcherText)) { drawer.setOnDrawerCloseListener(new MultipleOrientationSlidingDrawer.OnDrawerCloseListener() { @Override public void onDrawerClosed() { mSwitcher.setText(newSwitcherText); mSwitcherCurrentText = newSwitcherText; } }); drawer.setOnDrawerOpenListener(new MultipleOrientationSlidingDrawer.OnDrawerOpenListener() { @Override public void onDrawerOpened() { mSwitcher.setText(newSwitcherText); mSwitcherCurrentText = newSwitcherText; } }); } } @SuppressWarnings("UnusedParameters") public void callSafeRide(View view) { Intent callIntent = new Intent(Intent.ACTION_DIAL); callIntent.setData(Uri.parse("tel:12129928267")); startActivity(callIntent); } @SuppressWarnings("UnusedParameters") public void createEndDialog(View view) { // Get all stops connected to the start stop. if (startStop == null) return; final ArrayList<Stop> connectedStops = BusManager.getBusManager().getConnectedStops(startStop); if (connectedStops.size() > 0) { ListView listView = new ListView(this); // ListView to populate the dialog. listView.setId(R.id.end_stop_list); listView.setDivider(new ColorDrawable(getResources().getColor(R.color.time_list_background))); listView.setDividerHeight(2); AlertDialog.Builder builder = new AlertDialog.Builder(this); // Used to build the dialog with the list of connected Stops. builder.setView(listView); final Dialog dialog = builder.create(); // An adapter takes some data, then adapts it to fit into a view. The adapter supplies the individual view elements of // the list view. So, in this case, we supply the StopAdapter with a list of stops, and it gives us back the nice // views with a heart button to signify favorites and a TextView with the name of the stop. // We provide the onClickListeners to the adapter, which then attaches them to the respective views. StopAdapter adapter = new StopAdapter(getApplicationContext(), connectedStops, new View.OnClickListener() { @Override public void onClick(View view) { // Clicked on a Stop. So, make it the end and dismiss the dialog. Stop s = (Stop) view.getTag(); setEndStop(s); // Actually set the end stop. dialog.dismiss(); } }, cbListener); listView.setAdapter(adapter); dialog.setCanceledOnTouchOutside(true); dialog.show(); // Dismissed when a stop is clicked. } else if (startStop != null) { displayStopError(); } } @SuppressWarnings("UnusedParameters") public void createStartDialog(View view) { final ArrayList<Stop> stops = BusManager.getBusManager().getStops(); // Show every stop as an option to start. if (stops.size() > 0) { ListView listView = new ListView(this); listView.setId(R.id.start_stop); listView.setDivider(new ColorDrawable(getResources().getColor(R.color.time_list_background))); listView.setDividerHeight(1); AlertDialog.Builder builder = new AlertDialog.Builder(this); builder.setView(listView); final Dialog dialog = builder.create(); StopAdapter adapter = new StopAdapter(getApplicationContext(), stops, new View.OnClickListener() { @Override public void onClick(View view) { Stop s = (Stop) view.getTag(); setStartStop(s); // Actually set the start stop. dialog.dismiss(); } }, cbListener); listView.setAdapter(adapter); dialog.setCanceledOnTouchOutside(true); dialog.show(); } else { displayStopError(); } } public void displayStopError() { Context context = getApplicationContext(); CharSequence text = getString(R.string.no_stops_available); int duration = Toast.LENGTH_LONG; if (context != null) { Toast.makeText(context, text, duration).show(); } } @SuppressWarnings("UnusedParameters") public void createInfoDialog(View view) { AlertDialog.Builder builder = new AlertDialog.Builder(MainActivity.this); LinearLayout linearLayout = (LinearLayout) getLayoutInflater() .inflate( R.layout.information_layout, (ViewGroup) ((ViewGroup) this.findViewById(android.R.id.content)).getChildAt(0), false ); builder.setView(linearLayout); Dialog dialog = builder.create(); dialog.setCanceledOnTouchOutside(true); dialog.show(); } @SuppressWarnings("UnusedParameters") public void goToGitHub(View view) { String url = "https://github.com/tpalsulich/NYU-BusTracker-Android"; Intent i = new Intent(Intent.ACTION_VIEW); i.setData(Uri.parse(url)); startActivity(i); } @SuppressWarnings("UnusedParameters") public void goToWebsite(View view) { String url = "http://www.nyubustracker.com"; Intent i = new Intent(Intent.ACTION_VIEW); i.setData(Uri.parse(url)); startActivity(i); } private void deleteEverythingInMemory() { if (LOCAL_LOGV) Log.v(REFACTOR_LOG_TAG, "Trying to delete all files."); File directory = new File(getFilesDir(), Downloader.CREATED_FILES_DIR); File[] files = directory.listFiles(); if (files != null) { for (File f : files) { if (f.delete()) { if (LOCAL_LOGV) Log.v(REFACTOR_LOG_TAG, "Deleted " + f.toString()); } else if (LOCAL_LOGV) Log.v(REFACTOR_LOG_TAG, "Could not delete " + f.toString()); } } } private void showErrorAndFinish() { AlertDialog.Builder builder = new AlertDialog.Builder(this); builder.setMessage("Error downloading") .setCancelable(false) .setPositiveButton("Refresh", new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int id) { finish(); } }) .setNegativeButton("Try again later", new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialogInterface, int i) { downloadEverything(true); } }); AlertDialog alert = builder.create(); alert.show(); } }
Prevent rare NPE when the next bus time has a null route.
NYUBusTracker/src/main/java/com/nyubustracker/activities/MainActivity.java
Prevent rare NPE when the next bus time has a null route.
<ide><path>YUBusTracker/src/main/java/com/nyubustracker/activities/MainActivity.java <ide> <ide> if (BusManager.getBusManager().isNotDuringSafeRide()) { <ide> String routeText; <del> String[] routeArray = nextBusTime.getRoute().split("\\s"); <ide> String route = nextBusTime.getRoute(); <add> if (route == null) route = "Unknown"; <add> String[] routeArray = route.split("\\s"); <ide> if (routeArray[0].length() == 1) { // We have the A, B, C, E, etc. So, prepend route. <ide> routeText = getString(R.string.route) + route; <ide> }
Java
lgpl-2.1
2d0f0384f806413f23e82407dec98a55ee0d34c9
0
julie-sullivan/phytomine,julie-sullivan/phytomine,julie-sullivan/phytomine,julie-sullivan/phytomine,julie-sullivan/phytomine,julie-sullivan/phytomine,julie-sullivan/phytomine
package org.intermine.api.bag; /* * Copyright (C) 2002-2010 FlyMine * * This code may be freely distributed and modified under the * terms of the GNU Lesser General Public Licence. This should * be distributed with the code. See the LICENSE file for more * information or http://www.gnu.org/copyleft/lesser.html. * */ import java.util.Collection; import java.util.HashMap; import java.util.HashSet; import java.util.Iterator; import java.util.List; import java.util.Map; import java.util.Set; import org.apache.log4j.Logger; import org.intermine.api.profile.InterMineBag; import org.intermine.api.profile.Profile; import org.intermine.api.profile.TagManager; import org.intermine.api.profile.TagManagerFactory; import org.intermine.api.tag.TagNames; import org.intermine.api.tag.TagTypes; import org.intermine.metadata.ClassDescriptor; import org.intermine.metadata.Model; import org.intermine.model.userprofile.Tag; import org.intermine.objectstore.ObjectStore; import org.intermine.objectstore.query.ObjectStoreBag; import org.intermine.objectstore.query.ObjectStoreBagsForObject; import org.intermine.objectstore.query.Query; import org.intermine.objectstore.query.Results; /** * A BagManager provides access to all global and/or user bags and methods to fetch them by * type, etc. * @author Richard Smith * */ public class BagManager { private static final Logger LOG = Logger.getLogger(BagManager.class); private Profile superProfile; private final TagManager tagManager; private final Model model; private ObjectStore osProduction; /** * The BagManager references the super user profile to fetch global bags. * @param superProfile the super user profile * @param model the object model */ public BagManager(Profile superProfile, Model model) { this.superProfile = superProfile; if (superProfile == null) { String msg = "Unable to retrieve superuser profile. Check that the superuser profile " + "in the MINE.properties file matches the superuser in the userprofile database."; LOG.error(msg); throw new RuntimeException(msg); } this.model = model; this.tagManager = new TagManagerFactory(superProfile.getProfileManager()).getTagManager(); this.osProduction = superProfile.getProfileManager().getProductionObjectStore(); } /** * Fetch globally available bags - superuser public bags that are available to everyone. * @return a map from bag name to bag */ public Map<String, InterMineBag> getGlobalBags() { return getBagsWithTag(superProfile, TagNames.IM_PUBLIC); } /** * Fetch bags from given protocol with a particular tag assigned to them. * @param profile the user to fetch bags from * @param tag the tag to filter * @return a map from bag name to bag */ protected Map<String, InterMineBag> getBagsWithTag(Profile profile, String tag) { Map<String, InterMineBag> bagsWithTag = new HashMap<String, InterMineBag>(); for (Map.Entry<String, InterMineBag> entry : profile.getSavedBags().entrySet()) { InterMineBag bag = entry.getValue(); List<Tag> tags = tagManager.getTags(tag, bag.getName(), TagTypes.BAG, profile.getUsername()); if (tags.size() > 0) { bagsWithTag.put(entry.getKey(), entry.getValue()); } } return bagsWithTag; } /** * Fetch bags for the given profile. * @param profile the user to fetch bags for * @return a map from bag name to bag */ public Map<String, InterMineBag> getUserBags(Profile profile) { return profile.getSavedBags(); } /** * Fetch all global bags and user bags combined in the same map. If user has a bag with the * same name as a global bag the user's bag takes precedence. * @param profile the user to fetch bags for * @return a map from bag name to bag */ public Map<String, InterMineBag> getUserAndGlobalBags(Profile profile) { // add global bags first, any user bags with same name take precedence Map<String, InterMineBag> allBags = new HashMap<String, InterMineBag>(); allBags.putAll(getGlobalBags()); allBags.putAll(profile.getSavedBags()); return allBags; } /** * Fetch a global bag by name. * @param bagName the name of bag to fetch * @return the bag or null if not found */ public InterMineBag getGlobalBag(String bagName) { return getGlobalBags().get(bagName); } /** * Fetch a user bag by name. * @param profile the user to fetch bags for * @param bagName the name of bag to fetch * @return the bag or null if not found */ public InterMineBag getUserBag(Profile profile, String bagName) { return getUserBags(profile).get(bagName); } /** * Fetch a global or user bag by name. If user has a bag with the same name as a global bag * the user's bag takes precedence. * @param profile the user to fetch bags for * @param bagName the name of bag to fetch * @return the bag or null if not found */ public InterMineBag getUserOrGlobalBag(Profile profile, String bagName) { return getUserAndGlobalBags(profile).get(bagName); } /** * Fetch global and user bags of the specified type or a subclass of the specified type. * @param profile the user to fetch bags for * @param type an unqualified class name * @return a map from bag name to bag */ public Map<String, InterMineBag> getUserOrGlobalBagsOfType(Profile profile, String type) { Set<String> classAndSubs = new HashSet<String>(); classAndSubs.add(type); ClassDescriptor bagTypeCld = model.getClassDescriptorByName(type); if (bagTypeCld == null) { throw new NullPointerException("Could not find ClassDescriptor for name " + type); } for (ClassDescriptor cld : model.getAllSubs(bagTypeCld)) { classAndSubs.add(cld.getUnqualifiedName()); } Map<String, InterMineBag> bagsOfType = new HashMap<String, InterMineBag>(); for (Map.Entry<String, InterMineBag> entry : getUserAndGlobalBags(profile).entrySet()) { InterMineBag bag = entry.getValue(); if (classAndSubs.contains(bag.getType())) { bagsOfType.put(entry.getKey(), bag); } } return bagsOfType; } /** * Fetch global bags that contain the given id. * @param id the id to search bags for * @return bags containing the given id */ public Collection<InterMineBag> getGlobalBagsContainingId(Integer id) { return getBagsContainingId(getGlobalBags(), id); } /** * Fetch user bags that contain the given id. * @param id the id to search bags for * @param profile the user to fetch bags from * @return bags containing the given id */ public Collection<InterMineBag> getUserBagsContainingId(Profile profile, Integer id) { return getBagsContainingId(getUserBags(profile), id); } /** * Fetch user or global bags that contain the given id. If user has a bag with the same name * as a global bag the user's bag takes precedence. * @param id the id to search bags for * @param profile the user to fetch bags from * @return bags containing the given id */ public Collection<InterMineBag> getUserOrGlobalBagsContainingId(Profile profile, Integer id) { HashSet<InterMineBag> bagsContainingId = new HashSet<InterMineBag>(); bagsContainingId.addAll(getGlobalBagsContainingId(id)); // System.out.println("superuser:" + bagsContainingId.size()); bagsContainingId.addAll(getUserBagsContainingId(profile, id)); // System.out.println("user:" + bagsContainingId.size()); return bagsContainingId; } private Collection<InterMineBag> getBagsContainingId(Map<String, InterMineBag> imBags, Integer id) { Collection<ObjectStoreBag> objectStoreBags = getObjectStoreBags(imBags.values()); Map<Integer, InterMineBag> osBagIdToInterMineBag = getOsBagIdToInterMineBag(imBags.values()); // this searches bags for an object ObjectStoreBagsForObject osbo = new ObjectStoreBagsForObject(id, objectStoreBags); // run query Query q = new Query(); q.addToSelect(osbo); Collection<InterMineBag> bagsContainingId = new HashSet<InterMineBag>(); // this should return all bags with that object Results res = osProduction.executeSingleton(q); Iterator<Object> resIter = res.iterator(); while (resIter.hasNext()) { Integer osBagId = (Integer) resIter.next(); bagsContainingId.add(osBagIdToInterMineBag.get(osBagId)); } return bagsContainingId; } private Map<Integer, InterMineBag> getOsBagIdToInterMineBag(Collection<InterMineBag> imBags) { Map<Integer, InterMineBag> osBagIdToInterMineBag = new HashMap<Integer, InterMineBag>(); for (InterMineBag imBag : imBags) { osBagIdToInterMineBag.put(imBag.getOsb().getBagId(), imBag); } return osBagIdToInterMineBag; } private Collection<ObjectStoreBag> getObjectStoreBags(Collection<InterMineBag> imBags) { Set<ObjectStoreBag> objectStoreBags = new HashSet<ObjectStoreBag>(); for (InterMineBag imBag : imBags) { objectStoreBags.add(imBag.getOsb()); } return objectStoreBags; } }
intermine/api/main/src/org/intermine/api/bag/BagManager.java
package org.intermine.api.bag; /* * Copyright (C) 2002-2010 FlyMine * * This code may be freely distributed and modified under the * terms of the GNU Lesser General Public Licence. This should * be distributed with the code. See the LICENSE file for more * information or http://www.gnu.org/copyleft/lesser.html. * */ import java.util.Collection; import java.util.HashMap; import java.util.HashSet; import java.util.Iterator; import java.util.List; import java.util.Map; import java.util.Set; import org.apache.log4j.Logger; import org.intermine.api.profile.InterMineBag; import org.intermine.api.profile.Profile; import org.intermine.api.profile.TagManager; import org.intermine.api.profile.TagManagerFactory; import org.intermine.api.tag.TagNames; import org.intermine.api.tag.TagTypes; import org.intermine.metadata.ClassDescriptor; import org.intermine.metadata.Model; import org.intermine.model.userprofile.Tag; import org.intermine.objectstore.ObjectStore; import org.intermine.objectstore.query.ObjectStoreBag; import org.intermine.objectstore.query.ObjectStoreBagsForObject; import org.intermine.objectstore.query.Query; import org.intermine.objectstore.query.Results; /** * A BagManager provides access to all global and/or user bags and methods to fetch them by * type, etc. * @author Richard Smith * */ public class BagManager { private static final Logger LOG = Logger.getLogger(BagManager.class); private Profile superProfile; private final TagManager tagManager; private final Model model; private ObjectStore osProduction; /** * The BagManager references the super user profile to fetch global bags. * @param superProfile the super user profile * @param model the object model */ public BagManager(Profile superProfile, Model model) { this.superProfile = superProfile; if (superProfile == null) { String msg = "Unable to retrieve superuser profile. Check that the superuser profile " + "in the MINE.properties file matches the superuser in the userprofile database."; LOG.error(msg); throw new RuntimeException(msg); } this.model = model; this.tagManager = new TagManagerFactory(superProfile.getProfileManager()).getTagManager(); this.osProduction = superProfile.getProfileManager().getProductionObjectStore(); } /** * Fetch globally available bags - superuser public bags that are available to everyone. * @return a map from bag name to bag */ public Map<String, InterMineBag> getGlobalBags() { return getBagsWithTag(superProfile, TagNames.IM_PUBLIC); } /** * Fetch bags from given protocol with a particular tag assigned to them. * @param profile the user to fetch bags from * @param tag the tag to filter * @return a map from bag name to bag */ protected Map<String, InterMineBag> getBagsWithTag(Profile profile, String tag) { Map<String, InterMineBag> bagsWithTag = new HashMap<String, InterMineBag>(); for (Map.Entry<String, InterMineBag> entry : profile.getSavedBags().entrySet()) { InterMineBag bag = entry.getValue(); List<Tag> tags = tagManager.getTags(tag, bag.getName(), TagTypes.BAG, profile.getUsername()); if (tags.size() > 0) { bagsWithTag.put(entry.getKey(), entry.getValue()); } } return bagsWithTag; } /** * Fetch bags for the given profile. * @param profile the user to fetch bags for * @return a map from bag name to bag */ public Map<String, InterMineBag> getUserBags(Profile profile) { return profile.getSavedBags(); } /** * Fetch all global bags and user bags combined in the same map. If user has a bag with the * same name as a global bag the user's bag takes precedence. * @param profile the user to fetch bags for * @return a map from bag name to bag */ public Map<String, InterMineBag> getUserAndGlobalBags(Profile profile) { // add global bags first, any user bags with same name take precedence Map<String, InterMineBag> allBags = new HashMap<String, InterMineBag>(); allBags.putAll(getGlobalBags()); allBags.putAll(profile.getSavedBags()); return allBags; } /** * Fetch a global bag by name. * @param bagName the name of bag to fetch * @return the bag or null if not found */ public InterMineBag getGlobalBag(String bagName) { return getGlobalBags().get(bagName); } /** * Fetch a user bag by name. * @param profile the user to fetch bags for * @param bagName the name of bag to fetch * @return the bag or null if not found */ public InterMineBag getUserBag(Profile profile, String bagName) { return getUserBags(profile).get(bagName); } /** * Fetch a global or user bag by name. If user has a bag with the same name as a global bag * the user's bag takes precedence. * @param profile the user to fetch bags for * @param bagName the name of bag to fetch * @return the bag or null if not found */ public InterMineBag getUserOrGlobalBag(Profile profile, String bagName) { return getUserAndGlobalBags(profile).get(bagName); } /** * Fetch global and user bags of the specified type or a subclass of the specified type. * @param profile the user to fetch bags for * @param type an unqualified class name * @return a map from bag name to bag */ public Map<String, InterMineBag> getUserOrGlobalBagsOfType(Profile profile, String type) { Set<String> classAndSubs = new HashSet<String>(); classAndSubs.add(type); ClassDescriptor bagTypeCld = model.getClassDescriptorByName(type); if (bagTypeCld == null) { throw new NullPointerException("Could not find ClassDescriptor for name " + type); } for (ClassDescriptor cld : model.getAllSubs(bagTypeCld)) { classAndSubs.add(cld.getUnqualifiedName()); } Map<String, InterMineBag> bagsOfType = new HashMap<String, InterMineBag>(); for (Map.Entry<String, InterMineBag> entry : getUserAndGlobalBags(profile).entrySet()) { InterMineBag bag = entry.getValue(); if (classAndSubs.contains(bag.getType())) { bagsOfType.put(entry.getKey(), bag); } } return bagsOfType; } /** * Fetch global bags that contain the given id. * @param id the id to search bags for * @return bags containing the given id */ public Collection<InterMineBag> getGlobalBagsContainingId(Integer id) { return getBagsContainingId(getGlobalBags(), id); } /** * Fetch user bags that contain the given id. * @param id the id to search bags for * @param profile the user to fetch bags from * @return bags containing the given id */ public Collection<InterMineBag> getUserBagsContainingId(Profile profile, Integer id) { return getBagsContainingId(getUserBags(profile), id); } /** * Fetch user or global bags that contain the given id. If user has a bag with the same name * as a global bag the user's bag takes precedence. * @param id the id to search bags for * @param profile the user to fetch bags from * @return bags containing the given id */ public Collection<InterMineBag> getUserOrGlobalBagsContainingId(Profile profile, Integer id) { HashSet<InterMineBag> bagsContainingId = new HashSet<InterMineBag>(); bagsContainingId.addAll(getGlobalBagsContainingId(id)); System.out.println("superuser:" + bagsContainingId.size()); bagsContainingId.addAll(getUserBagsContainingId(profile, id)); System.out.println("user:" + bagsContainingId.size()); return bagsContainingId; } private Collection<InterMineBag> getBagsContainingId(Map<String, InterMineBag> imBags, Integer id) { Collection<ObjectStoreBag> objectStoreBags = getObjectStoreBags(imBags.values()); Map<Integer, InterMineBag> osBagIdToInterMineBag = getOsBagIdToInterMineBag(imBags.values()); // this searches bags for an object ObjectStoreBagsForObject osbo = new ObjectStoreBagsForObject(id, objectStoreBags); // run query Query q = new Query(); q.addToSelect(osbo); Collection<InterMineBag> bagsContainingId = new HashSet<InterMineBag>(); // this should return all bags with that object Results res = osProduction.executeSingleton(q); Iterator<Object> resIter = res.iterator(); while (resIter.hasNext()) { Integer osBagId = (Integer) resIter.next(); bagsContainingId.add(osBagIdToInterMineBag.get(osBagId)); } return bagsContainingId; } private Map<Integer, InterMineBag> getOsBagIdToInterMineBag(Collection<InterMineBag> imBags) { Map<Integer, InterMineBag> osBagIdToInterMineBag = new HashMap<Integer, InterMineBag>(); for (InterMineBag imBag : imBags) { osBagIdToInterMineBag.put(imBag.getOsb().getBagId(), imBag); } return osBagIdToInterMineBag; } private Collection<ObjectStoreBag> getObjectStoreBags(Collection<InterMineBag> imBags) { Set<ObjectStoreBag> objectStoreBags = new HashSet<ObjectStoreBag>(); for (InterMineBag imBag : imBags) { objectStoreBags.add(imBag.getOsb()); } return objectStoreBags; } }
commented out log message (in catalina.out) Former-commit-id: 467afc802ce5ecbe7257469738490c36639bd781
intermine/api/main/src/org/intermine/api/bag/BagManager.java
commented out log message (in catalina.out)
<ide><path>ntermine/api/main/src/org/intermine/api/bag/BagManager.java <ide> public Collection<InterMineBag> getUserOrGlobalBagsContainingId(Profile profile, Integer id) { <ide> HashSet<InterMineBag> bagsContainingId = new HashSet<InterMineBag>(); <ide> bagsContainingId.addAll(getGlobalBagsContainingId(id)); <del> System.out.println("superuser:" + bagsContainingId.size()); <add> // System.out.println("superuser:" + bagsContainingId.size()); <ide> bagsContainingId.addAll(getUserBagsContainingId(profile, id)); <del> System.out.println("user:" + bagsContainingId.size()); <add> // System.out.println("user:" + bagsContainingId.size()); <ide> return bagsContainingId; <ide> } <ide>
JavaScript
apache-2.0
eacad12008dae648c6118b699265b872456a6062
0
wildfly-swarm/wildfly-swarm-topology-webapp,wildfly-swarm/wildfly-swarm-topology-webapp
var topology = (function() { var defaults = { headers: {}, method: 'GET', keycloak: false, keycloakUpdateInterval: 30, context: '/topology' }, topology = {}, scheduler; function factory( options ) { options = merge(defaults, options); function ajax( serviceName, path, settings ) { var nextServer = scheduler.next(serviceName), deferredResult = deferred(), keycloak = options.keycloak; if (!nextServer) { return deferredResult.reject('No servers available').promise; } // ensure some default settings exist settings = merge({ method: options.method, headers: options.headers, data: undefined }, settings); path = path || '/'; settings.url = '//' + nextServer.endpoint + path; // Set relevant headers if (settings.method === 'POST') { settings.headers['Content-Type'] = 'application/json'; } if (!keycloak || !keycloak.authenticated) { // If we're not authenticating, go ahead and make the request return doRequest( settings ); } else { // TODO: Make token update interval configurable keycloak.updateToken(30).success( function() { console.log( "topology.js: keycloak token refreshed" ); // Using keycloak, update token, and make the request settings.headers.Authorization = 'Bearer ' + keycloak.token; // make the request doRequest( settings ).then( function(result) { deferredResult.resolve(result); }); }).error( function(e) { console.log( "topology.js: Failed to update keycloak token. " + e ); deferredResult.reject('Failed to update keycloak token. ' + e); }); } return deferredResult.promise; } function doRequest(settings) { var request = new XMLHttpRequest(), deferredResponse = deferred(); // set the state change handler and open the http request request.onreadystatechange = changeState(request, deferredResponse); request.open(settings.method, settings.url); getHeaders(settings.headers).forEach(function(header) { request.setRequestHeader(header.field, header.value); }); if (settings.data) request.send(settings.data); else request.send(); // return a deferred promise return deferredResponse; function changeState(request, deferredResponse) { return function() { switch(request.readyState) { case 0: case 1: case 2: case 3: break; case 4: processResponse(request, deferredResponse); break; default: console.log('topology.js: Unexpected XMLHttpRequest state'); deferred.reject('Unexpected XMLHttpRequst state'); } }; } function processResponse(request, response) { if (request.status === 200) { response.resolve(JSON.parse(request.responseText)); } else { response.reject('topology.js: Bad request: ' + request.statusText); } } function getHeaders(headers) { var headerList = []; for (var key in headers) { if (headers.hasOwnProperty(key)) { headerList.push({ field: key, value: headers[key] }); } } return headerList; } } function getJSON(serviceName, path, data) { //var _data = (typeof data === 'string') ? data : JSON.stringify(data); var qs = '?'; for (var k in data) { if (data.hasOwnProperty(k)) { qs += k + '=' + data[k]; } } if ( typeof(path) == 'undefined' ) { path = '/'; } path = path + qs; return ajax( serviceName, path ); } function postJSON(serviceName, path, data) { if (typeof path === 'object') { data = path; path = '/'; } var _data = (typeof data === 'string') ? data : JSON.stringify(data); return ajax( serviceName, path, { method: 'POST', data: _data }); } function schedule(initialState) { var o = { next: next }, topology = parseInitialState(initialState); function next(serviceName) { var service = topology[serviceName]; if (!service || service.length < 1) return null; return service.next(); } function parseInitialState(initialState) { var o = {}; for(var key in initialState) { if (initialState[key] && initialState.hasOwnProperty(key)) { o[key] = { instances: initialState[key], currentIndex: 0, length: initialState[key].length }; o[key].next = increment(o[key]); } } function increment(o) { return function() { var index = o.currentIndex, _next = o.instances[index]; o.currentIndex = ++index % o.length; return _next; }; } return o; } return o; } var sse = new EventSource( options.context + "/system/stream" ); sse.addEventListener('topologyChange', function(message) { console.log('topology.js: topology changed: ', message.data); topology = JSON.parse(message.data); scheduler = schedule(topology); }); sse.onerror = function(e) { console.log( "topology.js: topology SSE error", e ); }; function onTopologyChange(f) { sse.addEventListener('topologyChange', function(message) { f(JSON.parse(message.data)); }); f(topology); } var _topology = { ajax: ajax, postJSON: postJSON, getJSON: getJSON, onTopologyChange: onTopologyChange }; Object.defineProperty(_topology, 'topology', { get: function() { return topology; }, enumerable: true }); Object.freeze(_topology); return _topology; } function merge(defaults, provided) { var obj = {}; if (!provided) provided = {}; for (var key in defaults) { if (defaults.hasOwnProperty(key)) obj[key] = provided[key] || defaults[key]; } return obj; } function promises() { var PENDING = 0, FULFILLED = 1, REJECTED = 2; function promise(fn) { var p = { state: PENDING, identify: 'fidelity', value: null, queue: [], handlers: { fulfill: null, reject: null } }; p.then = then(p); if (isA('function', fn)) { fn( function(v) { resolve(p, v); }, function(r) { reject(p, r); } ); } return p; } function then(p) { return function(onFulfilled, onRejected) { var q = promise(); if (isA('function', onFulfilled)) { q.handlers.fulfill = onFulfilled; } if (isA('function', onRejected)) { q.handlers.reject = onRejected; } p.queue.push(q); process(p); return q; }; } function resolve(p, x) { if (x === p) reject(p, new TypeError('The promise and its value are the same.')); if (isPromise(x)) { if (x.state === PENDING) { x.then(function(value) { resolve(p, value); }, function(cause) { reject(p, cause); }); } else { transition(p, x.state, x.value); } } else if (isA('function', x) || isA('object', x)) { var called = false, thenFunction; try { thenFunction = x.then; if (isA('function', thenFunction)) { thenFunction.call(x, function(y) { if (!called) { resolve(p, y); called = true; } }, function (r) { if (!called) { reject(p, r); called = true; } }); } else { fulfill(p, x); called = true; } } catch (e) { if (!called) { reject(p, e); called = true; } } } else fulfill(p, x); } function fulfill(p, result) { transition(p, FULFILLED, result); } function reject(p, cause) { transition(p, REJECTED, cause); } function defaultFulfill(v) { return v; } function defaultReject(r) { throw r; } function process(p) { if (p.state === PENDING) return; setTimeout(function() { while(p.queue.length) { var qp = p.queue.shift(), handler, value; if (p.state === FULFILLED) { handler = qp.handlers.fulfill || defaultFulfill; } else if (p.state === REJECTED) { handler = qp.handlers.reject || defaultReject; } try { value = handler(p.value); } catch(e) { transition(qp, REJECTED, e); continue; } resolve(qp, value); } }, 0); } function transition(p, state, value) { if (p.state === state || p.state !== PENDING || arguments.length !== 3) return; p.state = state; p.value = value; process(p); } function isA(type, x) { return x && typeof x === type; } function isPromise(x) { return x && x.identify === 'fidelity'; } promise.PENDING = PENDING; promise.FULFILLED = FULFILLED; promise.REJECTED = REJECTED; return promise; } var promise = promises(), deferred = function() { var resolver, rejecter, p = promise(function(resolve, reject) { resolver = resolve; rejecter = reject; }); function resolve(value) { resolver(value); return this; } function reject(cause) { rejecter(cause); return this; } return { promise: p, resolve: resolve, reject: reject, then: p.then }; }; return factory; })();
runtime/src/main/resources/topology.js
var topology = (function() { var defaults = { headers: {}, method: 'GET', keycloak: false, keycloakUpdateInterval: 30, context: '/topology' }, topology = {}; function factory( options ) { options = merge(defaults, options); function ajax( serviceName, path, settings ) { var allServers = topology[serviceName], deferredResult = deferred(), keycloak = options.keycloak; if (!allServers || allServers.length < 1 ) { return deferredResult.reject('No servers available').promise; } // ensure some default settings exist settings = merge({ method: options.method, headers: options.headers, data: undefined }, settings); path = path || '/'; // TODO: Try other URLs if there is more than one server settings.url = '//' + allServers[0].endpoint + path; // Set relevant headers if (settings.method === 'POST') { settings.headers['Content-Type'] = 'application/json'; } if (!keycloak || !keycloak.authenticated) { // If we're not authenticating, go ahead and make the request return doRequest( settings ); } else { // TODO: Make token update interval configurable keycloak.updateToken(30).success( function() { console.log( "topology.js: keycloak token refreshed" ); // Using keycloak, update token, and make the request settings.headers.Authorization = 'Bearer ' + keycloak.token; // make the request doRequest( settings ).then( function(result) { deferredResult.resolve(result); }); }).error( function(e) { console.log( "topology.js: Failed to update keycloak token. " + e ); deferredResult.reject('Failed to update keycloak token. ' + e); }); } return deferredResult.promise; } function doRequest(settings) { var request = new XMLHttpRequest(), deferredResponse = deferred(); // set the state change handler and open the http request request.onreadystatechange = changeState(request, deferredResponse); request.open(settings.method, settings.url); getHeaders(settings.headers).forEach(function(header) { request.setRequestHeader(header.field, header.value); }); if (settings.data) request.send(settings.data); else request.send(); // return a deferred promise return deferredResponse; function changeState(request, deferredResponse) { return function() { switch(request.readyState) { case 0: case 1: case 2: case 3: break; case 4: processResponse(request, deferredResponse); break; default: console.log('topology.js: Unexpected XMLHttpRequest state'); deferred.reject('Unexpected XMLHttpRequst state'); } }; } function processResponse(request, response) { if (request.status === 200) { response.resolve(JSON.parse(request.responseText)); } else { response.reject('topology.js: Bad request: ' + request.statusText); } } function getHeaders(headers) { var headerList = []; for (var key in headers) { if (headers.hasOwnProperty(key)) { headerList.push({ field: key, value: headers[key] }); } } return headerList; } } function getJSON(serviceName, path, data) { //var _data = (typeof data === 'string') ? data : JSON.stringify(data); var qs = '?'; for (var k in data) { if (data.hasOwnProperty(k)) { qs += k + '=' + data[k]; } } if ( typeof(path) == 'undefined' ) { path = '/'; } path = path + qs; return ajax( serviceName, path ); } function postJSON(serviceName, path, data) { if (typeof path === 'object') { data = path; path = '/'; } var _data = (typeof data === 'string') ? data : JSON.stringify(data); return ajax( serviceName, path, { method: 'POST', data: _data }); } var sse = new EventSource( options.context + "/system/stream" ); sse.addEventListener('topologyChange', function(message) { console.log('topology.js: topology changed: ', message.data); topology = JSON.parse(message.data); }); sse.onerror = function(e) { console.log( "topology.js: topology SSE error", e ); }; function onTopologyChange(f) { sse.addEventListener('topologyChange', function(message) { f(JSON.parse(message.data)); }); f(topology); } var _topology = { ajax: ajax, postJSON: postJSON, getJSON: getJSON, onTopologyChange: onTopologyChange }; Object.defineProperty(_topology, 'topology', { get: function() { return topology; }, enumerable: true }); Object.freeze(_topology); return _topology; } function merge(defaults, provided) { var obj = {}; if (!provided) provided = {}; for (var key in defaults) { if (defaults.hasOwnProperty(key)) obj[key] = provided[key] || defaults[key]; } return obj; } function promises() { var PENDING = 0, FULFILLED = 1, REJECTED = 2; function promise(fn) { var p = { state: PENDING, identify: 'fidelity', value: null, queue: [], handlers: { fulfill: null, reject: null } }; p.then = then(p); if (isA('function', fn)) { fn( function(v) { resolve(p, v); }, function(r) { reject(p, r); } ); } return p; } function then(p) { return function(onFulfilled, onRejected) { var q = promise(); if (isA('function', onFulfilled)) { q.handlers.fulfill = onFulfilled; } if (isA('function', onRejected)) { q.handlers.reject = onRejected; } p.queue.push(q); process(p); return q; }; } function resolve(p, x) { if (x === p) reject(p, new TypeError('The promise and its value are the same.')); if (isPromise(x)) { if (x.state === PENDING) { x.then(function(value) { resolve(p, value); }, function(cause) { reject(p, cause); }); } else { transition(p, x.state, x.value); } } else if (isA('function', x) || isA('object', x)) { var called = false, thenFunction; try { thenFunction = x.then; if (isA('function', thenFunction)) { thenFunction.call(x, function(y) { if (!called) { resolve(p, y); called = true; } }, function (r) { if (!called) { reject(p, r); called = true; } }); } else { fulfill(p, x); called = true; } } catch (e) { if (!called) { reject(p, e); called = true; } } } else fulfill(p, x); } function fulfill(p, result) { transition(p, FULFILLED, result); } function reject(p, cause) { transition(p, REJECTED, cause); } function defaultFulfill(v) { return v; } function defaultReject(r) { throw r; } function process(p) { if (p.state === PENDING) return; setTimeout(function() { while(p.queue.length) { var qp = p.queue.shift(), handler, value; if (p.state === FULFILLED) { handler = qp.handlers.fulfill || defaultFulfill; } else if (p.state === REJECTED) { handler = qp.handlers.reject || defaultReject; } try { value = handler(p.value); } catch(e) { transition(qp, REJECTED, e); continue; } resolve(qp, value); } }, 0); } function transition(p, state, value) { if (p.state === state || p.state !== PENDING || arguments.length !== 3) return; p.state = state; p.value = value; process(p); } function isA(type, x) { return x && typeof x === type; } function isPromise(x) { return x && x.identify === 'fidelity'; } promise.PENDING = PENDING; promise.FULFILLED = FULFILLED; promise.REJECTED = REJECTED; return promise; } var promise = promises(), deferred = function() { var resolver, rejecter, p = promise(function(resolve, reject) { resolver = resolve; rejecter = reject; }); function resolve(value) { resolver(value); return this; } function reject(cause) { rejecter(cause); return this; } return { promise: p, resolve: resolve, reject: reject, then: p.then }; }; return factory; })();
SWARM-247: Provide scheduling for topology-webapp. Motivation: This commit addresses SWARM-247 (Improve load balancing for ribbon-webapp). The fraction is now known as topology-webapp. The client side JavaScript in this fraction was pretty stupid about utilizing multiple hosts for a given service name. It only ever used the first one it found. Modifications: Added a simple round robin scheduler to topology.js so that clients will now take advantage of an admittedly simple scheduler, instead of always hitting the same endpoint for a given service. The public facing side of the topology.js API did not change. Result: Clients will now automatically round robin requests to ribbon services at multiple endpoints.
runtime/src/main/resources/topology.js
SWARM-247: Provide scheduling for topology-webapp.
<ide><path>untime/src/main/resources/topology.js <ide> keycloak: false, <ide> keycloakUpdateInterval: 30, <ide> context: '/topology' <del> }, topology = {}; <add> }, topology = {}, scheduler; <ide> <ide> function factory( options ) { <ide> options = merge(defaults, options); <ide> <ide> function ajax( serviceName, path, settings ) { <del> var allServers = topology[serviceName], <add> var nextServer = scheduler.next(serviceName), <ide> deferredResult = deferred(), <ide> keycloak = options.keycloak; <ide> <del> if (!allServers || allServers.length < 1 ) { <add> if (!nextServer) { <ide> return deferredResult.reject('No servers available').promise; <ide> } <ide> <ide> }, settings); <ide> <ide> path = path || '/'; <del> <del> // TODO: Try other URLs if there is more than one server <del> settings.url = '//' + allServers[0].endpoint + path; <add> settings.url = '//' + nextServer.endpoint + path; <ide> <ide> // Set relevant headers <ide> if (settings.method === 'POST') { <ide> }); <ide> } <ide> <add> function schedule(initialState) { <add> var o = { <add> next: next <add> }, topology = parseInitialState(initialState); <add> <add> function next(serviceName) { <add> var service = topology[serviceName]; <add> if (!service || service.length < 1) return null; <add> return service.next(); <add> } <add> <add> function parseInitialState(initialState) { <add> var o = {}; <add> for(var key in initialState) { <add> if (initialState[key] && initialState.hasOwnProperty(key)) { <add> o[key] = { <add> instances: initialState[key], <add> currentIndex: 0, <add> length: initialState[key].length <add> }; <add> o[key].next = increment(o[key]); <add> } <add> } <add> <add> function increment(o) { <add> return function() { <add> var index = o.currentIndex, <add> _next = o.instances[index]; <add> o.currentIndex = ++index % o.length; <add> return _next; <add> }; <add> } <add> return o; <add> } <add> <add> return o; <add> } <add> <add> <ide> var sse = new EventSource( options.context + "/system/stream" ); <ide> sse.addEventListener('topologyChange', function(message) { <ide> console.log('topology.js: topology changed: ', message.data); <ide> topology = JSON.parse(message.data); <add> scheduler = schedule(topology); <ide> }); <ide> <ide> sse.onerror = function(e) {
Java
epl-1.0
014c30245b8a78ca9d134d61d302a4e2cedc8d99
0
gnodet/wikitext
/******************************************************************************* * Copyright (c) 2005, 2007 Mylyn project committers and others. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/epl-v10.html *******************************************************************************/ package org.eclipse.mylyn.jira.tests; import java.io.IOException; import java.io.Reader; import java.io.StringReader; import junit.framework.TestCase; import org.eclipse.mylyn.internal.jira.ui.html.HTML2TextReader; /** * @author Steffen Pingel * @author George Lindholm */ public class HTML2TextReaderTest extends TestCase { public void testReadOnlyWhitespacesWithSkip() throws Exception { String text = " "; StringReader stringReader = new StringReader(text); HTML2TextReader html2TextReader = new HTML2TextReader(stringReader, null) { @Override public int read(char[] cbuf, int off, int len) throws IOException { setSkipWhitespace(true); return super.read(cbuf, off, len); } }; char[] chars = new char[text.length()]; int len = html2TextReader.read(chars, 0, text.length()); assertEquals(-1, len); } public void testReadOnlyWhitespaces() throws Exception { String text = " "; StringReader stringReader = new StringReader(text); HTML2TextReader html2TextReader = new HTML2TextReader(stringReader, null); char[] chars = new char[text.length()]; int len = html2TextReader.read(chars, 0, text.length()); assertEquals(1, len); assertEquals(" ", new String(chars, 0, len)); text = "&nbsp;"; stringReader = new StringReader(text); html2TextReader = new HTML2TextReader(stringReader, null); chars = new char[text.length()]; len = html2TextReader.read(chars, 0, text.length()); assertEquals(1, len); assertEquals(" ", new String(chars, 0, len)); } public void testHeadCpuLoop() throws IOException { assertEquals("b ", read("b <head> a ")); assertEquals("b ", read("b <head> a </head>")); } public void testPreCpuLoop() throws IOException { assertEquals("b b ", read("b <pre> b ")); assertEquals("b b ", read("b <pre> b </pre>")); } private String read(final String text) throws IOException { Reader stringReader = new StringReader(text); HTML2TextReader html2TextReader = new HTML2TextReader(stringReader, null); char[] chars = new char[text.length()]; int len = html2TextReader.read(chars, 0, chars.length); return new String(chars, 0, len); } }
org.eclipse.mylyn.jira.tests/src/org/eclipse/mylyn/jira/tests/HTML2TextReaderTest.java
/******************************************************************************* * Copyright (c) 2005, 2007 Mylyn project committers and others. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/epl-v10.html *******************************************************************************/ package org.eclipse.mylyn.jira.tests; import java.io.IOException; import java.io.Reader; import java.io.StringReader; import junit.framework.TestCase; import org.eclipse.mylyn.internal.jira.ui.html.HTML2TextReader; /** * @author Steffen Pingel * @author George Lindholm */ public class HTML2TextReaderTest extends TestCase { public void testReadOnlyWhitespacesWithSkip() throws Exception { String text = " "; StringReader stringReader = new StringReader(text); HTML2TextReader html2TextReader = new HTML2TextReader(stringReader, null) { @Override public int read(char[] cbuf, int off, int len) throws IOException { setSkipWhitespace(true); return super.read(cbuf, off, len); } }; char[] chars = new char[text.length()]; int len = html2TextReader.read(chars, 0, text.length()); assertEquals(-1, len); } public void testReadOnlyWhitespaces() throws Exception { String text = " "; StringReader stringReader = new StringReader(text); HTML2TextReader html2TextReader = new HTML2TextReader(stringReader, null); char[] chars = new char[text.length()]; int len = html2TextReader.read(chars, 0, text.length()); assertEquals(1, len); assertEquals(" ", new String(chars, 0, len)); text = "&nbsp;"; stringReader = new StringReader(text); html2TextReader = new HTML2TextReader(stringReader, null); chars = new char[text.length()]; len = html2TextReader.read(chars, 0, text.length()); assertEquals(1, len); assertEquals(" ", new String(chars, 0, len)); } public void testHeadCpuLoop() throws IOException { assertEquals("b <head> a ", "b <head> a "); } public void testPreCpuLoop() throws IOException { assertEquals("b b ", read("b <pre> b ")); } private String read(final String text) throws IOException { Reader stringReader = new StringReader(text); HTML2TextReader html2TextReader = new HTML2TextReader(stringReader, null); char[] chars = new char[text.length()]; int len = html2TextReader.read(chars, 0, chars.length); return new String(chars, 0, len); } }
NEW - bug 207567: HTML2Text reader get stuck in infinite loop https://bugs.eclipse.org/bugs/show_bug.cgi?id=207567
org.eclipse.mylyn.jira.tests/src/org/eclipse/mylyn/jira/tests/HTML2TextReaderTest.java
NEW - bug 207567: HTML2Text reader get stuck in infinite loop https://bugs.eclipse.org/bugs/show_bug.cgi?id=207567
<ide><path>rg.eclipse.mylyn.jira.tests/src/org/eclipse/mylyn/jira/tests/HTML2TextReaderTest.java <ide> } <ide> <ide> public void testHeadCpuLoop() throws IOException { <del> assertEquals("b <head> a ", "b <head> a "); <add> assertEquals("b ", read("b <head> a ")); <add> assertEquals("b ", read("b <head> a </head>")); <ide> } <ide> <ide> public void testPreCpuLoop() throws IOException { <ide> assertEquals("b b ", read("b <pre> b ")); <add> assertEquals("b b ", read("b <pre> b </pre>")); <ide> } <ide> <ide> private String read(final String text) throws IOException {
Java
apache-2.0
d08d21a2e14d91de0ad924b86a9aab72d4c565ff
0
adligo/models_core.adligo.org
package org.adligo.models.core.client; import org.adligo.i.util.client.ClassUtils; import org.adligo.i.util.client.StringUtils; import org.adligo.models.core.client.ids.I_StorageIdentifier; import org.adligo.models.core.client.ids.StorageIdentifierValidator; import org.adligo.models.core.client.ids.VersionValidator; public class OrganizationMutant extends ChangeableMutant implements I_OrganizationMutant { /** * */ private static final long serialVersionUID = 1L; public static final String SET_NAME = "setName"; public static final String SET_TYPE = "setType"; public static final String ORGANIZAITION = "Organization"; private String name; /** * the type pertains to something like a School, Band, Company * to be defined depending on your problem domain */ private I_StorageIdentifier type; /** * custom info specific to your system */ private I_CustomInfo customInfo; /** * for gwt serialization */ public OrganizationMutant() {} public OrganizationMutant(I_Organization p) throws InvalidParameterException { super(p); try { if (p.getId() != null) { setId(p.getId()); } //this may come from a unversioned system Integer version = p.getVersion(); if (version != null) { setVersion(version); } I_StorageInfo storageInfo = p.getStorageInfo(); if (storageInfo != null) { setStorageInfo(storageInfo); } setName(p.getName()); setType(p.getType()); I_CustomInfo customInfo = p.getCustomInfo(); if (customInfo != null) { setCustomInfo(customInfo); } } catch (InvalidParameterException x) { InvalidParameterException ipe = new InvalidParameterException( x.getMessage(), ORGANIZAITION, x); throw ipe; } } public String getName() { return name; } public void setName(String p) throws InvalidParameterException { if (StringUtils.isEmpty(p)) { throw new InvalidParameterException(ModelsCoreConstantsObtainer.getConstants() .getOrgEmptyNameError(),SET_NAME); } name = p; } /* (non-Javadoc) * @see org.adligo.models.core.client.I_Org#getType() */ public I_StorageIdentifier getType() { return type; } public void setType(I_StorageIdentifier p) throws InvalidParameterException { if (p == null) { throw new InvalidParameterException(ModelsCoreConstantsObtainer.getConstants() .getOrgEmptyTypeError(),SET_TYPE); } if (!p.hasValue()) { throw new InvalidParameterException(ModelsCoreConstantsObtainer.getConstants() .getOrgEmptyTypeError(),SET_TYPE); } type = p; } public void isValid() throws ValidationException { StorableValidator.validate(this, I_Validateable.IS_VALID); try { OrganizationMutant other = new OrganizationMutant(); other.setName(getName()); other.setType(getType()); if (customInfo != null) { if (customInfo.isValidatable()) { ((I_Validateable) customInfo).isValid(); } } } catch (InvalidParameterException e) { throw new ValidationException(e.getMessage(), I_Validateable.IS_VALID, e); } } public int hashCode() { return genHashCode(this); } public static int genHashCode(I_Organization me) { final int prime = 31; int result = 1; String name = me.getName(); I_StorageIdentifier type = me.getType(); result = prime * result + ((name == null) ? 0 : name.hashCode()); result = prime * result + ((type == null) ? 0 : type.hashCode()); return result; } public boolean equals(Object obj) { if (this == obj) return true; if (obj == null) return false; try { return equals(this, (I_Organization) obj); } catch (ClassCastException x) { //eat gwt doesn't impl instance of } return false; } public static boolean equals(I_Organization me, I_Organization other) { if (me.getName() == null) { if (other.getName() != null) return false; } else if (!me.getName().equals(other.getName())) return false; if (me.getType() == null) { if (other.getType() != null) return false; } else if (!me.getType().equals(other.getType())) return false; return true; } public String toString() { return toString(this.getClass(),this); } public String toString(Class c, I_Organization p) { StringBuffer sb = new StringBuffer(); sb.append(ClassUtils.getClassShortName(c)); sb.append(" [name="); sb.append(p.getName()); sb.append(",type="); sb.append(p.getType()); sb.append(",id="); sb.append(p.getId()); sb.append(",customInfo="); sb.append(p.getCustomInfo()); sb.append(",storageInfo="); sb.append(p.getStorageInfo()); sb.append("]"); return sb.toString(); } public I_CustomInfo getCustomInfo() { return customInfo; } public void setCustomInfo(I_CustomInfo customInfo) throws InvalidParameterException { try { this.customInfo = customInfo.toMutant(); } catch (ValidationException ve) { throw new InvalidParameterException(ve); } } public I_Organization toImmutable() throws ValidationException { try { return new Organization(this); } catch (InvalidParameterException ipe) { throw new ValidationException(ipe); } } public I_OrganizationMutant toMutant() throws ValidationException { return this; } public boolean isStored() throws ValidationException { return StorableValidator.validate(this, I_Storable.IS_STORED); } }
src/org/adligo/models/core/client/OrganizationMutant.java
package org.adligo.models.core.client; import org.adligo.i.util.client.ClassUtils; import org.adligo.i.util.client.StringUtils; import org.adligo.models.core.client.ids.I_StorageIdentifier; import org.adligo.models.core.client.ids.StorageIdentifierValidator; import org.adligo.models.core.client.ids.VersionValidator; public class OrganizationMutant extends ChangeableMutant implements I_OrganizationMutant { /** * */ private static final long serialVersionUID = 1L; public static final String SET_NAME = "setName"; public static final String SET_TYPE = "setType"; public static final String ORGANIZAITION = "Organization"; private String name; /** * the type pertains to something like a School, Band, Company * to be defined depending on your problem domain */ private I_StorageIdentifier type; /** * custom info specific to your system */ private I_CustomInfo customInfo; /** * for gwt serialization */ public OrganizationMutant() {} public OrganizationMutant(I_Organization p) throws InvalidParameterException { super(p); try { if (p.getId() != null) { setId(p.getId()); } //this may come from a unversioned system Integer version = p.getVersion(); if (version != null) { setVersion(version); } I_StorageInfo storageInfo = p.getStorageInfo(); if (storageInfo != null) { setStorageInfo(storageInfo); } setName(p.getName()); setType(p.getType()); I_CustomInfo customInfo = p.getStorageInfo(); if (customInfo != null) { setCustomInfo(customInfo); } } catch (InvalidParameterException x) { InvalidParameterException ipe = new InvalidParameterException( x.getMessage(), ORGANIZAITION, x); throw ipe; } } public String getName() { return name; } public void setName(String p) throws InvalidParameterException { if (StringUtils.isEmpty(p)) { throw new InvalidParameterException(ModelsCoreConstantsObtainer.getConstants() .getOrgEmptyNameError(),SET_NAME); } name = p; } /* (non-Javadoc) * @see org.adligo.models.core.client.I_Org#getType() */ public I_StorageIdentifier getType() { return type; } public void setType(I_StorageIdentifier p) throws InvalidParameterException { if (p == null) { throw new InvalidParameterException(ModelsCoreConstantsObtainer.getConstants() .getOrgEmptyTypeError(),SET_TYPE); } if (!p.hasValue()) { throw new InvalidParameterException(ModelsCoreConstantsObtainer.getConstants() .getOrgEmptyTypeError(),SET_TYPE); } type = p; } public void isValid() throws ValidationException { StorableValidator.validate(this, I_Validateable.IS_VALID); try { OrganizationMutant other = new OrganizationMutant(); other.setName(getName()); other.setType(getType()); if (customInfo != null) { if (customInfo.isValidatable()) { ((I_Validateable) customInfo).isValid(); } } } catch (InvalidParameterException e) { throw new ValidationException(e.getMessage(), I_Validateable.IS_VALID, e); } } public int hashCode() { return genHashCode(this); } public static int genHashCode(I_Organization me) { final int prime = 31; int result = 1; String name = me.getName(); I_StorageIdentifier type = me.getType(); result = prime * result + ((name == null) ? 0 : name.hashCode()); result = prime * result + ((type == null) ? 0 : type.hashCode()); return result; } public boolean equals(Object obj) { if (this == obj) return true; if (obj == null) return false; try { return equals(this, (I_Organization) obj); } catch (ClassCastException x) { //eat gwt doesn't impl instance of } return false; } public static boolean equals(I_Organization me, I_Organization other) { if (me.getName() == null) { if (other.getName() != null) return false; } else if (!me.getName().equals(other.getName())) return false; if (me.getType() == null) { if (other.getType() != null) return false; } else if (!me.getType().equals(other.getType())) return false; return true; } public String toString() { return toString(this.getClass(),this); } public String toString(Class c, I_Organization p) { StringBuffer sb = new StringBuffer(); sb.append(ClassUtils.getClassShortName(c)); sb.append(" [name="); sb.append(p.getName()); sb.append(",type="); sb.append(p.getType()); sb.append(",id="); sb.append(p.getId()); sb.append(",customInfo="); sb.append(p.getCustomInfo()); sb.append(",storageInfo="); sb.append(p.getStorageInfo()); sb.append("]"); return sb.toString(); } public I_CustomInfo getCustomInfo() { return customInfo; } public void setCustomInfo(I_CustomInfo customInfo) throws InvalidParameterException { try { this.customInfo = customInfo.toMutant(); } catch (ValidationException ve) { throw new InvalidParameterException(ve); } } public I_Organization toImmutable() throws ValidationException { try { return new Organization(this); } catch (InvalidParameterException ipe) { throw new ValidationException(ipe); } } public I_OrganizationMutant toMutant() throws ValidationException { return this; } public boolean isStored() throws ValidationException { return StorableValidator.validate(this, I_Storable.IS_STORED); } }
fixed old typo
src/org/adligo/models/core/client/OrganizationMutant.java
fixed old typo
<ide><path>rc/org/adligo/models/core/client/OrganizationMutant.java <ide> setName(p.getName()); <ide> setType(p.getType()); <ide> <del> I_CustomInfo customInfo = p.getStorageInfo(); <add> I_CustomInfo customInfo = p.getCustomInfo(); <ide> if (customInfo != null) { <ide> setCustomInfo(customInfo); <ide> }
Java
apache-2.0
05c7c629441a0eac5942a50492f88e17c3749c40
0
richkadel/cesium-gwt,richkadel/cesium-gwt,richkadel/cesium-gwt
package org.cesiumjs.cesium; import com.google.gwt.core.client.JavaScriptObject; import com.google.gwt.dom.client.Element; /** * @author richkadel * */ public final class ScreenSpaceCameraController extends JavaScriptObject { // Overlay types always have protected, zero argument constructors. protected ScreenSpaceCameraController(){} public final native static ScreenSpaceCameraController create(Element canvas, Camera camera) /*-{ return new Cesium.ScreenSpaceCameraController(canvas, camera) }-*/; public native boolean getEnableInputs() /*-{ return this.enableInputs; }-*/; public native void setEnableInputs(boolean enable) /*-{ this.enableInputs = enable; }-*/; public native boolean getEnableLook() /*-{ return this.enableLook; }-*/; public native void setEnableLook(boolean enable) /*-{ this.enableLook = enable; }-*/; public native boolean getEnableRotate() /*-{ return this.enableRotate; }-*/; public native void setEnableRotate(boolean enable) /*-{ this.enableRotate = enable; }-*/; public native boolean getEnableTilt() /*-{ return this.enableTilt; }-*/; public native void setEnableTilt(boolean enable) /*-{ this.enableTilt = enable; }-*/; public native boolean getEnableTranslate() /*-{ return this.enableTranslate; }-*/; public native void setEnableTranslate(boolean enable) /*-{ this.enableTranslate = enable; }-*/; public native boolean getEnableZoom() /*-{ return this.enableZoom; }-*/; public native void setEnableZoom(boolean enable) /*-{ this.enableZoom = enable; }-*/; }
src/main/java/org/cesiumjs/cesium/ScreenSpaceCameraController.java
package org.cesiumjs.cesium; import com.google.gwt.core.client.JavaScriptObject; import com.google.gwt.dom.client.Element; /** * @author richkadel * */ public final class ScreenSpaceCameraController extends JavaScriptObject { // Overlay types always have protected, zero argument constructors. protected ScreenSpaceCameraController(){} public final native static ScreenSpaceCameraController create(Element canvas, Camera camera) /*-{ return new Cesium.ScreenSpaceCameraController(canvas, camera) }-*/; }
Added additional ScreenSpaceCameraController functions
src/main/java/org/cesiumjs/cesium/ScreenSpaceCameraController.java
Added additional ScreenSpaceCameraController functions
<ide><path>rc/main/java/org/cesiumjs/cesium/ScreenSpaceCameraController.java <ide> */ <ide> public final class ScreenSpaceCameraController extends JavaScriptObject { <ide> // Overlay types always have protected, zero argument constructors. <del> protected ScreenSpaceCameraController(){} <add> protected ScreenSpaceCameraController(){} <ide> <del> public final native static ScreenSpaceCameraController create(Element canvas, Camera camera) /*-{ <del> return new Cesium.ScreenSpaceCameraController(canvas, camera) <del> }-*/; <add> public final native static ScreenSpaceCameraController create(Element canvas, Camera camera) /*-{ <add> return new Cesium.ScreenSpaceCameraController(canvas, camera) <add> }-*/; <add> <add> public native boolean getEnableInputs() /*-{ <add> return this.enableInputs; <add> }-*/; <add> <add> public native void setEnableInputs(boolean enable) /*-{ <add> this.enableInputs = enable; <add> }-*/; <add> <add> public native boolean getEnableLook() /*-{ <add> return this.enableLook; <add> }-*/; <add> <add> public native void setEnableLook(boolean enable) /*-{ <add> this.enableLook = enable; <add> }-*/; <add> <add> public native boolean getEnableRotate() /*-{ <add> return this.enableRotate; <add> }-*/; <add> <add> public native void setEnableRotate(boolean enable) /*-{ <add> this.enableRotate = enable; <add> }-*/; <add> <add> public native boolean getEnableTilt() /*-{ <add> return this.enableTilt; <add> }-*/; <add> <add> public native void setEnableTilt(boolean enable) /*-{ <add> this.enableTilt = enable; <add> }-*/; <add> <add> public native boolean getEnableTranslate() /*-{ <add> return this.enableTranslate; <add> }-*/; <add> <add> public native void setEnableTranslate(boolean enable) /*-{ <add> this.enableTranslate = enable; <add> }-*/; <add> <add> public native boolean getEnableZoom() /*-{ <add> return this.enableZoom; <add> }-*/; <add> <add> public native void setEnableZoom(boolean enable) /*-{ <add> this.enableZoom = enable; <add> }-*/; <add> <add> <add> <add> <add> <ide> }
Java
mit
38131305ce96a54b4138e168bfe84b662da14d0b
0
way2muchnoise/refinedstorage,raoulvdberge/refinedstorage,way2muchnoise/refinedstorage,raoulvdberge/refinedstorage
package com.raoulvdberge.refinedstorage.apiimpl.util; import com.google.common.collect.ArrayListMultimap; import com.raoulvdberge.refinedstorage.api.util.IComparer; import com.raoulvdberge.refinedstorage.api.util.IItemStackList; import net.minecraft.item.ItemStack; import net.minecraftforge.oredict.OreDictionary; import javax.annotation.Nonnull; import javax.annotation.Nullable; import java.util.Collection; import java.util.List; import java.util.Map; import java.util.stream.Collectors; public class OreDictedItemStackList implements IItemStackList { private IItemStackList underlyingList; private ArrayListMultimap<Integer, ItemStack> stacks = ArrayListMultimap.create(); private OreDictedItemStackList() {} public OreDictedItemStackList(IItemStackList list) { this.underlyingList = list; initOreDict(); } private void initOreDict() { for (ItemStack stack : underlyingList.getStacks()) { for (int id : OreDictionary.getOreIDs(stack)) { stacks.put(id, stack); } } } @Override public void add(ItemStack stack) { underlyingList.add(stack); ItemStack internalStack = underlyingList.get(stack); if (internalStack != null && internalStack.stackSize == stack.stackSize) { for (int id : OreDictionary.getOreIDs(internalStack)) { stacks.put(id, internalStack); } } } @Override public boolean remove(@Nonnull ItemStack stack, int size, boolean removeIfReachedZero) { boolean rvalue = underlyingList.remove(stack, size, removeIfReachedZero); if (removeIfReachedZero) { localClean(); } return rvalue; } @Override public boolean trackedRemove(@Nonnull ItemStack stack, int size, boolean removeIfReachedZero) { boolean rvalue = underlyingList.trackedRemove(stack, size, removeIfReachedZero); if (removeIfReachedZero) { localClean(); } return rvalue; } @Override public List<ItemStack> getRemoveTracker() { return underlyingList.getRemoveTracker(); } @Override public void undo() { underlyingList.getRemoveTracker().forEach(this::add); underlyingList.getRemoveTracker().clear(); } @Nullable @Override public ItemStack get(@Nonnull ItemStack stack, int flags) { if ((flags & IComparer.COMPARE_OREDICT) == IComparer.COMPARE_OREDICT) { int[] ids = OreDictionary.getOreIDs(stack); for (int id : ids) { List<ItemStack> stacks = this.stacks.get(id); if (stacks != null && !stacks.isEmpty()) { return stacks.get(0); } } } return underlyingList.get(stack, flags); } @Nullable @Override public ItemStack get(int hash) { return underlyingList.get(hash); } @Override public void clear() { underlyingList.clear(); } private void localClean() { List<Map.Entry<Integer, ItemStack>> toRemove = stacks.entries().stream() .filter(entry -> entry.getValue().stackSize <= 0) .collect(Collectors.toList()); toRemove.forEach(entry -> stacks.remove(entry.getKey(), entry.getValue())); } @Override public void clean() { localClean(); underlyingList.clean(); } @Override public boolean isEmpty() { return underlyingList.isEmpty(); } @Nonnull @Override public Collection<ItemStack> getStacks() { return underlyingList.getStacks(); } @Nonnull @Override public IItemStackList copy() { OreDictedItemStackList newList = new OreDictedItemStackList(); newList.underlyingList = this.underlyingList.copy(); for (Map.Entry<Integer, ItemStack> entry : this.stacks.entries()) { newList.stacks.put(entry.getKey(), entry.getValue()); } return newList; } @Nonnull @Override public IItemStackList prepOreDict() { return this; } }
src/main/java/com/raoulvdberge/refinedstorage/apiimpl/util/OreDictedItemStackList.java
package com.raoulvdberge.refinedstorage.apiimpl.util; import com.google.common.collect.ArrayListMultimap; import com.raoulvdberge.refinedstorage.api.util.IComparer; import com.raoulvdberge.refinedstorage.api.util.IItemStackList; import net.minecraft.item.ItemStack; import net.minecraftforge.oredict.OreDictionary; import javax.annotation.Nonnull; import javax.annotation.Nullable; import java.util.Collection; import java.util.List; import java.util.Map; import java.util.stream.Collectors; public class OreDictedItemStackList implements IItemStackList { private IItemStackList underlyingList; private ArrayListMultimap<Integer, ItemStack> stacks = ArrayListMultimap.create(); private OreDictedItemStackList() {} public OreDictedItemStackList(IItemStackList list) { this.underlyingList = list; initOreDict(); } private void initOreDict() { for (ItemStack stack : underlyingList.getStacks()) { for (int id : OreDictionary.getOreIDs(stack)) { stacks.put(id, stack); } } } @Override public void add(ItemStack stack) { underlyingList.add(stack); if (underlyingList.get(stack).stackSize == stack.stackSize) { for (int id : OreDictionary.getOreIDs(stack)) { stacks.put(id, stack); } } } @Override public boolean remove(@Nonnull ItemStack stack, int size, boolean removeIfReachedZero) { boolean rvalue = underlyingList.remove(stack, size, removeIfReachedZero); if (removeIfReachedZero) { localClean(); } return rvalue; } @Override public boolean trackedRemove(@Nonnull ItemStack stack, int size, boolean removeIfReachedZero) { boolean rvalue = underlyingList.trackedRemove(stack, size, removeIfReachedZero); if (removeIfReachedZero) { localClean(); } return rvalue; } @Override public List<ItemStack> getRemoveTracker() { return underlyingList.getRemoveTracker(); } @Override public void undo() { underlyingList.getRemoveTracker().forEach(this::add); underlyingList.getRemoveTracker().clear(); } @Nullable @Override public ItemStack get(@Nonnull ItemStack stack, int flags) { if ((flags & IComparer.COMPARE_OREDICT) == IComparer.COMPARE_OREDICT) { int[] ids = OreDictionary.getOreIDs(stack); for (int id : ids) { List<ItemStack> stacks = this.stacks.get(id); if (stacks != null && !stacks.isEmpty()) { return stacks.get(0); } } } return underlyingList.get(stack, flags); } @Nullable @Override public ItemStack get(int hash) { return underlyingList.get(hash); } @Override public void clear() { underlyingList.clear(); } private void localClean() { List<Map.Entry<Integer, ItemStack>> toRemove = stacks.entries().stream() .filter(entry -> entry.getValue().stackSize <= 0) .collect(Collectors.toList()); toRemove.forEach(entry -> stacks.remove(entry.getKey(), entry.getValue())); } @Override public void clean() { localClean(); underlyingList.clean(); } @Override public boolean isEmpty() { return underlyingList.isEmpty(); } @Nonnull @Override public Collection<ItemStack> getStacks() { return underlyingList.getStacks(); } @Nonnull @Override public IItemStackList copy() { OreDictedItemStackList newList = new OreDictedItemStackList(); newList.underlyingList = this.underlyingList.copy(); for (Map.Entry<Integer, ItemStack> entry : this.stacks.entries()) { newList.stacks.put(entry.getKey(), entry.getValue()); } return newList; } @Nonnull @Override public IItemStackList prepOreDict() { return this; } }
use internal stack for the oredict list
src/main/java/com/raoulvdberge/refinedstorage/apiimpl/util/OreDictedItemStackList.java
use internal stack for the oredict list
<ide><path>rc/main/java/com/raoulvdberge/refinedstorage/apiimpl/util/OreDictedItemStackList.java <ide> @Override <ide> public void add(ItemStack stack) { <ide> underlyingList.add(stack); <del> if (underlyingList.get(stack).stackSize == stack.stackSize) { <del> for (int id : OreDictionary.getOreIDs(stack)) { <del> stacks.put(id, stack); <add> ItemStack internalStack = underlyingList.get(stack); <add> if (internalStack != null && internalStack.stackSize == stack.stackSize) { <add> for (int id : OreDictionary.getOreIDs(internalStack)) { <add> stacks.put(id, internalStack); <ide> } <ide> } <ide> }
Java
apache-2.0
5c6aab0c8799aa349d5b1fe6c1dcd3c9bcfd01b3
0
smartcommunitylab/AAC,smartcommunitylab/AAC,smartcommunitylab/AAC,smartcommunitylab/AAC
/******************************************************************************* * Copyright 2015 Fondazione Bruno Kessler * * 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 it.smartcommunitylab.aac.config; import java.beans.PropertyVetoException; import java.util.ArrayList; import java.util.Arrays; import java.util.List; import javax.servlet.Filter; import javax.sql.DataSource; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Value; import org.springframework.boot.autoconfigure.security.oauth2.resource.UserInfoTokenServices; import org.springframework.boot.context.properties.ConfigurationProperties; import org.springframework.boot.context.properties.EnableConfigurationProperties; import org.springframework.boot.web.servlet.FilterRegistrationBean; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import org.springframework.core.io.Resource; import org.springframework.http.HttpMethod; import org.springframework.security.authentication.AuthenticationManager; import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder; import org.springframework.security.config.annotation.web.builders.HttpSecurity; import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter; import org.springframework.security.core.userdetails.UserDetailsService; import org.springframework.security.oauth2.client.OAuth2ClientContext; import org.springframework.security.oauth2.client.OAuth2RestTemplate; import org.springframework.security.oauth2.client.filter.OAuth2ClientAuthenticationProcessingFilter; import org.springframework.security.oauth2.client.filter.OAuth2ClientContextFilter; import org.springframework.security.oauth2.config.annotation.configurers.ClientDetailsServiceConfigurer; import org.springframework.security.oauth2.config.annotation.web.configuration.AuthorizationServerConfigurerAdapter; import org.springframework.security.oauth2.config.annotation.web.configuration.EnableAuthorizationServer; import org.springframework.security.oauth2.config.annotation.web.configuration.EnableOAuth2Client; import org.springframework.security.oauth2.config.annotation.web.configuration.ResourceServerConfiguration; import org.springframework.security.oauth2.config.annotation.web.configuration.ResourceServerConfigurer; import org.springframework.security.oauth2.config.annotation.web.configuration.ResourceServerConfigurerAdapter; import org.springframework.security.oauth2.config.annotation.web.configurers.AuthorizationServerEndpointsConfigurer; import org.springframework.security.oauth2.config.annotation.web.configurers.AuthorizationServerSecurityConfigurer; import org.springframework.security.oauth2.config.annotation.web.configurers.ResourceServerSecurityConfigurer; import org.springframework.security.oauth2.provider.ClientDetailsService; import org.springframework.security.oauth2.provider.CompositeTokenGranter; import org.springframework.security.oauth2.provider.OAuth2RequestFactory; import org.springframework.security.oauth2.provider.TokenGranter; import org.springframework.security.oauth2.provider.client.JdbcClientDetailsService; import org.springframework.security.oauth2.provider.token.TokenStore; import org.springframework.security.web.authentication.LoginUrlAuthenticationEntryPoint; import org.springframework.security.web.authentication.logout.LogoutSuccessHandler; import org.springframework.security.web.authentication.logout.SimpleUrlLogoutSuccessHandler; import org.springframework.security.web.authentication.rememberme.JdbcTokenRepositoryImpl; import org.springframework.security.web.authentication.rememberme.PersistentTokenBasedRememberMeServices; import org.springframework.security.web.authentication.rememberme.PersistentTokenRepository; import org.springframework.security.web.authentication.www.BasicAuthenticationFilter; import org.springframework.web.cors.CorsConfiguration; import org.springframework.web.cors.UrlBasedCorsConfigurationSource; import org.springframework.web.filter.CompositeFilter; import org.springframework.web.filter.CorsFilter; import org.yaml.snakeyaml.Yaml; import it.smartcommunitylab.aac.Config; import it.smartcommunitylab.aac.apimanager.APIProviderManager; import it.smartcommunitylab.aac.common.Utils; import it.smartcommunitylab.aac.manager.FileEmailIdentitySource; import it.smartcommunitylab.aac.manager.IdentitySource; import it.smartcommunitylab.aac.manager.OAuth2ClientDetailsProviderImpl; import it.smartcommunitylab.aac.manager.ProviderServiceAdapter; import it.smartcommunitylab.aac.manager.UserManager; import it.smartcommunitylab.aac.model.ClientDetailsRowMapper; import it.smartcommunitylab.aac.model.MockDataMappings; import it.smartcommunitylab.aac.oauth.AACRememberMeServices; import it.smartcommunitylab.aac.oauth.AACTokenEnhancer; import it.smartcommunitylab.aac.oauth.AutoJdbcAuthorizationCodeServices; import it.smartcommunitylab.aac.oauth.AutoJdbcTokenStore; import it.smartcommunitylab.aac.oauth.ClientCredentialsRegistrationFilter; import it.smartcommunitylab.aac.oauth.ClientCredentialsTokenEndpointFilter; import it.smartcommunitylab.aac.oauth.ContextExtender; import it.smartcommunitylab.aac.oauth.AACOAuth2RequestFactory; import it.smartcommunitylab.aac.oauth.AACOAuth2RequestValidator; import it.smartcommunitylab.aac.oauth.InternalPasswordEncoder; import it.smartcommunitylab.aac.oauth.InternalUserDetailsRepo; import it.smartcommunitylab.aac.oauth.MockDataAwareOAuth2SuccessHandler; import it.smartcommunitylab.aac.oauth.MultitenantOAuth2ClientAuthenticationProcessingFilter; import it.smartcommunitylab.aac.oauth.NativeTokenGranter; import it.smartcommunitylab.aac.oauth.NonRemovingTokenServices; import it.smartcommunitylab.aac.oauth.OAuth2ClientDetailsProvider; import it.smartcommunitylab.aac.oauth.OAuthProviders; import it.smartcommunitylab.aac.oauth.OAuthProviders.ClientResources; import it.smartcommunitylab.aac.oauth.UserApprovalHandler; import it.smartcommunitylab.aac.oauth.UserDetailsRepo; import it.smartcommunitylab.aac.repository.ClientDetailsRepository; import it.smartcommunitylab.aac.repository.UserRepository; @Configuration @EnableOAuth2Client @EnableConfigurationProperties public class SecurityConfig extends WebSecurityConfigurerAdapter { @Value("classpath:/testdata.yml") private Resource dataMapping; @Value("${application.url}") private String applicationURL; @Value("${security.restricted}") private boolean restrictedAccess; @Value("${security.rememberme.key}") private String remembermeKey; @Autowired OAuth2ClientContext oauth2ClientContext; @Autowired private ClientDetailsRepository clientDetailsRepository; @Autowired private UserRepository userRepository; @Autowired private DataSource dataSource; @Bean public AutoJdbcTokenStore getTokenStore() throws PropertyVetoException { return new AutoJdbcTokenStore(dataSource); } @Bean public JdbcClientDetailsService getClientDetails() throws PropertyVetoException { JdbcClientDetailsService bean = new JdbcClientDetailsService(dataSource); bean.setRowMapper(getClientDetailsRowMapper()); return bean; } @Bean public PersistentTokenBasedRememberMeServices rememberMeServices() { AACRememberMeServices service = new AACRememberMeServices(remembermeKey, new UserDetailsRepo(userRepository), persistentTokenRepository()); service.setCookieName(Config.COOKIE_REMEMBER_ME); service.setParameter(Config.PARAM_REMEMBER_ME); service.setTokenValiditySeconds(3600 * 24 * 60); // two month return service; } @Bean public PersistentTokenRepository persistentTokenRepository() { JdbcTokenRepositoryImpl tokenRepositoryImpl = new JdbcTokenRepositoryImpl(); tokenRepositoryImpl.setDataSource(dataSource); return tokenRepositoryImpl; } @Bean public UserDetailsService getInternalUserDetailsService() { return new InternalUserDetailsRepo(); } @Bean public ClientDetailsRowMapper getClientDetailsRowMapper() { return new ClientDetailsRowMapper(); } @Bean public OAuth2ClientDetailsProvider getOAuth2ClientDetailsProvider() throws PropertyVetoException { return new OAuth2ClientDetailsProviderImpl(clientDetailsRepository); } @Bean public APIProviderManager tokenEmitter() { return new APIProviderManager(); } @Bean public FilterRegistrationBean oauth2ClientFilterRegistration(OAuth2ClientContextFilter filter) { FilterRegistrationBean registration = new FilterRegistrationBean(); registration.setFilter(filter); registration.setOrder(-100); return registration; } @Bean public FilterRegistrationBean corsFilter() { UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource(); CorsConfiguration config = new CorsConfiguration(); config.setAllowCredentials(true); config.addAllowedOrigin("*"); config.addAllowedHeader("*"); config.addAllowedMethod("*"); source.registerCorsConfiguration("/**", config); FilterRegistrationBean bean = new FilterRegistrationBean(new CorsFilter(source)); bean.setOrder(0); return bean; } @Bean @ConfigurationProperties("oauth-providers") public OAuthProviders oauthProviders() { return new OAuthProviders(); } @Bean public InternalPasswordEncoder getInternalPasswordEncoder() { return new InternalPasswordEncoder(); } @Bean public IdentitySource getIdentitySource() { return new FileEmailIdentitySource(); } private Filter extOAuth2Filter() throws Exception { CompositeFilter filter = new CompositeFilter(); List<Filter> filters = new ArrayList<>(); List<ClientResources> providers = oauthProviders().getProviders(); for (ClientResources client : providers) { String id = client.getProvider(); filters.add(extOAuth2Filter(client, Utils.filterRedirectURL(id), "/eauth/" + id)); } filter.setFilters(filters); return filter; } private Filter extOAuth2Filter(ClientResources client, String path, String target) throws Exception { OAuth2ClientAuthenticationProcessingFilter filter = new MultitenantOAuth2ClientAuthenticationProcessingFilter(client.getProvider(), path, getOAuth2ClientDetailsProvider()); Yaml yaml = new Yaml(); MockDataMappings data = yaml.loadAs(dataMapping.getInputStream(), MockDataMappings.class); filter.setAuthenticationSuccessHandler(new MockDataAwareOAuth2SuccessHandler(target, data)); OAuth2RestTemplate template = new OAuth2RestTemplate(client.getClient(), oauth2ClientContext); filter.setRestTemplate(template); UserInfoTokenServices tokenServices = new UserInfoTokenServices(client.getResource().getUserInfoUri(), client.getClient().getClientId()); tokenServices.setRestTemplate(template); filter.setTokenServices(tokenServices); return filter; } @Override public void configure(HttpSecurity http) throws Exception { http .anonymous().disable() .authorizeRequests() .antMatchers("/eauth/authorize/**").permitAll() .antMatchers("/oauth/authorize", "/eauth/**").authenticated() .antMatchers("/", "/dev**").hasAnyAuthority((restrictedAccess ? "ROLE_MANAGER" : "ROLE_USER"), "ROLE_ADMIN") .antMatchers("/admin/**").hasAnyAuthority("ROLE_ADMIN") .antMatchers("/mgmt/**").hasAnyAuthority("ROLE_PROVIDER") .and() .exceptionHandling() .authenticationEntryPoint(new LoginUrlAuthenticationEntryPoint("/login")) .accessDeniedPage("/accesserror") .and() .logout() .logoutSuccessHandler(logoutSuccessHandler()).permitAll() .and() .rememberMe() .key(remembermeKey) .rememberMeServices(rememberMeServices()) .and() .csrf() .disable() .addFilterBefore(extOAuth2Filter(), BasicAuthenticationFilter.class); } /** * @return */ private LogoutSuccessHandler logoutSuccessHandler() { SimpleUrlLogoutSuccessHandler handler = new SimpleUrlLogoutSuccessHandler(); handler.setDefaultTargetUrl("/"); handler.setTargetUrlParameter("target"); return handler; } @Override public AuthenticationManager authenticationManagerBean() throws Exception { return super.authenticationManagerBean(); } @Override protected void configure(AuthenticationManagerBuilder auth) throws Exception { auth.userDetailsService(getInternalUserDetailsService()); } @Bean protected ContextExtender contextExtender() { return new ContextExtender(); } @Configuration @EnableAuthorizationServer protected class AuthorizationServerConfiguration extends AuthorizationServerConfigurerAdapter { @Autowired private DataSource dataSource; @Autowired private TokenStore tokenStore; @Autowired private UserApprovalHandler userApprovalHandler; @Autowired private AuthenticationManager authenticationManager; @Autowired private ClientDetailsService clientDetailsService; @Autowired private ClientDetailsRepository clientDetailsRepository; @Autowired private ProviderServiceAdapter providerServiceAdapter; @Bean public AutoJdbcAuthorizationCodeServices getAuthorizationCodeServices() throws PropertyVetoException { return new AutoJdbcAuthorizationCodeServices(dataSource); } @Bean public OAuth2RequestFactory getOAuth2RequestFactory() throws PropertyVetoException { AACOAuth2RequestFactory<UserManager> result = new AACOAuth2RequestFactory<>(); return result; } // @Bean("appTokenServices") public NonRemovingTokenServices getTokenServices() throws PropertyVetoException { NonRemovingTokenServices bean = new NonRemovingTokenServices(); bean.setTokenStore(tokenStore); bean.setSupportRefreshToken(true); bean.setReuseRefreshToken(true); bean.setClientDetailsService(clientDetailsService); bean.setTokenEnhancer(new AACTokenEnhancer()); return bean; } @Bean public UserApprovalHandler getUserApprovalHandler() throws PropertyVetoException { UserApprovalHandler bean = new UserApprovalHandler(); bean.setTokenStore(tokenStore); bean.setRequestFactory(getOAuth2RequestFactory()); return bean; } Filter endpointFilter() { ClientCredentialsTokenEndpointFilter filter = new ClientCredentialsTokenEndpointFilter( clientDetailsRepository); filter.setAuthenticationManager(authenticationManager); // need to initialize success/failure handlers filter.afterPropertiesSet(); return filter; } @Override public void configure(ClientDetailsServiceConfigurer clients) throws Exception { clients.jdbc(dataSource).clients(clientDetailsService); } @Override public void configure(AuthorizationServerEndpointsConfigurer endpoints) throws Exception { endpoints.tokenStore(tokenStore).userApprovalHandler(userApprovalHandler) .authenticationManager(authenticationManager) .tokenGranter(tokenGranter(endpoints)) .requestFactory(getOAuth2RequestFactory()) .requestValidator(new AACOAuth2RequestValidator()) .tokenServices(getTokenServices()); } @Override public void configure(AuthorizationServerSecurityConfigurer oauthServer) throws Exception { oauthServer.addTokenEndpointAuthenticationFilter(endpointFilter()); } private TokenGranter tokenGranter(final AuthorizationServerEndpointsConfigurer endpoints) { List<TokenGranter> granters = new ArrayList<TokenGranter>(Arrays.asList(endpoints.getTokenGranter())); granters.add(new NativeTokenGranter(providerServiceAdapter, endpoints.getTokenServices(), endpoints.getClientDetailsService(), endpoints.getOAuth2RequestFactory(), "native")); return new CompositeTokenGranter(granters); } } @Bean protected ResourceServerConfiguration profileResources() { ResourceServerConfiguration resource = new ResourceServerConfiguration() { public void setConfigurers(List<ResourceServerConfigurer> configurers) { super.setConfigurers(configurers); } }; resource.setConfigurers(Arrays.<ResourceServerConfigurer>asList(new ResourceServerConfigurerAdapter() { public void configure(ResourceServerSecurityConfigurer resources) throws Exception { resources.resourceId(null); } public void configure(HttpSecurity http) throws Exception { http.antMatcher("/*profile/**").authorizeRequests().antMatchers(HttpMethod.OPTIONS, "/*profile/**").permitAll() .antMatchers("/basicprofile/all/**").access("#oauth2.hasScope('profile.basicprofile.all')") .antMatchers("/basicprofile/profiles/**").access("#oauth2.hasScope('profile.basicprofile.all')") .antMatchers("/basicprofile/me").access("#oauth2.hasScope('profile.basicprofile.me')") .antMatchers("/accountprofile/profiles").access("#oauth2.hasScope('profile.accountprofile.all')") .antMatchers("/accountprofile/me").access("#oauth2.hasScope('profile.accountprofile.me')") .and().csrf().disable(); } })); resource.setOrder(4); return resource; } @Bean protected ResourceServerConfiguration restRegistrationResources() { ResourceServerConfiguration resource = new ResourceServerConfiguration() { public void setConfigurers(List<ResourceServerConfigurer> configurers) { super.setConfigurers(configurers); } }; resource.setConfigurers(Arrays.<ResourceServerConfigurer>asList(new ResourceServerConfigurerAdapter() { public void configure(ResourceServerSecurityConfigurer resources) throws Exception { resources.resourceId(null); } Filter endpointFilter() throws Exception { ClientCredentialsRegistrationFilter filter = new ClientCredentialsRegistrationFilter(clientDetailsRepository); filter.setFilterProcessesUrl("/internal/register/rest"); filter.setAuthenticationManager(authenticationManagerBean()); // need to initialize success/failure handlers filter.afterPropertiesSet(); return filter; } public void configure(HttpSecurity http) throws Exception { http.addFilterAfter(endpointFilter(), BasicAuthenticationFilter.class); http.antMatcher("/internal/register/rest").authorizeRequests().anyRequest() .fullyAuthenticated().and().csrf().disable(); } })); resource.setOrder(5); return resource; } // @Bean // protected ResourceServerConfiguration apiMgmtResources() { // ResourceServerConfiguration resource = new ResourceServerConfiguration() // { // public void setConfigurers(List<ResourceServerConfigurer> configurers) { // super.setConfigurers(configurers); // } // }; // resource.setConfigurers(Arrays.<ResourceServerConfigurer> asList(new // ResourceServerConfigurerAdapter() { // public void configure(ResourceServerSecurityConfigurer resources) throws // Exception { resources.resourceId(null); } // public void configure(HttpSecurity http) throws Exception { // http // .antMatcher("/mgmt/apis") // .authorizeRequests() // .antMatchers(HttpMethod.OPTIONS, "/mgmt/apis").permitAll() // .anyRequest().authenticated() // .and().csrf().disable(); // } // // })); // resource.setOrder(6); // return resource; // } @Bean protected ResourceServerConfiguration rolesResources() { ResourceServerConfiguration resource = new ResourceServerConfiguration() { public void setConfigurers(List<ResourceServerConfigurer> configurers) { super.setConfigurers(configurers); } }; resource.setConfigurers(Arrays.<ResourceServerConfigurer>asList(new ResourceServerConfigurerAdapter() { public void configure(ResourceServerSecurityConfigurer resources) throws Exception { resources.resourceId(null); } public void configure(HttpSecurity http) throws Exception { http.antMatcher("/*userroles/**").authorizeRequests().antMatchers(HttpMethod.OPTIONS, "/*userroles/**") .permitAll() .antMatchers("/userroles/me").access("#oauth2.hasScope('user.roles.me')") .antMatchers("/userroles/all/user").access("#oauth2.hasScope('user.roles.read.all')") .antMatchers(HttpMethod.GET, "/userroles/user").access("#oauth2.hasScope('user.roles.read')") .antMatchers(HttpMethod.PUT, "/userroles/user").access("#oauth2.hasScope('user.roles.write')") .antMatchers(HttpMethod.DELETE, "/userroles/user").access("#oauth2.hasScope('user.roles.write')") .antMatchers("/userroles/client").access("#oauth2.hasScope('client.roles.read.all')") .and().csrf().disable(); } })); resource.setOrder(6); return resource; } @Bean protected ResourceServerConfiguration wso2ClientResources() { ResourceServerConfiguration resource = new ResourceServerConfiguration() { public void setConfigurers(List<ResourceServerConfigurer> configurers) { super.setConfigurers(configurers); } }; resource.setConfigurers(Arrays.<ResourceServerConfigurer>asList(new ResourceServerConfigurerAdapter() { public void configure(ResourceServerSecurityConfigurer resources) throws Exception { resources.resourceId(null); } public void configure(HttpSecurity http) throws Exception { http.antMatcher("/wso2/client/**").authorizeRequests().anyRequest() .access("#oauth2.hasScope('clientmanagement')").and().csrf().disable(); } })); resource.setOrder(7); return resource; } @Bean protected ResourceServerConfiguration wso2APIResources() { ResourceServerConfiguration resource = new ResourceServerConfiguration() { public void setConfigurers(List<ResourceServerConfigurer> configurers) { super.setConfigurers(configurers); } }; resource.setConfigurers(Arrays.<ResourceServerConfigurer>asList(new ResourceServerConfigurerAdapter() { public void configure(ResourceServerSecurityConfigurer resources) throws Exception { resources.resourceId(null); } public void configure(HttpSecurity http) throws Exception { http.antMatcher("/wso2/resources/**").authorizeRequests().anyRequest() .access("#oauth2.hasScope('apimanagement')").and().csrf().disable(); } })); resource.setOrder(8); return resource; } @Bean protected ResourceServerConfiguration authorizationResources() { ResourceServerConfiguration resource = new ResourceServerConfiguration() { public void setConfigurers(List<ResourceServerConfigurer> configurers) { super.setConfigurers(configurers); } }; resource.setConfigurers(Arrays.<ResourceServerConfigurer>asList(new ResourceServerConfigurerAdapter() { public void configure(ResourceServerSecurityConfigurer resources) throws Exception { resources.resourceId(null); } public void configure(HttpSecurity http) throws Exception { http.antMatcher("/*authorization/**").authorizeRequests().antMatchers(HttpMethod.OPTIONS, "/*authorization/**") .permitAll() .antMatchers("/authorization/**").access("#oauth2.hasScope('authorization.manage')") .antMatchers("/authorization/*/schema/**").access("#oauth2.hasScope('authorization.schema.manage')") .and().csrf().disable(); } })); resource.setOrder(9); return resource; } @Bean protected ResourceServerConfiguration apiKeyResources() { ResourceServerConfiguration resource = new ResourceServerConfiguration() { public void setConfigurers(List<ResourceServerConfigurer> configurers) { super.setConfigurers(configurers); } }; resource.setConfigurers(Arrays.<ResourceServerConfigurer>asList(new ResourceServerConfigurerAdapter() { public void configure(ResourceServerSecurityConfigurer resources) throws Exception { resources.resourceId(null); } public void configure(HttpSecurity http) throws Exception { http.antMatcher("/apikey/**").authorizeRequests().antMatchers(HttpMethod.OPTIONS, "/apikey/**") .permitAll() .antMatchers("/apikey/**").fullyAuthenticated() .and().csrf().disable(); } })); resource.setOrder(10); return resource; } }
src/main/java/it/smartcommunitylab/aac/config/SecurityConfig.java
/******************************************************************************* * Copyright 2015 Fondazione Bruno Kessler * * 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 it.smartcommunitylab.aac.config; import java.beans.PropertyVetoException; import java.util.ArrayList; import java.util.Arrays; import java.util.List; import javax.servlet.Filter; import javax.sql.DataSource; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Value; import org.springframework.boot.autoconfigure.security.oauth2.resource.UserInfoTokenServices; import org.springframework.boot.context.properties.ConfigurationProperties; import org.springframework.boot.context.properties.EnableConfigurationProperties; import org.springframework.boot.web.servlet.FilterRegistrationBean; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import org.springframework.core.io.Resource; import org.springframework.http.HttpMethod; import org.springframework.security.authentication.AuthenticationManager; import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder; import org.springframework.security.config.annotation.web.builders.HttpSecurity; import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter; import org.springframework.security.core.userdetails.UserDetailsService; import org.springframework.security.oauth2.client.OAuth2ClientContext; import org.springframework.security.oauth2.client.OAuth2RestTemplate; import org.springframework.security.oauth2.client.filter.OAuth2ClientAuthenticationProcessingFilter; import org.springframework.security.oauth2.client.filter.OAuth2ClientContextFilter; import org.springframework.security.oauth2.config.annotation.configurers.ClientDetailsServiceConfigurer; import org.springframework.security.oauth2.config.annotation.web.configuration.AuthorizationServerConfigurerAdapter; import org.springframework.security.oauth2.config.annotation.web.configuration.EnableAuthorizationServer; import org.springframework.security.oauth2.config.annotation.web.configuration.EnableOAuth2Client; import org.springframework.security.oauth2.config.annotation.web.configuration.ResourceServerConfiguration; import org.springframework.security.oauth2.config.annotation.web.configuration.ResourceServerConfigurer; import org.springframework.security.oauth2.config.annotation.web.configuration.ResourceServerConfigurerAdapter; import org.springframework.security.oauth2.config.annotation.web.configurers.AuthorizationServerEndpointsConfigurer; import org.springframework.security.oauth2.config.annotation.web.configurers.AuthorizationServerSecurityConfigurer; import org.springframework.security.oauth2.config.annotation.web.configurers.ResourceServerSecurityConfigurer; import org.springframework.security.oauth2.provider.ClientDetailsService; import org.springframework.security.oauth2.provider.CompositeTokenGranter; import org.springframework.security.oauth2.provider.OAuth2RequestFactory; import org.springframework.security.oauth2.provider.TokenGranter; import org.springframework.security.oauth2.provider.client.JdbcClientDetailsService; import org.springframework.security.oauth2.provider.token.TokenStore; import org.springframework.security.web.authentication.LoginUrlAuthenticationEntryPoint; import org.springframework.security.web.authentication.logout.LogoutSuccessHandler; import org.springframework.security.web.authentication.logout.SimpleUrlLogoutSuccessHandler; import org.springframework.security.web.authentication.rememberme.JdbcTokenRepositoryImpl; import org.springframework.security.web.authentication.rememberme.PersistentTokenBasedRememberMeServices; import org.springframework.security.web.authentication.rememberme.PersistentTokenRepository; import org.springframework.security.web.authentication.www.BasicAuthenticationFilter; import org.springframework.web.cors.CorsConfiguration; import org.springframework.web.cors.UrlBasedCorsConfigurationSource; import org.springframework.web.filter.CompositeFilter; import org.springframework.web.filter.CorsFilter; import org.yaml.snakeyaml.Yaml; import it.smartcommunitylab.aac.Config; import it.smartcommunitylab.aac.apimanager.APIProviderManager; import it.smartcommunitylab.aac.common.Utils; import it.smartcommunitylab.aac.manager.FileEmailIdentitySource; import it.smartcommunitylab.aac.manager.IdentitySource; import it.smartcommunitylab.aac.manager.OAuth2ClientDetailsProviderImpl; import it.smartcommunitylab.aac.manager.ProviderServiceAdapter; import it.smartcommunitylab.aac.manager.UserManager; import it.smartcommunitylab.aac.model.ClientDetailsRowMapper; import it.smartcommunitylab.aac.model.MockDataMappings; import it.smartcommunitylab.aac.oauth.AACRememberMeServices; import it.smartcommunitylab.aac.oauth.AACTokenEnhancer; import it.smartcommunitylab.aac.oauth.AutoJdbcAuthorizationCodeServices; import it.smartcommunitylab.aac.oauth.AutoJdbcTokenStore; import it.smartcommunitylab.aac.oauth.ClientCredentialsRegistrationFilter; import it.smartcommunitylab.aac.oauth.ClientCredentialsTokenEndpointFilter; import it.smartcommunitylab.aac.oauth.ContextExtender; import it.smartcommunitylab.aac.oauth.AACOAuth2RequestFactory; import it.smartcommunitylab.aac.oauth.AACOAuth2RequestValidator; import it.smartcommunitylab.aac.oauth.InternalPasswordEncoder; import it.smartcommunitylab.aac.oauth.InternalUserDetailsRepo; import it.smartcommunitylab.aac.oauth.MockDataAwareOAuth2SuccessHandler; import it.smartcommunitylab.aac.oauth.MultitenantOAuth2ClientAuthenticationProcessingFilter; import it.smartcommunitylab.aac.oauth.NativeTokenGranter; import it.smartcommunitylab.aac.oauth.NonRemovingTokenServices; import it.smartcommunitylab.aac.oauth.OAuth2ClientDetailsProvider; import it.smartcommunitylab.aac.oauth.OAuthProviders; import it.smartcommunitylab.aac.oauth.OAuthProviders.ClientResources; import it.smartcommunitylab.aac.oauth.UserApprovalHandler; import it.smartcommunitylab.aac.oauth.UserDetailsRepo; import it.smartcommunitylab.aac.repository.ClientDetailsRepository; import it.smartcommunitylab.aac.repository.UserRepository; @Configuration @EnableOAuth2Client @EnableConfigurationProperties public class SecurityConfig extends WebSecurityConfigurerAdapter { @Value("classpath:/testdata.yml") private Resource dataMapping; @Value("${application.url}") private String applicationURL; @Value("${security.restricted}") private boolean restrictedAccess; @Value("${security.rememberme.key}") private String remembermeKey; @Autowired OAuth2ClientContext oauth2ClientContext; @Autowired private ClientDetailsRepository clientDetailsRepository; @Autowired private UserRepository userRepository; @Autowired private DataSource dataSource; @Bean public AutoJdbcTokenStore getTokenStore() throws PropertyVetoException { return new AutoJdbcTokenStore(dataSource); } @Bean public JdbcClientDetailsService getClientDetails() throws PropertyVetoException { JdbcClientDetailsService bean = new JdbcClientDetailsService(dataSource); bean.setRowMapper(getClientDetailsRowMapper()); return bean; } @Bean public PersistentTokenBasedRememberMeServices rememberMeServices() { AACRememberMeServices service = new AACRememberMeServices(remembermeKey, new UserDetailsRepo(userRepository), persistentTokenRepository()); service.setCookieName(Config.COOKIE_REMEMBER_ME); service.setParameter(Config.PARAM_REMEMBER_ME); service.setTokenValiditySeconds(3600 * 24 * 60); // two month return service; } @Bean public PersistentTokenRepository persistentTokenRepository() { JdbcTokenRepositoryImpl tokenRepositoryImpl = new JdbcTokenRepositoryImpl(); tokenRepositoryImpl.setDataSource(dataSource); return tokenRepositoryImpl; } @Bean public UserDetailsService getInternalUserDetailsService() { return new InternalUserDetailsRepo(); } @Bean public ClientDetailsRowMapper getClientDetailsRowMapper() { return new ClientDetailsRowMapper(); } @Bean public OAuth2ClientDetailsProvider getOAuth2ClientDetailsProvider() throws PropertyVetoException { return new OAuth2ClientDetailsProviderImpl(clientDetailsRepository); } @Bean public APIProviderManager tokenEmitter() { return new APIProviderManager(); } @Bean public FilterRegistrationBean oauth2ClientFilterRegistration(OAuth2ClientContextFilter filter) { FilterRegistrationBean registration = new FilterRegistrationBean(); registration.setFilter(filter); registration.setOrder(-100); return registration; } @Bean public FilterRegistrationBean corsFilter() { UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource(); CorsConfiguration config = new CorsConfiguration(); config.setAllowCredentials(true); config.addAllowedOrigin("*"); config.addAllowedHeader("*"); config.addAllowedMethod("*"); source.registerCorsConfiguration("/**", config); FilterRegistrationBean bean = new FilterRegistrationBean(new CorsFilter(source)); bean.setOrder(0); return bean; } @Bean @ConfigurationProperties("oauth-providers") public OAuthProviders oauthProviders() { return new OAuthProviders(); } @Bean public InternalPasswordEncoder getInternalPasswordEncoder() { return new InternalPasswordEncoder(); } @Bean public IdentitySource getIdentitySource() { return new FileEmailIdentitySource(); } private Filter extOAuth2Filter() throws Exception { CompositeFilter filter = new CompositeFilter(); List<Filter> filters = new ArrayList<>(); List<ClientResources> providers = oauthProviders().getProviders(); for (ClientResources client : providers) { String id = client.getProvider(); filters.add(extOAuth2Filter(client, Utils.filterRedirectURL(id), "/eauth/" + id)); } filter.setFilters(filters); return filter; } private Filter extOAuth2Filter(ClientResources client, String path, String target) throws Exception { OAuth2ClientAuthenticationProcessingFilter filter = new MultitenantOAuth2ClientAuthenticationProcessingFilter(client.getProvider(), path, getOAuth2ClientDetailsProvider()); Yaml yaml = new Yaml(); MockDataMappings data = yaml.loadAs(dataMapping.getInputStream(), MockDataMappings.class); filter.setAuthenticationSuccessHandler(new MockDataAwareOAuth2SuccessHandler(target, data)); OAuth2RestTemplate template = new OAuth2RestTemplate(client.getClient(), oauth2ClientContext); filter.setRestTemplate(template); UserInfoTokenServices tokenServices = new UserInfoTokenServices(client.getResource().getUserInfoUri(), client.getClient().getClientId()); tokenServices.setRestTemplate(template); filter.setTokenServices(tokenServices); return filter; } @Override public void configure(HttpSecurity http) throws Exception { http .authorizeRequests() .antMatchers("/eauth/authorize/**").permitAll() .antMatchers("/oauth/authorize", "/eauth/**").authenticated() .antMatchers("/", "/dev**").hasAnyAuthority((restrictedAccess ? "ROLE_MANAGER" : "ROLE_USER"), "ROLE_ADMIN") .antMatchers("/admin/**").hasAnyAuthority("ROLE_ADMIN") .antMatchers("/mgmt/**").hasAnyAuthority("ROLE_PROVIDER") .and() .exceptionHandling() .authenticationEntryPoint(new LoginUrlAuthenticationEntryPoint("/login")) .accessDeniedPage("/accesserror") .and() .logout() .logoutSuccessHandler(logoutSuccessHandler()).permitAll() .and() .rememberMe() .key(remembermeKey) .rememberMeServices(rememberMeServices()) .and() .csrf() .disable() .addFilterBefore(extOAuth2Filter(), BasicAuthenticationFilter.class); } /** * @return */ private LogoutSuccessHandler logoutSuccessHandler() { SimpleUrlLogoutSuccessHandler handler = new SimpleUrlLogoutSuccessHandler(); handler.setDefaultTargetUrl("/"); handler.setTargetUrlParameter("target"); return handler; } @Override public AuthenticationManager authenticationManagerBean() throws Exception { return super.authenticationManagerBean(); } @Override protected void configure(AuthenticationManagerBuilder auth) throws Exception { auth.userDetailsService(getInternalUserDetailsService()); } @Bean protected ContextExtender contextExtender() { return new ContextExtender(); } @Configuration @EnableAuthorizationServer protected class AuthorizationServerConfiguration extends AuthorizationServerConfigurerAdapter { @Autowired private DataSource dataSource; @Autowired private TokenStore tokenStore; @Autowired private UserApprovalHandler userApprovalHandler; @Autowired private AuthenticationManager authenticationManager; @Autowired private ClientDetailsService clientDetailsService; @Autowired private ClientDetailsRepository clientDetailsRepository; @Autowired private ProviderServiceAdapter providerServiceAdapter; @Bean public AutoJdbcAuthorizationCodeServices getAuthorizationCodeServices() throws PropertyVetoException { return new AutoJdbcAuthorizationCodeServices(dataSource); } @Bean public OAuth2RequestFactory getOAuth2RequestFactory() throws PropertyVetoException { AACOAuth2RequestFactory<UserManager> result = new AACOAuth2RequestFactory<>(); return result; } // @Bean("appTokenServices") public NonRemovingTokenServices getTokenServices() throws PropertyVetoException { NonRemovingTokenServices bean = new NonRemovingTokenServices(); bean.setTokenStore(tokenStore); bean.setSupportRefreshToken(true); bean.setReuseRefreshToken(true); bean.setClientDetailsService(clientDetailsService); bean.setTokenEnhancer(new AACTokenEnhancer()); return bean; } @Bean public UserApprovalHandler getUserApprovalHandler() throws PropertyVetoException { UserApprovalHandler bean = new UserApprovalHandler(); bean.setTokenStore(tokenStore); bean.setRequestFactory(getOAuth2RequestFactory()); return bean; } Filter endpointFilter() { ClientCredentialsTokenEndpointFilter filter = new ClientCredentialsTokenEndpointFilter( clientDetailsRepository); filter.setAuthenticationManager(authenticationManager); // need to initialize success/failure handlers filter.afterPropertiesSet(); return filter; } @Override public void configure(ClientDetailsServiceConfigurer clients) throws Exception { clients.jdbc(dataSource).clients(clientDetailsService); } @Override public void configure(AuthorizationServerEndpointsConfigurer endpoints) throws Exception { endpoints.tokenStore(tokenStore).userApprovalHandler(userApprovalHandler) .authenticationManager(authenticationManager) .tokenGranter(tokenGranter(endpoints)) .requestFactory(getOAuth2RequestFactory()) .requestValidator(new AACOAuth2RequestValidator()) .tokenServices(getTokenServices()); } @Override public void configure(AuthorizationServerSecurityConfigurer oauthServer) throws Exception { oauthServer.addTokenEndpointAuthenticationFilter(endpointFilter()); } private TokenGranter tokenGranter(final AuthorizationServerEndpointsConfigurer endpoints) { List<TokenGranter> granters = new ArrayList<TokenGranter>(Arrays.asList(endpoints.getTokenGranter())); granters.add(new NativeTokenGranter(providerServiceAdapter, endpoints.getTokenServices(), endpoints.getClientDetailsService(), endpoints.getOAuth2RequestFactory(), "native")); return new CompositeTokenGranter(granters); } } @Bean protected ResourceServerConfiguration profileResources() { ResourceServerConfiguration resource = new ResourceServerConfiguration() { public void setConfigurers(List<ResourceServerConfigurer> configurers) { super.setConfigurers(configurers); } }; resource.setConfigurers(Arrays.<ResourceServerConfigurer>asList(new ResourceServerConfigurerAdapter() { public void configure(ResourceServerSecurityConfigurer resources) throws Exception { resources.resourceId(null); } public void configure(HttpSecurity http) throws Exception { http.antMatcher("/*profile/**").authorizeRequests().antMatchers(HttpMethod.OPTIONS, "/*profile/**").permitAll() .antMatchers("/basicprofile/all/**").access("#oauth2.hasScope('profile.basicprofile.all')") .antMatchers("/basicprofile/profiles/**").access("#oauth2.hasScope('profile.basicprofile.all')") .antMatchers("/basicprofile/me").access("#oauth2.hasScope('profile.basicprofile.me')") .antMatchers("/accountprofile/profiles").access("#oauth2.hasScope('profile.accountprofile.all')") .antMatchers("/accountprofile/me").access("#oauth2.hasScope('profile.accountprofile.me')") .and().csrf().disable(); } })); resource.setOrder(4); return resource; } @Bean protected ResourceServerConfiguration restRegistrationResources() { ResourceServerConfiguration resource = new ResourceServerConfiguration() { public void setConfigurers(List<ResourceServerConfigurer> configurers) { super.setConfigurers(configurers); } }; resource.setConfigurers(Arrays.<ResourceServerConfigurer>asList(new ResourceServerConfigurerAdapter() { public void configure(ResourceServerSecurityConfigurer resources) throws Exception { resources.resourceId(null); } Filter endpointFilter() throws Exception { ClientCredentialsRegistrationFilter filter = new ClientCredentialsRegistrationFilter(clientDetailsRepository); filter.setFilterProcessesUrl("/internal/register/rest"); filter.setAuthenticationManager(authenticationManagerBean()); // need to initialize success/failure handlers filter.afterPropertiesSet(); return filter; } public void configure(HttpSecurity http) throws Exception { http.addFilterAfter(endpointFilter(), BasicAuthenticationFilter.class); http.antMatcher("/internal/register/rest").authorizeRequests().anyRequest() .fullyAuthenticated().and().csrf().disable(); } })); resource.setOrder(5); return resource; } // @Bean // protected ResourceServerConfiguration apiMgmtResources() { // ResourceServerConfiguration resource = new ResourceServerConfiguration() // { // public void setConfigurers(List<ResourceServerConfigurer> configurers) { // super.setConfigurers(configurers); // } // }; // resource.setConfigurers(Arrays.<ResourceServerConfigurer> asList(new // ResourceServerConfigurerAdapter() { // public void configure(ResourceServerSecurityConfigurer resources) throws // Exception { resources.resourceId(null); } // public void configure(HttpSecurity http) throws Exception { // http // .antMatcher("/mgmt/apis") // .authorizeRequests() // .antMatchers(HttpMethod.OPTIONS, "/mgmt/apis").permitAll() // .anyRequest().authenticated() // .and().csrf().disable(); // } // // })); // resource.setOrder(6); // return resource; // } @Bean protected ResourceServerConfiguration rolesResources() { ResourceServerConfiguration resource = new ResourceServerConfiguration() { public void setConfigurers(List<ResourceServerConfigurer> configurers) { super.setConfigurers(configurers); } }; resource.setConfigurers(Arrays.<ResourceServerConfigurer>asList(new ResourceServerConfigurerAdapter() { public void configure(ResourceServerSecurityConfigurer resources) throws Exception { resources.resourceId(null); } public void configure(HttpSecurity http) throws Exception { http.antMatcher("/*userroles/**").authorizeRequests().antMatchers(HttpMethod.OPTIONS, "/*userroles/**") .permitAll() .antMatchers("/userroles/me").access("#oauth2.hasScope('user.roles.me')") .antMatchers("/userroles/all/user").access("#oauth2.hasScope('user.roles.read.all')") .antMatchers(HttpMethod.GET, "/userroles/user").access("#oauth2.hasScope('user.roles.read')") .antMatchers(HttpMethod.PUT, "/userroles/user").access("#oauth2.hasScope('user.roles.write')") .antMatchers(HttpMethod.DELETE, "/userroles/user").access("#oauth2.hasScope('user.roles.write')") .antMatchers("/userroles/client").access("#oauth2.hasScope('client.roles.read.all')") .and().csrf().disable(); } })); resource.setOrder(6); return resource; } @Bean protected ResourceServerConfiguration wso2ClientResources() { ResourceServerConfiguration resource = new ResourceServerConfiguration() { public void setConfigurers(List<ResourceServerConfigurer> configurers) { super.setConfigurers(configurers); } }; resource.setConfigurers(Arrays.<ResourceServerConfigurer>asList(new ResourceServerConfigurerAdapter() { public void configure(ResourceServerSecurityConfigurer resources) throws Exception { resources.resourceId(null); } public void configure(HttpSecurity http) throws Exception { http.antMatcher("/wso2/client/**").authorizeRequests().anyRequest() .access("#oauth2.hasScope('clientmanagement')").and().csrf().disable(); } })); resource.setOrder(7); return resource; } @Bean protected ResourceServerConfiguration wso2APIResources() { ResourceServerConfiguration resource = new ResourceServerConfiguration() { public void setConfigurers(List<ResourceServerConfigurer> configurers) { super.setConfigurers(configurers); } }; resource.setConfigurers(Arrays.<ResourceServerConfigurer>asList(new ResourceServerConfigurerAdapter() { public void configure(ResourceServerSecurityConfigurer resources) throws Exception { resources.resourceId(null); } public void configure(HttpSecurity http) throws Exception { http.antMatcher("/wso2/resources/**").authorizeRequests().anyRequest() .access("#oauth2.hasScope('apimanagement')").and().csrf().disable(); } })); resource.setOrder(8); return resource; } @Bean protected ResourceServerConfiguration authorizationResources() { ResourceServerConfiguration resource = new ResourceServerConfiguration() { public void setConfigurers(List<ResourceServerConfigurer> configurers) { super.setConfigurers(configurers); } }; resource.setConfigurers(Arrays.<ResourceServerConfigurer>asList(new ResourceServerConfigurerAdapter() { public void configure(ResourceServerSecurityConfigurer resources) throws Exception { resources.resourceId(null); } public void configure(HttpSecurity http) throws Exception { http.antMatcher("/*authorization/**").authorizeRequests().antMatchers(HttpMethod.OPTIONS, "/*authorization/**") .permitAll() .antMatchers("/authorization/**").access("#oauth2.hasScope('authorization.manage')") .antMatchers("/authorization/*/schema/**").access("#oauth2.hasScope('authorization.schema.manage')") .and().csrf().disable(); } })); resource.setOrder(9); return resource; } @Bean protected ResourceServerConfiguration apiKeyResources() { ResourceServerConfiguration resource = new ResourceServerConfiguration() { public void setConfigurers(List<ResourceServerConfigurer> configurers) { super.setConfigurers(configurers); } }; resource.setConfigurers(Arrays.<ResourceServerConfigurer>asList(new ResourceServerConfigurerAdapter() { public void configure(ResourceServerSecurityConfigurer resources) throws Exception { resources.resourceId(null); } public void configure(HttpSecurity http) throws Exception { http.antMatcher("/apikey/**").authorizeRequests().antMatchers(HttpMethod.OPTIONS, "/apikey/**") .permitAll() .antMatchers("/apikey/**").fullyAuthenticated() .and().csrf().disable(); } })); resource.setOrder(10); return resource; } }
disable anonymous
src/main/java/it/smartcommunitylab/aac/config/SecurityConfig.java
disable anonymous
<ide><path>rc/main/java/it/smartcommunitylab/aac/config/SecurityConfig.java <ide> @Override <ide> public void configure(HttpSecurity http) throws Exception { <ide> http <add> .anonymous().disable() <ide> .authorizeRequests() <ide> .antMatchers("/eauth/authorize/**").permitAll() <ide> .antMatchers("/oauth/authorize", "/eauth/**").authenticated()
Java
apache-2.0
ea00b16d0df91c2af15c667c37dd220f8dec658e
0
thingsboard/thingsboard,volodymyr-babak/thingsboard,volodymyr-babak/thingsboard,thingsboard/thingsboard,volodymyr-babak/thingsboard,thingsboard/thingsboard,volodymyr-babak/thingsboard,thingsboard/thingsboard,thingsboard/thingsboard,volodymyr-babak/thingsboard,volodymyr-babak/thingsboard,thingsboard/thingsboard
/** * Copyright © 2016-2020 The Thingsboard Authors * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.thingsboard.server.dao.sql.query; import lombok.extern.slf4j.Slf4j; import org.apache.commons.lang3.StringUtils; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.jdbc.core.namedparam.NamedParameterJdbcTemplate; import org.springframework.stereotype.Repository; import org.thingsboard.server.common.data.EntityType; import org.thingsboard.server.common.data.id.CustomerId; import org.thingsboard.server.common.data.id.EntityId; import org.thingsboard.server.common.data.id.TenantId; import org.thingsboard.server.common.data.page.PageData; import org.thingsboard.server.common.data.query.AssetSearchQueryFilter; import org.thingsboard.server.common.data.query.AssetTypeFilter; import org.thingsboard.server.common.data.query.DeviceSearchQueryFilter; import org.thingsboard.server.common.data.query.DeviceTypeFilter; import org.thingsboard.server.common.data.query.EntityCountQuery; import org.thingsboard.server.common.data.query.EntityData; import org.thingsboard.server.common.data.query.EntityDataPageLink; import org.thingsboard.server.common.data.query.EntityDataQuery; import org.thingsboard.server.common.data.query.EntityDataSortOrder; import org.thingsboard.server.common.data.query.EntityFilter; import org.thingsboard.server.common.data.query.EntityFilterType; import org.thingsboard.server.common.data.query.EntityListFilter; import org.thingsboard.server.common.data.query.EntityNameFilter; import org.thingsboard.server.common.data.query.EntitySearchQueryFilter; import org.thingsboard.server.common.data.query.EntityViewTypeFilter; import org.thingsboard.server.common.data.query.RelationsQueryFilter; import org.thingsboard.server.common.data.query.SingleEntityFilter; import org.thingsboard.server.common.data.relation.EntitySearchDirection; import org.thingsboard.server.common.data.relation.EntityTypeFilter; import org.thingsboard.server.dao.util.SqlDao; import java.math.BigInteger; import java.util.Collections; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.Optional; import java.util.UUID; import java.util.stream.Collectors; @SqlDao @Repository @Slf4j public class DefaultEntityQueryRepository implements EntityQueryRepository { //TODO: rafactoring to protect from SQL injections; private static final Map<EntityType, String> entityTableMap = new HashMap<>(); static { entityTableMap.put(EntityType.ASSET, "asset"); entityTableMap.put(EntityType.DEVICE, "device"); entityTableMap.put(EntityType.ENTITY_VIEW, "entity_view"); entityTableMap.put(EntityType.DASHBOARD, "dashboard"); entityTableMap.put(EntityType.CUSTOMER, "customer"); entityTableMap.put(EntityType.USER, "tb_user"); entityTableMap.put(EntityType.TENANT, "tenant"); } public static final String HIERARCHICAL_QUERY_TEMPLATE = " FROM (WITH RECURSIVE related_entities(from_id, from_type, to_id, to_type, relation_type, lvl) AS (" + " SELECT from_id, from_type, to_id, to_type, relation_type, 1 as lvl" + " FROM relation" + " WHERE $in_id = :relation_root_id and $in_type = :relation_root_type and relation_type_group = 'COMMON'" + " UNION ALL" + " SELECT r.from_id, r.from_type, r.to_id, r.to_type, r.relation_type, lvl + 1" + " FROM relation r" + " INNER JOIN related_entities re ON" + " r.$in_id = re.$out_id and r.$in_type = re.$out_type and" + " relation_type_group = 'COMMON' %s)" + " SELECT re.$out_id entity_id, re.$out_type entity_type, re.lvl lvl" + " from related_entities re" + " %s ) entity"; public static final String HIERARCHICAL_TO_QUERY_TEMPLATE = HIERARCHICAL_QUERY_TEMPLATE.replace("$in", "to").replace("$out", "from"); public static final String HIERARCHICAL_FROM_QUERY_TEMPLATE = HIERARCHICAL_QUERY_TEMPLATE.replace("$in", "from").replace("$out", "to"); @Autowired protected NamedParameterJdbcTemplate jdbcTemplate; @Override public long countEntitiesByQuery(TenantId tenantId, CustomerId customerId, EntityCountQuery query) { EntityType entityType = resolveEntityType(query.getEntityFilter()); EntityQueryContext ctx = new EntityQueryContext(); ctx.append("select count(e.id) from "); ctx.append(addEntityTableQuery(ctx, query.getEntityFilter(), entityType)); ctx.append(" e where "); ctx.append(buildEntityWhere(ctx, tenantId, customerId, query.getEntityFilter(), Collections.emptyList(), entityType)); return jdbcTemplate.queryForObject(ctx.getQuery(), ctx, Long.class); } @Override public PageData<EntityData> findEntityDataByQuery(TenantId tenantId, CustomerId customerId, EntityDataQuery query) { EntityQueryContext ctx = new EntityQueryContext(); EntityType entityType = resolveEntityType(query.getEntityFilter()); EntityDataPageLink pageLink = query.getPageLink(); List<EntityKeyMapping> mappings = EntityKeyMapping.prepareKeyMapping(query); List<EntityKeyMapping> selectionMapping = mappings.stream().filter(EntityKeyMapping::isSelection) .collect(Collectors.toList()); List<EntityKeyMapping> entityFieldsSelectionMapping = selectionMapping.stream().filter(mapping -> !mapping.isLatest()) .collect(Collectors.toList()); List<EntityKeyMapping> latestSelectionMapping = selectionMapping.stream().filter(EntityKeyMapping::isLatest) .collect(Collectors.toList()); List<EntityKeyMapping> filterMapping = mappings.stream().filter(EntityKeyMapping::hasFilter) .collect(Collectors.toList()); List<EntityKeyMapping> entityFieldsFiltersMapping = filterMapping.stream().filter(mapping -> !mapping.isLatest()) .collect(Collectors.toList()); List<EntityKeyMapping> latestFiltersMapping = filterMapping.stream().filter(EntityKeyMapping::isLatest) .collect(Collectors.toList()); List<EntityKeyMapping> allLatestMappings = mappings.stream().filter(EntityKeyMapping::isLatest) .collect(Collectors.toList()); String entityWhereClause = this.buildEntityWhere(ctx, tenantId, customerId, query.getEntityFilter(), entityFieldsFiltersMapping, entityType); String latestJoins = EntityKeyMapping.buildLatestJoins(ctx, query.getEntityFilter(), entityType, allLatestMappings); String whereClause = this.buildWhere(ctx, latestFiltersMapping); String textSearchQuery = this.buildTextSearchQuery(ctx, selectionMapping, pageLink.getTextSearch()); String entityFieldsSelection = EntityKeyMapping.buildSelections(entityFieldsSelectionMapping); String entityTypeStr; if (query.getEntityFilter().getType().equals(EntityFilterType.RELATIONS_QUERY)) { entityTypeStr = "e.entity_type"; } else { entityTypeStr = "'" + entityType.name() + "'"; } if (!StringUtils.isEmpty(entityFieldsSelection)) { entityFieldsSelection = String.format("e.id id, %s entity_type, %s", entityTypeStr, entityFieldsSelection); } else { entityFieldsSelection = String.format("e.id id, %s entity_type", entityTypeStr); } String latestSelection = EntityKeyMapping.buildSelections(latestSelectionMapping); String topSelection = "entities.*"; if (!StringUtils.isEmpty(latestSelection)) { topSelection = topSelection + ", " + latestSelection; } String fromClause = String.format("from (select %s from (select %s from %s e where %s) entities %s %s) result %s", topSelection, entityFieldsSelection, addEntityTableQuery(ctx, query.getEntityFilter(), entityType), entityWhereClause, latestJoins, whereClause, textSearchQuery); int totalElements = jdbcTemplate.queryForObject(String.format("select count(*) %s", fromClause), ctx, Integer.class); String dataQuery = String.format("select * %s", fromClause); EntityDataSortOrder sortOrder = pageLink.getSortOrder(); if (sortOrder != null) { Optional<EntityKeyMapping> sortOrderMappingOpt = mappings.stream().filter(EntityKeyMapping::isSortOrder).findFirst(); if (sortOrderMappingOpt.isPresent()) { EntityKeyMapping sortOrderMapping = sortOrderMappingOpt.get(); dataQuery = String.format("%s order by %s", dataQuery, sortOrderMapping.getValueAlias()); if (sortOrder.getDirection() == EntityDataSortOrder.Direction.ASC) { dataQuery += " asc"; } else { dataQuery += " desc"; } } } int startIndex = pageLink.getPageSize() * pageLink.getPage(); if (pageLink.getPageSize() > 0) { dataQuery = String.format("%s limit %s offset %s", dataQuery, pageLink.getPageSize(), startIndex); } List<Map<String, Object>> rows = jdbcTemplate.queryForList(dataQuery, ctx); return EntityDataAdapter.createEntityData(pageLink, selectionMapping, rows, totalElements); } private String buildEntityWhere(EntityQueryContext ctx, TenantId tenantId, CustomerId customerId, EntityFilter entityFilter, List<EntityKeyMapping> entityFieldsFilters, EntityType entityType) { String permissionQuery = this.buildPermissionQuery(ctx, entityFilter, tenantId, customerId, entityType); String entityFilterQuery = this.buildEntityFilterQuery(ctx, entityFilter); String result = permissionQuery; if (!entityFilterQuery.isEmpty()) { result += " and " + entityFilterQuery; } if (!entityFieldsFilters.isEmpty()) { result += " and " + entityFieldsFilters; } return result; } private String buildPermissionQuery(EntityQueryContext ctx, EntityFilter entityFilter, TenantId tenantId, CustomerId customerId, EntityType entityType) { switch (entityFilter.getType()) { case RELATIONS_QUERY: case DEVICE_SEARCH_QUERY: case ASSET_SEARCH_QUERY: return this.defaultPermissionQuery(ctx, tenantId, customerId, entityType); default: if (entityType == EntityType.TENANT) { ctx.addUuidParameter("permissions_tenant_id", tenantId.getId()); return "e.id=:permissions_tenant_id"; } else { return this.defaultPermissionQuery(ctx, tenantId, customerId, entityType); } } } private String defaultPermissionQuery(EntityQueryContext ctx, TenantId tenantId, CustomerId customerId, EntityType entityType) { ctx.addUuidParameter("permissions_tenant_id", tenantId.getId()); if (customerId != null && !customerId.isNullUid()) { ctx.addUuidParameter("permissions_customer_id", customerId.getId()); if (entityType == EntityType.CUSTOMER) { return "e.tenant_id=:permissions_tenant_id and e.id=:permissions_customer_id"; } else { return "e.tenant_id=:permissions_tenant_id and e.customer_id=:permissions_customer_id"; } } else { return "e.tenant_id=:permissions_tenant_id"; } } private String buildEntityFilterQuery(EntityQueryContext ctx, EntityFilter entityFilter) { switch (entityFilter.getType()) { case SINGLE_ENTITY: return this.singleEntityQuery(ctx, (SingleEntityFilter) entityFilter); case ENTITY_LIST: return this.entityListQuery(ctx, (EntityListFilter) entityFilter); case ENTITY_NAME: return this.entityNameQuery(ctx, (EntityNameFilter) entityFilter); case ASSET_TYPE: case DEVICE_TYPE: case ENTITY_VIEW_TYPE: return this.typeQuery(ctx, entityFilter); case RELATIONS_QUERY: case DEVICE_SEARCH_QUERY: case ASSET_SEARCH_QUERY: return ""; default: throw new RuntimeException("Not implemented!"); } } private String addEntityTableQuery(EntityQueryContext ctx, EntityFilter entityFilter, EntityType entityType) { switch (entityFilter.getType()) { case RELATIONS_QUERY: return relationQuery(ctx, (RelationsQueryFilter) entityFilter); case DEVICE_SEARCH_QUERY: DeviceSearchQueryFilter deviceQuery = (DeviceSearchQueryFilter) entityFilter; return entitySearchQuery(ctx, deviceQuery, EntityType.DEVICE, deviceQuery.getDeviceTypes()); case ASSET_SEARCH_QUERY: AssetSearchQueryFilter assetQuery = (AssetSearchQueryFilter) entityFilter; return entitySearchQuery(ctx, assetQuery, EntityType.ASSET, assetQuery.getAssetTypes()); default: return entityTableMap.get(entityType); } } private String entitySearchQuery(EntityQueryContext ctx, EntitySearchQueryFilter entityFilter, EntityType entityType, List<String> types) { EntityId rootId = entityFilter.getRootEntity(); //TODO: fetch last level only. //TODO: fetch distinct records. String lvlFilter = getLvlFilter(entityFilter.getMaxLevel()); String selectFields = "SELECT tenant_id, customer_id, id, type, name, label FROM " + entityType.name() + " WHERE id in ( SELECT entity_id"; String from = getQueryTemplate(entityFilter.getDirection()); String whereFilter = " WHERE re.relation_type = :where_relation_type AND re.to_type = :where_entity_type"; from = String.format(from, lvlFilter, whereFilter); String query = "( " + selectFields + from + ")"; if (types != null && !types.isEmpty()) { query += " and type in (:relation_sub_types)"; ctx.addStringListParameter("relation_sub_types", types); } query += " )"; ctx.addUuidParameter("relation_root_id", rootId.getId()); ctx.addStringParameter("relation_root_type", rootId.getEntityType().name()); ctx.addStringParameter("where_relation_type", entityFilter.getRelationType()); ctx.addStringParameter("where_entity_type", entityType.name()); return query; } private String relationQuery(EntityQueryContext ctx, RelationsQueryFilter entityFilter) { EntityId rootId = entityFilter.getRootEntity(); String lvlFilter = getLvlFilter(entityFilter.getMaxLevel()); String selectFields = getSelectTenantId() + ", " + getSelectCustomerId() + ", " + " entity.entity_id as id," + getSelectType() + ", " + getSelectName() + ", " + getSelectLabel() + ", entity.entity_type as entity_type"; String from = getQueryTemplate(entityFilter.getDirection()); ctx.addUuidParameter("relation_root_id", rootId.getId()); ctx.addStringParameter("relation_root_type", rootId.getEntityType().name()); StringBuilder whereFilter; if (entityFilter.getFilters() != null && !entityFilter.getFilters().isEmpty()) { whereFilter = new StringBuilder(" WHERE "); boolean first = true; boolean single = entityFilter.getFilters().size() == 1; int entityTypeFilterIdx = 0; for (EntityTypeFilter etf : entityFilter.getFilters()) { if (first) { first = false; } else { whereFilter.append(" AND "); } String relationType = etf.getRelationType(); if (!single) { whereFilter.append(" ("); } whereFilter.append(" re.relation_type = :where_relation_type").append(entityTypeFilterIdx).append(" and re.") .append(entityFilter.getDirection().equals(EntitySearchDirection.FROM) ? "to" : "from") .append("_type in (:where_entity_types").append(entityTypeFilterIdx).append(")"); if (!single) { whereFilter.append(" )"); } ctx.addStringParameter("where_relation_type" + entityTypeFilterIdx, relationType); ctx.addStringListParameter("where_entity_types" + entityTypeFilterIdx, etf.getEntityTypes().stream().map(EntityType::name).collect(Collectors.toList())); entityTypeFilterIdx++; } } else { whereFilter = new StringBuilder(); } from = String.format(from, lvlFilter, whereFilter); return "( " + selectFields + from + ")"; } private String getLvlFilter(int maxLevel) { return maxLevel > 0 ? ("and lvl <= " + (maxLevel - 1)) : ""; } private String getQueryTemplate(EntitySearchDirection direction) { String from; if (direction.equals(EntitySearchDirection.FROM)) { from = HIERARCHICAL_FROM_QUERY_TEMPLATE; } else { from = HIERARCHICAL_TO_QUERY_TEMPLATE; } return from; } private String getSelectTenantId() { return "SELECT CASE" + " WHEN entity.entity_type = 'TENANT' THEN entity_id" + " WHEN entity.entity_type = 'CUSTOMER'" + " THEN (select tenant_id from customer where id = entity_id)" + " WHEN entity.entity_type = 'USER'" + " THEN (select tenant_id from tb_user where id = entity_id)" + " WHEN entity.entity_type = 'DASHBOARD'" + " THEN (select tenant_id from dashboard where id = entity_id)" + " WHEN entity.entity_type = 'ASSET'" + " THEN (select tenant_id from asset where id = entity_id)" + " WHEN entity.entity_type = 'DEVICE'" + " THEN (select tenant_id from device where id = entity_id)" + " WHEN entity.entity_type = 'ENTITY_VIEW'" + " THEN (select tenant_id from entity_view where id = entity_id)" + " END as tenant_id"; } private String getSelectCustomerId() { return "CASE" + " WHEN entity.entity_type = 'TENANT'" + " THEN UUID('" + TenantId.NULL_UUID + "')" + " WHEN entity.entity_type = 'CUSTOMER' THEN entity_id" + " WHEN entity.entity_type = 'USER'" + " THEN (select customer_id from tb_user where id = entity_id)" + " WHEN entity.entity_type = 'DASHBOARD'" + //TODO: parse assigned customers or use contains? " THEN NULL" + " WHEN entity.entity_type = 'ASSET'" + " THEN (select customer_id from asset where id = entity_id)" + " WHEN entity.entity_type = 'DEVICE'" + " THEN (select customer_id from device where id = entity_id)" + " WHEN entity.entity_type = 'ENTITY_VIEW'" + " THEN (select customer_id from entity_view where id = entity_id)" + " END as customer_id"; } private String getSelectName() { return " CASE" + " WHEN entity.entity_type = 'TENANT'" + " THEN (select title from tenant where id = entity_id)" + " WHEN entity.entity_type = 'CUSTOMER' " + " THEN (select title from customer where id = entity_id)" + " WHEN entity.entity_type = 'USER'" + " THEN (select CONCAT (first_name, ' ', last_name) from tb_user where id = entity_id)" + " WHEN entity.entity_type = 'DASHBOARD'" + " THEN (select title from dashboard where id = entity_id)" + " WHEN entity.entity_type = 'ASSET'" + " THEN (select name from asset where id = entity_id)" + " WHEN entity.entity_type = 'DEVICE'" + " THEN (select name from device where id = entity_id)" + " WHEN entity.entity_type = 'ENTITY_VIEW'" + " THEN (select name from entity_view where id = entity_id)" + " END as name"; } private String getSelectType() { return " CASE" + " WHEN entity.entity_type = 'USER'" + " THEN (select authority from tb_user where id = entity_id)" + " WHEN entity.entity_type = 'ASSET'" + " THEN (select type from asset where id = entity_id)" + " WHEN entity.entity_type = 'DEVICE'" + " THEN (select type from device where id = entity_id)" + " WHEN entity.entity_type = 'ENTITY_VIEW'" + " THEN (select type from entity_view where id = entity_id)" + " ELSE entity.entity_type END as type"; } private String getSelectLabel() { return " CASE" + " WHEN entity.entity_type = 'TENANT'" + " THEN (select title from tenant where id = entity_id)" + " WHEN entity.entity_type = 'CUSTOMER' " + " THEN (select title from customer where id = entity_id)" + " WHEN entity.entity_type = 'USER'" + " THEN (select CONCAT (first_name, ' ', last_name) from tb_user where id = entity_id)" + " WHEN entity.entity_type = 'DASHBOARD'" + " THEN (select title from dashboard where id = entity_id)" + " WHEN entity.entity_type = 'ASSET'" + " THEN (select label from asset where id = entity_id)" + " WHEN entity.entity_type = 'DEVICE'" + " THEN (select label from device where id = entity_id)" + " WHEN entity.entity_type = 'ENTITY_VIEW'" + " THEN (select name from entity_view where id = entity_id)" + " END as label"; } private String buildWhere(EntityQueryContext ctx, List<EntityKeyMapping> latestFiltersMapping) { String latestFilters = EntityKeyMapping.buildQuery(ctx, latestFiltersMapping); if (!StringUtils.isEmpty(latestFilters)) { return String.format("where %s", latestFilters); } else { return ""; } } private String buildTextSearchQuery(EntityQueryContext ctx, List<EntityKeyMapping> selectionMapping, String searchText) { if (!StringUtils.isEmpty(searchText) && !selectionMapping.isEmpty()) { String lowerSearchText = searchText.toLowerCase() + "%"; List<String> searchPredicates = selectionMapping.stream().map(mapping -> { String paramName = mapping.getValueAlias() + "_lowerSearchText"; ctx.addStringParameter(paramName, lowerSearchText); return String.format("LOWER(%s) LIKE concat('%%', :%s, '%%')", mapping.getValueAlias(), paramName); } ).collect(Collectors.toList()); return String.format(" WHERE %s", String.join(" or ", searchPredicates)); } else { return ""; } } private String singleEntityQuery(EntityQueryContext ctx, SingleEntityFilter filter) { ctx.addUuidParameter("entity_filter_single_entity_id", filter.getSingleEntity().getId()); return "e.id=:entity_filter_single_entity_id"; } private String entityListQuery(EntityQueryContext ctx, EntityListFilter filter) { ctx.addUuidListParameter("entity_filter_entity_ids", filter.getEntityList().stream().map(UUID::fromString).collect(Collectors.toList())); return "e.id in (:entity_filter_entity_ids)"; } private String entityNameQuery(EntityQueryContext ctx, EntityNameFilter filter) { ctx.addStringParameter("entity_filter_name_filter", filter.getEntityNameFilter()); return "lower(e.search_text) like lower(concat(:entity_filter_name_filter, '%%'))"; } private String typeQuery(EntityQueryContext ctx, EntityFilter filter) { String type; String name; switch (filter.getType()) { case ASSET_TYPE: type = ((AssetTypeFilter) filter).getAssetType(); name = ((AssetTypeFilter) filter).getAssetNameFilter(); break; case DEVICE_TYPE: type = ((DeviceTypeFilter) filter).getDeviceType(); name = ((DeviceTypeFilter) filter).getDeviceNameFilter(); break; case ENTITY_VIEW_TYPE: type = ((EntityViewTypeFilter) filter).getEntityViewType(); name = ((EntityViewTypeFilter) filter).getEntityViewNameFilter(); break; default: throw new RuntimeException("Not supported!"); } ctx.addStringParameter("entity_filter_type_query_type", type); ctx.addStringParameter("entity_filter_type_query_name", name); return "e.type = :entity_filter_type_query_type and lower(e.search_text) like lower(concat(:entity_filter_type_query_name, '%%'))"; } private EntityType resolveEntityType(EntityFilter entityFilter) { switch (entityFilter.getType()) { case SINGLE_ENTITY: return ((SingleEntityFilter) entityFilter).getSingleEntity().getEntityType(); case ENTITY_LIST: return ((EntityListFilter) entityFilter).getEntityType(); case ENTITY_NAME: return ((EntityNameFilter) entityFilter).getEntityType(); case ASSET_TYPE: case ASSET_SEARCH_QUERY: return EntityType.ASSET; case DEVICE_TYPE: case DEVICE_SEARCH_QUERY: return EntityType.DEVICE; case ENTITY_VIEW_TYPE: case ENTITY_VIEW_SEARCH_QUERY: return EntityType.ENTITY_VIEW; case RELATIONS_QUERY: return ((RelationsQueryFilter) entityFilter).getRootEntity().getEntityType(); default: throw new RuntimeException("Not implemented!"); } } }
dao/src/main/java/org/thingsboard/server/dao/sql/query/DefaultEntityQueryRepository.java
/** * Copyright © 2016-2020 The Thingsboard Authors * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.thingsboard.server.dao.sql.query; import lombok.extern.slf4j.Slf4j; import org.apache.commons.lang3.StringUtils; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.jdbc.core.namedparam.NamedParameterJdbcTemplate; import org.springframework.stereotype.Repository; import org.thingsboard.server.common.data.EntityType; import org.thingsboard.server.common.data.id.CustomerId; import org.thingsboard.server.common.data.id.EntityId; import org.thingsboard.server.common.data.id.TenantId; import org.thingsboard.server.common.data.page.PageData; import org.thingsboard.server.common.data.query.AssetSearchQueryFilter; import org.thingsboard.server.common.data.query.AssetTypeFilter; import org.thingsboard.server.common.data.query.DeviceSearchQueryFilter; import org.thingsboard.server.common.data.query.DeviceTypeFilter; import org.thingsboard.server.common.data.query.EntityCountQuery; import org.thingsboard.server.common.data.query.EntityData; import org.thingsboard.server.common.data.query.EntityDataPageLink; import org.thingsboard.server.common.data.query.EntityDataQuery; import org.thingsboard.server.common.data.query.EntityDataSortOrder; import org.thingsboard.server.common.data.query.EntityFilter; import org.thingsboard.server.common.data.query.EntityFilterType; import org.thingsboard.server.common.data.query.EntityListFilter; import org.thingsboard.server.common.data.query.EntityNameFilter; import org.thingsboard.server.common.data.query.EntitySearchQueryFilter; import org.thingsboard.server.common.data.query.EntityViewTypeFilter; import org.thingsboard.server.common.data.query.RelationsQueryFilter; import org.thingsboard.server.common.data.query.SingleEntityFilter; import org.thingsboard.server.common.data.relation.EntitySearchDirection; import org.thingsboard.server.common.data.relation.EntityTypeFilter; import org.thingsboard.server.dao.util.SqlDao; import java.math.BigInteger; import java.util.Collections; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.Optional; import java.util.UUID; import java.util.stream.Collectors; @SqlDao @Repository @Slf4j public class DefaultEntityQueryRepository implements EntityQueryRepository { //TODO: rafactoring to protect from SQL injections; private static final Map<EntityType, String> entityTableMap = new HashMap<>(); static { entityTableMap.put(EntityType.ASSET, "asset"); entityTableMap.put(EntityType.DEVICE, "device"); entityTableMap.put(EntityType.ENTITY_VIEW, "entity_view"); entityTableMap.put(EntityType.DASHBOARD, "dashboard"); entityTableMap.put(EntityType.CUSTOMER, "customer"); entityTableMap.put(EntityType.USER, "tb_user"); entityTableMap.put(EntityType.TENANT, "tenant"); } public static final String HIERARCHICAL_QUERY_TEMPLATE = " FROM (WITH RECURSIVE related_entities(from_id, from_type, to_id, to_type, relation_type, lvl) AS (" + " SELECT from_id, from_type, to_id, to_type, relation_type, 1 as lvl" + " FROM relation" + " WHERE $in_id = :relation_root_id and $in_type = :relation_root_type and relation_type_group = 'COMMON'" + " UNION ALL" + " SELECT r.from_id, r.from_type, r.to_id, r.to_type, r.relation_type, lvl + 1" + " FROM relation r" + " INNER JOIN related_entities re ON" + " r.$in_id = re.$out_id and r.$in_type = re.$out_type and" + " relation_type_group = 'COMMON' %s)" + " SELECT re.$out_id entity_id, re.$out_type entity_type, re.lvl lvl" + " from related_entities re" + " %s ) entity"; public static final String HIERARCHICAL_TO_QUERY_TEMPLATE = HIERARCHICAL_QUERY_TEMPLATE.replace("$in", "to").replace("$out", "from"); public static final String HIERARCHICAL_FROM_QUERY_TEMPLATE = HIERARCHICAL_QUERY_TEMPLATE.replace("$in", "from").replace("$out", "to"); @Autowired protected NamedParameterJdbcTemplate jdbcTemplate; @Override public long countEntitiesByQuery(TenantId tenantId, CustomerId customerId, EntityCountQuery query) { EntityType entityType = resolveEntityType(query.getEntityFilter()); EntityQueryContext ctx = new EntityQueryContext(); ctx.append("select count(e.id) from "); ctx.append(addEntityTableQuery(ctx, query.getEntityFilter(), entityType)); ctx.append(" e where "); ctx.append(buildEntityWhere(ctx, tenantId, customerId, query.getEntityFilter(), Collections.emptyList(), entityType)); return jdbcTemplate.queryForObject(ctx.getQuery(), ctx, Long.class); } @Override public PageData<EntityData> findEntityDataByQuery(TenantId tenantId, CustomerId customerId, EntityDataQuery query) { EntityQueryContext ctx = new EntityQueryContext(); EntityType entityType = resolveEntityType(query.getEntityFilter()); EntityDataPageLink pageLink = query.getPageLink(); List<EntityKeyMapping> mappings = EntityKeyMapping.prepareKeyMapping(query); List<EntityKeyMapping> selectionMapping = mappings.stream().filter(EntityKeyMapping::isSelection) .collect(Collectors.toList()); List<EntityKeyMapping> entityFieldsSelectionMapping = selectionMapping.stream().filter(mapping -> !mapping.isLatest()) .collect(Collectors.toList()); List<EntityKeyMapping> latestSelectionMapping = selectionMapping.stream().filter(EntityKeyMapping::isLatest) .collect(Collectors.toList()); List<EntityKeyMapping> filterMapping = mappings.stream().filter(EntityKeyMapping::hasFilter) .collect(Collectors.toList()); List<EntityKeyMapping> entityFieldsFiltersMapping = filterMapping.stream().filter(mapping -> !mapping.isLatest()) .collect(Collectors.toList()); List<EntityKeyMapping> latestFiltersMapping = filterMapping.stream().filter(EntityKeyMapping::isLatest) .collect(Collectors.toList()); List<EntityKeyMapping> allLatestMappings = mappings.stream().filter(EntityKeyMapping::isLatest) .collect(Collectors.toList()); String entityWhereClause = this.buildEntityWhere(ctx, tenantId, customerId, query.getEntityFilter(), entityFieldsFiltersMapping, entityType); String latestJoins = EntityKeyMapping.buildLatestJoins(ctx, query.getEntityFilter(), entityType, allLatestMappings); String whereClause = this.buildWhere(ctx, latestFiltersMapping); String textSearchQuery = this.buildTextSearchQuery(ctx, selectionMapping, pageLink.getTextSearch()); String entityFieldsSelection = EntityKeyMapping.buildSelections(entityFieldsSelectionMapping); String entityTypeStr; if (query.getEntityFilter().getType().equals(EntityFilterType.RELATIONS_QUERY)) { entityTypeStr = "e.entity_type"; } else { entityTypeStr = "'" + entityType.name() + "'"; } if (!StringUtils.isEmpty(entityFieldsSelection)) { entityFieldsSelection = String.format("e.id id, %s entity_type, %s", entityTypeStr, entityFieldsSelection); } else { entityFieldsSelection = String.format("e.id id, %s entity_type", entityTypeStr); } String latestSelection = EntityKeyMapping.buildSelections(latestSelectionMapping); String topSelection = "entities.*"; if (!StringUtils.isEmpty(latestSelection)) { topSelection = topSelection + ", " + latestSelection; } String fromClause = String.format("from (select %s from (select %s from %s e where %s) entities %s %s) result %s", topSelection, entityFieldsSelection, addEntityTableQuery(ctx, query.getEntityFilter(), entityType), entityWhereClause, latestJoins, whereClause, textSearchQuery); int totalElements = jdbcTemplate.queryForObject(String.format("select count(*) %s", fromClause), ctx, Integer.class); String dataQuery = String.format("select * %s", fromClause); EntityDataSortOrder sortOrder = pageLink.getSortOrder(); if (sortOrder != null) { Optional<EntityKeyMapping> sortOrderMappingOpt = mappings.stream().filter(EntityKeyMapping::isSortOrder).findFirst(); if (sortOrderMappingOpt.isPresent()) { EntityKeyMapping sortOrderMapping = sortOrderMappingOpt.get(); dataQuery = String.format("%s order by %s", dataQuery, sortOrderMapping.getValueAlias()); if (sortOrder.getDirection() == EntityDataSortOrder.Direction.ASC) { dataQuery += " asc"; } else { dataQuery += " desc"; } } } int startIndex = pageLink.getPageSize() * pageLink.getPage(); if (pageLink.getPageSize() > 0) { dataQuery = String.format("%s limit %s offset %s", dataQuery, pageLink.getPageSize(), startIndex); } List<Map<String, Object>> rows = jdbcTemplate.queryForList(dataQuery, ctx); return EntityDataAdapter.createEntityData(pageLink, selectionMapping, rows, totalElements); } private String buildEntityWhere(EntityQueryContext ctx, TenantId tenantId, CustomerId customerId, EntityFilter entityFilter, List<EntityKeyMapping> entityFieldsFilters, EntityType entityType) { String permissionQuery = this.buildPermissionQuery(ctx, entityFilter, tenantId, customerId, entityType); String entityFilterQuery = this.buildEntityFilterQuery(ctx, entityFilter); String result = permissionQuery; if (!entityFilterQuery.isEmpty()) { result += " and " + entityFilterQuery; } if (!entityFieldsFilters.isEmpty()) { result += " and " + entityFieldsFilters; } return result; } private String buildPermissionQuery(EntityQueryContext ctx, EntityFilter entityFilter, TenantId tenantId, CustomerId customerId, EntityType entityType) { switch (entityFilter.getType()) { case RELATIONS_QUERY: case DEVICE_SEARCH_QUERY: case ASSET_SEARCH_QUERY: return this.defaultPermissionQuery(ctx, tenantId, customerId, entityType); default: if (entityType == EntityType.TENANT) { ctx.addUuidParameter("permissions_tenant_id", tenantId.getId()); return "e.id=:permissions_tenant_id"; } else { return this.defaultPermissionQuery(ctx, tenantId, customerId, entityType); } } } private String defaultPermissionQuery(EntityQueryContext ctx, TenantId tenantId, CustomerId customerId, EntityType entityType) { ctx.addUuidParameter("permissions_tenant_id", tenantId.getId()); if (customerId != null && !customerId.isNullUid()) { ctx.addUuidParameter("permissions_customer_id", customerId.getId()); if (entityType == EntityType.CUSTOMER) { return "e.tenant_id=:permissions_tenant_id and e.id=:permissions_customer_id"; } else { return "e.tenant_id=:permissions_tenant_id and e.customer_id=:permissions_customer_id"; } } else { return "e.tenant_id=:permissions_tenant_id"; } } private String buildEntityFilterQuery(EntityQueryContext ctx, EntityFilter entityFilter) { switch (entityFilter.getType()) { case SINGLE_ENTITY: return this.singleEntityQuery(ctx, (SingleEntityFilter) entityFilter); case ENTITY_LIST: return this.entityListQuery(ctx, (EntityListFilter) entityFilter); case ENTITY_NAME: return this.entityNameQuery(ctx, (EntityNameFilter) entityFilter); case ASSET_TYPE: case DEVICE_TYPE: case ENTITY_VIEW_TYPE: return this.typeQuery(ctx, entityFilter); case RELATIONS_QUERY: case DEVICE_SEARCH_QUERY: case ASSET_SEARCH_QUERY: return ""; default: throw new RuntimeException("Not implemented!"); } } private String addEntityTableQuery(EntityQueryContext ctx, EntityFilter entityFilter, EntityType entityType) { switch (entityFilter.getType()) { case RELATIONS_QUERY: return relationQuery(ctx, (RelationsQueryFilter) entityFilter); case DEVICE_SEARCH_QUERY: DeviceSearchQueryFilter deviceQuery = (DeviceSearchQueryFilter) entityFilter; return entitySearchQuery(ctx, deviceQuery, EntityType.DEVICE, deviceQuery.getDeviceTypes()); case ASSET_SEARCH_QUERY: AssetSearchQueryFilter assetQuery = (AssetSearchQueryFilter) entityFilter; return entitySearchQuery(ctx, assetQuery, EntityType.ASSET, assetQuery.getAssetTypes()); default: return entityTableMap.get(entityType); } } private String entitySearchQuery(EntityQueryContext ctx, EntitySearchQueryFilter entityFilter, EntityType entityType, List<String> types) { EntityId rootId = entityFilter.getRootEntity(); //TODO: fetch last level only. //TODO: fetch distinct records. String lvlFilter = getLvlFilter(entityFilter.getMaxLevel()); String selectFields = "SELECT tenant_id, customer_id, id, type, name, label FROM " + entityType.name() + " WHERE id in ( SELECT entity_id"; String from = getQueryTemplate(entityFilter.getDirection()); String whereFilter = " WHERE re.relation_type = :where_relation_type AND re.to_type = :where_entity_type"; from = String.format(from, lvlFilter, whereFilter); String query = "( " + selectFields + from + ")"; if (types != null && !types.isEmpty()) { query += " and type in (:relation_sub_types)"; ctx.addStringListParameter("relation_sub_types", types); } query += " )"; ctx.addUuidParameter("relation_root_id", rootId.getId()); ctx.addStringParameter("relation_root_type", rootId.getEntityType().name()); ctx.addStringParameter("where_relation_type", entityFilter.getRelationType()); ctx.addStringParameter("where_entity_type", entityType.name()); return query; } private String relationQuery(EntityQueryContext ctx, RelationsQueryFilter entityFilter) { EntityId rootId = entityFilter.getRootEntity(); String lvlFilter = getLvlFilter(entityFilter.getMaxLevel()); String selectFields = getSelectTenantId() + ", " + getSelectCustomerId() + ", " + " entity.entity_id as id," + getSelectType() + ", " + getSelectName() + ", " + getSelectLabel() + ", entity.entity_type as entity_type"; String from = getQueryTemplate(entityFilter.getDirection()); ctx.addUuidParameter("relation_root_id", rootId.getId()); ctx.addStringParameter("relation_root_type", rootId.getEntityType().name()); StringBuilder whereFilter; if (entityFilter.getFilters() != null && !entityFilter.getFilters().isEmpty()) { whereFilter = new StringBuilder(" WHERE "); boolean first = true; boolean single = entityFilter.getFilters().size() == 1; int entityTypeFilterIdx = 0; for (EntityTypeFilter etf : entityFilter.getFilters()) { if (first) { first = false; } else { whereFilter.append(" AND "); } String relationType = etf.getRelationType(); if (!single) { whereFilter.append(" ("); } whereFilter.append(" re.relation_type = :where_relation_type").append(entityTypeFilterIdx).append(" and re.") .append(entityFilter.getDirection().equals(EntitySearchDirection.FROM) ? "to" : "from") .append("_type in (:where_entity_types").append(entityTypeFilterIdx).append(")"); if (!single) { whereFilter.append(" )"); } ctx.addStringParameter("where_relation_type" + entityTypeFilterIdx, relationType); ctx.addStringListParameter("where_entity_types" + entityTypeFilterIdx, etf.getEntityTypes().stream().map(EntityType::name).collect(Collectors.toList())); entityTypeFilterIdx++; } } else { whereFilter = new StringBuilder(); } from = String.format(from, lvlFilter, whereFilter); return "( " + selectFields + from + ")"; } private String getLvlFilter(int maxLevel) { return maxLevel > 0 ? ("and lvl <= " + (maxLevel - 1)) : ""; } private String getQueryTemplate(EntitySearchDirection direction) { String from; if (direction.equals(EntitySearchDirection.FROM)) { from = HIERARCHICAL_FROM_QUERY_TEMPLATE; } else { from = HIERARCHICAL_TO_QUERY_TEMPLATE; } return from; } private String getSelectTenantId() { return "SELECT CASE" + " WHEN entity.entity_type = 'TENANT' THEN entity_id" + " WHEN entity.entity_type = 'CUSTOMER'" + " THEN (select tenant_id from customer where id = entity_id)" + " WHEN entity.entity_type = 'USER'" + " THEN (select tenant_id from tb_user where id = entity_id)" + " WHEN entity.entity_type = 'DASHBOARD'" + " THEN (select tenant_id from dashboard where id = entity_id)" + " WHEN entity.entity_type = 'ASSET'" + " THEN (select tenant_id from asset where id = entity_id)" + " WHEN entity.entity_type = 'DEVICE'" + " THEN (select tenant_id from device where id = entity_id)" + " WHEN entity.entity_type = 'ENTITY_VIEW'" + " THEN (select tenant_id from entity_view where id = entity_id)" + " END as tenant_id"; } private String getSelectCustomerId() { return "CASE" + " WHEN entity.entity_type = 'TENANT'" + " THEN UUID('" + TenantId.NULL_UUID + "')" + " WHEN entity.entity_type = 'CUSTOMER' THEN entity_id" + " WHEN entity.entity_type = 'USER'" + " THEN (select customer_id from tb_user where id = entity_id)" + " WHEN entity.entity_type = 'DASHBOARD'" + //TODO: parse assigned customers or use contains? " THEN NULL" + " WHEN entity.entity_type = 'ASSET'" + " THEN (select customer_id from asset where id = entity_id)" + " WHEN entity.entity_type = 'DEVICE'" + " THEN (select customer_id from device where id = entity_id)" + " WHEN entity.entity_type = 'ENTITY_VIEW'" + " THEN (select customer_id from entity_view where id = entity_id)" + " END as customer_id"; } private String getSelectName() { return " CASE" + " WHEN entity.entity_type = 'TENANT'" + " THEN (select title from tenant where id = entity_id)" + " WHEN entity.entity_type = 'CUSTOMER' " + " THEN (select title from customer where id = entity_id)" + " WHEN entity.entity_type = 'USER'" + " THEN (select CONCAT (first_name, ' ', last_name) from tb_user where id = entity_id)" + " WHEN entity.entity_type = 'DASHBOARD'" + " THEN (select title from dashboard where id = entity_id)" + " WHEN entity.entity_type = 'ASSET'" + " THEN (select name from asset where id = entity_id)" + " WHEN entity.entity_type = 'DEVICE'" + " THEN (select name from device where id = entity_id)" + " WHEN entity.entity_type = 'ENTITY_VIEW'" + " THEN (select name from entity_view where id = entity_id)" + " END as name"; } private String getSelectType() { return " CASE" + " WHEN entity.entity_type = 'USER'" + " THEN (select authority from tb_user where id = entity_id)" + " WHEN entity.entity_type = 'ASSET'" + " THEN (select type from asset where id = entity_id)" + " WHEN entity.entity_type = 'DEVICE'" + " THEN (select type from device where id = entity_id)" + " WHEN entity.entity_type = 'ENTITY_VIEW'" + " THEN (select type from entity_view where id = entity_id)" + " ELSE entity.entity_type END as type"; } private String getSelectLabel() { return " CASE" + " WHEN entity.entity_type = 'TENANT'" + " THEN (select title from tenant where id = entity_id)" + " WHEN entity.entity_type = 'CUSTOMER' " + " THEN (select title from customer where id = entity_id)" + " WHEN entity.entity_type = 'USER'" + " THEN (select CONCAT (first_name, ' ', last_name) from tb_user where id = entity_id)" + " WHEN entity.entity_type = 'DASHBOARD'" + " THEN (select title from dashboard where id = entity_id)" + " WHEN entity.entity_type = 'ASSET'" + " THEN (select label from asset where id = entity_id)" + " WHEN entity.entity_type = 'DEVICE'" + " THEN (select label from device where id = entity_id)" + " WHEN entity.entity_type = 'ENTITY_VIEW'" + " THEN (select name from entity_view where id = entity_id)" + " END as label"; } private String buildWhere(EntityQueryContext ctx, List<EntityKeyMapping> latestFiltersMapping) { String latestFilters = EntityKeyMapping.buildQuery(ctx, latestFiltersMapping); if (!StringUtils.isEmpty(latestFilters)) { return String.format("where %s", latestFilters); } else { return ""; } } private String buildTextSearchQuery(EntityQueryContext ctx, List<EntityKeyMapping> selectionMapping, String searchText) { if (!StringUtils.isEmpty(searchText) && !selectionMapping.isEmpty()) { String lowerSearchText = searchText.toLowerCase() + "%"; List<String> searchPredicates = selectionMapping.stream().map(mapping -> { String paramName = mapping.getValueAlias() + "_lowerSearchText"; ctx.addStringParameter(paramName, lowerSearchText); return String.format("LOWER(%s) LIKE :%s", mapping.getValueAlias(), paramName); } ).collect(Collectors.toList()); return String.format(" WHERE %s", String.join(" or ", searchPredicates)); } else { return ""; } } private String singleEntityQuery(EntityQueryContext ctx, SingleEntityFilter filter) { ctx.addUuidParameter("entity_filter_single_entity_id", filter.getSingleEntity().getId()); return "e.id=:entity_filter_single_entity_id"; } private String entityListQuery(EntityQueryContext ctx, EntityListFilter filter) { ctx.addUuidListParameter("entity_filter_entity_ids", filter.getEntityList().stream().map(UUID::fromString).collect(Collectors.toList())); return "e.id in (:entity_filter_entity_ids)"; } private String entityNameQuery(EntityQueryContext ctx, EntityNameFilter filter) { ctx.addStringParameter("entity_filter_name_filter", filter.getEntityNameFilter()); return "lower(e.search_text) like lower(concat(:entity_filter_name_filter, '%%'))"; } private String typeQuery(EntityQueryContext ctx, EntityFilter filter) { String type; String name; switch (filter.getType()) { case ASSET_TYPE: type = ((AssetTypeFilter) filter).getAssetType(); name = ((AssetTypeFilter) filter).getAssetNameFilter(); break; case DEVICE_TYPE: type = ((DeviceTypeFilter) filter).getDeviceType(); name = ((DeviceTypeFilter) filter).getDeviceNameFilter(); break; case ENTITY_VIEW_TYPE: type = ((EntityViewTypeFilter) filter).getEntityViewType(); name = ((EntityViewTypeFilter) filter).getEntityViewNameFilter(); break; default: throw new RuntimeException("Not supported!"); } ctx.addStringParameter("entity_filter_type_query_type", type); ctx.addStringParameter("entity_filter_type_query_name", name); return "e.type = :entity_filter_type_query_type and lower(e.search_text) like lower(concat(:entity_filter_type_query_name, '%%'))"; } private EntityType resolveEntityType(EntityFilter entityFilter) { switch (entityFilter.getType()) { case SINGLE_ENTITY: return ((SingleEntityFilter) entityFilter).getSingleEntity().getEntityType(); case ENTITY_LIST: return ((EntityListFilter) entityFilter).getEntityType(); case ENTITY_NAME: return ((EntityNameFilter) entityFilter).getEntityType(); case ASSET_TYPE: case ASSET_SEARCH_QUERY: return EntityType.ASSET; case DEVICE_TYPE: case DEVICE_SEARCH_QUERY: return EntityType.DEVICE; case ENTITY_VIEW_TYPE: case ENTITY_VIEW_SEARCH_QUERY: return EntityType.ENTITY_VIEW; case RELATIONS_QUERY: return ((RelationsQueryFilter) entityFilter).getRootEntity().getEntityType(); default: throw new RuntimeException("Not implemented!"); } } }
Full text search for backward compatibility
dao/src/main/java/org/thingsboard/server/dao/sql/query/DefaultEntityQueryRepository.java
Full text search for backward compatibility
<ide><path>ao/src/main/java/org/thingsboard/server/dao/sql/query/DefaultEntityQueryRepository.java <ide> List<String> searchPredicates = selectionMapping.stream().map(mapping -> { <ide> String paramName = mapping.getValueAlias() + "_lowerSearchText"; <ide> ctx.addStringParameter(paramName, lowerSearchText); <del> return String.format("LOWER(%s) LIKE :%s", mapping.getValueAlias(), paramName); <add> return String.format("LOWER(%s) LIKE concat('%%', :%s, '%%')", mapping.getValueAlias(), paramName); <ide> } <ide> ).collect(Collectors.toList()); <ide> return String.format(" WHERE %s", String.join(" or ", searchPredicates));
Java
bsd-2-clause
f7bf73f5fd6ed789c0ea8bdb88d25d3d8bf61a99
0
imagej/imagej-legacy,imagej/imagej-legacy,imagej/imagej-legacy,imagej/imagej-legacy
/* * #%L * ImageJ software for multidimensional image processing and analysis. * %% * Copyright (C) 2009 - 2014 Board of Regents of the University of * Wisconsin-Madison, Broad Institute of MIT and Harvard, and Max Planck * Institute of Molecular Cell Biology and Genetics. * %% * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * 1. Redistributions of source code must retain the above copyright notice, * this list of conditions and the following disclaimer. * 2. Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDERS OR CONTRIBUTORS BE * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * #L% */ package net.imagej.legacy.plugin; import java.util.Arrays; import java.util.List; import javax.script.ScriptEngine; import net.imagej.legacy.DefaultLegacyService; import org.scijava.plugin.Parameter; import org.scijava.plugin.Plugin; import org.scijava.script.AbstractScriptLanguage; import org.scijava.script.ScriptLanguage; /** * Implements a factory for the ImageJ 1.x Macro language engine. * * @author Johannes Schindelin */ @Plugin(type = ScriptLanguage.class, name = "IJ1 Macro") public class IJ1MacroLanguage extends AbstractScriptLanguage { @Parameter(required = false) private DefaultLegacyService legacyService; @Override public List<String> getExtensions() { return Arrays.asList("ijm"); } @Override public ScriptEngine getScriptEngine() { return new IJ1MacroEngine(legacyService().getIJ1Helper()); } private DefaultLegacyService legacyService() { if (legacyService != null) return legacyService; synchronized (this) { if (legacyService != null) return legacyService; legacyService = getContext().getService(DefaultLegacyService.class); if (legacyService == null) { throw new RuntimeException("No legacy service available!"); } return legacyService; } } }
src/main/java/net/imagej/legacy/plugin/IJ1MacroLanguage.java
/* * #%L * ImageJ software for multidimensional image processing and analysis. * %% * Copyright (C) 2009 - 2014 Board of Regents of the University of * Wisconsin-Madison, Broad Institute of MIT and Harvard, and Max Planck * Institute of Molecular Cell Biology and Genetics. * %% * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * 1. Redistributions of source code must retain the above copyright notice, * this list of conditions and the following disclaimer. * 2. Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDERS OR CONTRIBUTORS BE * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * #L% */ package net.imagej.legacy.plugin; import java.util.Arrays; import java.util.List; import javax.script.ScriptEngine; import net.imagej.legacy.DefaultLegacyService; import org.scijava.plugin.Parameter; import org.scijava.plugin.Plugin; import org.scijava.script.AbstractScriptLanguage; import org.scijava.script.ScriptLanguage; /** * Implements a factory for the ImageJ 1.x Macro language engine. * * @author Johannes Schindelin */ @Plugin(type = ScriptLanguage.class, name = "IJ1 Macro") public class IJ1MacroLanguage extends AbstractScriptLanguage { @Parameter(required = false) private DefaultLegacyService legacyService; @Override public List<String> getExtensions() { return Arrays.asList("ijm"); } @Override public String getLanguageName() { return "IJ1 Macro"; } @Override public ScriptEngine getScriptEngine() { return new IJ1MacroEngine(legacyService().getIJ1Helper()); } private DefaultLegacyService legacyService() { if (legacyService != null) return legacyService; synchronized (this) { if (legacyService != null) return legacyService; legacyService = getContext().getService(DefaultLegacyService.class); if (legacyService == null) { throw new RuntimeException("No legacy service available!"); } return legacyService; } } }
IJ1MacroLanguage: remove unneeded override The getLanguageName method now defaults to the @Plugin name attribute, so we no longer need to explicitly override it.
src/main/java/net/imagej/legacy/plugin/IJ1MacroLanguage.java
IJ1MacroLanguage: remove unneeded override
<ide><path>rc/main/java/net/imagej/legacy/plugin/IJ1MacroLanguage.java <ide> } <ide> <ide> @Override <del> public String getLanguageName() { <del> return "IJ1 Macro"; <del> } <del> <del> @Override <ide> public ScriptEngine getScriptEngine() { <ide> return new IJ1MacroEngine(legacyService().getIJ1Helper()); <ide> }
Java
apache-2.0
c4c1c6d038b7cde3530306f9faf2b2156c187d18
0
jesse-gallagher/frostillic.us-Blog,jesse-gallagher/frostillic.us-Blog,jesse-gallagher/frostillic.us-Blog,jesse-gallagher/frostillic.us-Blog
package model; import com.darwino.commons.json.JsonException; import com.darwino.commons.json.JsonObject; import com.darwino.jsonstore.Database; import com.darwino.jsonstore.Store; import frostillicus.blog.app.AppDatabaseDef; import javax.enterprise.inject.spi.CDI; import java.util.Collection; import java.util.TreeSet; public enum PostUtil { ; public static final int PAGE_LENGTH = 10; public static int getPostCount() throws JsonException { Database database = CDI.current().select(Database.class).get(); Store store = database.getStore(AppDatabaseDef.STORE_POSTS); return store.openCursor() .query(JsonObject.of("form", Post.class.getSimpleName())) //$NON-NLS-1$ .count(); } public static Collection<String> getPostMonths() throws JsonException { Collection<String> months = new TreeSet<>(); Database database = CDI.current().select(Database.class).get(); Store store = database.getStore(AppDatabaseDef.STORE_POSTS); store.openCursor() .query(JsonObject.of("form", Post.class.getSimpleName())) //$NON-NLS-1$ .findDocuments(doc -> { String posted = doc.getString("posted"); //$NON-NLS-1$ if(posted != null && posted.length() >= 7) { months.add(posted.substring(0, 7)); } return true; }); return months; } }
frostillicus-blog/frostillicus-blog-j2ee/src/main/java/model/PostUtil.java
package model; import com.darwino.commons.json.JsonException; import com.darwino.commons.json.JsonObject; import com.darwino.jsonstore.Database; import com.darwino.jsonstore.Store; import frostillicus.blog.app.AppDatabaseDef; import javax.enterprise.inject.spi.CDI; public enum PostUtil { ; public static final int PAGE_LENGTH = 10; public static int getPostCount() throws JsonException { Database database = CDI.current().select(Database.class).get(); Store store = database.getStore(AppDatabaseDef.STORE_POSTS); return store.openCursor() .query(JsonObject.of("form", Post.class.getSimpleName())) //$NON-NLS-1$ .count(); } }
De-dupe some code
frostillicus-blog/frostillicus-blog-j2ee/src/main/java/model/PostUtil.java
De-dupe some code
<ide><path>rostillicus-blog/frostillicus-blog-j2ee/src/main/java/model/PostUtil.java <ide> import frostillicus.blog.app.AppDatabaseDef; <ide> <ide> import javax.enterprise.inject.spi.CDI; <add>import java.util.Collection; <add>import java.util.TreeSet; <ide> <ide> public enum PostUtil { <ide> ; <ide> .query(JsonObject.of("form", Post.class.getSimpleName())) //$NON-NLS-1$ <ide> .count(); <ide> } <add> <add> public static Collection<String> getPostMonths() throws JsonException { <add> Collection<String> months = new TreeSet<>(); <add> <add> Database database = CDI.current().select(Database.class).get(); <add> Store store = database.getStore(AppDatabaseDef.STORE_POSTS); <add> store.openCursor() <add> .query(JsonObject.of("form", Post.class.getSimpleName())) //$NON-NLS-1$ <add> .findDocuments(doc -> { <add> String posted = doc.getString("posted"); //$NON-NLS-1$ <add> if(posted != null && posted.length() >= 7) { <add> months.add(posted.substring(0, 7)); <add> } <add> return true; <add> }); <add> <add> return months; <add> } <ide> }
Java
bsd-2-clause
a89420902a51531857b383a78b6531213aec87f0
0
christ66/stapler,vjuranek/stapler,ohtake/stapler,tempbottle/stapler,aldaris/stapler,vjuranek/stapler,ohtake/stapler,stapler/stapler,stapler/stapler,tfennelly/stapler,ohtake/stapler,ohtake/stapler,christ66/stapler,tempbottle/stapler,christ66/stapler,tfennelly/stapler,tfennelly/stapler,vjuranek/stapler,aldaris/stapler,vjuranek/stapler,ohtake/stapler,christ66/stapler,vjuranek/stapler,stapler/stapler,stapler/stapler,aldaris/stapler,stapler/stapler,aldaris/stapler,tempbottle/stapler,tfennelly/stapler,tempbottle/stapler,tempbottle/stapler,christ66/stapler,tfennelly/stapler,aldaris/stapler
package org.kohsuke.stapler; import net.sf.json.JSONObject; import org.apache.commons.beanutils.ConversionException; import org.apache.commons.beanutils.ConvertUtils; import org.apache.commons.beanutils.ConvertUtilsBean; import org.apache.commons.beanutils.Converter; import org.apache.commons.beanutils.converters.DoubleConverter; import org.apache.commons.beanutils.converters.FloatConverter; import org.apache.commons.beanutils.converters.IntegerConverter; import org.apache.commons.fileupload.FileItem; import static org.kohsuke.stapler.Dispatcher.traceable; import static org.kohsuke.stapler.Dispatcher.traceEval; import javax.servlet.RequestDispatcher; import javax.servlet.ServletConfig; import javax.servlet.ServletContext; import javax.servlet.ServletContextEvent; import javax.servlet.ServletContextListener; import javax.servlet.ServletException; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import static javax.servlet.http.HttpServletResponse.SC_NOT_FOUND; import java.io.File; import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; import java.io.PrintWriter; import java.io.DataInputStream; import java.lang.reflect.InvocationTargetException; import java.net.MalformedURLException; import java.net.URI; import java.net.URISyntaxException; import java.net.URL; import java.net.URLConnection; import java.text.ParseException; import java.text.SimpleDateFormat; import java.util.ArrayList; import java.util.Arrays; import java.util.Date; import java.util.HashSet; import java.util.Locale; import java.util.Set; import java.util.TimeZone; import java.util.regex.Pattern; import java.util.regex.Matcher; import java.util.logging.Level; import java.util.logging.Logger; /** * Maps an HTTP request to a method call / JSP invocation against a model object * by evaluating the request URL in a EL-ish way. * * <p> * This servlet should be used as the default servlet. * * @author Kohsuke Kawaguchi */ public class Stapler extends HttpServlet { private /*final*/ ServletContext context; private /*final*/ WebApp webApp; public @Override void init(ServletConfig servletConfig) throws ServletException { super.init(servletConfig); this.context = servletConfig.getServletContext(); this.webApp = WebApp.get(context); String defaultEncodings = servletConfig.getInitParameter("default-encodings"); if(defaultEncodings!=null) { for(String t : defaultEncodings.split(";")) { t=t.trim(); int idx=t.indexOf('='); if(idx<0) throw new ServletException("Invalid format: "+t); webApp.defaultEncodingForStaticResources.put(t.substring(0,idx),t.substring(idx+1)); } } } public WebApp getWebApp() { return webApp; } protected @Override void service(HttpServletRequest req, HttpServletResponse rsp) throws ServletException, IOException { Thread t = Thread.currentThread(); final String oldName = t.getName(); try { t.setName("Handling "+req.getMethod()+' '+req.getRequestURI()+" : "+oldName); String servletPath = getServletPath(req); if(LOGGER.isLoggable(Level.FINE)) LOGGER.fine("Processing request for "+servletPath); boolean staticLink = false; if(servletPath.startsWith("/static/")) { // skip "/static/..../ portion int idx = servletPath.indexOf('/',8); servletPath=servletPath.substring(idx); staticLink = true; } if(servletPath.length()!=0) { // getResource requires '/' prefix (and resin insists on that, too) but servletPath can be empty string (hudson #879) OpenConnection con = openResourcePathByLocale(req,servletPath); if(con!=null) { long expires = MetaClass.NO_CACHE ? 0 : 24L * 60 * 60 * 1000; /*1 day*/ if(staticLink) expires*=365; // static resources are unique, so we can set a long expiration date if(serveStaticResource(req, new ResponseImpl(this, rsp), con, expires)) return; // done } } Object root = context.getAttribute("app"); if(root==null) throw new ServletException("there's no \"app\" attribute in the application context."); // consider reusing this ArrayList. invoke( req, rsp, root, servletPath); } finally { t.setName(oldName); } } /** * Tomcat and GlassFish returns a fresh {@link InputStream} every time * {@link URLConnection#getInputStream()} is invoked in their {@code org.apache.naming.resources.DirContextURLConnection}. * * <p> * All the other {@link URLConnection}s in JDK don't do this --- they return the same {@link InputStream}, * even the one for the file:// URLs. * * <p> * In Tomcat (and most likely in GlassFish, although this is not verifid), resource look up on * {@link ServletContext#getResource(String)} successfully returns non-existent URL, and * the failure can be only detected by {@link IOException} from {@link URLConnection#getInputStream()}. * * <p> * Therefore, for the whole thing to work without resource leak, once we open {@link InputStream} * for the sake of really making sure that the resource exists, we need to hang on to that stream. * * <p> * Hence the need for this tuple. */ private static final class OpenConnection { final URLConnection connection; final InputStream stream; private OpenConnection(URLConnection connection, InputStream stream) { this.connection = connection; this.stream = stream; } private OpenConnection(URLConnection connection) throws IOException { this(connection,connection.getInputStream()); } } private OpenConnection openResourcePathByLocale(HttpServletRequest req,String resourcePath) throws IOException { URL url = getServletContext().getResource(resourcePath); if(url==null) return null; return selectResourceByLocale(url,req.getLocale()); } /** * Basically works like {@link URL#openConnection()} but it uses the * locale specific resource if available, by using the given locale. * * <p> * The syntax of the locale specific resource is the same as property file localization. * So Japanese resource for <tt>foo.html</tt> would be named <tt>foo_ja.html</tt>. */ OpenConnection selectResourceByLocale(URL url, Locale locale) throws IOException { String s = url.toString(); int idx = s.lastIndexOf('.'); if(idx<0) // no file extension, so no locale switch available return openURL(url); String base = s.substring(0,idx); String ext = s.substring(idx); if(ext.indexOf('/')>=0) // the '.' we found was not an extension separator return openURL(url); OpenConnection con; // try locale specific resources first. con = openURL(new URL(base+'_'+ locale.getLanguage()+'_'+ locale.getCountry()+'_'+ locale.getVariant()+ext)); if(con!=null) return con; con = openURL(new URL(base+'_'+ locale.getLanguage()+'_'+ locale.getCountry()+ext)); if(con!=null) return con; con = openURL(new URL(base+'_'+ locale.getLanguage()+ext)); if(con!=null) return con; // default return openURL(url); } /** * Serves the specified {@link URLConnection} as a static resource. */ boolean serveStaticResource(HttpServletRequest req, StaplerResponse rsp, OpenConnection con, long expiration) throws IOException { if(con==null) return false; return serveStaticResource(req,rsp, con.stream, con.connection.getLastModified(), expiration, con.connection.getContentLength(), con.connection.getURL().toString()); } /** * Serves the specified {@link URL} as a static resource. */ boolean serveStaticResource(HttpServletRequest req, StaplerResponse rsp, URL url, long expiration) throws IOException { return serveStaticResource(req,rsp,openURL(url),expiration); } /** * Opens URL, with error handling to absorb container differences. * <p> * This method returns null if the resource pointed by URL doesn't exist. The initial attempt was to * distinguish "resource exists but failed to load" vs "resource doesn't exist", but as more reports * from the field come in, we discovered that it's impossible to make such a distinction and work with * many environments both at the same time. */ private OpenConnection openURL(URL url) { if(url==null) return null; // jetty reports directories as URLs, which isn't what this is intended for, // so check and reject. File f = toFile(url); if(f!=null && f.isDirectory()) return null; try { // in normal protocol handlers like http/file, openConnection doesn't actually open a connection // (that's deferred until URLConnection.connect()), so this method doesn't result in an error, // even if URL points to something that doesn't exist. // // but we've heard a report from http://github.com/adreghiciu that some URLS backed by custom // protocol handlers can throw an exception as early as here. So treat this IOException // as "the resource pointed by URL is missing". URLConnection con = url.openConnection(); OpenConnection c = new OpenConnection(con); // Some URLs backed by custom broken protocol handler can return null from getInputStream(), // so let's be defensive here. An example of that is an OSGi container --- unfortunately // we don't have more details than that. if(c.stream==null) return null; return c; } catch (IOException e) { // Tomcat only reports a missing resource error here, from URLConnection.getInputStream() return null; } } /** * Serves the specified {@link InputStream} as a static resource. * * @param contentLength * if the length of the input stream is known in advance, specify that value * so that HTTP keep-alive works. Otherwise specify -1 to indicate that the length is unknown. * @param expiration * The number of milliseconds until the resource will "expire". * Until it expires the browser will be allowed to cache it * and serve it without checking back with the server. * After it expires, the client will send conditional GET to * check if the resource is actually modified or not. * If 0, it will immediately expire. * @param fileName * file name of this resource. Used to determine the MIME type. * Since the only important portion is the file extension, this could be just a file name, * or a full path name, or even a pseudo file name that doesn't actually exist. * It supports both '/' and '\\' as the path separator. * @return false * if the resource doesn't exist. */ boolean serveStaticResource(HttpServletRequest req, StaplerResponse rsp, InputStream in, long lastModified, long expiration, int contentLength, String fileName) throws IOException { try { {// send out Last-Modified, or check If-Modified-Since if(lastModified!=0) { String since = req.getHeader("If-Modified-Since"); SimpleDateFormat format = HTTP_DATE_FORMAT.get(); if(since!=null) { try { long ims = format.parse(since).getTime(); if(lastModified<ims+1000) { // +1000 because date header is second-precision and Java has milli-second precision rsp.setStatus(HttpServletResponse.SC_NOT_MODIFIED); return true; } } catch (ParseException e) { // just ignore and serve the content } catch (NumberFormatException e) { // trying to locate a bug with Jetty getServletContext().log("Error parsing ["+since+"]",e); throw e; } } String lastModifiedStr = format.format(new Date(lastModified)); rsp.setHeader("Last-Modified", lastModifiedStr); if(expiration<=0) rsp.setHeader("Expires",lastModifiedStr); else rsp.setHeader("Expires",format.format(new Date(new Date().getTime()+expiration))); } } rsp.setHeader("Accept-Ranges","bytes"); // advertize that we support the range header String mimeType = getMimeType(fileName); rsp.setContentType(mimeType); int idx = fileName.lastIndexOf('.'); String ext = fileName.substring(idx+1); OutputStream out = null; if(mimeType.startsWith("text/") || TEXT_FILES.contains(ext)) { // Need to duplicate this logic from ResponseImpl.getCompressedOutputStream, // since we want to set content length if we are not using encoding. String acceptEncoding = req.getHeader("Accept-Encoding"); if (acceptEncoding != null && acceptEncoding.indexOf("gzip") != -1) { // with gzip compression, Content-Length header needs to indicate the # of bytes after compression, // so we can't compute it upfront. out = rsp.getCompressedOutputStream(req); } } // somewhat limited implementation of the partial GET String range = req.getHeader("Range"); if(range!=null && contentLength!=-1) {// I'm lazy and only implementing this for known content length case if(range.startsWith("bytes=")) { range = range.substring(6); Matcher m = RANGE_SPEC.matcher(range); if(m.matches()) { int s = Integer.valueOf(m.group(1)); int e = m.group(2).length()>0 ? Integer.valueOf(m.group(2))+1 //range set is inclusive : contentLength; // unspecified value means "all the way to the end e = Math.min(e,contentLength); // ritual for responding to a partial GET rsp.setStatus(HttpServletResponse.SC_PARTIAL_CONTENT); rsp.setHeader("Content-Range",s+"-"+e+'/'+contentLength); // prepare to send the partial content new DataInputStream(in).skipBytes(s); in = new TruncatedInputStream(in,e-s); contentLength = Math.min(e-s,contentLength); } // if the Range header doesn't look like what we can handle, // pretend as if we didn't understand it, instead of doing a proper error reporting } } if (out == null) { if(contentLength!=-1) rsp.setContentLength(contentLength); out = rsp.getOutputStream(); } byte[] buf = new byte[1024]; int len; while((len=in.read(buf))>0) out.write(buf,0,len); out.close(); return true; } finally { in.close(); } } /** * Strings like "5-300", "0-900", or "100-" */ private static final Pattern RANGE_SPEC = Pattern.compile("([\\d]+)-([\\d]*)"); private String getMimeType(String fileName) { if(fileName.startsWith("mime-type:")) return fileName.substring("mime-type:".length()); int idx = fileName.lastIndexOf('/'); fileName = fileName.substring(idx+1); idx = fileName.lastIndexOf('\\'); fileName = fileName.substring(idx+1); String extension = fileName.substring(fileName.lastIndexOf('.')+1); String mimeType = webApp.mimeTypes.get(extension); if(mimeType==null) mimeType = getServletContext().getMimeType(fileName); if(mimeType==null) mimeType="application/octet-stream"; if(webApp.defaultEncodingForStaticResources.containsKey(mimeType)) mimeType += ";charset="+webApp.defaultEncodingForStaticResources.get(mimeType); return mimeType; } /** * If the URL is "file://", return its file representation. */ private File toFile(URL url) { String urlstr = url.toExternalForm(); if(!urlstr.startsWith("file:")) return null; try { //when URL contains escapes like %20, this does the conversion correctly return new File(url.toURI()); } catch (URISyntaxException e) { try { // some containers, such as Winstone, doesn't escape ' ', and for those // we need to do this. This method doesn't fail when urlstr contains '%20', // so toURI() has to be tried first. return new File(new URI(null,urlstr,null).getPath()); } catch (URISyntaxException _) { // the whole thing could fail anyway. return null; } } } /** * Performs stapler processing on the given root object and request URL. */ public void invoke(HttpServletRequest req, HttpServletResponse rsp, Object root, String url) throws IOException, ServletException { RequestImpl sreq = new RequestImpl(this, req, new ArrayList<AncestorImpl>(), new TokenList(url)); RequestImpl oreq = CURRENT_REQUEST.get(); CURRENT_REQUEST.set(sreq); ResponseImpl srsp = new ResponseImpl(this, rsp); ResponseImpl orsp = CURRENT_RESPONSE.get(); CURRENT_RESPONSE.set(srsp); try { invoke(sreq,srsp,root); } finally { CURRENT_REQUEST.set(oreq); CURRENT_RESPONSE.set(orsp); } } void invoke(RequestImpl req, ResponseImpl rsp, Object node ) throws IOException, ServletException { if(traceable()) traceEval(req,rsp,node); if(node instanceof StaplerProxy) { if(traceable()) traceEval(req,rsp,node,"((StaplerProxy)",").getTarget()"); Object n = ((StaplerProxy)node).getTarget(); if(n==node || n==null) { // if the proxy returns itself, assume that it doesn't want to proxy. // if null, no one will handle the request } else { // recursion helps debugging by leaving the trace in the stack. invoke(req,rsp,n); return; } } // adds this node to ancestor list AncestorImpl a = new AncestorImpl(req.ancestors); a.set(node,req); if(node==null) { // node is null if(!Dispatcher.isTraceEnabled(req)) { rsp.sendError(SC_NOT_FOUND); } else { // show error page rsp.setStatus(SC_NOT_FOUND); rsp.setContentType("text/html;charset=UTF-8"); PrintWriter w = rsp.getWriter(); w.println("<html><body>"); w.println("<h1>404 Not Found</h1>"); w.println("<p>Stapler processed this HTTP request as follows, but couldn't find the resource to consume the request"); w.println("<pre>"); EvaluationTrace.get(req).printHtml(w); w.println("<font color=red>-&gt; unexpected null!</font>"); w.println("</pre>"); w.println("<p>If this 404 is unexpected, double check the last part of the trace to see if it should have evaluated to null."); w.println("</body></html>"); } return; } MetaClass metaClass = webApp.getMetaClass(node.getClass()); if(!req.tokens.hasMore()) { String servletPath = getServletPath(req); if(!servletPath.endsWith("/")) { String target = req.getContextPath() + servletPath + '/'; if(req.getQueryString()!=null) target += '?' + req.getQueryString(); if(LOGGER.isLoggable(Level.FINE)) LOGGER.fine("Redirecting to "+target); rsp.sendRedirect2(target); return; } if(req.getMethod().equals("DELETE")) { if(node instanceof HttpDeletable) { ((HttpDeletable)node).delete(req,rsp); return; } } for (Facet f : webApp.facets) { if(f.handleIndexRequest(req,rsp,node,metaClass)) return; } URL indexHtml = getSideFileURL(node,"index.html"); if(indexHtml!=null && serveStaticResource(req,rsp,indexHtml,0)) return; // done } try { for( Dispatcher d : metaClass.dispatchers ) { if(d.dispatch(req,rsp,node)) { if(LOGGER.isLoggable(Level.FINE)) LOGGER.fine("Handled by "+d); return; } } } catch (IllegalAccessException e) { // this should never really happen getServletContext().log("Error while serving "+req.getRequestURL(),e); throw new ServletException(e); } catch (InvocationTargetException e) { Throwable cause = e.getCause(); if (cause == null) { // ??? getServletContext().log("Error while serving " + req.getRequestURL(), e); throw new ServletException(); } StringBuffer url = req.getRequestURL(); if (cause instanceof IOException) { getServletContext().log("Error while serving " + url, e); throw (IOException) cause; } if (cause instanceof ServletException) { getServletContext().log("Error while serving " + url, e); throw (ServletException) cause; } for (Class<?> c = cause.getClass(); c != null; c = c.getSuperclass()) { if (c == Object.class) { getServletContext().log("Error while serving " + url, e); } else if (c.getName().equals("org.acegisecurity.AccessDeniedException")) { // [HUDSON-4834] A stack trace is too noisy for this; could just need to log in. // (Could consider doing this for all AcegiSecurityException's.) getServletContext().log("While serving " + url + ": " + cause); break; } } throw new ServletException(cause); } if(node instanceof StaplerFallback) { if(traceable()) traceEval(req,rsp,node,"((StaplerFallback)",").getStaplerFallback()"); Object n = ((StaplerFallback)node).getStaplerFallback(); if(n!=node && n!=null) { // delegate to the fallback object invoke(req,rsp,n); return; } } // we really run out of options. if(!Dispatcher.isTraceEnabled(req)) { rsp.sendError(SC_NOT_FOUND); } else { // show error page rsp.setStatus(SC_NOT_FOUND); rsp.setContentType("text/html;charset=UTF-8"); PrintWriter w = rsp.getWriter(); w.println("<html><body>"); w.println("<h1>404 Not Found</h1>"); w.println("<p>Stapler processed this HTTP request as follows, but couldn't find the resource to consume the request"); w.println("<pre>"); EvaluationTrace.get(req).printHtml(w); w.printf("<font color=red>-&gt; No matching rule was found on &lt;%s&gt; for \"%s\"</font>\n",node,req.tokens.assembleOriginalRestOfPath()); w.println("</pre>"); w.printf("<p>&lt;%s&gt; has the following URL mappings, in the order of preference:",node); w.println("<ol>"); for (Dispatcher d : metaClass.dispatchers) { w.println("<li>"); w.println(d.toString()); } w.println("</ol>"); w.println("</body></html>"); } } public void forward(RequestDispatcher dispatcher, StaplerRequest req, HttpServletResponse rsp) throws ServletException, IOException { dispatcher.forward(req,new ResponseImpl(this,rsp)); } private URL getSideFileURL(Object node,String fileName) throws MalformedURLException { for( Class c = node.getClass(); c!=Object.class; c=c.getSuperclass() ) { String name = "/WEB-INF/side-files/"+c.getName().replace('.','/')+'/'+fileName; URL url = getServletContext().getResource(name); if(url!=null) return url; } return null; } /** * Gets the URL (e.g., "/WEB-INF/side-files/fully/qualified/class/name/jspName") * from a class and the JSP name. */ public static String getViewURL(Class clazz,String jspName) { return "/WEB-INF/side-files/"+clazz.getName().replace('.','/')+'/'+jspName; } /** * Sets the specified object as the root of the web application. * * <p> * This method should be invoked from your implementation of * {@link ServletContextListener#contextInitialized(ServletContextEvent)}. * * <p> * This is just a convenience method to invoke * <code>servletContext.setAttribute("app",rootApp)</code>. * * <p> * The root object is bound to the URL '/' and used to resolve * all the requests to this web application. */ public static void setRoot( ServletContextEvent event, Object rootApp ) { event.getServletContext().setAttribute("app",rootApp); } /** * Sets the classloader used by {@link StaplerRequest#bindJSON(Class, JSONObject)} and its sibling methods. * * @deprecated * Use {@link WebApp#setClassLoader(ClassLoader)} */ public static void setClassLoader( ServletContext context, ClassLoader classLoader ) { WebApp.get(context).setClassLoader(classLoader); } /** * @deprecated * Use {@link WebApp#getClassLoader()} */ public static ClassLoader getClassLoader( ServletContext context ) { return WebApp.get(context).getClassLoader(); } /** * @deprecated * Use {@link WebApp#getClassLoader()} */ public ClassLoader getClassLoader() { return webApp.getClassLoader(); } /** * Gets the current {@link StaplerRequest} that the calling thread is associated with. */ public static StaplerRequest getCurrentRequest() { return CURRENT_REQUEST.get(); } /** * Gets the current {@link StaplerResponse} that the calling thread is associated with. */ public static StaplerResponse getCurrentResponse() { return CURRENT_RESPONSE.get(); } /** * Gets the current {@link Stapler} that the calling thread is associated with. */ public static Stapler getCurrent() { return CURRENT_REQUEST.get().getStapler(); } /** * HTTP date format. Notice that {@link SimpleDateFormat} is thread unsafe. */ static final ThreadLocal<SimpleDateFormat> HTTP_DATE_FORMAT = new ThreadLocal<SimpleDateFormat>() { protected @Override SimpleDateFormat initialValue() { // RFC1945 section 3.3 Date/Time Formats states that timezones must be in GMT SimpleDateFormat format = new SimpleDateFormat("EEE, dd MMM yyyy HH:mm:ss zzz", Locale.US); format.setTimeZone(TimeZone.getTimeZone("GMT")); return format; } }; private static ThreadLocal<RequestImpl> CURRENT_REQUEST = new ThreadLocal<RequestImpl>(); private static ThreadLocal<ResponseImpl> CURRENT_RESPONSE = new ThreadLocal<ResponseImpl>(); private static final Logger LOGGER = Logger.getLogger(Stapler.class.getName()); /** * Extensions that look like text files. */ private static final Set<String> TEXT_FILES = new HashSet<String>(Arrays.asList( "css","js","html","txt","java","htm","c","cpp","h","rb","pl","py","xml" )); /** * Get raw servlet path (decoded in TokenList). */ private String getServletPath(HttpServletRequest req) { return req.getRequestURI().substring(req.getContextPath().length()); } /** * This is the {@link Converter} registry that Stapler uses, primarily * for form-to-JSON binding in {@link StaplerRequest#bindJSON(Class, JSONObject)} * and its family of methods. */ public static final ConvertUtilsBean CONVERT_UTILS = new ConvertUtilsBean(); public static Converter lookupConverter(Class type) { Converter c = CONVERT_UTILS.lookup(type); if(c!=null) return c; // fall back to compatibility behavior return ConvertUtils.lookup(type); } static { CONVERT_UTILS.register(new Converter() { public Object convert(Class type, Object value) { if(value==null) return null; try { return new URL(value.toString()); } catch (MalformedURLException e) { throw new ConversionException(e); } } }, URL.class); CONVERT_UTILS.register(new Converter() { public FileItem convert(Class type, Object value) { if(value==null) return null; try { return Stapler.getCurrentRequest().getFileItem(value.toString()); } catch (ServletException e) { throw new ConversionException(e); } catch (IOException e) { throw new ConversionException(e); } } }, FileItem.class); // mapping for boxed types should map null to null, instead of null to zero. CONVERT_UTILS.register(new IntegerConverter(null),Integer.class); CONVERT_UTILS.register(new FloatConverter(null),Float.class); CONVERT_UTILS.register(new DoubleConverter(null),Double.class); } }
core/src/main/java/org/kohsuke/stapler/Stapler.java
package org.kohsuke.stapler; import org.apache.commons.beanutils.ConversionException; import org.apache.commons.beanutils.ConvertUtils; import org.apache.commons.beanutils.ConvertUtilsBean; import org.apache.commons.beanutils.Converter; import org.apache.commons.beanutils.converters.DoubleConverter; import org.apache.commons.beanutils.converters.FloatConverter; import org.apache.commons.beanutils.converters.IntegerConverter; import org.apache.commons.fileupload.FileItem; import static org.kohsuke.stapler.Dispatcher.traceable; import static org.kohsuke.stapler.Dispatcher.traceEval; import javax.servlet.RequestDispatcher; import javax.servlet.ServletConfig; import javax.servlet.ServletContext; import javax.servlet.ServletContextEvent; import javax.servlet.ServletContextListener; import javax.servlet.ServletException; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import static javax.servlet.http.HttpServletResponse.SC_NOT_FOUND; import java.io.File; import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; import java.io.PrintWriter; import java.io.DataInputStream; import java.lang.reflect.InvocationTargetException; import java.net.MalformedURLException; import java.net.URI; import java.net.URISyntaxException; import java.net.URL; import java.net.URLConnection; import java.text.ParseException; import java.text.SimpleDateFormat; import java.util.ArrayList; import java.util.Arrays; import java.util.Date; import java.util.HashSet; import java.util.Locale; import java.util.Set; import java.util.TimeZone; import java.util.regex.Pattern; import java.util.regex.Matcher; import java.util.logging.Level; import java.util.logging.Logger; /** * Maps an HTTP request to a method call / JSP invocation against a model object * by evaluating the request URL in a EL-ish way. * * <p> * This servlet should be used as the default servlet. * * @author Kohsuke Kawaguchi */ public class Stapler extends HttpServlet { private /*final*/ ServletContext context; private /*final*/ WebApp webApp; public @Override void init(ServletConfig servletConfig) throws ServletException { super.init(servletConfig); this.context = servletConfig.getServletContext(); this.webApp = WebApp.get(context); String defaultEncodings = servletConfig.getInitParameter("default-encodings"); if(defaultEncodings!=null) { for(String t : defaultEncodings.split(";")) { t=t.trim(); int idx=t.indexOf('='); if(idx<0) throw new ServletException("Invalid format: "+t); webApp.defaultEncodingForStaticResources.put(t.substring(0,idx),t.substring(idx+1)); } } } public WebApp getWebApp() { return webApp; } protected @Override void service(HttpServletRequest req, HttpServletResponse rsp) throws ServletException, IOException { Thread t = Thread.currentThread(); final String oldName = t.getName(); try { t.setName("Handling "+req.getMethod()+' '+req.getRequestURI()+" : "+oldName); String servletPath = getServletPath(req); if(LOGGER.isLoggable(Level.FINE)) LOGGER.fine("Processing request for "+servletPath); boolean staticLink = false; if(servletPath.startsWith("/static/")) { // skip "/static/..../ portion int idx = servletPath.indexOf('/',8); servletPath=servletPath.substring(idx); staticLink = true; } if(servletPath.length()!=0) { // getResource requires '/' prefix (and resin insists on that, too) but servletPath can be empty string (hudson #879) OpenConnection con = openResourcePathByLocale(req,servletPath); if(con!=null) { long expires = MetaClass.NO_CACHE ? 0 : 24L * 60 * 60 * 1000; /*1 day*/ if(staticLink) expires*=365; // static resources are unique, so we can set a long expiration date if(serveStaticResource(req, new ResponseImpl(this, rsp), con, expires)) return; // done } } Object root = context.getAttribute("app"); if(root==null) throw new ServletException("there's no \"app\" attribute in the application context."); // consider reusing this ArrayList. invoke( req, rsp, root, servletPath); } finally { t.setName(oldName); } } /** * Tomcat and GlassFish returns a fresh {@link InputStream} every time * {@link URLConnection#getInputStream()} is invoked in their {@code org.apache.naming.resources.DirContextURLConnection}. * * <p> * All the other {@link URLConnection}s in JDK don't do this --- they return the same {@link InputStream}, * even the one for the file:// URLs. * * <p> * In Tomcat (and most likely in GlassFish, although this is not verifid), resource look up on * {@link ServletContext#getResource(String)} successfully returns non-existent URL, and * the failure can be only detected by {@link IOException} from {@link URLConnection#getInputStream()}. * * <p> * Therefore, for the whole thing to work without resource leak, once we open {@link InputStream} * for the sake of really making sure that the resource exists, we need to hang on to that stream. * * <p> * Hence the need for this tuple. */ private static final class OpenConnection { final URLConnection connection; final InputStream stream; private OpenConnection(URLConnection connection, InputStream stream) { this.connection = connection; this.stream = stream; } private OpenConnection(URLConnection connection) throws IOException { this(connection,connection.getInputStream()); } } private OpenConnection openResourcePathByLocale(HttpServletRequest req,String resourcePath) throws IOException { URL url = getServletContext().getResource(resourcePath); if(url==null) return null; return selectResourceByLocale(url,req.getLocale()); } /** * Basically works like {@link URL#openConnection()} but it uses the * locale specific resource if available, by using the given locale. * * <p> * The syntax of the locale specific resource is the same as property file localization. * So Japanese resource for <tt>foo.html</tt> would be named <tt>foo_ja.html</tt>. */ OpenConnection selectResourceByLocale(URL url, Locale locale) throws IOException { String s = url.toString(); int idx = s.lastIndexOf('.'); if(idx<0) // no file extension, so no locale switch available return openURL(url); String base = s.substring(0,idx); String ext = s.substring(idx); if(ext.indexOf('/')>=0) // the '.' we found was not an extension separator return openURL(url); OpenConnection con; // try locale specific resources first. con = openURL(new URL(base+'_'+ locale.getLanguage()+'_'+ locale.getCountry()+'_'+ locale.getVariant()+ext)); if(con!=null) return con; con = openURL(new URL(base+'_'+ locale.getLanguage()+'_'+ locale.getCountry()+ext)); if(con!=null) return con; con = openURL(new URL(base+'_'+ locale.getLanguage()+ext)); if(con!=null) return con; // default return openURL(url); } /** * Serves the specified {@link URLConnection} as a static resource. */ boolean serveStaticResource(HttpServletRequest req, StaplerResponse rsp, OpenConnection con, long expiration) throws IOException { if(con==null) return false; return serveStaticResource(req,rsp, con.stream, con.connection.getLastModified(), expiration, con.connection.getContentLength(), con.connection.getURL().toString()); } /** * Serves the specified {@link URL} as a static resource. */ boolean serveStaticResource(HttpServletRequest req, StaplerResponse rsp, URL url, long expiration) throws IOException { return serveStaticResource(req,rsp,openURL(url),expiration); } /** * Opens URL, with error handling to absorb container differences. */ private OpenConnection openURL(URL url) throws IOException { if(url==null) return null; // jetty reports directories as URLs, which isn't what this is intended for, // so check and reject. File f = toFile(url); if(f!=null && f.isDirectory()) return null; URLConnection con = url.openConnection(); try { return new OpenConnection(con); } catch (IOException e) { // Tomcat only reports a missing resource error here, from URLConnection.getInputStream() return null; } } /** * Serves the specified {@link InputStream} as a static resource. * * @param contentLength * if the length of the input stream is known in advance, specify that value * so that HTTP keep-alive works. Otherwise specify -1 to indicate that the length is unknown. * @param expiration * The number of milliseconds until the resource will "expire". * Until it expires the browser will be allowed to cache it * and serve it without checking back with the server. * After it expires, the client will send conditional GET to * check if the resource is actually modified or not. * If 0, it will immediately expire. * @param fileName * file name of this resource. Used to determine the MIME type. * Since the only important portion is the file extension, this could be just a file name, * or a full path name, or even a pseudo file name that doesn't actually exist. * It supports both '/' and '\\' as the path separator. * @return false * if the resource doesn't exist. */ boolean serveStaticResource(HttpServletRequest req, StaplerResponse rsp, InputStream in, long lastModified, long expiration, int contentLength, String fileName) throws IOException { try { {// send out Last-Modified, or check If-Modified-Since if(lastModified!=0) { String since = req.getHeader("If-Modified-Since"); SimpleDateFormat format = HTTP_DATE_FORMAT.get(); if(since!=null) { try { long ims = format.parse(since).getTime(); if(lastModified<ims+1000) { // +1000 because date header is second-precision and Java has milli-second precision rsp.setStatus(HttpServletResponse.SC_NOT_MODIFIED); return true; } } catch (ParseException e) { // just ignore and serve the content } catch (NumberFormatException e) { // trying to locate a bug with Jetty getServletContext().log("Error parsing ["+since+"]",e); throw e; } } String lastModifiedStr = format.format(new Date(lastModified)); rsp.setHeader("Last-Modified", lastModifiedStr); if(expiration<=0) rsp.setHeader("Expires",lastModifiedStr); else rsp.setHeader("Expires",format.format(new Date(new Date().getTime()+expiration))); } } rsp.setHeader("Accept-Ranges","bytes"); // advertize that we support the range header String mimeType = getMimeType(fileName); rsp.setContentType(mimeType); int idx = fileName.lastIndexOf('.'); String ext = fileName.substring(idx+1); OutputStream out = null; if(mimeType.startsWith("text/") || TEXT_FILES.contains(ext)) { // Need to duplicate this logic from ResponseImpl.getCompressedOutputStream, // since we want to set content length if we are not using encoding. String acceptEncoding = req.getHeader("Accept-Encoding"); if (acceptEncoding != null && acceptEncoding.indexOf("gzip") != -1) { // with gzip compression, Content-Length header needs to indicate the # of bytes after compression, // so we can't compute it upfront. out = rsp.getCompressedOutputStream(req); } } // somewhat limited implementation of the partial GET String range = req.getHeader("Range"); if(range!=null && contentLength!=-1) {// I'm lazy and only implementing this for known content length case if(range.startsWith("bytes=")) { range = range.substring(6); Matcher m = RANGE_SPEC.matcher(range); if(m.matches()) { int s = Integer.valueOf(m.group(1)); int e = m.group(2).length()>0 ? Integer.valueOf(m.group(2))+1 //range set is inclusive : contentLength; // unspecified value means "all the way to the end e = Math.min(e,contentLength); // ritual for responding to a partial GET rsp.setStatus(HttpServletResponse.SC_PARTIAL_CONTENT); rsp.setHeader("Content-Range",s+"-"+e+'/'+contentLength); // prepare to send the partial content new DataInputStream(in).skipBytes(s); in = new TruncatedInputStream(in,e-s); contentLength = Math.min(e-s,contentLength); } // if the Range header doesn't look like what we can handle, // pretend as if we didn't understand it, instead of doing a proper error reporting } } if (out == null) { if(contentLength!=-1) rsp.setContentLength(contentLength); out = rsp.getOutputStream(); } byte[] buf = new byte[1024]; int len; while((len=in.read(buf))>0) out.write(buf,0,len); out.close(); return true; } finally { in.close(); } } /** * Strings like "5-300", "0-900", or "100-" */ private static final Pattern RANGE_SPEC = Pattern.compile("([\\d]+)-([\\d]*)"); private String getMimeType(String fileName) { if(fileName.startsWith("mime-type:")) return fileName.substring("mime-type:".length()); int idx = fileName.lastIndexOf('/'); fileName = fileName.substring(idx+1); idx = fileName.lastIndexOf('\\'); fileName = fileName.substring(idx+1); String extension = fileName.substring(fileName.lastIndexOf('.')+1); String mimeType = webApp.mimeTypes.get(extension); if(mimeType==null) mimeType = getServletContext().getMimeType(fileName); if(mimeType==null) mimeType="application/octet-stream"; if(webApp.defaultEncodingForStaticResources.containsKey(mimeType)) mimeType += ";charset="+webApp.defaultEncodingForStaticResources.get(mimeType); return mimeType; } /** * If the URL is "file://", return its file representation. */ private File toFile(URL url) { String urlstr = url.toExternalForm(); if(!urlstr.startsWith("file:")) return null; try { //when URL contains escapes like %20, this does the conversion correctly return new File(url.toURI()); } catch (URISyntaxException e) { try { // some containers, such as Winstone, doesn't escape ' ', and for those // we need to do this. This method doesn't fail when urlstr contains '%20', // so toURI() has to be tried first. return new File(new URI(null,urlstr,null).getPath()); } catch (URISyntaxException _) { // the whole thing could fail anyway. return null; } } } /** * Performs stapler processing on the given root object and request URL. */ public void invoke(HttpServletRequest req, HttpServletResponse rsp, Object root, String url) throws IOException, ServletException { RequestImpl sreq = new RequestImpl(this, req, new ArrayList<AncestorImpl>(), new TokenList(url)); RequestImpl oreq = CURRENT_REQUEST.get(); CURRENT_REQUEST.set(sreq); ResponseImpl srsp = new ResponseImpl(this, rsp); ResponseImpl orsp = CURRENT_RESPONSE.get(); CURRENT_RESPONSE.set(srsp); try { invoke(sreq,srsp,root); } finally { CURRENT_REQUEST.set(oreq); CURRENT_RESPONSE.set(orsp); } } void invoke(RequestImpl req, ResponseImpl rsp, Object node ) throws IOException, ServletException { if(traceable()) traceEval(req,rsp,node); if(node instanceof StaplerProxy) { if(traceable()) traceEval(req,rsp,node,"((StaplerProxy)",").getTarget()"); Object n = ((StaplerProxy)node).getTarget(); if(n==node || n==null) { // if the proxy returns itself, assume that it doesn't want to proxy. // if null, no one will handle the request } else { // recursion helps debugging by leaving the trace in the stack. invoke(req,rsp,n); return; } } // adds this node to ancestor list AncestorImpl a = new AncestorImpl(req.ancestors); a.set(node,req); if(node==null) { // node is null if(!Dispatcher.isTraceEnabled(req)) { rsp.sendError(SC_NOT_FOUND); } else { // show error page rsp.setStatus(SC_NOT_FOUND); rsp.setContentType("text/html;charset=UTF-8"); PrintWriter w = rsp.getWriter(); w.println("<html><body>"); w.println("<h1>404 Not Found</h1>"); w.println("<p>Stapler processed this HTTP request as follows, but couldn't find the resource to consume the request"); w.println("<pre>"); EvaluationTrace.get(req).printHtml(w); w.println("<font color=red>-&gt; unexpected null!</font>"); w.println("</pre>"); w.println("<p>If this 404 is unexpected, double check the last part of the trace to see if it should have evaluated to null."); w.println("</body></html>"); } return; } MetaClass metaClass = webApp.getMetaClass(node.getClass()); if(!req.tokens.hasMore()) { String servletPath = getServletPath(req); if(!servletPath.endsWith("/")) { String target = req.getContextPath() + servletPath + '/'; if(req.getQueryString()!=null) target += '?' + req.getQueryString(); if(LOGGER.isLoggable(Level.FINE)) LOGGER.fine("Redirecting to "+target); rsp.sendRedirect2(target); return; } if(req.getMethod().equals("DELETE")) { if(node instanceof HttpDeletable) { ((HttpDeletable)node).delete(req,rsp); return; } } for (Facet f : webApp.facets) { if(f.handleIndexRequest(req,rsp,node,metaClass)) return; } URL indexHtml = getSideFileURL(node,"index.html"); if(indexHtml!=null && serveStaticResource(req,rsp,indexHtml,0)) return; // done } try { for( Dispatcher d : metaClass.dispatchers ) { if(d.dispatch(req,rsp,node)) { if(LOGGER.isLoggable(Level.FINE)) LOGGER.fine("Handled by "+d); return; } } } catch (IllegalAccessException e) { // this should never really happen getServletContext().log("Error while serving "+req.getRequestURL(),e); throw new ServletException(e); } catch (InvocationTargetException e) { Throwable cause = e.getCause(); if (cause == null) { // ??? getServletContext().log("Error while serving " + req.getRequestURL(), e); throw new ServletException(); } StringBuffer url = req.getRequestURL(); if (cause instanceof IOException) { getServletContext().log("Error while serving " + url, e); throw (IOException) cause; } if (cause instanceof ServletException) { getServletContext().log("Error while serving " + url, e); throw (ServletException) cause; } for (Class<?> c = cause.getClass(); c != null; c = c.getSuperclass()) { if (c == Object.class) { getServletContext().log("Error while serving " + url, e); } else if (c.getName().equals("org.acegisecurity.AccessDeniedException")) { // [HUDSON-4834] A stack trace is too noisy for this; could just need to log in. // (Could consider doing this for all AcegiSecurityException's.) getServletContext().log("While serving " + url + ": " + cause); break; } } throw new ServletException(cause); } if(node instanceof StaplerFallback) { if(traceable()) traceEval(req,rsp,node,"((StaplerFallback)",").getStaplerFallback()"); Object n = ((StaplerFallback)node).getStaplerFallback(); if(n!=node && n!=null) { // delegate to the fallback object invoke(req,rsp,n); return; } } // we really run out of options. if(!Dispatcher.isTraceEnabled(req)) { rsp.sendError(SC_NOT_FOUND); } else { // show error page rsp.setStatus(SC_NOT_FOUND); rsp.setContentType("text/html;charset=UTF-8"); PrintWriter w = rsp.getWriter(); w.println("<html><body>"); w.println("<h1>404 Not Found</h1>"); w.println("<p>Stapler processed this HTTP request as follows, but couldn't find the resource to consume the request"); w.println("<pre>"); EvaluationTrace.get(req).printHtml(w); w.printf("<font color=red>-&gt; No matching rule was found on &lt;%s&gt; for \"%s\"</font>\n",node,req.tokens.assembleOriginalRestOfPath()); w.println("</pre>"); w.printf("<p>&lt;%s&gt; has the following URL mappings, in the order of preference:",node); w.println("<ol>"); for (Dispatcher d : metaClass.dispatchers) { w.println("<li>"); w.println(d.toString()); } w.println("</ol>"); w.println("</body></html>"); } } public void forward(RequestDispatcher dispatcher, StaplerRequest req, HttpServletResponse rsp) throws ServletException, IOException { dispatcher.forward(req,new ResponseImpl(this,rsp)); } private URL getSideFileURL(Object node,String fileName) throws MalformedURLException { for( Class c = node.getClass(); c!=Object.class; c=c.getSuperclass() ) { String name = "/WEB-INF/side-files/"+c.getName().replace('.','/')+'/'+fileName; URL url = getServletContext().getResource(name); if(url!=null) return url; } return null; } /** * Gets the URL (e.g., "/WEB-INF/side-files/fully/qualified/class/name/jspName") * from a class and the JSP name. */ public static String getViewURL(Class clazz,String jspName) { return "/WEB-INF/side-files/"+clazz.getName().replace('.','/')+'/'+jspName; } /** * Sets the specified object as the root of the web application. * * <p> * This method should be invoked from your implementation of * {@link ServletContextListener#contextInitialized(ServletContextEvent)}. * * <p> * This is just a convenience method to invoke * <code>servletContext.setAttribute("app",rootApp)</code>. * * <p> * The root object is bound to the URL '/' and used to resolve * all the requests to this web application. */ public static void setRoot( ServletContextEvent event, Object rootApp ) { event.getServletContext().setAttribute("app",rootApp); } /** * Sets the classloader used by {@link StaplerRequest#bindJSON(Class, JSONObject)} and its sibling methods. * * @deprecated * Use {@link WebApp#setClassLoader(ClassLoader)} */ public static void setClassLoader( ServletContext context, ClassLoader classLoader ) { WebApp.get(context).setClassLoader(classLoader); } /** * @deprecated * Use {@link WebApp#getClassLoader()} */ public static ClassLoader getClassLoader( ServletContext context ) { return WebApp.get(context).getClassLoader(); } /** * @deprecated * Use {@link WebApp#getClassLoader()} */ public ClassLoader getClassLoader() { return webApp.getClassLoader(); } /** * Gets the current {@link StaplerRequest} that the calling thread is associated with. */ public static StaplerRequest getCurrentRequest() { return CURRENT_REQUEST.get(); } /** * Gets the current {@link StaplerResponse} that the calling thread is associated with. */ public static StaplerResponse getCurrentResponse() { return CURRENT_RESPONSE.get(); } /** * Gets the current {@link Stapler} that the calling thread is associated with. */ public static Stapler getCurrent() { return CURRENT_REQUEST.get().getStapler(); } /** * HTTP date format. Notice that {@link SimpleDateFormat} is thread unsafe. */ static final ThreadLocal<SimpleDateFormat> HTTP_DATE_FORMAT = new ThreadLocal<SimpleDateFormat>() { protected @Override SimpleDateFormat initialValue() { // RFC1945 section 3.3 Date/Time Formats states that timezones must be in GMT SimpleDateFormat format = new SimpleDateFormat("EEE, dd MMM yyyy HH:mm:ss zzz", Locale.US); format.setTimeZone(TimeZone.getTimeZone("GMT")); return format; } }; private static ThreadLocal<RequestImpl> CURRENT_REQUEST = new ThreadLocal<RequestImpl>(); private static ThreadLocal<ResponseImpl> CURRENT_RESPONSE = new ThreadLocal<ResponseImpl>(); private static final Logger LOGGER = Logger.getLogger(Stapler.class.getName()); /** * Extensions that look like text files. */ private static final Set<String> TEXT_FILES = new HashSet<String>(Arrays.asList( "css","js","html","txt","java","htm","c","cpp","h","rb","pl","py","xml" )); /** * Get raw servlet path (decoded in TokenList). */ private String getServletPath(HttpServletRequest req) { return req.getRequestURI().substring(req.getContextPath().length()); } /** * This is the {@link Converter} registry that Stapler uses, primarily * for form-to-JSON binding in {@link StaplerRequest#bindJSON(Class, JSONObject)} * and its family of methods. */ public static final ConvertUtilsBean CONVERT_UTILS = new ConvertUtilsBean(); public static Converter lookupConverter(Class type) { Converter c = CONVERT_UTILS.lookup(type); if(c!=null) return c; // fall back to compatibility behavior return ConvertUtils.lookup(type); } static { CONVERT_UTILS.register(new Converter() { public Object convert(Class type, Object value) { if(value==null) return null; try { return new URL(value.toString()); } catch (MalformedURLException e) { throw new ConversionException(e); } } }, URL.class); CONVERT_UTILS.register(new Converter() { public FileItem convert(Class type, Object value) { if(value==null) return null; try { return Stapler.getCurrentRequest().getFileItem(value.toString()); } catch (ServletException e) { throw new ConversionException(e); } catch (IOException e) { throw new ConversionException(e); } } }, FileItem.class); // mapping for boxed types should map null to null, instead of null to zero. CONVERT_UTILS.register(new IntegerConverter(null),Integer.class); CONVERT_UTILS.register(new FloatConverter(null),Float.class); CONVERT_UTILS.register(new DoubleConverter(null),Double.class); } }
Effectively the same change as http://github.com/adreghiciu/stapler/commit/901811600e1d911fa3ec7031d7fe2f2fb6627dfe but with a better explanation of the rationale/thinking behind it.
core/src/main/java/org/kohsuke/stapler/Stapler.java
Effectively the same change as http://github.com/adreghiciu/stapler/commit/901811600e1d911fa3ec7031d7fe2f2fb6627dfe but with a better explanation of the rationale/thinking behind it.
<ide><path>ore/src/main/java/org/kohsuke/stapler/Stapler.java <ide> package org.kohsuke.stapler; <ide> <add>import net.sf.json.JSONObject; <ide> import org.apache.commons.beanutils.ConversionException; <ide> import org.apache.commons.beanutils.ConvertUtils; <ide> import org.apache.commons.beanutils.ConvertUtilsBean; <ide> <ide> /** <ide> * Opens URL, with error handling to absorb container differences. <del> */ <del> private OpenConnection openURL(URL url) throws IOException { <add> * <p> <add> * This method returns null if the resource pointed by URL doesn't exist. The initial attempt was to <add> * distinguish "resource exists but failed to load" vs "resource doesn't exist", but as more reports <add> * from the field come in, we discovered that it's impossible to make such a distinction and work with <add> * many environments both at the same time. <add> */ <add> private OpenConnection openURL(URL url) { <ide> if(url==null) return null; <ide> <ide> // jetty reports directories as URLs, which isn't what this is intended for, <ide> if(f!=null && f.isDirectory()) <ide> return null; <ide> <del> URLConnection con = url.openConnection(); <del> <ide> try { <del> return new OpenConnection(con); <add> // in normal protocol handlers like http/file, openConnection doesn't actually open a connection <add> // (that's deferred until URLConnection.connect()), so this method doesn't result in an error, <add> // even if URL points to something that doesn't exist. <add> // <add> // but we've heard a report from http://github.com/adreghiciu that some URLS backed by custom <add> // protocol handlers can throw an exception as early as here. So treat this IOException <add> // as "the resource pointed by URL is missing". <add> URLConnection con = url.openConnection(); <add> <add> OpenConnection c = new OpenConnection(con); <add> // Some URLs backed by custom broken protocol handler can return null from getInputStream(), <add> // so let's be defensive here. An example of that is an OSGi container --- unfortunately <add> // we don't have more details than that. <add> if(c.stream==null) <add> return null; <add> return c; <ide> } catch (IOException e) { <ide> // Tomcat only reports a missing resource error here, from URLConnection.getInputStream() <ide> return null;
JavaScript
mit
6dbbf2de4ae0d1d84610fc0bdc1a8fad7b091363
0
skpm/skpm
import path from 'path' import fs from 'fs' import requestWithCallback from 'request' import parseAuthor from 'parse-author' /* eslint-disable no-not-accumulator-reassign/no-not-accumulator-reassign */ function getErrorFromBody(body, opts) { if (typeof body === 'string') { try { body = JSON.parse(body) } catch (e) { body = {} } } // hide token from logs opts.headers.Authorization = 'Token **********' // log the request options to help debugging body.request = opts return new Error(JSON.stringify(body, null, ' ')) } /* eslint-enable */ function request(opts) { return new Promise((resolve, reject) => { requestWithCallback(opts, (err, response, body) => { if (err) { return reject(err) } const is2xx = !err && /^2/.test(String(response.statusCode)) if (!is2xx) { return reject(getErrorFromBody(body, opts)) } return resolve(body) }) }) } function options(token, url, method) { return { method: method || 'GET', url, headers: { Accept: 'application/vnd.github.v3+json', Authorization: `Token ${token}`, 'User-Agent': 'SKPM-Release-Agent', }, } } export default { getUser(token) { return request(options(token, 'https://api.github.com/user')) }, getRepo(token, repo) { if (!token) { return Promise.reject( new Error('You are not logged in. Please run `skpm login` first.') ) } return request(options(token, `https://api.github.com/repos/${repo}`)).then( res => { const permissions = JSON.parse(res).permissions || {} if (!permissions.push) { throw new Error( `You don't have the right permissions on the repo. Need the "push" permission and only got:\n' ${JSON.stringify( permissions, null, ' ' )}` ) } } ) }, createDraftRelease(token, repo, tag) { const opts = options( token, `https://api.github.com/repos/${repo}/releases`, 'POST' ) opts.json = { tag_name: tag, name: tag, draft: true, } return request(opts) }, updateAsset(token, repo, releaseId, assetName, fileName) { const opts = options( token, `https://uploads.github.com/repos/${repo}/releases/${releaseId}/assets?name=${encodeURIComponent( fileName )}&label=${encodeURIComponent( 'To install: download this file, unzip and double click on the .sketchplugin' )}`, 'POST' ) const asset = path.join(process.cwd(), assetName) const stat = fs.statSync(asset) const rd = fs.createReadStream(asset) opts.headers['Content-Type'] = 'application/zip' opts.headers['Content-Length'] = stat.size const us = requestWithCallback(opts) return new Promise((resolve, reject) => { rd.on('error', err => reject(err)) us.on('error', err => reject(err)) us.on('end', () => resolve()) rd.pipe(us) }) }, publishRelease(token, repo, releaseId) { const opts = options( token, `https://api.github.com/repos/${repo}/releases/${releaseId}`, 'PATCH' ) opts.json = { draft: false, } return request(opts) }, // get the upstream plugins.json // if we haven't added the plugin yet // get or create a fork // delete any existing branch for this plugin // check if origin master is up to date with upstream (update otherwise) // branch // update origin plugins.json // open PR addPluginToPluginsRegistryRepo(token, skpmConfig, repo) { const owner = repo.split('/')[0] const name = repo.split('/')[1] function getCurrentUpstreamPluginJSON() { return request( options( token, 'https://api.github.com/repos/sketchplugins/plugin-directory/contents/plugins.json' ) ) .then(data => { const file = JSON.parse(data) const buf = Buffer.from(file.content, 'base64') return { plugins: JSON.parse(buf.toString('utf-8')), file, } }) .then(res => ({ existingPlugin: res.plugins.find( plugin => plugin.title === skpmConfig.name || name === plugin.name ), plugins: res.plugins, file: res.file, })) } function deleteExistingBranch(fork) { const opts = options( token, `https://api.github.com/repos/${fork.full_name}/git/refs/heads/${repo}`, 'DELETE' ) return request(opts).catch(() => {}) } function getOriginBranchSHA(fork) { return deleteExistingBranch().then(() => Promise.all([ request( options( token, `https://api.github.com/repos/${ fork.full_name }/git/refs/heads/master` ) ), request( options( token, `https://api.github.com/repos/sketchplugins/plugin-directory/git/refs/heads/master` ) ), ]) .then(([originData, upstreamData]) => ({ originSHA: JSON.parse(originData).object.sha, upstreamSHA: JSON.parse(upstreamData).object.sha, })) .then(({ originSHA, upstreamSHA }) => { if (originSHA === upstreamSHA) { return originSHA } // merge upstream master so that there is no conflicts const opts = options( token, `https://api.github.com/repos/${ fork.full_name }/git/refs/heads/master`, 'PATCH' ) opts.json = { sha: upstreamSHA, } return request(opts).then(() => upstreamSHA) }) .then(headSHA => { const opts = options( token, `https://api.github.com/repos/${fork.full_name}/git/refs`, 'POST' ) opts.json = { ref: `refs/heads/${repo}`, sha: headSHA, } return request(opts) }) .then(() => // now we just need to get the SHA of the file in the branch request( options( token, `https://api.github.com/repos/${ fork.full_name }/contents/plugins.json?ref=${repo}` ) ).then(data => JSON.parse(data).sha) ) ) } function forkUpstream(res) { return request( options( token, 'https://api.github.com/repos/sketchplugins/plugin-directory/forks', 'POST' ) ) .then(fork => JSON.parse(fork)) .then(fork => getOriginBranchSHA(fork).then(sha => ({ pluginUpdate: res, fork, sha, })) ) } function updatePluginJSON({ pluginUpdate, fork, sha }) { const opts = options( token, `https://api.github.com/repos/${fork.full_name}/contents/plugins.json`, 'PUT' ) const plugin = { title: skpmConfig.title || skpmConfig.name, description: skpmConfig.description, name, owner, appcast: `https://raw.githubusercontent.com/${repo}/master/.appcast.xml`, homepage: skpmConfig.homepage || `https://github.com/${repo}`, } if (skpmConfig.author) { let { author } = skpmConfig if (typeof skpmConfig.author === 'string') { author = parseAuthor(skpmConfig.author) } plugin.author = author.name } const newPlugins = JSON.stringify( pluginUpdate.plugins.concat(plugin), null, 2 ) let buf if (typeof Buffer.from === 'function') { // Node 5.10+ buf = Buffer.from(newPlugins, 'utf-8') } else { // older Node versions buf = new Buffer(newPlugins, 'utf-8') // eslint-disable-line } opts.json = { path: 'plugins.json', message: `Add the ${repo} plugin`, committer: { name: 'skpm-bot', email: '[email protected]', }, sha, content: buf.toString('base64'), branch: repo, } return request(opts).then(res => ({ res, fork, sha, })) } function openPR({ fork }) { const prOptions = options( token, 'https://api.github.com/repos/sketchplugins/plugin-directory/pulls', 'POST' ) prOptions.json = { title: `Add the ${repo} plugin`, head: `${fork.owner.login}:${repo}`, body: `Hello Ale :waves: The plugin is [here](${skpmConfig.homepage || `https://github.com/${repo}`}) if you want to have a look. Hope you are having a great day :) `, base: 'master', maintainer_can_modify: true, } return request(prOptions) } return getCurrentUpstreamPluginJSON().then(res => { if (!res.existingPlugin) { return forkUpstream(res) .then(updatePluginJSON) .then(openPR) } return 'already added' }) }, }
packages/skpm/src/utils/github.js
import path from 'path' import fs from 'fs' import requestWithCallback from 'request' import parseAuthor from 'parse-author' /* eslint-disable no-not-accumulator-reassign/no-not-accumulator-reassign */ function getErrorFromBody(body, opts) { if (typeof body === 'string') { try { body = JSON.parse(body) } catch (e) { body = {} } } // hide token from logs opts.headers.Authorization = 'Token **********' // log the request options to help debugging body.request = opts return new Error(JSON.stringify(body, null, ' ')) } /* eslint-enable */ function request(opts) { return new Promise((resolve, reject) => { requestWithCallback(opts, (err, response, body) => { if (err) { return reject(err) } const is2xx = !err && /^2/.test(String(response.statusCode)) if (!is2xx) { return reject(getErrorFromBody(body, opts)) } return resolve(body) }) }) } function options(token, url, method) { return { method: method || 'GET', url, headers: { Accept: 'application/vnd.github.v3+json', Authorization: `Token ${token}`, 'User-Agent': 'SKPM-Release-Agent', }, } } export default { getUser(token) { return request(options(token, 'https://api.github.com/user')) }, getRepo(token, repo) { if (!token) { return Promise.reject( new Error('You are not logged in. Please run `skpm login` first.') ) } return request(options(token, `https://api.github.com/repos/${repo}`)).then( res => { const permissions = JSON.parse(res).permissions || {} if (!permissions.push) { throw new Error( `You don't have the right permissions on the repo. Need the "push" permission and only got:\n' ${JSON.stringify( permissions, null, ' ' )}` ) } } ) }, createDraftRelease(token, repo, tag) { const opts = options( token, `https://api.github.com/repos/${repo}/releases`, 'POST' ) opts.json = { tag_name: tag, name: tag, draft: true, } return request(opts) }, updateAsset(token, repo, releaseId, assetName, fileName) { const opts = options( token, `https://uploads.github.com/repos/${repo}/releases/${releaseId}/assets?name=${encodeURIComponent( fileName )}&label=${encodeURIComponent( 'To install: download this file, unzip and double click on the .sketchplugin' )}`, 'POST' ) const asset = path.join(process.cwd(), assetName) const stat = fs.statSync(asset) const rd = fs.createReadStream(asset) opts.headers['Content-Type'] = 'application/zip' opts.headers['Content-Length'] = stat.size const us = requestWithCallback(opts) return new Promise((resolve, reject) => { rd.on('error', err => reject(err)) us.on('error', err => reject(err)) us.on('end', () => resolve()) rd.pipe(us) }) }, publishRelease(token, repo, releaseId) { const opts = options( token, `https://api.github.com/repos/${repo}/releases/${releaseId}`, 'PATCH' ) opts.json = { draft: false, } return request(opts) }, addPluginToPluginsRegistryRepo(token, skpmConfig, repo) { const owner = repo.split('/')[0] const name = repo.split('/')[1] function getCurrentUpstreamPluginJSON() { return request( options( token, 'https://api.github.com/repos/sketchplugins/plugin-directory/contents/plugins.json' ) ) .then(data => { const file = JSON.parse(data) let buf if (typeof Buffer.from === 'function') { // Node 5.10+ buf = Buffer.from(file.content, 'base64') } else { // older Node versions buf = new Buffer(file.content, 'base64') // eslint-disable-line } return { plugins: JSON.parse(buf.toString('utf-8')), file, } }) .then(res => ({ existingPlugin: res.plugins.find( plugin => plugin.title === skpmConfig.name || name === plugin.name ), plugins: res.plugins, file: res.file, })) } function getOriginBranchSHA({ res, fork }) { return request( options( token, `https://api.github.com/repos/${ fork.full_name }/contents/plugins.json?ref=${repo}` ) ).then( data => JSON.parse(data).sha, () => // we need to create the branch here but to do so, we need the sha of the HEAD request( options( token, `https://api.github.com/repos/${fork.full_name}/git/refs/heads` ) ).then(data => { const headSHA = JSON.parse(data)[0].object.sha const opts = options( token, `https://api.github.com/repos/${fork.full_name}/git/refs`, 'POST' ) opts.json = { ref: `refs/heads/${repo}`, sha: headSHA, } return request(opts).then(() => // now we just need to get the SHA of the file in the branch getOriginBranchSHA({ res, fork }) ) }) ) } function forkUpstream(res) { return request( options( token, 'https://api.github.com/repos/sketchplugins/plugin-directory/forks', 'POST' ) ) .then(fork => JSON.parse(fork)) .then(fork => getOriginBranchSHA({ res, fork }).then(sha => ({ pluginUpdate: res, fork, sha, })) ) } function updatePluginJSON({ pluginUpdate, fork, sha }) { const opts = options( token, `https://api.github.com/repos/${fork.full_name}/contents/plugins.json`, 'PUT' ) const plugin = { title: skpmConfig.title || skpmConfig.name, description: skpmConfig.description, name, owner, appcast: `https://raw.githubusercontent.com/${repo}/master/.appcast.xml`, homepage: `https://github.com/${repo}`, } if (skpmConfig.author) { let { author } = skpmConfig if (typeof skpmConfig.author === 'string') { author = parseAuthor(skpmConfig.author) } plugin.author = author.name } const newPlugins = JSON.stringify( pluginUpdate.plugins.concat(plugin), null, 2 ) let buf if (typeof Buffer.from === 'function') { // Node 5.10+ buf = Buffer.from(newPlugins, 'utf-8') } else { // older Node versions buf = new Buffer(newPlugins, 'utf-8') // eslint-disable-line } opts.json = { path: 'plugins.json', message: `Add the ${repo} plugin`, committer: { name: 'skpm-bot', email: '[email protected]', }, sha, content: buf.toString('base64'), branch: repo, } return request(opts).then(res => ({ res, fork, sha, })) } function openPR({ fork }) { const prOptions = options( token, 'https://api.github.com/repos/sketchplugins/plugin-directory/pulls', 'POST' ) prOptions.json = { title: `Add the ${repo} plugin`, head: `${fork.owner.login}:${repo}`, base: 'master', maintainer_can_modify: true, } return request(prOptions) } return getCurrentUpstreamPluginJSON().then(res => { if (!res.existingPlugin) { return forkUpstream(res) .then(updatePluginJSON) .then(openPR) } return 'already added' }) }, }
be nice to Ale
packages/skpm/src/utils/github.js
be nice to Ale
<ide><path>ackages/skpm/src/utils/github.js <ide> } <ide> return request(opts) <ide> }, <add> // get the upstream plugins.json <add> // if we haven't added the plugin yet <add> // get or create a fork <add> // delete any existing branch for this plugin <add> // check if origin master is up to date with upstream (update otherwise) <add> // branch <add> // update origin plugins.json <add> // open PR <ide> addPluginToPluginsRegistryRepo(token, skpmConfig, repo) { <ide> const owner = repo.split('/')[0] <ide> const name = repo.split('/')[1] <ide> ) <ide> .then(data => { <ide> const file = JSON.parse(data) <del> let buf <del> if (typeof Buffer.from === 'function') { <del> // Node 5.10+ <del> buf = Buffer.from(file.content, 'base64') <del> } else { <del> // older Node versions <del> buf = new Buffer(file.content, 'base64') // eslint-disable-line <del> } <add> const buf = Buffer.from(file.content, 'base64') <ide> return { <ide> plugins: JSON.parse(buf.toString('utf-8')), <ide> file, <ide> })) <ide> } <ide> <del> function getOriginBranchSHA({ res, fork }) { <del> return request( <del> options( <del> token, <del> `https://api.github.com/repos/${ <del> fork.full_name <del> }/contents/plugins.json?ref=${repo}` <del> ) <del> ).then( <del> data => JSON.parse(data).sha, <del> () => <del> // we need to create the branch here but to do so, we need the sha of the HEAD <add> function deleteExistingBranch(fork) { <add> const opts = options( <add> token, <add> `https://api.github.com/repos/${fork.full_name}/git/refs/heads/${repo}`, <add> 'DELETE' <add> ) <add> return request(opts).catch(() => {}) <add> } <add> <add> function getOriginBranchSHA(fork) { <add> return deleteExistingBranch().then(() => <add> Promise.all([ <ide> request( <ide> options( <ide> token, <del> `https://api.github.com/repos/${fork.full_name}/git/refs/heads` <add> `https://api.github.com/repos/${ <add> fork.full_name <add> }/git/refs/heads/master` <ide> ) <del> ).then(data => { <del> const headSHA = JSON.parse(data)[0].object.sha <add> ), <add> request( <add> options( <add> token, <add> `https://api.github.com/repos/sketchplugins/plugin-directory/git/refs/heads/master` <add> ) <add> ), <add> ]) <add> .then(([originData, upstreamData]) => ({ <add> originSHA: JSON.parse(originData).object.sha, <add> upstreamSHA: JSON.parse(upstreamData).object.sha, <add> })) <add> .then(({ originSHA, upstreamSHA }) => { <add> if (originSHA === upstreamSHA) { <add> return originSHA <add> } <add> // merge upstream master so that there is no conflicts <add> const opts = options( <add> token, <add> `https://api.github.com/repos/${ <add> fork.full_name <add> }/git/refs/heads/master`, <add> 'PATCH' <add> ) <add> opts.json = { <add> sha: upstreamSHA, <add> } <add> return request(opts).then(() => upstreamSHA) <add> }) <add> .then(headSHA => { <ide> const opts = options( <ide> token, <ide> `https://api.github.com/repos/${fork.full_name}/git/refs`, <ide> ref: `refs/heads/${repo}`, <ide> sha: headSHA, <ide> } <del> return request(opts).then(() => <del> // now we just need to get the SHA of the file in the branch <del> getOriginBranchSHA({ res, fork }) <del> ) <add> return request(opts) <ide> }) <add> .then(() => <add> // now we just need to get the SHA of the file in the branch <add> request( <add> options( <add> token, <add> `https://api.github.com/repos/${ <add> fork.full_name <add> }/contents/plugins.json?ref=${repo}` <add> ) <add> ).then(data => JSON.parse(data).sha) <add> ) <ide> ) <ide> } <ide> <ide> ) <ide> .then(fork => JSON.parse(fork)) <ide> .then(fork => <del> getOriginBranchSHA({ res, fork }).then(sha => ({ <add> getOriginBranchSHA(fork).then(sha => ({ <ide> pluginUpdate: res, <ide> fork, <ide> sha, <ide> name, <ide> owner, <ide> appcast: `https://raw.githubusercontent.com/${repo}/master/.appcast.xml`, <del> homepage: `https://github.com/${repo}`, <add> homepage: skpmConfig.homepage || `https://github.com/${repo}`, <ide> } <ide> <ide> if (skpmConfig.author) { <ide> prOptions.json = { <ide> title: `Add the ${repo} plugin`, <ide> head: `${fork.owner.login}:${repo}`, <add> body: `Hello Ale :waves: <add> <add>The plugin is [here](${skpmConfig.homepage || <add> `https://github.com/${repo}`}) if you want to have a look. <add> <add>Hope you are having a great day :) <add>`, <ide> base: 'master', <ide> maintainer_can_modify: true, <ide> }
Java
apache-2.0
045b9aa86e8f8721157851088769115eedcda29f
0
xquery/marklogic-sesame,marklogic/marklogic-sesame,marklogic/marklogic-sesame,xquery/marklogic-sesame,marklogic/marklogic-sesame,xquery/marklogic-sesame
package com.marklogic.sesame.functionaltests; import com.marklogic.client.DatabaseClient; import com.marklogic.client.DatabaseClientFactory; import com.marklogic.client.document.XMLDocumentManager; import com.marklogic.client.io.Format; import com.marklogic.client.io.StringHandle; import com.marklogic.client.query.*; import com.marklogic.client.semantics.Capability; import com.marklogic.client.semantics.GraphManager; import com.marklogic.client.semantics.GraphPermissions; import com.marklogic.client.semantics.SPARQLRuleset; import com.marklogic.semantics.sesame.MarkLogicRepository; import com.marklogic.semantics.sesame.MarkLogicRepositoryConnection; import com.marklogic.semantics.sesame.MarkLogicTransactionException; import com.marklogic.semantics.sesame.config.MarkLogicRepositoryConfig; import com.marklogic.semantics.sesame.config.MarkLogicRepositoryFactory; import com.marklogic.semantics.sesame.query.MarkLogicBooleanQuery; import com.marklogic.semantics.sesame.query.MarkLogicQuery; import com.marklogic.semantics.sesame.query.MarkLogicTupleQuery; import com.marklogic.semantics.sesame.query.MarkLogicUpdateQuery; import com.marklogic.sesame.functionaltests.util.ConnectedRESTQA; import com.marklogic.sesame.functionaltests.util.StatementIterable; import com.marklogic.sesame.functionaltests.util.StatementIterator; import com.marklogic.sesame.functionaltests.util.StatementList; import info.aduna.iteration.CloseableIteration; import info.aduna.iteration.Iteration; import info.aduna.iteration.Iterations; import info.aduna.iteration.IteratorIteration; import org.junit.*; import org.openrdf.IsolationLevels; import org.openrdf.OpenRDFException; import org.openrdf.model.*; import org.openrdf.model.vocabulary.XMLSchema; import org.openrdf.query.*; import org.openrdf.repository.Repository; import org.openrdf.repository.RepositoryConnection; import org.openrdf.repository.RepositoryException; import org.openrdf.repository.RepositoryResult; import org.openrdf.repository.UnknownTransactionStateException; import org.openrdf.repository.config.RepositoryConfigException; import org.openrdf.repository.config.RepositoryFactory; import org.openrdf.repository.config.RepositoryImplConfig; import org.openrdf.rio.RDFFormat; import org.openrdf.rio.RDFHandlerException; import org.openrdf.rio.RDFParseException; import org.openrdf.rio.RioSetting; import org.openrdf.rio.helpers.BasicParserSettings; import org.openrdf.rio.helpers.RDFHandlerBase; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import java.io.*; import java.net.URL; import java.util.*; import java.util.Map.Entry; import static org.hamcrest.core.AnyOf.anyOf; import static org.hamcrest.core.Is.is; import static org.hamcrest.core.IsEqual.equalTo; import static org.hamcrest.core.IsNot.not; import static org.hamcrest.core.IsNull.notNullValue; import static org.hamcrest.core.IsNull.nullValue; import static org.junit.Assert.*; public class MarkLogicRepositoryConnectionTest extends ConnectedRESTQA { private static final String TEST_DIR_PREFIX = "/testdata/"; private static String dbName = "MLSesame"; private static String [] fNames = {"MLSesame-1"}; private static String restServer = "REST-MLSesame-API-Server"; private static int restPort = 8023; protected static DatabaseClient databaseClient ; protected static MarkLogicRepository testAdminRepository; protected static MarkLogicRepository testReaderRepository; protected static MarkLogicRepository testWriterRepository; protected static MarkLogicRepositoryConnection testAdminCon; protected static MarkLogicRepositoryConnection testReaderCon; protected static MarkLogicRepositoryConnection testWriterCon; protected final Logger logger = LoggerFactory.getLogger(this.getClass()); protected ValueFactory vf; protected ValueFactory vfWrite; protected URI graph1; protected URI graph2; protected URI dirgraph; protected URI dirgraph1; protected URI john; protected URI micah; protected URI fei; protected URI fname; protected URI lname; protected URI email; protected URI homeTel; protected Literal johnfname; protected Literal johnlname; protected Literal johnemail; protected Literal johnhomeTel; protected Literal micahfname; protected Literal micahlname; protected Literal micahhomeTel; protected Literal feifname; protected Literal feilname; protected Literal feiemail; protected URI writeFuncSpecOf ; protected URI type ; protected URI worksFor ; protected URI developPrototypeOf ; protected URI ml ; protected URI semantics ; protected URI inference ; protected URI sEngineer ; protected URI lEngineer ; protected URI engineer ; protected URI employee ; protected URI design ; protected URI subClass ; protected URI subProperty ; protected URI eqProperty ; protected URI develop ; protected QueryManager qmgr; private static final String ID = "id"; private static final String ADDRESS = "addressbook"; protected static final String NS = "http://marklogicsparql.com/"; protected static final String RDFS = "http://www.w3.org/2000/01/rdf-schema#"; protected static final String OWL = "http://www.w3.org/2002/07/owl#"; @BeforeClass public static void initialSetup() throws Exception { setupJavaRESTServer(dbName, fNames[0], restServer, restPort); setupAppServicesConstraint(dbName); enableCollectionLexicon(dbName); enableTripleIndex(dbName); createRESTUser("reader", "reader", "rest-reader"); createRESTUser("writer", "writer", "rest-writer"); } @AfterClass public static void tearDownSetup() throws Exception { tearDownJavaRESTServer(dbName, fNames, restServer); deleteUserRole("test-eval"); deleteRESTUser("reader"); deleteRESTUser("writer"); } @Before public void setUp() throws Exception { logger.debug("Initializing repository"); createRepository(); vf = testAdminCon.getValueFactory(); vfWrite = testWriterCon.getValueFactory(); john = vf.createURI(NS+ID+"#1111"); micah = vf.createURI(NS+ID+"#2222"); fei = vf.createURI(NS+ID+"#3333"); fname = vf.createURI(NS+ADDRESS+"#firstName"); lname = vf.createURI(NS+ADDRESS+"#lastName"); email = vf.createURI(NS+ADDRESS+"#email"); homeTel =vf.createURI(NS+ADDRESS+"#homeTel"); writeFuncSpecOf =vf.createURI(NS+"writeFuncSpecOf"); type = vf.createURI("http://www.w3.org/1999/02/22-rdf-syntax-ns#type"); worksFor =vf.createURI(NS+"worksFor"); developPrototypeOf =vf.createURI(NS+"developPrototypeOf"); ml =vf.createURI(NS+"MarkLogic"); semantics = vf.createURI(NS+"Semantics"); inference = vf.createURI(NS+"Inference"); sEngineer = vf.createURI(NS+"SeniorEngineer"); lEngineer = vf.createURI(NS+"LeadEngineer"); engineer = vf.createURI(NS+"Engineer"); employee = vf.createURI(NS+"Employee"); design = vf.createURI(NS+"design"); develop = vf.createURI(NS+"develop"); subClass = vf.createURI(RDFS+"subClassOf"); subProperty = vf.createURI(RDFS+"subPropertyOf"); eqProperty = vf.createURI(OWL+"equivalentProperty"); johnfname = vf.createLiteral("John"); johnlname = vf.createLiteral("Snelson"); johnhomeTel = vf.createLiteral(111111111D); johnemail = vf.createLiteral("[email protected]"); micahfname = vf.createLiteral("Micah"); micahlname = vf.createLiteral("Dubinko"); micahhomeTel = vf.createLiteral(22222222D); feifname = vf.createLiteral("Fei"); feilname = vf.createLiteral("Ling"); feiemail = vf.createLiteral("[email protected]"); } @After public void tearDown() throws Exception { clearDB(restPort); testAdminCon.close(); testAdminRepository.shutDown(); testAdminRepository = null; testAdminCon = null; testReaderRepository.shutDown(); testReaderRepository = null; testReaderCon = null; testWriterCon.close(); testWriterRepository.shutDown(); testWriterCon = null; testWriterRepository = null; logger.info("tearDown complete."); } /** * Gets an (uninitialized) instance of the repository that should be tested. * * @return void * @throws RepositoryConfigException * @throws RepositoryException */ protected void createRepository() throws Exception { //Creating MLSesame Connection object Using MarkLogicRepositoryConfig MarkLogicRepositoryConfig adminconfig = new MarkLogicRepositoryConfig(); adminconfig.setHost("localhost"); adminconfig.setAuth("DIGEST"); adminconfig.setUser("admin"); adminconfig.setPassword("admin"); adminconfig.setPort(restPort); RepositoryFactory factory = new MarkLogicRepositoryFactory(); Assert.assertEquals("marklogic:MarkLogicRepository", factory.getRepositoryType()); try { testAdminRepository = (MarkLogicRepository) factory.getRepository(adminconfig); } catch (RepositoryConfigException e) { // TODO Auto-generated catch block e.printStackTrace(); } try { testAdminRepository.initialize(); testAdminCon = (MarkLogicRepositoryConnection) testAdminRepository.getConnection(); } catch (RepositoryException e) { // TODO Auto-generated catch block e.printStackTrace(); } // Creating testAdminCon with MarkLogicRepositoryConfig constructor testAdminCon.close(); testAdminRepository.shutDown(); testAdminRepository = null; testAdminCon = null; adminconfig = new MarkLogicRepositoryConfig("localhost",restPort,"admin","admin","DIGEST"); Assert.assertEquals("marklogic:MarkLogicRepository", factory.getRepositoryType()); testAdminRepository = (MarkLogicRepository) factory.getRepository(adminconfig); testAdminRepository.initialize(); testAdminCon = testAdminRepository.getConnection(); Assert.assertTrue(testAdminCon instanceof MarkLogicRepositoryConnection); Repository otherrepo = factory.getRepository(adminconfig); try{ //try to get connection without initializing repo, will throw error RepositoryConnection conn = otherrepo.getConnection(); Assert.assertTrue(false); } catch(Exception e){ Assert.assertTrue(e instanceof RepositoryException); otherrepo.shutDown(); } Assert.assertTrue(testAdminCon instanceof MarkLogicRepositoryConnection); graph1 = testAdminCon.getValueFactory().createURI("http://marklogic.com/Graph1"); graph2 = testAdminCon.getValueFactory().createURI("http://marklogic.com/Graph2"); dirgraph = testAdminCon.getValueFactory().createURI("http://marklogic.com/dirgraph"); dirgraph1 = testAdminCon.getValueFactory().createURI("http://marklogic.com/dirgraph1"); //Creating MLSesame Connection object Using MarkLogicRepository overloaded constructor if(testReaderCon == null || testReaderRepository ==null){ testReaderRepository = new MarkLogicRepository("localhost", restPort, "reader", "reader", "DIGEST"); try { testReaderRepository.initialize(); Assert.assertNotNull(testReaderRepository); testReaderCon = (MarkLogicRepositoryConnection) testReaderRepository.getConnection(); } catch (RepositoryException e) { // TODO Auto-generated catch block e.printStackTrace(); } Assert.assertTrue(testReaderCon instanceof MarkLogicRepositoryConnection); } //Creating MLSesame Connection object Using MarkLogicRepository(databaseclient) constructor if (databaseClient == null) databaseClient = DatabaseClientFactory.newClient("localhost", restPort, "writer", "writer", DatabaseClientFactory.Authentication.valueOf("DIGEST")); if(testWriterCon == null || testWriterRepository ==null){ testWriterRepository = new MarkLogicRepository(databaseClient); qmgr = databaseClient.newQueryManager(); try { testWriterRepository.initialize(); Assert.assertNotNull(testWriterRepository); testWriterCon = (MarkLogicRepositoryConnection) testWriterRepository.getConnection(); } catch (RepositoryException e) { // TODO Auto-generated catch block e.printStackTrace(); } } } @Test public void testMultiThreadedAdd() throws Exception{ class MyRunnable implements Runnable { @Override public void run(){ try { testAdminCon.begin(); for (int j =0 ;j < 100; j++){ URI subject = vf.createURI(NS+ID+"/"+Thread.currentThread().getId()+"/"+j+"#1111"); URI predicate = fname = vf.createURI(NS+ADDRESS+"/"+Thread.currentThread().getId()+"/"+"#firstName"); Literal object = vf.createLiteral(Thread.currentThread().getId()+ "-" + j +"-" +"John"); testAdminCon.add(subject, predicate,object, dirgraph); } testAdminCon.commit(); } catch (RepositoryException e1) { // TODO Auto-generated catch block e1.printStackTrace(); } finally{ try { if(testAdminCon.isActive()) testAdminCon.rollback(); } catch (UnknownTransactionStateException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (RepositoryException e) { // TODO Auto-generated catch block e.printStackTrace(); } } } } class MyRunnable1 implements Runnable { @Override public void run(){ try { testWriterCon.begin(); for (int j =0 ;j <100; j++){ URI subject = vf.createURI(NS+ID+"/"+Thread.currentThread().getId()+"/"+j+"#1111"); URI predicate = fname = vf.createURI(NS+ADDRESS+"/"+Thread.currentThread().getId()+"/"+"#firstName"); Literal object = vf.createLiteral(Thread.currentThread().getId()+ "-" + j +"-" +"John"); testWriterCon.add(subject, predicate,object, dirgraph); } testWriterCon.commit(); } catch (RepositoryException e1) { e1.printStackTrace(); } finally{ try { if(testWriterCon.isActive()) testWriterCon.rollback(); } catch (UnknownTransactionStateException e) { e.printStackTrace(); } catch (RepositoryException e) { e.printStackTrace(); } } } } Thread t1,t2; t1 = new Thread(new MyRunnable()); t1.setName("T1"); t2 = new Thread(new MyRunnable1()); t2.setName("T2"); t1.start(); t2.start(); t1.join(); t2.join(); Assert.assertEquals(200, testAdminCon.size()); } @Test public void testMultiThreadedAdd1() throws Exception{ class MyRunnable implements Runnable { @Override public void run(){ MarkLogicRepositoryConnection tempConn = null; try { if(! testAdminRepository.isInitialized()) testAdminRepository.initialize(); tempConn= testAdminRepository.getConnection(); tempConn.begin(); for (int j =0 ;j < 100; j++){ URI subject = vf.createURI(NS+ID+"/"+Thread.currentThread().getId()+"/"+j+"#1111"); URI predicate = fname = vf.createURI(NS+ADDRESS+"/"+Thread.currentThread().getId()+"/"+"#firstName"); Literal object = vf.createLiteral(Thread.currentThread().getId()+ "-" + j +"-" +"John"); tempConn.add(subject, predicate,object, dirgraph); } tempConn.commit(); } catch (RepositoryException e1) { // TODO Auto-generated catch block e1.printStackTrace(); } finally{ try { if(tempConn.isActive()) tempConn.rollback(); } catch (UnknownTransactionStateException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (RepositoryException e) { // TODO Auto-generated catch block e.printStackTrace(); } } } } Thread t1,t2,t3,t4; t1 = new Thread(new MyRunnable()); t1.setName("T1"); t2 = new Thread(new MyRunnable()); t2.setName("T2"); t3 = new Thread(new MyRunnable()); t3.setName("T3"); t4 = new Thread(new MyRunnable()); t4.setName("T4"); t1.start(); t2.start(); t3.start(); t4.start(); t1.join(); t2.join(); t3.join(); t4.join(); Assert.assertEquals(400, testAdminCon.size()); } @Test public void testMultiThreadedAdd2() throws Exception{ class MyRunnable implements Runnable { @Override public void run(){ try { for (int j =0 ;j < 100; j++){ URI subject = vf.createURI(NS+ID+"/"+Thread.currentThread().getId()+"/"+j+"#1111"); URI predicate = fname = vf.createURI(NS+ADDRESS+"/"+Thread.currentThread().getId()+"/"+"#firstName"); Literal object = vf.createLiteral(Thread.currentThread().getId()+ "-" + j +"-" +"John"); testAdminCon.add(subject, predicate,object, dirgraph); } } catch (RepositoryException e1) { // TODO Auto-generated catch block e1.printStackTrace(); } } } Thread t1,t2,t3,t4; t1 = new Thread(new MyRunnable()); t1.setName("T1"); t2 = new Thread(new MyRunnable()); t2.setName("T2"); t3 = new Thread(new MyRunnable()); t3.setName("T2"); t4 = new Thread(new MyRunnable()); t4.setName("T2"); t1.start(); t2.start(); t3.start(); t4.start(); t1.join(); t2.join(); t3.join(); t4.join(); Assert.assertEquals(400, testAdminCon.size()); } @Test public void testMultiThreadedAddDuplicate() throws Exception{ class MyRunnable implements Runnable { @Override public void run() { for (int j =0 ;j < 100; j++){ URI subject = vf.createURI(NS+ID+"/"+j+"#1111"); URI predicate = fname = vf.createURI(NS+ADDRESS+"/"+"#firstName"); Literal object = vf.createLiteral(j +"-" +"John"); try { testAdminCon.add(subject, predicate,object, dirgraph); } catch (RepositoryException e) { // TODO Auto-generated catch block e.printStackTrace(); } } } } Thread t1,t2,t3,t4,t5; t1 = new Thread(new MyRunnable()); t2 = new Thread(new MyRunnable()); t3 = new Thread(new MyRunnable()); t4 = new Thread(new MyRunnable()); t5 = new Thread(new MyRunnable()); t1.start(); t2.start(); t3.start(); t4.start(); t5.start(); t1.join(); t2.join(); t3.join(); t4.join(); t5.join(); Assert.assertEquals(100, testAdminCon.size()); } //ISSUE - 19 @Test public void testPrepareBooleanQuery1() throws Exception{ Assert.assertEquals(0L, testAdminCon.size()); InputStream in = MarkLogicRepositoryConnectionTest.class.getResourceAsStream(TEST_DIR_PREFIX + "tigers.ttl"); testAdminCon.add(in, "", RDFFormat.TURTLE); in.close(); Assert.assertEquals(107L, testAdminCon.size()); String query1 = "PREFIX bb: <http://marklogic.com/baseball/players#>"+ " ASK "+ " WHERE"+ " {"+ " ?id bb:lastname ?name ."+ " FILTER EXISTS { ?id bb:country ?countryname }"+ " }"; boolean result1 = testAdminCon.prepareBooleanQuery(QueryLanguage.SPARQL, query1).evaluate(); Assert.assertFalse(result1); String query2 = "PREFIX bb: <http://marklogic.com/baseball/players#>"+ "PREFIX r: <http://marklogic.com/baseball/rules#>"+ " ASK WHERE"+ " {"+ " ?id bb:team r:Tigers."+ " ?id bb:position \"pitcher\"."+ " }"; boolean result2 = testAdminCon.prepareBooleanQuery(QueryLanguage.SPARQL, query2).evaluate(); Assert.assertTrue(result2); } // ISSUE 32, 45 @Test public void testPrepareBooleanQuery2() throws Exception{ InputStream in = MarkLogicRepositoryConnectionTest.class.getResourceAsStream(TEST_DIR_PREFIX + "tigers.ttl"); Reader reader = new InputStreamReader(in); testAdminCon.add(reader, "http://marklogic.com/baseball/", RDFFormat.TURTLE, graph1); reader.close(); Assert.assertEquals(107L, testAdminCon.size(graph1, null)); String query1 = "ASK FROM <http://marklogic.com/Graph1>"+ " WHERE"+ " {"+ " ?player ?team <#Tigers>."+ " }"; boolean result1 = testAdminCon.prepareBooleanQuery(QueryLanguage.SPARQL, query1,"http://marklogic.com/baseball/rules").evaluate(); Assert.assertTrue(result1); String query2 = "PREFIX bb: <http://marklogic.com/baseball/players#>"+ " PREFIX r: <http://marklogic.com/baseball/rules#>"+ " ASK FROM <http://marklogic.com/Graph1> WHERE"+ " {"+ " ?id bb:team r:Tigers."+ " ?id bb:position \"pitcher\"."+ " }"; boolean result2 = testAdminCon.prepareBooleanQuery(QueryLanguage.SPARQL, query2, "").evaluate(); Assert.assertTrue(result2); } @Test public void testPrepareBooleanQuery3() throws Exception{ URL url = MarkLogicRepositoryConnectionTest.class.getResource(TEST_DIR_PREFIX+"tigers.ttl"); testAdminCon.add(url, "", RDFFormat.TURTLE, graph1); Assert.assertEquals(107L, testAdminCon.size()); String query1 = "PREFIX bb: <http://marklogic.com/baseball/players#>"+ "ASK "+ "WHERE"+ "{"+ " ?s bb:position ?o."+ "}"; BooleanQuery bq = testAdminCon.prepareBooleanQuery(query1); bq.setBinding("o", vf.createLiteral("coach")); boolean result1 = bq.evaluate(); Assert.assertTrue(result1); bq.clearBindings(); bq.setBinding("o", vf.createLiteral("pitcher")); boolean result2 = bq.evaluate(); Assert.assertTrue(result2); bq.clearBindings(); bq.setBinding("o", vf.createLiteral("abcd")); boolean result3 = bq.evaluate(); Assert.assertFalse(result3); } @Test public void testPrepareBooleanQuery4() throws Exception{ File file = new File(MarkLogicRepositoryConnectionTest.class.getResource(TEST_DIR_PREFIX+ "tigers.ttl").getFile()); testAdminCon.add(file, "", RDFFormat.TURTLE, graph1); logger.debug(file.getAbsolutePath()); Assert.assertEquals(107L, testAdminCon.size(graph1)); String query1 = "PREFIX bb: <http://marklogic.com/baseball/players#>"+ "ASK FROM <http://marklogic.com/Graph1>"+ "WHERE"+ "{"+ "<#119> <#lastname> \"Verlander\"."+ "<#119> <#team> ?tigers."+ "}"; boolean result1 = testAdminCon.prepareBooleanQuery(query1,"http://marklogic.com/baseball/players").evaluate(); Assert.assertTrue(result1); } // ISSUE 20 , 25 @Test public void testPrepareTupleQuery1() throws Exception{ Assert.assertEquals(0, testAdminCon.size()); Statement st1 = vf.createStatement(john, fname, johnfname, dirgraph); Statement st2 = vf.createStatement(john, lname, johnlname, dirgraph); Statement st3 = vf.createStatement(john, homeTel, johnhomeTel, dirgraph); Statement st4 = vf.createStatement(john, email, johnemail, dirgraph); Statement st5 = vf.createStatement(micah, fname, micahfname, dirgraph); Statement st6 = vf.createStatement(micah, lname, micahlname, dirgraph); Statement st7 = vf.createStatement(micah, homeTel, micahhomeTel, dirgraph); Statement st8 = vf.createStatement(fei, fname, feifname, dirgraph); Statement st9 = vf.createStatement(fei, lname, feilname, dirgraph); Statement st10 = vf.createStatement(fei, email, feiemail, dirgraph); testAdminCon.add(st1, dirgraph); testAdminCon.add(st2, dirgraph); testAdminCon.add(st3, dirgraph); testAdminCon.add(st4, dirgraph); testAdminCon.add(st5, dirgraph); testAdminCon.add(st6, dirgraph); testAdminCon.add(st7, dirgraph); testAdminCon.add(st8, dirgraph); testAdminCon.add(st9, dirgraph); testAdminCon.add(st10, dirgraph); Assert.assertEquals(10, testAdminCon.size(dirgraph)); StringBuilder queryBuilder = new StringBuilder(); queryBuilder.append("PREFIX ad: <http://marklogicsparql.com/addressbook#>"); queryBuilder.append(" PREFIX d: <http://marklogicsparql.com/id#>"); queryBuilder.append(" SELECT DISTINCT ?person"); queryBuilder.append(" FROM <http://marklogic.com/dirgraph>"); queryBuilder.append(" WHERE"); queryBuilder.append(" {?person ad:firstName ?firstname ;"); queryBuilder.append(" ad:lastName ?lastname."); queryBuilder.append(" OPTIONAL {?person ad:homeTel ?phonenumber .}"); queryBuilder.append(" FILTER (?firstname = \"Fei\")}"); TupleQuery query = testAdminCon.prepareTupleQuery(QueryLanguage.SPARQL, queryBuilder.toString()); TupleQueryResult result = query.evaluate(); try { assertThat(result, is(notNullValue())); assertThat(result.hasNext(), is(equalTo(true))); while (result.hasNext()) { BindingSet solution = result.next(); assertThat(solution.hasBinding("person"), is(equalTo(true))); Value nameResult = solution.getValue("person"); Assert.assertEquals(nameResult.stringValue(),fei.stringValue()); } } finally { result.close(); } } @Test public void testPrepareTupleQuery2() throws Exception{ testAdminCon.add(john, fname, johnfname, dirgraph); testAdminCon.add(john, lname, johnlname, dirgraph); testAdminCon.add(john, homeTel, johnhomeTel, dirgraph); testAdminCon.add(john, email, johnemail, dirgraph); testAdminCon.add(micah, fname, micahfname, dirgraph); testAdminCon.add(micah, lname, micahlname, dirgraph); testAdminCon.add(micah, homeTel, micahhomeTel, dirgraph); testAdminCon.add(fei, fname, feifname, dirgraph); testAdminCon.add(fei, lname, feilname, dirgraph); testAdminCon.add(fei, email, feiemail, dirgraph); try{ Assert.assertEquals(10, testAdminCon.size(dirgraph)); } catch(Exception ex){ logger.error("Failed :", ex); } StringBuilder queryBuilder = new StringBuilder(); queryBuilder.append("PREFIX ad: <http://marklogicsparql.com/addressbook#>"); queryBuilder.append(" PREFIX d: <http://marklogicsparql.com/id#>"); queryBuilder.append(" SELECT ?person ?lastname"); queryBuilder.append(" WHERE"); queryBuilder.append(" {?person <#firstName> ?firstname ;"); queryBuilder.append(" <#lastName> ?lastname."); queryBuilder.append(" OPTIONAL {?person <#email> ?email.}"); queryBuilder.append(" FILTER EXISTS {?person <#homeTel> ?tel .}} ORDER BY ?lastname"); TupleQuery query = testAdminCon.prepareTupleQuery(QueryLanguage.SPARQL, queryBuilder.toString(),"http://marklogicsparql.com/addressbook"); TupleQueryResult result = query.evaluate(); String [] expectedPersonresult = {micah.stringValue(), john.stringValue()}; String [] expectedLnameresult = {micahlname.stringValue(), johnlname.stringValue()}; int i = 0; try { assertThat(result, is(notNullValue())); Assert.assertTrue(result.hasNext()); while (result.hasNext()) { BindingSet solution = result.next(); assertThat(solution.hasBinding("person"), is(equalTo(true))); assertThat(solution.hasBinding("lastname"), is(equalTo(true))); Value personResult = solution.getValue("person"); Value nameResult = solution.getValue("lastname"); Assert.assertEquals(personResult.stringValue(),expectedPersonresult[i]); Assert.assertEquals(nameResult.stringValue(),expectedLnameresult[i]); i++; } } finally { result.close(); } } @Test public void testPrepareTupleQuery3() throws Exception{ Statement st1 = vf.createStatement(john, fname, johnfname); Statement st2 = vf.createStatement(john, lname, johnlname); Statement st3 = vf.createStatement(john, homeTel, johnhomeTel); Statement st4 = vf.createStatement(john, email, johnemail); Statement st5 = vf.createStatement(micah, fname, micahfname); Statement st6 = vf.createStatement(micah, lname, micahlname); Statement st7 = vf.createStatement(micah, homeTel, micahhomeTel); Statement st8 = vf.createStatement(fei, fname, feifname); Statement st9 = vf.createStatement(fei, lname, feilname); Statement st10 = vf.createStatement(fei, email, feiemail); testAdminCon.add(st1, dirgraph); testAdminCon.add(st2, dirgraph); testAdminCon.add(st3, dirgraph); testAdminCon.add(st4, dirgraph); testAdminCon.add(st5, dirgraph); testAdminCon.add(st6, dirgraph); testAdminCon.add(st7, dirgraph); testAdminCon.add(st8, dirgraph); testAdminCon.add(st9, dirgraph); testAdminCon.add(st10, dirgraph); try{ Assert.assertEquals(10, testAdminCon.size(dirgraph)); } catch(Exception ex){ logger.error("Failed :", ex); } StringBuilder queryBuilder = new StringBuilder(); queryBuilder.append(" PREFIX ad: <http://marklogicsparql.com/addressbook#> "); queryBuilder.append(" SELECT ?name ?id ?g "); queryBuilder.append(" FROM NAMED "); queryBuilder.append("<").append(dirgraph.stringValue()).append(">"); queryBuilder.append(" WHERE "); queryBuilder.append(" { "); queryBuilder.append(" GRAPH ?g { ?id ad:lastName ?name .} "); queryBuilder.append(" FILTER EXISTS { GRAPH ?g {?id ad:email ?email ; "); queryBuilder.append(" ad:firstName ?fname.}"); queryBuilder.append(" } "); queryBuilder.append(" } "); queryBuilder.append(" ORDER BY ?name "); TupleQuery query = testAdminCon.prepareTupleQuery(queryBuilder.toString()); TupleQueryResult result = query.evaluate(); String [] epectedPersonresult = {fei.stringValue(), john.stringValue()}; String [] expectedLnameresult = {feilname.stringValue(), johnlname.stringValue()}; String [] expectedGraphresult = {dirgraph.stringValue(), dirgraph.stringValue()}; int i = 0; try { assertThat(result, is(notNullValue())); Assert.assertTrue(result.hasNext()); while (result.hasNext()) { BindingSet solution = result.next(); assertThat(solution.hasBinding("name"), is(equalTo(true))); assertThat(solution.hasBinding("id"), is(equalTo(true))); assertThat(solution.hasBinding("g"), is(equalTo(true))); Value idResult = solution.getValue("id"); Value nameResult = solution.getValue("name"); Value graphResult = solution.getValue("g"); Assert.assertEquals(idResult.stringValue(),epectedPersonresult[i]); Assert.assertEquals(nameResult.stringValue(),expectedLnameresult[i]); Assert.assertEquals(graphResult.stringValue(),expectedGraphresult[i]); i++; } } finally { result.close(); } } // ISSSUE 109 @Test public void testPrepareTupleQuery4() throws Exception{ Statement st1 = vf.createStatement(john, fname, johnfname, dirgraph); Statement st2 = vf.createStatement(john, lname, johnlname, dirgraph); Statement st3 = vf.createStatement(john, homeTel, johnhomeTel, dirgraph); Statement st4 = vf.createStatement(john, email, johnemail, dirgraph); Statement st5 = vf.createStatement(micah, fname, micahfname, dirgraph); Statement st6 = vf.createStatement(micah, lname, micahlname, dirgraph); Statement st7 = vf.createStatement(micah, homeTel, micahhomeTel, dirgraph); Statement st8 = vf.createStatement(fei, fname, feifname, dirgraph); Statement st9 = vf.createStatement(fei, lname, feilname, dirgraph); Statement st10 = vf.createStatement(fei, email, feiemail, dirgraph); testAdminCon.add(st1); testAdminCon.add(st2); testAdminCon.add(st3); testAdminCon.add(st4); testAdminCon.add(st5); testAdminCon.add(st6); testAdminCon.add(st7); testAdminCon.add(st8); testAdminCon.add(st9); testAdminCon.add(st10); try{ Assert.assertEquals(10, testAdminCon.size(dirgraph)); } catch(Exception ex){ logger.error("Failed :", ex); } StringBuilder queryBuilder = new StringBuilder(64); queryBuilder.append("PREFIX ad: <http://marklogicsparql.com/addressbook#> "); queryBuilder.append(" SELECT ?person ?firstname ?lastname ?phonenumber"); queryBuilder.append(" FROM <").append(dirgraph.stringValue()).append(">"); queryBuilder.append(" WHERE"); queryBuilder.append(" { "); queryBuilder.append(" ?person <#firstName> ?firstname ;"); queryBuilder.append(" <#lastName> ?lastname. "); queryBuilder.append(" OPTIONAL {?person <#homeTel> ?phonenumber .} "); queryBuilder.append(" VALUES ?firstname { \"Micah\" \"Fei\" }"); queryBuilder.append(" } "); queryBuilder.append(" ORDER BY ?firstname"); TupleQuery query = testAdminCon.prepareTupleQuery(queryBuilder.toString(),"http://marklogicsparql.com/addressbook"); TupleQueryResult result = query.evaluate(); String [] epectedPersonresult = {"http://marklogicsparql.com/id#3333", "http://marklogicsparql.com/id#2222"}; String [] expectedLnameresult = {"Ling", "Dubinko"}; String [] expectedFnameresult = {"Fei", "Micah"}; int i = 0; try { assertThat(result, is(notNullValue())); Assert.assertTrue(result.hasNext()); while (result.hasNext()) { BindingSet solution = result.next(); assertThat(solution.hasBinding("person"), is(equalTo(true))); assertThat(solution.hasBinding("lastname"), is(equalTo(true))); Value personResult = solution.getValue("person"); Value lnameResult = solution.getValue("lastname"); Value fnameResult = solution.getValue("firstname"); Literal phoneResult = (Literal) solution.getValue("phonenumber"); Assert.assertEquals(epectedPersonresult[i], personResult.stringValue()); Assert.assertEquals(expectedLnameresult[i], lnameResult.stringValue()); Assert.assertEquals(expectedFnameresult[i], fnameResult.stringValue()); try{ assertThat(phoneResult.doubleValue(), is(equalTo(new Double(22222222D)))); } catch(NullPointerException e){ } i++; } } finally { result.close(); } } // ISSUE 197 @Test public void testPrepareTupleQuerywithBidings() throws Exception{ Statement st1 = vf.createStatement(john, fname, johnfname, dirgraph); Statement st2 = vf.createStatement(john, lname, johnlname, dirgraph); Statement st3 = vf.createStatement(john, homeTel, johnhomeTel, dirgraph); Statement st4 = vf.createStatement(john, email, johnemail, dirgraph); Statement st5 = vf.createStatement(micah, fname, micahfname, dirgraph); Statement st6 = vf.createStatement(micah, lname, micahlname, dirgraph); Statement st7 = vf.createStatement(micah, homeTel, micahhomeTel, dirgraph); Statement st8 = vf.createStatement(fei, fname, feifname, dirgraph); Statement st9 = vf.createStatement(fei, lname, feilname, dirgraph); Statement st10 = vf.createStatement(fei, email, feiemail, dirgraph); testAdminCon.add(st1); testAdminCon.add(st2); testAdminCon.add(st3); testAdminCon.add(st4); testAdminCon.add(st5); testAdminCon.add(st6); testAdminCon.add(st7); testAdminCon.add(st8); testAdminCon.add(st9); testAdminCon.add(st10); try{ Assert.assertEquals(10, testAdminCon.size(dirgraph)); } catch(Exception ex){ logger.error("Failed :", ex); } StringBuilder queryBuilder = new StringBuilder(64); queryBuilder.append(" SELECT ?person ?firstname ?lastname ?phonenumber"); queryBuilder.append(" FROM <").append(dirgraph.stringValue()).append(">"); queryBuilder.append(" WHERE"); queryBuilder.append(" { "); queryBuilder.append(" ?person <#firstName> ?firstname ;"); queryBuilder.append(" <#lastName> ?lastname ; "); queryBuilder.append(" <#homeTel> ?phonenumber .} "); queryBuilder.append(" ORDER BY ?lastname"); TupleQuery query = testAdminCon.prepareTupleQuery(queryBuilder.toString(),"http://marklogicsparql.com/addressbook"); query.setBinding("firstname", vf.createLiteral("Micah")); TupleQueryResult result = query.evaluate(); String [] epectedPersonresult = {"http://marklogicsparql.com/id#2222"}; String [] expectedLnameresult = {"Dubinko"}; String [] expectedFnameresult = {"Micah"}; int i = 0; try { assertThat(result, is(notNullValue())); Assert.assertTrue(result.hasNext()); while (result.hasNext()) { BindingSet solution = result.next(); assertThat(solution.hasBinding("person"), is(equalTo(true))); assertThat(solution.hasBinding("lastname"), is(equalTo(true))); Value personResult = solution.getValue("person"); Value lnameResult = solution.getValue("lastname"); Value fnameResult = solution.getValue("firstname"); Literal phoneResult = (Literal) solution.getValue("phonenumber"); Assert.assertEquals(epectedPersonresult[i], personResult.stringValue()); Assert.assertEquals(expectedLnameresult[i], lnameResult.stringValue()); Assert.assertEquals(expectedFnameresult[i], fnameResult.stringValue()); assertThat(phoneResult.doubleValue(), is(equalTo(new Double(22222222D)))); i++; } } finally { result.close(); } } @Test public void testPrepareTupleQueryEmptyResult() throws Exception{ Statement st1 = vf.createStatement(john, fname, johnfname, dirgraph); Statement st2 = vf.createStatement(john, homeTel, johnhomeTel, dirgraph); Statement st3 = vf.createStatement(micah, fname, micahfname, dirgraph); Statement st4 = vf.createStatement(micah, homeTel, micahhomeTel, dirgraph); testAdminCon.add(st1); testAdminCon.add(st2); testAdminCon.add(st3); testAdminCon.add(st4); try{ Assert.assertEquals(4, testAdminCon.size(dirgraph)); } catch(Exception ex){ logger.error("Failed :", ex); } StringBuilder queryBuilder = new StringBuilder(64); queryBuilder.append("PREFIX ad: <http://marklogicsparql.com/addressbook#> "); queryBuilder.append(" SELECT ?person ?p ?o"); queryBuilder.append(" FROM <").append(dirgraph.stringValue()).append(">"); queryBuilder.append(" WHERE"); queryBuilder.append(" { "); queryBuilder.append(" ?person <#firstName> ?firstname ;"); queryBuilder.append(" <#lastName> ?lastname. "); queryBuilder.append(" OPTIONAL {?person <#homeTel> ?phonenumber .} "); queryBuilder.append(" FILTER NOT EXISTS {?person ?p ?o .}"); queryBuilder.append(" } "); queryBuilder.append(" ORDER BY ?person"); TupleQuery query = testAdminCon.prepareTupleQuery(queryBuilder.toString(),"http://marklogicsparql.com/addressbook"); TupleQueryResult result = query.evaluate(); assertThat(result, is(notNullValue())); Assert.assertFalse(result.hasNext()); } // ISSUE 230 @Test public void testPrepareGraphQuery1() throws Exception { StringBuilder queryBuilder = new StringBuilder(128); queryBuilder.append(" PREFIX ad: <http://marklogicsparql.com/addressbook#>"); queryBuilder.append(" CONSTRUCT{ ?person ?p ?o .} "); queryBuilder.append(" FROM <http://marklogic.com/dirgraph>"); queryBuilder.append(" WHERE "); queryBuilder.append(" { "); queryBuilder.append(" ?person ad:firstName ?firstname ; "); queryBuilder.append(" ad:lastName ?lastname ; "); queryBuilder.append(" ?p ?o . "); queryBuilder.append(" } "); queryBuilder.append(" order by $person ?p ?o "); GraphQuery emptyQuery = testAdminCon.prepareGraphQuery(QueryLanguage.SPARQL, queryBuilder.toString()); emptyQuery.setBinding("firstname", vf.createLiteral("Micah")); GraphQueryResult emptyResult = emptyQuery.evaluate(); assertThat(emptyResult.hasNext(), is(equalTo(false))); Statement st1 = vf.createStatement(john, fname, johnfname, dirgraph); Statement st2 = vf.createStatement(john, lname, johnlname, dirgraph); Statement st3 = vf.createStatement(john, homeTel, johnhomeTel, dirgraph); Statement st4 = vf.createStatement(john, email, johnemail, dirgraph); Statement st5 = vf.createStatement(micah, fname, micahfname, dirgraph); Statement st6 = vf.createStatement(micah, lname, micahlname, dirgraph); Statement st7 = vf.createStatement(micah, homeTel, micahhomeTel, dirgraph); Statement st8 = vf.createStatement(fei, fname, feifname, dirgraph); Statement st9 = vf.createStatement(fei, lname, feilname, dirgraph); Statement st10 = vf.createStatement(fei, email, feiemail, dirgraph); StatementList<Statement> sL = new StatementList<Statement>(st1); sL.add(st2); sL.add(st3); sL.add(st4); sL.add(st5); sL.add(st6); sL.add(st7); sL.add(st8); sL.add(st9); sL.add(st10); StatementIterator iter = new StatementIterator(sL); testAdminCon.add(new StatementIterable(iter), dirgraph); Assert.assertEquals(10, testAdminCon.size(dirgraph)); GraphQuery query = testAdminCon.prepareGraphQuery(QueryLanguage.SPARQL, queryBuilder.toString()); query.setBinding("firstname", vf.createLiteral("Micah")); GraphQueryResult result = query.evaluate(); Literal [] expectedObjectresult = {micahfname, micahhomeTel, micahlname}; URI [] expectedPredicateresult = {fname, homeTel, lname}; int i = 0; try { assertThat(result, is(notNullValue())); assertThat(result.hasNext(), is(equalTo(true))); while (result.hasNext()) { Statement st = result.next(); URI subject = (URI) st.getSubject(); Assert.assertEquals(subject, micah); URI predicate = st.getPredicate(); Assert.assertEquals(predicate, expectedPredicateresult[i]); Value object = st.getObject(); Assert.assertEquals(object, expectedObjectresult[i]); i++; } } finally { result.close(); } StringBuilder qB = new StringBuilder(128); qB.append(" PREFIX ad: <http://marklogicsparql.com/addressbook#>"); qB.append(" CONSTRUCT{ ?person ?p ?o .} "); qB.append(" FROM <http://marklogic.com/dirgraph>"); qB.append(" WHERE "); qB.append(" { "); qB.append(" ?person ad:firstname ?firstname ; "); qB.append(" ?p ?o . "); qB.append(" VALUES ?firstname { \"Fei\" } "); qB.append(" } "); qB.append(" order by $person ?p ?o "); GraphQuery query1 = testAdminCon.prepareGraphQuery(QueryLanguage.SPARQL, qB.toString()); GraphQueryResult result1 = query1.evaluate(); assertThat(result1, is(notNullValue())); Assert.assertFalse(result1.hasNext()); } // ISSUE 45 @Test public void testPrepareGraphQuery2() throws Exception { Statement st1 = vf.createStatement(john, fname, johnfname, dirgraph); Statement st2 = vf.createStatement(john, lname, johnlname, dirgraph); Statement st3 = vf.createStatement(john, homeTel, johnhomeTel, dirgraph); Statement st4 = vf.createStatement(john, email, johnemail, dirgraph); Statement st5 = vf.createStatement(micah, fname, micahfname, dirgraph); Statement st6 = vf.createStatement(micah, lname, micahlname, dirgraph); Statement st7 = vf.createStatement(micah, homeTel, micahhomeTel, dirgraph); Statement st8 = vf.createStatement(fei, fname, feifname, dirgraph); Statement st9 = vf.createStatement(fei, lname, feilname, dirgraph); Statement st10 = vf.createStatement(fei, email, feiemail, dirgraph); StatementList<Statement> sL = new StatementList<Statement>(st1); sL.add(st2); sL.add(st3); sL.add(st4); sL.add(st5); sL.add(st6); sL.add(st7); sL.add(st8); sL.add(st9); sL.add(st10); StatementIterator iter = new StatementIterator(sL); Iteration<Statement, Exception> it = new IteratorIteration<Statement, Exception> (iter); testAdminCon.add(it, dirgraph); Assert.assertEquals(10, testAdminCon.size(dirgraph)); StringBuilder queryBuilder = new StringBuilder(128); queryBuilder.append(" PREFIX ad: <http://marklogicsparql.com/addressbook#>"); queryBuilder.append(" PREFIX id: <http://marklogicsparql.com/id#> "); queryBuilder.append(" CONSTRUCT{ <#1111> ad:email ?e .} "); queryBuilder.append(" FROM <http://marklogic.com/dirgraph> "); queryBuilder.append(" WHERE "); queryBuilder.append(" { "); queryBuilder.append(" <#1111> ad:lastName ?o; "); queryBuilder.append(" ad:email ?e. "); queryBuilder.append(" } "); GraphQuery query = testAdminCon.prepareGraphQuery(QueryLanguage.SPARQL, queryBuilder.toString(), "http://marklogicsparql.com/id"); GraphQueryResult result = query.evaluate(); Literal [] expectedObjectresult = {johnemail}; URI [] expectedPredicateresult = {email}; int i = 0; try { assertThat(result, is(notNullValue())); while (result.hasNext()) { Statement st = result.next(); URI subject = (URI) st.getSubject(); Assert.assertEquals(subject, john); URI predicate = st.getPredicate(); Assert.assertEquals(predicate, expectedPredicateresult[i]); Value object = st.getObject(); Assert.assertEquals(object, expectedObjectresult[i]); i++; } } finally { result.close(); } } // ISSUE 44, 53, 138, 153, 257 @Test public void testPrepareGraphQuery3() throws Exception { Statement st1 = vf.createStatement(john, fname, johnfname, dirgraph); Statement st2 = vf.createStatement(john, lname, johnlname, dirgraph); Statement st3 = vf.createStatement(john, homeTel, johnhomeTel, dirgraph); Statement st4 = vf.createStatement(john, email, johnemail, dirgraph); Statement st5 = vf.createStatement(micah, fname, micahfname, dirgraph); Statement st6 = vf.createStatement(micah, lname, micahlname, dirgraph); Statement st7 = vf.createStatement(micah, homeTel, micahhomeTel, dirgraph); Statement st8 = vf.createStatement(fei, fname, feifname, dirgraph); Statement st9 = vf.createStatement(fei, lname, feilname, dirgraph); Statement st10 = vf.createStatement(fei, email, feiemail, dirgraph); testWriterCon.add(st1); testWriterCon.add(st2); testWriterCon.add(st3); testWriterCon.add(st4); testWriterCon.add(st5); testWriterCon.add(st6); testWriterCon.add(st7); testWriterCon.add(st8); testWriterCon.add(st9); testWriterCon.add(st10); Assert.assertTrue(testWriterCon.hasStatement(st1, false)); Assert.assertFalse(testWriterCon.hasStatement(st1, false, (Resource)null)); Assert.assertFalse(testWriterCon.hasStatement(st1, false, null)); Assert.assertTrue(testWriterCon.hasStatement(st1, false, dirgraph)); Assert.assertEquals(10, testAdminCon.size(dirgraph)); String query = " DESCRIBE <http://marklogicsparql.com/addressbook#firstName> "; GraphQuery queryObj = testReaderCon.prepareGraphQuery(query); GraphQueryResult result = queryObj.evaluate(); result.hasNext(); try { assertThat(result, is(notNullValue())); assertThat(result.hasNext(), is(equalTo(false))); } finally { result.close(); } } // ISSUE 46 @Test public void testPrepareGraphQuery4() throws Exception{ Statement st1 = vf.createStatement(john, fname, johnfname); Statement st2 = vf.createStatement(john, lname, johnlname); Statement st3 = vf.createStatement(john, homeTel, johnhomeTel); Statement st4 = vf.createStatement(john, email, johnemail); Statement st5 = vf.createStatement(micah, fname, micahfname); Statement st6 = vf.createStatement(micah, lname, micahlname); Statement st7 = vf.createStatement(micah, homeTel, micahhomeTel); Statement st8 = vf.createStatement(fei, fname, feifname); Statement st9 = vf.createStatement(fei, lname, feilname); Statement st10 = vf.createStatement(fei, email, feiemail); testWriterCon.add(st1,dirgraph); testWriterCon.add(st2,dirgraph); testWriterCon.add(st3,dirgraph); testWriterCon.add(st4,dirgraph); testWriterCon.add(st5,dirgraph); testWriterCon.add(st6,dirgraph); testWriterCon.add(st7,dirgraph); testWriterCon.add(st8,dirgraph); testWriterCon.add(st9,dirgraph); testWriterCon.add(st10,dirgraph); Assert.assertEquals(10, testWriterCon.size(dirgraph)); String query = " DESCRIBE <#3333> "; GraphQuery queryObj = testReaderCon.prepareGraphQuery(query, "http://marklogicsparql.com/id"); GraphQueryResult result = queryObj.evaluate(); int i = 0; try { assertThat(result, is(notNullValue())); assertThat(result.hasNext(), is(equalTo(true))); while (result.hasNext()) { Statement st = result.next(); URI subject = (URI) st.getSubject(); Assert.assertNotNull(subject); URI predicate = st.getPredicate(); Assert.assertNotNull(predicate); Value object = st.getObject(); Assert.assertNotNull(object); i++; } } finally { result.close(); } Assert.assertEquals(3, i); } //ISSUE 70 @Test public void testPrepareQuery1() throws Exception { testAdminCon.add(MarkLogicRepositoryConnectionTest.class.getResourceAsStream(TEST_DIR_PREFIX + "companies_100.ttl"), "", RDFFormat.TURTLE, null); Assert.assertEquals(testAdminCon.size(), 1600L); StringBuilder queryBuilder = new StringBuilder(128); queryBuilder.append("PREFIX demor: <http://demo/resource#>"); queryBuilder.append(" PREFIX demov: <http://demo/verb#>"); queryBuilder.append(" PREFIX vcard: <http://www.w3.org/2006/vcard/ns#>"); queryBuilder.append(" SELECT (COUNT(?company) AS ?total)"); queryBuilder.append(" WHERE { "); queryBuilder.append(" ?company a vcard:Organization ."); queryBuilder.append(" ?company demov:industry ?industry ."); queryBuilder.append(" ?company vcard:hasAddress/vcard:postal-code ?zip ."); queryBuilder.append(" ?company vcard:hasAddress/vcard:postal-code ?whatcode "); queryBuilder.append(" } "); Query query = testAdminCon.prepareQuery(QueryLanguage.SPARQL, queryBuilder.toString()); query.setBinding("whatcode", vf.createLiteral("33333")); TupleQueryResult result = null; if (query instanceof TupleQuery) { result = ((TupleQuery) query).evaluate(); } try { assertThat(result, is(notNullValue())); while (result.hasNext()) { BindingSet solution = result.next(); assertThat(solution.hasBinding("total"), is(equalTo(true))); Value totalResult = solution.getValue("total"); Assert.assertEquals(vf.createLiteral("12",XMLSchema.UNSIGNED_LONG),totalResult); } } finally { result.close(); } } // ISSUE 70 @Test public void testPrepareQuery2() throws Exception{ Reader ir = new BufferedReader(new InputStreamReader(MarkLogicRepositoryConnectionTest.class.getResourceAsStream(TEST_DIR_PREFIX + "property-paths.ttl"))); testAdminCon.add(ir, "", RDFFormat.TURTLE, null); StringBuilder queryBuilder = new StringBuilder(128); queryBuilder.append(" prefix : <http://learningsparql.com/ns/papers#> "); queryBuilder.append(" prefix c: <http://learningsparql.com/ns/citations#>"); queryBuilder.append(" SELECT ?s"); queryBuilder.append(" WHERE { "); queryBuilder.append(" ?s ^c:cites :paperK2 . "); queryBuilder.append(" FILTER (?s != :paperK2)"); queryBuilder.append(" } "); queryBuilder.append(" ORDER BY ?s "); Query query = testAdminCon.prepareQuery(queryBuilder.toString()); query.setBinding("whatcode", vf.createLiteral("33333")); TupleQueryResult result = null; if (query instanceof TupleQuery) { result = ((TupleQuery) query).evaluate(); } try { assertThat(result, is(notNullValue())); while (result.hasNext()) { BindingSet solution = result.next(); assertThat(solution.hasBinding("s"), is(equalTo(true))); Value totalResult = solution.getValue("s"); Assert.assertEquals(vf.createURI("http://learningsparql.com/ns/papers#paperJ"),totalResult); } } finally { result.close(); } } @Test public void testPrepareQuery3() throws Exception{ Statement st1 = vf.createStatement(john, fname, johnfname); Statement st2 = vf.createStatement(john, lname, johnlname); Statement st3 = vf.createStatement(john, homeTel, johnhomeTel); testWriterCon.add(st1,dirgraph); testWriterCon.add(st2,dirgraph); testWriterCon.add(st3,dirgraph); Assert.assertEquals(3, testWriterCon.size(dirgraph)); String query = " DESCRIBE <http://marklogicsparql.com/id#1111> "; Query queryObj = testReaderCon.prepareQuery(query, "http://marklogicsparql.com/id"); GraphQueryResult result = null; if (queryObj instanceof GraphQuery) { result = ((GraphQuery) queryObj).evaluate(); } Literal [] expectedObjectresult = {johnfname, johnlname, johnhomeTel}; URI [] expectedPredicateresult = {fname, lname, homeTel}; int i = 0; try { assertThat(result, is(notNullValue())); assertThat(result.hasNext(), is(equalTo(true))); while (result.hasNext()) { Statement st = result.next(); URI subject = (URI) st.getSubject(); Assert.assertEquals(subject, john); URI predicate = st.getPredicate(); Assert.assertEquals(predicate, expectedPredicateresult[i]); Value object = st.getObject(); Assert.assertEquals(object, expectedObjectresult[i]); i++; } } finally { result.close(); } } //ISSUE 70 @Test public void testPrepareQuery4() throws Exception{ URL url = MarkLogicRepositoryConnectionTest.class.getResource(TEST_DIR_PREFIX+"tigers.ttl"); testAdminCon.add(url, "", RDFFormat.TURTLE); Assert.assertEquals(107L, testAdminCon.size()); String query1 = "ASK "+ "WHERE"+ "{"+ " ?s <#position> ?o."+ "}"; Query bq = testAdminCon.prepareQuery(query1, "http://marklogic.com/baseball/players"); bq.setBinding("o", vf.createLiteral("pitcher")); boolean result1 = ((BooleanQuery)bq).evaluate(); Assert.assertTrue(result1); } //Bug 35241 @Ignore public void testPrepareMultipleBaseURI1() throws Exception{ testAdminCon.add(john, fname, johnfname, dirgraph); testAdminCon.add(john, lname, johnlname, dirgraph); testAdminCon.add(john, homeTel, johnhomeTel, dirgraph); testAdminCon.add(john, email, johnemail, dirgraph); testAdminCon.add(micah, fname, micahfname, dirgraph); testAdminCon.add(micah, lname, micahlname, dirgraph); testAdminCon.add(micah, homeTel, micahhomeTel, dirgraph); testAdminCon.add(fei, fname, feifname, dirgraph); testAdminCon.add(fei, lname, feilname, dirgraph); testAdminCon.add(fei, email, feiemail, dirgraph); try{ Assert.assertEquals(10, testAdminCon.size(dirgraph)); } catch(Exception ex){ logger.error("Failed :", ex); } StringBuilder queryBuilder = new StringBuilder(); queryBuilder.append("PREFIX ad: <http://marklogicsparql.com/addressbook#>"); queryBuilder.append(" PREFIX d: <http://marklogicsparql.com/id#>"); queryBuilder.append(" BASE <http://marklogicsparql.com/addressbook>"); queryBuilder.append(" BASE <http://marklogicsparql.com/id>"); queryBuilder.append(" SELECT ?person ?lastname"); queryBuilder.append(" WHERE"); queryBuilder.append(" {?person <#firstName> ?firstname ;"); queryBuilder.append(" <#lastName> ?lastname."); queryBuilder.append(" OPTIONAL {<#1111> <#email> ?email.}"); queryBuilder.append(" FILTER EXISTS {?person <#homeTel> ?tel .}} ORDER BY ?lastname"); TupleQuery query = testAdminCon.prepareTupleQuery(QueryLanguage.SPARQL, queryBuilder.toString()); TupleQueryResult result = query.evaluate(); String [] expectedPersonresult = {micah.stringValue(), john.stringValue()}; String [] expectedLnameresult = {micahlname.stringValue(), johnlname.stringValue()}; int i = 0; try { assertThat(result, is(notNullValue())); Assert.assertTrue(result.hasNext()); while (result.hasNext()) { BindingSet solution = result.next(); assertThat(solution.hasBinding("person"), is(equalTo(true))); assertThat(solution.hasBinding("lastname"), is(equalTo(true))); Value personResult = solution.getValue("person"); Value nameResult = solution.getValue("lastname"); Assert.assertEquals(personResult.stringValue(),expectedPersonresult[i]); Assert.assertEquals(nameResult.stringValue(),expectedLnameresult[i]); i++; } } finally { result.close(); } } // ISSUE 106, 133, 183 @Test public void testCommit() throws Exception { try{ testAdminCon.begin(); testAdminCon.add(john, email, johnemail,dirgraph); assertTrue("Uncommitted update should be visible to own connection", testAdminCon.hasStatement(john, email, johnemail, false, dirgraph)); assertFalse("Uncommitted update should only be visible to own connection", testReaderCon.hasStatement(john, email, johnemail, false, dirgraph)); assertThat(testWriterCon.size(), is(equalTo(0L))); testAdminCon.commit(); } catch(Exception e){ logger.debug(e.getMessage()); } finally{ if(testAdminCon.isActive()) testAdminCon.rollback(); } assertThat(testWriterCon.size(), is(equalTo(1L))); assertTrue("Repository should contain statement after commit", testAdminCon.hasStatement(john, email, johnemail, false, dirgraph)); assertTrue("Committed update will be visible to all connection", testReaderCon.hasStatement(john, email, johnemail, false, dirgraph)); } // ISSUE 183 @Test public void testSizeRollback() throws Exception { testAdminCon.setIsolationLevel(IsolationLevels.SNAPSHOT); assertThat(testAdminCon.size(), is(equalTo(0L))); assertThat(testWriterCon.size(), is(equalTo(0L))); try{ testAdminCon.begin(); testAdminCon.add(john, fname, johnfname,dirgraph); assertThat(testAdminCon.size(), is(equalTo(1L))); assertThat(testWriterCon.size(), is(equalTo(0L))); testAdminCon.add(john, fname, feifname); assertThat(testAdminCon.size(), is(equalTo(2L))); assertThat(testWriterCon.size(), is(equalTo(0L))); testAdminCon.rollback(); } catch (Exception e){ } finally{ if (testAdminCon.isActive()) testAdminCon.rollback(); } assertThat(testAdminCon.size(), is(equalTo(0L))); assertThat(testWriterCon.size(), is(equalTo(0L))); } // ISSUE 133, 183 @Test public void testSizeCommit() throws Exception { testAdminCon.setIsolationLevel(IsolationLevels.SNAPSHOT); assertThat(testAdminCon.size(), is(equalTo(0L))); assertThat(testWriterCon.size(), is(equalTo(0L))); try{ testAdminCon.begin(); testAdminCon.add(john, fname, johnfname,dirgraph); assertThat(testAdminCon.size(), is(equalTo(1L))); assertThat(testWriterCon.size(), is(equalTo(0L))); testAdminCon.add(john, fname, feifname); assertThat(testAdminCon.size(), is(equalTo(2L))); assertThat(testWriterCon.size(), is(equalTo(0L))); testAdminCon.commit(); } catch (Exception e){ } finally{ if (testAdminCon.isActive()) testAdminCon.rollback(); } assertThat(testAdminCon.size(), is(equalTo(2L))); assertThat(testWriterCon.size(), is(equalTo(2L))); } //ISSUE 121, 174 @Test public void testTransaction() throws Exception{ testAdminCon.begin(); testAdminCon.commit(); try{ testAdminCon.commit(); Assert.assertFalse("Exception was not thrown, when it should have been", 1<2); } catch (Exception e){ Assert.assertTrue(e instanceof MarkLogicTransactionException); } finally{ if (testAdminCon.isActive()) testAdminCon.rollback(); } try{ testAdminCon.rollback(); Assert.assertFalse("Exception was not thrown, when it should have been", 1<2); } catch (Exception e2){ Assert.assertTrue(e2 instanceof MarkLogicTransactionException); } finally{ if (testAdminCon.isActive()) testAdminCon.rollback(); } testAdminCon.begin(); testAdminCon.prepareUpdate(QueryLanguage.SPARQL, "DELETE DATA {GRAPH <" + dirgraph.stringValue()+ "> { <" + micah.stringValue() + "> <" + homeTel.stringValue() + "> \"" + micahhomeTel.doubleValue() + "\"^^<http://www.w3.org/2001/XMLSchema#double>} }").execute(); testAdminCon.commit(); Assert.assertTrue(testAdminCon.size()==0); try{ testAdminCon.begin(); testAdminCon.begin(); Assert.assertFalse("Exception was not thrown, when it should have been", 1<2); } catch (Exception e){ Assert.assertTrue(e instanceof MarkLogicTransactionException); } finally{ if (testAdminCon.isActive()) testAdminCon.rollback(); } } // ISSUE 123, 122, 175, 185 @Test public void testGraphPerms1() throws Exception { GraphManager gmgr = databaseClient.newGraphManager(); createUserRolesWithPrevilages("test-role"); GraphPermissions gr = testAdminCon.getDefaultGraphPerms(); // ISSUE # 175 uncomment after issue is fixed Assert.assertEquals(0L, gr.size()); testAdminCon.setDefaultGraphPerms(gmgr.permission("test-role", Capability.READ, Capability.UPDATE)); String defGraphQuery = "CREATE GRAPH <http://marklogic.com/test/graph/permstest> "; MarkLogicUpdateQuery updateQuery = testAdminCon.prepareUpdate(QueryLanguage.SPARQL, defGraphQuery); updateQuery.execute(); String defGraphQuery1 = "INSERT DATA { GRAPH <http://marklogic.com/test/graph/permstest> { <http://marklogic.com/test1> <pp2> \"test\" } }"; String checkQuery = "ASK WHERE { GRAPH <http://marklogic.com/test/graph/permstest> {<http://marklogic.com/test> <pp2> \"test\" }}"; MarkLogicUpdateQuery updateQuery1 = testAdminCon.prepareUpdate(QueryLanguage.SPARQL, defGraphQuery1); updateQuery1.execute(); BooleanQuery booleanQuery = testAdminCon.prepareBooleanQuery(QueryLanguage.SPARQL, checkQuery); boolean results = booleanQuery.evaluate(); Assert.assertEquals(false, results); gr = testAdminCon.getDefaultGraphPerms(); Assert.assertEquals(1L, gr.size()); Iterator<Entry<String, Set<Capability>>> resultPerm = gr.entrySet().iterator(); while(resultPerm.hasNext()){ Entry<String, Set<Capability>> perms = resultPerm.next(); Assert.assertTrue("test-role" == perms.getKey()); Iterator<Capability> capability = perms.getValue().iterator(); while (capability.hasNext()) assertThat(capability.next().toString(), anyOf(equalTo("UPDATE"), is(equalTo("READ")))); } String defGraphQuery2 = "CREATE GRAPH <http://marklogic.com/test/graph/permstest1> "; testAdminCon.setDefaultGraphPerms(null); updateQuery = testAdminCon.prepareUpdate(QueryLanguage.SPARQL, defGraphQuery2); updateQuery.execute(); gr = testAdminCon.getDefaultGraphPerms(); Assert.assertEquals(0L, gr.size()); createUserRolesWithPrevilages("multitest-role"); testAdminCon.setDefaultGraphPerms(gmgr.permission("multitest-role", Capability.READ).permission("test-role", Capability.UPDATE)); defGraphQuery = "CREATE GRAPH <http://marklogic.com/test/graph/permstest2> "; updateQuery = testAdminCon.prepareUpdate(QueryLanguage.SPARQL, defGraphQuery); updateQuery.execute(); gr = testAdminCon.getDefaultGraphPerms(); Assert.assertEquals(2L, gr.size()); testAdminCon.setDefaultGraphPerms(null); testAdminCon.setDefaultGraphPerms(null); // ISSUE 180 //testAdminCon.setDefaultGraphPerms((GraphPermissions)null); gr = testAdminCon.getDefaultGraphPerms(); Assert.assertEquals(0L, gr.size()); } //ISSUE 108 @Test public void testAddDelete() throws OpenRDFException { final Statement st1 = vf.createStatement(john, fname, johnfname); testWriterCon.begin(); testWriterCon.add(st1); testWriterCon.prepareUpdate(QueryLanguage.SPARQL, "DELETE DATA {<" + john.stringValue() + "> <" + fname.stringValue() + "> \"" + johnfname.stringValue() + "\"}").execute(); testWriterCon.commit(); testWriterCon.exportStatements(null, null, null, false, new RDFHandlerBase() { @Override public void handleStatement(Statement st) throws RDFHandlerException { assertThat(st, is(not(equalTo(st1)))); } }); } //ISSUE 108, 250 @Test public final void testInsertRemove() throws OpenRDFException { Statement st = null; try{ testAdminCon.begin(); testAdminCon.prepareUpdate( "INSERT DATA {GRAPH <" + dirgraph.stringValue()+"> { <" + john.stringValue() + "> <" + homeTel.stringValue() + "> \"" + johnhomeTel.doubleValue() + "\"^^<http://www.w3.org/2001/XMLSchema#double>}}").execute(); RepositoryResult<Statement> result = testAdminCon.getStatements(null, null, null, false); try { assertNotNull("Iterator should not be null", result); assertTrue("Iterator should not be empty", result.hasNext()); Assert.assertEquals("There should be only one statement in repository",1L, testAdminCon.size()); while (result.hasNext()) { st = result.next(); assertNotNull("Statement should not be in a context ", st.getContext()); assertTrue("Statement predicate should be equal to homeTel ", st.getPredicate().equals(homeTel)); } } finally { result.close(); } testAdminCon.remove(st,dirgraph); testAdminCon.commit(); } catch(Exception e){ } finally{ if (testAdminCon.isActive()) testAdminCon.rollback(); } Assert.assertEquals(0L, testAdminCon.size()); testAdminCon.exportStatements(null, null, null, false, new RDFHandlerBase() { @Override public void handleStatement(Statement st1) throws RDFHandlerException { assertThat(st1, is((equalTo(null)))); } },dirgraph); } //ISSUE 108, 45 @Test public void testInsertDeleteInsertWhere() throws Exception { Assert.assertEquals(0L, testAdminCon.size()); final Statement st1 = vf.createStatement(john, email, johnemail, dirgraph); final Statement st2 = vf.createStatement(john, lname, johnlname); testAdminCon.add(st1); testAdminCon.add(st2,dirgraph); try{ testAdminCon.begin(); testAdminCon.prepareUpdate(QueryLanguage.SPARQL, "INSERT DATA {GRAPH <" + dirgraph.stringValue()+ "> { <" + john.stringValue() + "> <" + fname.stringValue() + "> \"" + johnfname.stringValue() + "\"} }").execute(); testAdminCon.prepareUpdate( "DELETE DATA {GRAPH <" + dirgraph.stringValue()+ "> { <" + john.stringValue() + "> <" + email.stringValue() + "> \"" + johnemail.stringValue() + "\"} }").execute(); String query1 ="PREFIX ad: <http://marklogicsparql.com/addressbook#>" +" INSERT {GRAPH <" + dirgraph.stringValue() + "> { <#1111> ad:email \"[email protected]\"}}" + " where { GRAPH <"+ dirgraph.stringValue()+">{<#1111> ad:lastName ?name .} } " ; testAdminCon.prepareUpdate(QueryLanguage.SPARQL,query1, "http://marklogicsparql.com/id").execute(); testAdminCon.commit(); } catch(Exception e){ logger.debug(e.getMessage()); } finally{ if(testAdminCon.isActive()) testAdminCon.rollback(); } final Statement expSt = vf.createStatement(john, email, vf.createLiteral("[email protected]")); Assert.assertEquals("Dirgraph's size must be 3",3L, testAdminCon.size(dirgraph)); testAdminCon.exportStatements(null, email, null, false, new RDFHandlerBase() { @Override public void handleStatement(Statement st) throws RDFHandlerException { assertThat(st, equalTo(expSt)); } }, dirgraph); } @Test public void testAddRemoveAdd() throws OpenRDFException { Statement st = vf.createStatement(john, lname, johnlname, dirgraph); testAdminCon.add(st); Assert.assertEquals(1L, testAdminCon.size()); testAdminCon.begin(); testAdminCon.remove(st, dirgraph); testAdminCon.add(st); testAdminCon.commit(); Assert.assertFalse(testAdminCon.isEmpty()); } @Test public void testAddDeleteAdd() throws OpenRDFException { Statement stmt = vf.createStatement(micah, homeTel, micahhomeTel, dirgraph); testAdminCon.add(stmt); testAdminCon.begin(); testAdminCon.prepareUpdate(QueryLanguage.SPARQL, "DELETE DATA {GRAPH <" + dirgraph.stringValue()+ "> { <" + micah.stringValue() + "> <" + homeTel.stringValue() + "> \"" + micahhomeTel.doubleValue() + "\"^^<http://www.w3.org/2001/XMLSchema#double>} }").execute(); Assert.assertTrue(testAdminCon.isEmpty()); testAdminCon.add(stmt); testAdminCon.commit(); Assert.assertFalse(testAdminCon.isEmpty()); } // ISSUE 133 @Test public void testAddRemoveInsert() throws OpenRDFException { Statement stmt = vf.createStatement(micah, homeTel, micahhomeTel); testAdminCon.add(stmt); try{ testAdminCon.begin(); testAdminCon.remove(stmt); Assert.assertEquals("The size of repository must be zero",0, testAdminCon.size()); testAdminCon.prepareUpdate( "INSERT DATA "+" { <" + micah.stringValue() + "> <#homeTel> \"" + micahhomeTel.doubleValue() + "\"^^<http://www.w3.org/2001/XMLSchema#double>} ","http://marklogicsparql.com/addressbook").execute(); testAdminCon.commit(); } catch (Exception e){ if (testAdminCon.isActive()) testAdminCon.rollback(); Assert.assertTrue("Failed within transaction", 1>2); } finally{ if (testAdminCon.isActive()) testAdminCon.rollback(); } Assert.assertFalse(testAdminCon.isEmpty()); Assert.assertEquals(1L, testAdminCon.size()); } // ISSSUE 106, 133 @Test public void testAddDeleteInsertWhere() throws OpenRDFException { testAdminCon.add(fei,lname,feilname); testAdminCon.add(fei, email, feiemail); try{ testAdminCon.begin(); testAdminCon.prepareUpdate( " DELETE { <" + fei.stringValue() + "> <#email> \"" + feiemail.stringValue() + "\"} "+ " INSERT { <" + fei.stringValue() + "> <#email> \"[email protected]\"} where{ ?s <#email> ?o}" ,"http://marklogicsparql.com/addressbook").execute(); Assert.assertTrue("The value of email should be updated", testAdminCon.hasStatement(vf.createStatement(fei, email, vf.createLiteral("[email protected]")), false)); testAdminCon.commit(); } catch(Exception e){ } finally{ if(testAdminCon.isActive()) testAdminCon.rollback(); } Assert.assertTrue(testAdminCon.hasStatement(vf.createStatement(fei, email, vf.createLiteral("[email protected]")), false)); Assert.assertFalse(testAdminCon.isEmpty()); } @Test public void testGraphOps() throws Exception { URI gr1 = vf.createURI("http://marklogic.com"); URI gr2 = vf.createURI("http://ml.com"); testAdminCon.add(fei,lname,feilname); testAdminCon.add(fei, email, feiemail); try{ testAdminCon.begin(); testAdminCon.prepareUpdate( " CREATE GRAPH <http://marklogic.com> ").execute(); testAdminCon.prepareUpdate( " CREATE GRAPH <http://ml.com> ").execute(); Assert.assertTrue("The graph should be empty", (testAdminCon.size(gr1) == 0)); Assert.assertTrue("The graph should be empty", (testAdminCon.size(gr2) == 0)); testAdminCon.commit(); } catch(Exception e){ } finally{ if(testAdminCon.isActive()) testAdminCon.rollback(); } testAdminCon.prepareUpdate( " COPY DEFAULT TO <http://marklogic.com> ").execute(); Assert.assertFalse(testAdminCon.isEmpty()); Assert.assertTrue("The graph gr1 should not be empty", (testAdminCon.size(gr1) == 2)); testWriterCon.prepareUpdate( " MOVE DEFAULT TO <http://ml.com> ").execute(); Assert.assertFalse(testWriterCon.isEmpty()); Assert.assertTrue("The graph gr2 should not be empty", (testWriterCon.size(gr2) == 2)); Assert.assertTrue("The graph gr2 should not be empty", (testAdminCon.size(gr2) == 2)); Assert.assertTrue("The default graph should be empty", (testAdminCon.size(null) == 0)); testWriterCon.prepareUpdate( " DROP GRAPH <http://ml.com> ").execute(); testWriterCon.prepareUpdate( " DROP GRAPH <http://marklogic.com> ").execute(); Assert.assertTrue("The default graph should be empty", (testAdminCon.size() == 0)); } @Test public void testAddDifferentFormats() throws Exception { testAdminCon.add(MarkLogicRepositoryConnectionTest.class.getResourceAsStream(TEST_DIR_PREFIX + "journal.nt"), "", RDFFormat.NTRIPLES, dirgraph); Assert.assertEquals(36L,testAdminCon.size()); testAdminCon.clear(); testAdminCon.add(new InputStreamReader(MarkLogicRepositoryConnectionTest.class.getResourceAsStream(TEST_DIR_PREFIX + "little.nq")), "", RDFFormat.NQUADS); Assert.assertEquals( 9L,testAdminCon.size()); testAdminCon.clear(); URL url = MarkLogicRepositoryConnectionTest.class.getResource(TEST_DIR_PREFIX+"semantics.trig"); testAdminCon.add(url, "",RDFFormat.TRIG); Assert.assertEquals(15L,testAdminCon.size()); testAdminCon.clear(); File file = new File(MarkLogicRepositoryConnectionTest.class.getResource(TEST_DIR_PREFIX+ "dir.json").getFile()); testAdminCon.add(file, "", RDFFormat.RDFJSON); Assert.assertEquals(12L, testAdminCon.size()); testAdminCon.clear(); Reader fr = new FileReader(new File(MarkLogicRepositoryConnectionTest.class.getResource(TEST_DIR_PREFIX+ "dir.xml").getFile())); testAdminCon.add(fr, "", RDFFormat.RDFXML); Assert.assertEquals(12L, testAdminCon.size()); testAdminCon.clear(); } //ISSUE 110 @Test public void testOpen() throws Exception { Statement stmt = vf.createStatement(micah, homeTel, micahhomeTel, dirgraph); try{ testAdminCon.begin(); assertThat("testAdminCon should be open",testAdminCon.isOpen(), is(equalTo(true))); assertThat("testWriterCon should be open",testWriterCon.isOpen(), is(equalTo(true))); testAdminCon.add(stmt); testAdminCon.commit(); } catch(Exception e){ } finally{ if(testAdminCon.isActive()) testAdminCon.rollback(); } testAdminCon.remove(stmt, dirgraph); testAdminCon.close(); Assert.assertFalse(testAdminCon.hasStatement(stmt, false, dirgraph)); try{ testAdminCon.add(stmt); fail("Adding triples after close should not be allowed"); } catch(Exception e){ Assert.assertTrue(e instanceof RepositoryException); } Assert.assertEquals("testAdminCon size should be zero",testAdminCon.size(),0); assertThat("testAdminCon should not be open",testAdminCon.isOpen(), is(equalTo(false))); assertThat("testWriterCon should be open",testWriterCon.isOpen(), is(equalTo(true))); testAdminRepository.shutDown(); testAdminRepository = null; testAdminCon = null; setUp(); assertThat(testAdminCon.isOpen(), is(equalTo(true))); } // ISSUE 126, 33 @Test public void testClear() throws Exception { testAdminCon.add(john, fname, johnfname,dirgraph); testAdminCon.add(john, fname, feifname); assertThat(testAdminCon.hasStatement(null, null, null, false), is(equalTo(true))); testAdminCon.clear(dirgraph); Assert.assertFalse(testAdminCon.isEmpty()); assertThat(testAdminCon.hasStatement(john, fname, johnfname, false), is(equalTo(false))); testAdminCon.clear(); Assert.assertTrue(testAdminCon.isEmpty()); assertThat(testAdminCon.hasStatement(null, null, null, false), is(equalTo(false))); } @Ignore public void testAddNullStatements() throws Exception{ Statement st1 = vf.createStatement(john, fname, null, dirgraph); Statement st2 = vf.createStatement(null, lname, johnlname, dirgraph); Statement st3 = vf.createStatement(john, homeTel, null ); Statement st4 = vf.createStatement(john, email, johnemail, null); Statement st5 = vf.createStatement(null, null , null, null); try{ testAdminCon.add(st1); Assert.assertFalse("Exception was not thrown, when it should have been", 1<2); } catch(Exception e){ e.printStackTrace(); Assert.assertTrue(e instanceof UnsupportedOperationException); } try{ testAdminCon.add(st2); Assert.assertFalse("Exception was not thrown, when it should have been", 1<2); } catch(Exception e){ Assert.assertTrue(e instanceof UnsupportedOperationException); } try{ testAdminCon.add(st3); Assert.assertFalse("Exception was not thrown, when it should have been", 1<2); } catch(Exception e){ Assert.assertTrue(e instanceof UnsupportedOperationException); } try{ testAdminCon.add(st5); Assert.assertFalse("Exception was not thrown, when it should have been", 1<2); } catch(Exception e){ Assert.assertTrue(e instanceof UnsupportedOperationException); } testAdminCon.add(st4); Assert.assertEquals(1L,testAdminCon.size()); } //ISSUE 65 @Test public void testAddMalformedLiteralsDefaultConfig() throws Exception { try { testAdminCon.add( MarkLogicRepositoryConnectionTest.class.getResourceAsStream(TEST_DIR_PREFIX + "malformed-literals.ttl"), "", RDFFormat.TURTLE); fail("upload of malformed literals should fail with error in default configuration"); } catch (Exception e) { Assert.assertTrue(e instanceof RDFParseException); } } @Test public void testAddMalformedLiteralsStrictConfig() throws Exception { Assert.assertEquals(0L, testAdminCon.size()); Set<RioSetting<?>> empty = Collections.emptySet(); testAdminCon.getParserConfig().setNonFatalErrors(empty); try { testAdminCon.add( MarkLogicRepositoryConnectionTest.class.getResourceAsStream(TEST_DIR_PREFIX + "malformed-literals.ttl"), "", RDFFormat.TURTLE); fail("upload of malformed literals should fail with error in strict configuration"); } catch (Exception e) { Assert.assertTrue(e instanceof RDFParseException); } } //ISSUE 106, 132, 61, 126 @Test public void testRemoveStatements() throws Exception { testAdminCon.begin(); testAdminCon.add(john, lname, johnlname, dirgraph); testAdminCon.add(john, fname, johnfname, dirgraph); testAdminCon.add(john, email, johnemail, dirgraph); testAdminCon.add(john, homeTel, johnhomeTel, dirgraph); testAdminCon.add(micah, lname, micahlname); testAdminCon.add(micah, fname, micahfname); testAdminCon.add(micah, homeTel, micahhomeTel); testAdminCon.commit(); testAdminCon.setDefaultRulesets(null); Statement st1 = vf.createStatement(john, fname, johnlname); testAdminCon.remove(st1); Assert.assertEquals("There is no triple st1 in the repository, so it shouldn't be deleted",7L, testAdminCon.size()); Statement st2 = vf.createStatement(john, lname, johnlname); assertThat(testAdminCon.hasStatement(st2, false, dirgraph), is(equalTo(true))); assertThat(testAdminCon.hasStatement(st2, true, null, dirgraph), is(equalTo(true))); assertThat(testAdminCon.hasStatement(st2, true, null), is(equalTo(false))); assertThat(testAdminCon.hasStatement(john, lname, johnlname, true, null), is(equalTo(false))); assertThat(testAdminCon.hasStatement(john, lname, johnlname, true, (Resource)null, dirgraph, dirgraph1), is(equalTo(true))); assertThat(testAdminCon.hasStatement(st2, true), is(equalTo(true))); testAdminCon.remove(st2, dirgraph); assertThat(testAdminCon.hasStatement(st2, true, null, dirgraph), is(equalTo(false))); Assert.assertEquals(6L, testAdminCon.size()); testAdminCon.remove(john,email, null); assertThat(testAdminCon.hasStatement(john, fname, johnfname, false, dirgraph), is(equalTo(true))); assertThat(testAdminCon.hasStatement(john, fname, johnfname, false), is(equalTo(true))); assertThat(testAdminCon.hasStatement(john, fname, johnfname, false, null), is(equalTo(false))); assertThat(testAdminCon.hasStatement(john, fname, johnfname, false, null, dirgraph), is(equalTo(true))); assertThat(testAdminCon.hasStatement(john, lname, johnlname, false, dirgraph), is(equalTo(false))); testAdminCon.remove(john,null,null); assertThat(testAdminCon.hasStatement(john, lname, johnlname, false, dirgraph), is(equalTo(false))); assertThat(testAdminCon.hasStatement(john, fname, johnfname, false, dirgraph), is(equalTo(false))); assertThat(testAdminCon.hasStatement(john, fname, johnfname, false, null, dirgraph), is(equalTo(false))); assertThat(testAdminCon.hasStatement(john, lname, johnlname, false, (Resource)null, dirgraph), is(equalTo(false))); assertThat(testAdminCon.hasStatement(micah, homeTel, johnhomeTel, false, null), is(equalTo(false))); assertThat(testAdminCon.hasStatement(micah, homeTel, micahhomeTel, false, (Resource)null), is(equalTo(true))); assertThat(testAdminCon.hasStatement(micah, homeTel, micahhomeTel, false, null), is(equalTo(true))); testAdminCon.remove((Resource)null, homeTel,(Value) null); testAdminCon.remove((Resource)null, homeTel, (Value)null); testAdminCon.remove(vf.createStatement(john, lname, johnlname), dirgraph); assertThat(testAdminCon.hasStatement(john, lname, johnlname, false), is(equalTo(false))); assertThat(testAdminCon.hasStatement(john, lname, johnlname, false, dirgraph), is(equalTo(false))); testAdminCon.add(john, fname, johnfname, dirgraph); assertThat(testAdminCon.hasStatement(john, homeTel, johnhomeTel, false, dirgraph), is(equalTo(false))); assertThat(testAdminCon.hasStatement(micah, homeTel, micahhomeTel, false), is(equalTo(false))); assertThat(testAdminCon.hasStatement(john, fname, johnfname, false, dirgraph), is(equalTo(true))); testAdminCon.remove(john, (URI)null, (Value)null); assertThat(testAdminCon.hasStatement(john, fname, johnfname, false, dirgraph), is(equalTo(false))); assertThat(testAdminCon.isEmpty(), is(equalTo(false))); testAdminCon.remove(null, null, micahlname); assertThat(testAdminCon.hasStatement(micah, fname, micahfname, false), is(equalTo(true))); assertThat(testAdminCon.hasStatement(micah, fname, micahfname, false, null, dirgraph), is(equalTo(true))); assertThat(testAdminCon.hasStatement(null, null, null, false, null), is(equalTo(true))); assertThat(testAdminCon.hasStatement(null, null, null, false), is(equalTo(true))); assertThat(testAdminCon.hasStatement(null, null, null, false, dirgraph), is(equalTo(false))); assertThat(testAdminCon.hasStatement(micah, fname, micahfname, false, dirgraph1, dirgraph), is(equalTo(false))); testAdminCon.remove((URI)null, null, null); assertThat(testAdminCon.isEmpty(), is(equalTo(true))); assertThat(testAdminCon.hasStatement((URI)null, (URI)null, (Literal)null, false,(Resource) null), is(equalTo(false))); } //ISSUE 130 @Test public void testRemoveStatementCollection() throws Exception { testAdminCon.begin(); testAdminCon.add(john, lname, johnlname); testAdminCon.add(john, fname, johnfname); testAdminCon.add(john, email, johnemail); testAdminCon.add(john, homeTel, johnhomeTel); testAdminCon.add(micah, lname, micahlname, dirgraph); testAdminCon.add(micah, fname, micahfname, dirgraph); testAdminCon.add(micah, homeTel, micahhomeTel, dirgraph); testAdminCon.commit(); assertThat(testAdminCon.hasStatement(john, lname, johnlname, false, dirgraph), is(equalTo(false))); assertThat(testAdminCon.hasStatement(john, lname, johnlname, false, null, dirgraph), is(equalTo(true))); assertThat(testAdminCon.hasStatement(micah, homeTel, micahhomeTel, false, dirgraph), is(equalTo(true))); Collection<Statement> c = Iterations.addAll(testAdminCon.getStatements(null, null, null, false), new ArrayList<Statement>()); testAdminCon.remove(c); assertThat(testAdminCon.hasStatement(john, lname, johnlname, false), is(equalTo(false))); assertThat(testAdminCon.hasStatement(micah, homeTel, micahhomeTel, false, dirgraph), is(equalTo(false))); assertThat(testAdminCon.isEmpty(), is(equalTo(true))); } // ISSUE 130 @Test public void testRemoveStatementIterable() throws Exception { testAdminCon.add(john,fname, johnfname); Statement st1 = vf.createStatement(fei, fname, feifname,dirgraph); Statement st2 = vf.createStatement(fei, lname, feilname, dirgraph); Statement st3 = vf.createStatement(fei, email, feiemail, dirgraph); StatementList<Statement> sL = new StatementList<Statement>(st1); sL.add(st2); sL.add(st3); StatementIterator iter = new StatementIterator(sL); Iterable<? extends Statement> iterable = new StatementIterable(iter); testAdminCon.add(iterable); Assert.assertEquals(4L,testAdminCon.size()); StatementList<Statement> sL1 = new StatementList<Statement>(st1); sL1.add(st2); sL1.add(st3); StatementIterator iter1 = new StatementIterator(sL1); Iterable<? extends Statement> iterable1 = new StatementIterable(iter1); Assert.assertTrue(iterable1.iterator().hasNext()); testAdminCon.remove(iterable1, dirgraph); Assert.assertEquals(1L,testAdminCon.size()); } // ISSUE 66 @Test public void testRemoveStatementIteration() throws Exception { testAdminCon.begin(); testAdminCon.add(john,fname, johnfname); testAdminCon.add(fei, fname, feifname, dirgraph); testAdminCon.add(fei, lname, feilname, dirgraph); testAdminCon.add(fei, email, feiemail, dirgraph); testAdminCon.commit(); Assert.assertEquals(4L,testAdminCon.size()); Statement st1 = vf.createStatement(fei, fname, feifname,dirgraph); Statement st2 = vf.createStatement(fei, lname, feilname, dirgraph); Statement st3 = vf.createStatement(fei, email, feiemail, dirgraph); StatementList<Statement> sL = new StatementList<Statement>(st1); sL.add(st2); sL.add(st3); StatementIterator iter = new StatementIterator(sL); Iteration<Statement, Exception> it = new IteratorIteration<Statement, Exception> (iter); Assert.assertTrue(it.hasNext()); testAdminCon.remove(it); Assert.assertEquals(1L,testAdminCon.size()); } // ISSUE 118, 129 @Test public void testGetStatements() throws Exception { testAdminCon.add(john, fname, johnfname); testAdminCon.add(john, lname, johnlname); testAdminCon.add(john, homeTel, johnhomeTel); testAdminCon.add(john, email, johnemail); try{ assertTrue("Repository should contain statement", testAdminCon.hasStatement(john, homeTel, johnhomeTel, false)); } catch (Exception e){ logger.debug(e.getMessage()); } RepositoryResult<Statement> result = testAdminCon.getStatements(null, homeTel, null, false); try { assertNotNull("Iterator should not be null", result); assertTrue("Iterator should not be empty", result.hasNext()); while (result.hasNext()) { Statement st = result.next(); // clarify with Charles if context is null or http://... Assert.assertNull("Statement should not be in a context ", st.getContext()); assertTrue("Statement predicate should be equal to name ", st.getPredicate().equals(homeTel)); } } finally { result.close(); } List<Statement> list = Iterations.addAll(testAdminCon.getStatements(null, john, null,false,dirgraph), new ArrayList<Statement>()); assertTrue("List should be empty", list.isEmpty()); } // ISSUE 131 @Test public void testGetStatementsMalformedTypedLiteral() throws Exception { testAdminCon.getParserConfig().addNonFatalError(BasicParserSettings.VERIFY_DATATYPE_VALUES); Literal invalidIntegerLiteral = vf.createLiteral("four", XMLSchema.INTEGER); try { testAdminCon.add(micah, homeTel, invalidIntegerLiteral, dirgraph); RepositoryResult<Statement> statements = testAdminCon.getStatements(micah, homeTel, null, true); assertNotNull(statements); assertTrue(statements.hasNext()); Statement st = statements.next(); assertTrue(st.getObject() instanceof Literal); assertTrue(st.getObject().equals(invalidIntegerLiteral)); } catch (RepositoryException e) { // shouldn't happen fail(e.getMessage()); } } // ISSUE 131, 178 @Test public void testGetStatementsLanguageLiteral() throws Exception { Literal validLanguageLiteral = vf.createLiteral("the number four", "en"); try { testAdminCon.add(micah, homeTel, validLanguageLiteral,dirgraph); RepositoryResult<Statement> statements = testAdminCon.getStatements(null, null, null, true,dirgraph); assertNotNull(statements); assertTrue(statements.hasNext()); Statement st = statements.next(); assertTrue(st.getObject() instanceof Literal); assertTrue(st.getObject().equals(validLanguageLiteral)); } catch (RepositoryException e) { // shouldn't happen fail(e.getMessage()); } // Uncomment after 178 is fixed. /* testAdminCon.clear(); Literal invalidLanguageLiteral = vf.createLiteral("the number four", "en_us"); try { testAdminCon.add(micah, homeTel, invalidLanguageLiteral,dirgraph); RepositoryResult<Statement> statements = testAdminCon.getStatements(null, null, null, true,dirgraph); assertNotNull(statements); assertTrue(statements.hasNext()); Statement st = statements.next(); assertTrue(st.getObject() instanceof Literal); assertTrue(st.getObject().equals(invalidLanguageLiteral)); } catch (RepositoryException e) { // shouldn't happen fail(e.getMessage()); }*/ } //ISSUE 26 , 83, 90, 106, 107, 120, 81 @Test public void testGetStatementsInSingleContext() throws Exception { try{ testAdminCon.begin(); testAdminCon.add(micah, lname, micahlname, dirgraph1); testAdminCon.add(micah, fname, micahfname, dirgraph1); testAdminCon.add(micah, homeTel, micahhomeTel, dirgraph1); testAdminCon.add(john, fname, johnfname,dirgraph); testAdminCon.add(john, lname, johnlname,dirgraph); testAdminCon.add(john, homeTel, johnhomeTel,dirgraph); Assert.assertEquals("Size of dirgraph1 must be 3",3, testAdminCon.size(dirgraph1)); Assert.assertEquals("Size of unknown context must be 0",0L, testAdminCon.size(vf.createURI(":asd"))); Assert.assertEquals("Size of dirgraph must be 3",3, testAdminCon.size(dirgraph)); Assert.assertEquals("Size of repository must be 6",6, testAdminCon.size()); Assert.assertEquals("Size of repository must be 6",6, testAdminCon.size(dirgraph,dirgraph1,null)); Assert.assertEquals("Size of repository must be 6",6, testAdminCon.size(dirgraph,dirgraph1)); Assert.assertEquals("Size of repository must be 3",3, testAdminCon.size(dirgraph,null)); Assert.assertEquals("Size of repository must be 3",3, testAdminCon.size(dirgraph1,null)); Assert.assertEquals("Size of default graph must be 0",0, testAdminCon.size(null)); testAdminCon.add(dirgraph, vf.createURI("http://TYPE"), vf.createLiteral("Directory Graph")); Assert.assertEquals("Size of default graph must be 1",1, testAdminCon.size((Resource)null)); Assert.assertEquals("Size of repository must be 4",4, testAdminCon.size(dirgraph,null)); testAdminCon.commit(); } catch(Exception e){ } finally{ if (testAdminCon.isActive()) testAdminCon.rollback(); } Assert.assertEquals("Size of repository must be 4",4, testAdminCon.size(dirgraph1,null)); Assert.assertEquals(1, testAdminCon.size(null)); Assert.assertEquals(1, testAdminCon.size(null, null)); Assert.assertEquals(3, testAdminCon.size(dirgraph, dirgraph)); assertTrue("Repository should contain statement", testAdminCon.hasStatement(john, homeTel, johnhomeTel, false)); assertTrue("Repository should contain statement in dirgraph1", testAdminCon.hasStatement(micah, lname, micahlname, false, dirgraph1)); assertFalse("Repository should not contain statement in context2", testAdminCon.hasStatement(micah, lname, micahlname, false, dirgraph)); // Check handling of getStatements without context IDs RepositoryResult<Statement> result = testAdminCon.getStatements(micah, lname, null, false); try { while (result.hasNext()) { Statement st = result.next(); assertThat(st.getSubject(), is(equalTo((Resource)micah))); assertThat(st.getPredicate(), is(equalTo(lname))); assertThat(st.getObject(), is(equalTo((Value)micahlname))); assertThat(st.getContext(), is(equalTo((Resource)dirgraph1))); } } finally { result.close(); } // Check handling of getStatements with a known context ID result = testAdminCon.getStatements(null, null, null, false, dirgraph); try { while (result.hasNext()) { Statement st = result.next(); assertThat(st.getContext(), is(equalTo((Resource)dirgraph))); } } finally { result.close(); } // Check handling of getStatements with null context result = testAdminCon.getStatements(null, null, null, false, null); assertThat(result, is(notNullValue())); try { while (result.hasNext()) { Statement st = result.next(); assertThat(st.getContext(), is(equalTo((Resource)null))); } } finally { result.close(); } // Check handling of getStatements with an unknown context ID result = testAdminCon.getStatements(null, null, null, false, vf.createURI(":unknownContext")); try { assertThat(result, is(notNullValue())); assertThat(result.hasNext(), is(equalTo(false))); } finally { result.close(); } List<Statement> list = Iterations.addAll(testAdminCon.getStatements(null, lname, null, false, dirgraph1), new ArrayList<Statement>()); assertNotNull("List should not be null", list); assertFalse("List should not be empty", list.isEmpty()); List<Statement> list1 = Iterations.addAll(testAdminCon.getStatements(dirgraph, null, null, false, null), new ArrayList<Statement>()); assertNotNull("List should not be null", list1); assertFalse("List should not be empty", list1.isEmpty()); } //ISSUE 82, 127, 129, 140 @Test public void testGetStatementsInMultipleContexts() throws Exception { URI ur = vf.createURI("http://abcd"); CloseableIteration<? extends Statement, RepositoryException> iter1 = testAdminCon.getStatements(null, null, null, false, null); try { int count = 0; while (iter1.hasNext()) { iter1.next(); count++; } assertEquals("there should be 0 statements", 0 , count); } finally { iter1.close(); iter1 = null; } testAdminCon.begin(); testAdminCon.add(micah, lname, micahlname, dirgraph1); testAdminCon.add(micah, fname, micahfname, dirgraph1); testAdminCon.add(micah, homeTel, micahhomeTel, dirgraph1); testAdminCon.add(dirgraph1, ur, vf.createLiteral("test")); testAdminCon.commit(); // get statements with either no context or dirgraph1 CloseableIteration<? extends Statement, RepositoryException> iter = testAdminCon.getStatements(null, null, null, false, null , dirgraph1); try { int count = 0; while (iter.hasNext()) { count++; Statement st = iter.next(); assertThat(st.getContext(), anyOf(is(nullValue(Resource.class)), is(equalTo((Resource)dirgraph1)))); } assertEquals("there should be four statements", 4, count); } finally { iter.close(); iter = null; } iter = testAdminCon.getStatements(null, null, null, false, dirgraph1, dirgraph); try { int count = 0; while (iter.hasNext()) { count++; Statement st = iter.next(); assertThat(st.getContext(), is(equalTo((Resource)dirgraph1))); } assertEquals("there should be three statements", 3 , count); } finally { iter.close(); iter = null; } // get all statements with unknownContext or context2. URI unknownContext = testAdminCon.getValueFactory().createURI("http://unknownContext"); iter = testAdminCon.getStatements(null, null, null, false, unknownContext, dirgraph1); try { int count = 0; while (iter.hasNext()) { Statement st = iter.next(); count++; assertThat(st.getContext(), is(equalTo((Resource)dirgraph1))); } assertEquals("there should be three statements", 3, count); } finally { iter.close(); iter = null; } // add statements to dirgraph try{ testAdminCon.begin(); testAdminCon.add(john, fname, johnfname, dirgraph); testAdminCon.add(john, lname, johnlname, dirgraph); testAdminCon.add(john, homeTel, johnhomeTel, dirgraph); testAdminCon.commit(); } catch(Exception e){ e.printStackTrace(); } finally{ if(testAdminCon.isActive()) testAdminCon.rollback(); } // get statements with either no context or dirgraph iter = testAdminCon.getStatements(null, null, null, false, null, dirgraph); try { assertThat(iter, is(notNullValue())); assertThat(iter.hasNext(), is(equalTo(true))); int count = 0; while (iter.hasNext()) { count++; Statement st = iter.next(); System.out.println("Context is "+st.getContext()); assertThat(st.getContext(), anyOf(is(nullValue(Resource.class)), is(equalTo((Resource)dirgraph)) )); } assertEquals("there should be four statements", 4, count); } finally { iter.close(); iter = null; } // get all statements with dirgraph or dirgraph1 iter = testAdminCon.getStatements(null, null, null, false, null, dirgraph, dirgraph1); try { int count = 0; while (iter.hasNext()) { count++; Statement st = iter.next(); assertThat(st.getContext(), anyOf(is(nullValue(Resource.class)),is(equalTo((Resource)dirgraph)), is(equalTo((Resource)dirgraph1)))); } assertEquals("there should be 7 statements", 7, count); } finally { iter.close(); iter = null; } // get all statements with dirgraph or dirgraph1 iter = testAdminCon.getStatements(null, null, null, false, dirgraph, dirgraph1); try { int count = 0; while (iter.hasNext()) { count++; Statement st = iter.next(); assertThat(st.getContext(), anyOf(is(equalTo((Resource)dirgraph)), is(equalTo((Resource)dirgraph1)))); } assertEquals("there should be 6 statements", 6, count); } finally { iter.close(); iter = null; } } @Test public void testPagination() throws Exception{ URL url = MarkLogicRepositoryConnectionTest.class.getResource(TEST_DIR_PREFIX+"tigers.ttl"); testAdminCon.add(url, "", RDFFormat.TURTLE, graph1); StringBuilder queryBuilder = new StringBuilder(128); queryBuilder.append(" PREFIX bb: <http://marklogic.com/baseball/players#> "); queryBuilder.append(" PREFIX r: <http://marklogic.com/baseball/rules#> "); queryBuilder.append(" SELECT ?id ?lastname "); queryBuilder.append(" { "); queryBuilder.append(" ?id bb:lastname ?lastname. "); queryBuilder.append(" } "); queryBuilder.append(" ORDER BY ?lastname"); Query query = testAdminCon.prepareQuery(queryBuilder.toString()); TupleQueryResult result1 = ((MarkLogicTupleQuery) query).evaluate(1,2); String [] expLname = {"Ausmus","Avila","Bernard","Cabrera","Carrera","Castellanos","Holaday","Joyner","Lamont","Nathan","Verlander"}; String [] expID ={"http://marklogic.com/baseball/players#157", "http://marklogic.com/baseball/players#120", "http://marklogic.com/baseball/players#130", "http://marklogic.com/baseball/players#123", "http://marklogic.com/baseball/players#131", "http://marklogic.com/baseball/players#124", "http://marklogic.com/baseball/players#121", "http://marklogic.com/baseball/players#159", "http://marklogic.com/baseball/players#158", "http://marklogic.com/baseball/players#107","http://marklogic.com/baseball/players#119"}; int i =0; while (result1.hasNext()) { BindingSet solution = result1.next(); assertThat(solution.hasBinding("lastname"), is(equalTo(true))); Value totalResult = solution.getValue("lastname"); Assert.assertEquals(expLname[i],totalResult.stringValue()); i++; } Assert.assertEquals(2, i); i=0; TupleQueryResult result2 = ((MarkLogicTupleQuery) query).evaluate(1,0); while (result2.hasNext()) { BindingSet solution = result2.next(); assertThat(solution.hasBinding("lastname"), is(equalTo(true))); Value totalResult = solution.getValue("lastname"); Assert.assertEquals(expLname[i],totalResult.stringValue()); logger.debug("String values : "+ expLname[i] ); i++; } try{ TupleQueryResult result3 = ((MarkLogicTupleQuery) query).evaluate(0,0); Assert.assertTrue(2>1); } catch(Exception e){ logger.debug(e.getMessage()); Assert.assertTrue(e instanceof IllegalArgumentException); } try{ TupleQueryResult result3 = ((MarkLogicTupleQuery) query).evaluate(-1,-1); Assert.assertTrue(2>1); } catch(Exception e){ logger.debug(e.getMessage()); Assert.assertTrue(e instanceof IllegalArgumentException); } try{ TupleQueryResult result3 = ((MarkLogicTupleQuery) query).evaluate(2,-1); Assert.assertTrue(2>1); } catch(Exception e){ logger.debug(e.getMessage()); Assert.assertTrue(e instanceof IllegalArgumentException); } try{ TupleQueryResult result3 = ((MarkLogicTupleQuery) query).evaluate(-2,2); Assert.assertTrue(2>1); } catch(Exception e){ logger.debug(e.getMessage()); Assert.assertTrue(e instanceof IllegalArgumentException); } i = 0; TupleQueryResult result4 = ((MarkLogicTupleQuery) query).evaluate(11,2); while (result4.hasNext()) { BindingSet solution = result4.next(); assertThat(solution.hasBinding("lastname"), is(equalTo(true))); Value totalResult = solution.getValue("lastname"); Assert.assertEquals(expLname[11-i-1],totalResult.stringValue()); i++; } Assert.assertEquals(1L, i); } // ISSUE 72 @Test public void testPrepareNonSparql() throws Exception{ URL url = MarkLogicRepositoryConnectionTest.class.getResource(TEST_DIR_PREFIX+"tigers.ttl"); testAdminCon.add(url, "", RDFFormat.TURTLE, graph1); Assert.assertEquals(107L, testAdminCon.size()); String query1 = "ASK "+ "WHERE"+ "{"+ " ?s <#position> ?o."+ "}"; try{ testAdminCon.prepareGraphQuery(QueryLanguage.SERQL, query1, "http://marklogic.com/baseball/players").evaluate(); Assert.assertFalse("Exception was not thrown, when it should have been", 1<2); } catch(UnsupportedQueryLanguageException ex){ Assert.assertEquals("Unsupported query language SeRQL", ex.getMessage()); } try{ testAdminCon.prepareTupleQuery(QueryLanguage.SERQO, query1).evaluate(1,2); Assert.assertFalse("Exception was not thrown, when it should have been", 1<2); } catch(UnsupportedQueryLanguageException ex1){ Assert.assertEquals("Unsupported query language SeRQO", ex1.getMessage()); } try{ testAdminCon.prepareBooleanQuery(QueryLanguage.SERQL, query1).evaluate(); Assert.assertFalse("Exception was not thrown, when it should have been", 1<2); } catch(UnsupportedQueryLanguageException ex1){ Assert.assertEquals("Unsupported query language SeRQL", ex1.getMessage()); } try{ testAdminCon.prepareUpdate(QueryLanguage.SERQO, query1); Assert.assertFalse("Exception was not thrown, when it should have been", 1<2); } catch(UnsupportedQueryLanguageException ex1){ Assert.assertEquals("Unsupported query language SeRQO", ex1.getMessage()); } try{ testAdminCon.prepareQuery(QueryLanguage.SERQL, query1); Assert.assertFalse("Exception was not thrown, when it should have been", 1<2); } catch(UnsupportedQueryLanguageException ex1){ Assert.assertEquals("Unsupported query language SeRQL", ex1.getMessage()); } } // ISSUE 73 @Test public void testPrepareInvalidSparql() throws Exception{ Assert.assertEquals(0L, testWriterCon.size()); Assert.assertTrue(testAdminCon.isEmpty()); Statement st1 = vf.createStatement(john, fname, johnfname); testWriterCon.add(st1,dirgraph); Assert.assertEquals(1L, testWriterCon.size(dirgraph)); String query = " DESCRIBE <http://marklogicsparql.com/id#1111> "; try{ boolean tq = testReaderCon.prepareBooleanQuery(query, "http://marklogicsparql.com/id").evaluate(); Assert.assertEquals(0L, 1L); } // Change exception IIlegalArgumentException catch(Exception ex1){ Assert.assertTrue(ex1 instanceof Exception); } String query1 = "ASK {"+ "{"+ " ?s <#position> ?o."+ "}"; try{ boolean tq = testReaderCon.prepareBooleanQuery(query1, "http://marklogicsparql.com/id").evaluate(); Assert.assertEquals(0L, 1L); } // Should be MalformedQueryException catch(Exception ex){ ex.printStackTrace(); Assert.assertTrue(ex instanceof Exception); } } //ISSUE # 133, 183 @Test public void testUnsupportedIsolationLevel() throws Exception{ Assert.assertEquals(IsolationLevels.SNAPSHOT, testAdminCon.getIsolationLevel()); try{ testAdminCon.begin(); testAdminCon.add(john, fname, johnfname); assertThat(testAdminCon.hasStatement(john, fname, johnfname, false), is(equalTo(true))); assertThat(testWriterCon.hasStatement(john, fname, johnfname, false), is(equalTo(false))); testAdminCon.commit(); } catch (Exception e){ logger.debug(e.getMessage()); } finally{ if(testAdminCon.isActive()) testAdminCon.rollback(); } assertThat(testAdminCon.hasStatement(john, fname, johnfname, false), is(equalTo(true))); assertThat(testWriterCon.hasStatement(john, fname, johnfname, false), is(equalTo(true))); try{ testAdminCon.setIsolationLevel(IsolationLevels.SNAPSHOT_READ); Assert.assertTrue(1>2); } catch(Exception e){ Assert.assertTrue(e instanceof IllegalStateException); } } //ISSUE # 252 @Test public void testIsolationLevel() throws Exception { RepositoryConnection repConn = null; Repository tempRep1 = null; try{ MarkLogicRepositoryConfig tempConfig1 = new MarkLogicRepositoryConfig(); tempConfig1.setHost("localhost"); tempConfig1.setAuth("DIGEST"); tempConfig1.setUser("admin"); tempConfig1.setPassword("admin"); tempConfig1.setPort(restPort); tempRep1 = new MarkLogicRepositoryFactory().getRepository(tempConfig1); tempRep1.initialize(); repConn = tempRep1.getConnection(); repConn.begin(); repConn.add(john, fname, johnfname); createRepconn(); assertThat(repConn.hasStatement(john, fname, johnfname, false), is(equalTo(true))); repConn.commit(); } catch (Exception e){ logger.debug(e.getMessage()); } finally{ if(repConn.isActive()) repConn.rollback(); tempRep1.shutDown(); repConn.close(); repConn = null; tempRep1 = null; } } private void createRepconn() throws Exception { RepositoryConnection repConn1 = null; Repository tempRep2 = null; try{ MarkLogicRepositoryConfig tempConfig2 = new MarkLogicRepositoryConfig(); tempConfig2.setHost("localhost"); tempConfig2.setAuth("DIGEST"); tempConfig2.setUser("admin"); tempConfig2.setPassword("admin"); tempConfig2.setPort(restPort); tempRep2 = new MarkLogicRepositoryFactory().getRepository(tempConfig2); tempRep2.initialize(); repConn1 = tempRep2.getConnection(); assertThat(repConn1.hasStatement(john, fname, johnfname, false), is(equalTo(false))); } catch (Exception e){ logger.debug(e.getMessage()); } finally{ if(repConn1.isActive()) repConn1.rollback(); tempRep2.shutDown(); repConn1.close(); repConn1 = null; tempRep2 = null; } } // ISSUE - 84 @Test public void testNoUpdateRole() throws Exception{ try{ testAdminCon.prepareUpdate("DROP GRAPH <abc>").execute(); Assert.assertTrue(false); } catch(Exception e){ Assert.assertTrue(e instanceof UpdateExecutionException); } try{ testReaderCon.prepareUpdate("CREATE GRAPH <abc>").execute(); Assert.assertTrue(false); } catch(Exception e){ Assert.assertTrue(e instanceof UpdateExecutionException); } testAdminCon.prepareUpdate("CREATE GRAPH <http://abc>").execute(); final Statement st1 = vf.createStatement(john, fname, johnfname); try{ testReaderCon.add(st1, vf.createURI("http://abc")); } catch(Exception e){ } try{ testReaderCon.begin(); testReaderCon.add(st1, vf.createURI("http://abc")); testReaderCon.commit(); } catch(Exception e){ } finally{ if(testReaderCon.isActive()) testReaderCon.rollback(); } } //ISSUE 112, 104 @Test public void testRuleSets1() throws Exception{ Assert.assertEquals(0L, testAdminCon.size()); testAdminCon.add(micah, lname, micahlname, dirgraph1); testAdminCon.add(micah, fname, micahfname, dirgraph1); testAdminCon.add(micah, developPrototypeOf, semantics, dirgraph1); testAdminCon.add(micah, type, sEngineer, dirgraph1); testAdminCon.add(micah, worksFor, ml, dirgraph1); testAdminCon.add(john, fname, johnfname, dirgraph1); testAdminCon.add(john, lname, johnlname, dirgraph1); testAdminCon.add(john, writeFuncSpecOf, inference, dirgraph1); testAdminCon.add(john, type, lEngineer, dirgraph1); testAdminCon.add(john, worksFor, ml, dirgraph1); testAdminCon.add(writeFuncSpecOf, eqProperty, design, dirgraph1); testAdminCon.add(developPrototypeOf, eqProperty, design, dirgraph1); testAdminCon.add(design, eqProperty, develop, dirgraph1); // String query = "select (count (?s) as ?totalcount) where {?s ?p ?o .} "; TupleQuery tupleQuery = testAdminCon.prepareTupleQuery(QueryLanguage.SPARQL, query); ((MarkLogicQuery) tupleQuery).setRulesets(SPARQLRuleset.EQUIVALENT_CLASS); TupleQueryResult result = tupleQuery.evaluate(); try { assertThat(result, is(notNullValue())); assertThat(result.hasNext(), is(equalTo(true))); while (result.hasNext()) { BindingSet solution = result.next(); assertThat(solution.hasBinding("totalcount"), is(equalTo(true))); Value count = solution.getValue("totalcount"); Assert.assertEquals(15, Integer.parseInt(count.stringValue())); } } finally { result.close(); } testAdminCon.setDefaultRulesets(SPARQLRuleset.EQUIVALENT_PROPERTY, null); TupleQuery tupleQuery1 = testAdminCon.prepareTupleQuery(QueryLanguage.SPARQL, query); TupleQueryResult result1 = tupleQuery1.evaluate(); try { assertThat(result1, is(notNullValue())); assertThat(result1.hasNext(), is(equalTo(true))); while (result1.hasNext()) { BindingSet solution = result1.next(); assertThat(solution.hasBinding("totalcount"), is(equalTo(true))); Value count = solution.getValue("totalcount"); Assert.assertEquals(23,Integer.parseInt(count.stringValue())); } } finally { result1.close(); } SPARQLRuleset [] ruleset = testAdminCon.getDefaultRulesets(); Assert.assertEquals(2, ruleset.length); Assert.assertEquals(ruleset[0],SPARQLRuleset.EQUIVALENT_PROPERTY ); Assert.assertEquals(ruleset[1],null ); testAdminCon.setDefaultRulesets(null); TupleQuery tupleQuery2 = testAdminCon.prepareTupleQuery(QueryLanguage.SPARQL, query); ((MarkLogicQuery) tupleQuery2).setRulesets(null); tupleQuery2.setIncludeInferred(false); TupleQueryResult result2 = tupleQuery2.evaluate(); try { assertThat(result2, is(notNullValue())); assertThat(result2.hasNext(), is(equalTo(true))); while (result2.hasNext()) { BindingSet solution = result2.next(); assertThat(solution.hasBinding("totalcount"), is(equalTo(true))); Value count = solution.getValue("totalcount"); Assert.assertEquals(13, Integer.parseInt(count.stringValue())); } } finally { result2.close(); } } // ISSUE 128, 163, 111, 112 (closed) @Test public void testRuleSets2() throws Exception{ Assert.assertEquals(0L, testAdminCon.size()); testAdminCon.add(micah, lname, micahlname, dirgraph1); testAdminCon.add(micah, fname, micahfname, dirgraph1); testAdminCon.add(micah, developPrototypeOf, semantics, dirgraph1); testAdminCon.add(micah, type, sEngineer, dirgraph1); testAdminCon.add(micah, worksFor, ml, dirgraph1); testAdminCon.add(john, fname, johnfname,dirgraph); testAdminCon.add(john, lname, johnlname,dirgraph); testAdminCon.add(john, writeFuncSpecOf, inference, dirgraph); testAdminCon.add(john, type, lEngineer, dirgraph); testAdminCon.add(john, worksFor, ml, dirgraph); testAdminCon.add(writeFuncSpecOf, subProperty, design, dirgraph1); testAdminCon.add(developPrototypeOf, subProperty, design, dirgraph1); testAdminCon.add(design, subProperty, develop, dirgraph1); testAdminCon.add(lEngineer, subClass, engineer, dirgraph1); testAdminCon.add(sEngineer, subClass, engineer, dirgraph1); testAdminCon.add(engineer, subClass, employee, dirgraph1); String query = "select (count (?s) as ?totalcount) where {?s ?p ?o .} "; TupleQuery tupleQuery = testAdminCon.prepareTupleQuery(QueryLanguage.SPARQL, query); ((MarkLogicQuery) tupleQuery).setRulesets(SPARQLRuleset.RDFS_PLUS_FULL); TupleQueryResult result = tupleQuery.evaluate(); try { assertThat(result, is(notNullValue())); assertThat(result.hasNext(), is(equalTo(true))); while (result.hasNext()) { BindingSet solution = result.next(); assertThat(solution.hasBinding("totalcount"), is(equalTo(true))); Value count = solution.getValue("totalcount"); Assert.assertEquals(374, Integer.parseInt(count.stringValue())); } } finally { result.close(); } RepositoryResult<Statement> resultg = testAdminCon.getStatements(null, null, null, true, dirgraph, dirgraph1); assertNotNull("Iterator should not be null", resultg); assertTrue("Iterator should not be empty", resultg.hasNext()); tupleQuery = testAdminCon.prepareTupleQuery(QueryLanguage.SPARQL, query); ((MarkLogicQuery) tupleQuery).setRulesets(SPARQLRuleset.EQUIVALENT_CLASS); result = tupleQuery.evaluate(); try { assertThat(result, is(notNullValue())); assertThat(result.hasNext(), is(equalTo(true))); while (result.hasNext()) { BindingSet solution = result.next(); assertThat(solution.hasBinding("totalcount"), is(equalTo(true))); Value count = solution.getValue("totalcount"); Assert.assertEquals(18, Integer.parseInt(count.stringValue())); } } finally { result.close(); } tupleQuery = testAdminCon.prepareTupleQuery(QueryLanguage.SPARQL, query); ((MarkLogicQuery) tupleQuery).setRulesets(SPARQLRuleset.RDFS,SPARQLRuleset.INVERSE_OF); result = tupleQuery.evaluate(); try { assertThat(result, is(notNullValue())); assertThat(result.hasNext(), is(equalTo(true))); while (result.hasNext()) { BindingSet solution = result.next(); assertThat(solution.hasBinding("totalcount"), is(equalTo(true))); Value count = solution.getValue("totalcount"); Assert.assertEquals(86, Integer.parseInt(count.stringValue())); } } finally { result.close(); } tupleQuery = testAdminCon.prepareTupleQuery(QueryLanguage.SPARQL, query); ((MarkLogicQuery) tupleQuery).setRulesets(null,SPARQLRuleset.INVERSE_OF); result = tupleQuery.evaluate(); try { assertThat(result, is(notNullValue())); assertThat(result.hasNext(), is(equalTo(true))); while (result.hasNext()) { BindingSet solution = result.next(); assertThat(solution.hasBinding("totalcount"), is(equalTo(true))); Value count = solution.getValue("totalcount"); Assert.assertEquals(18, Integer.parseInt(count.stringValue())); } } finally { result.close(); } tupleQuery = testAdminCon.prepareTupleQuery(QueryLanguage.SPARQL, query); ((MarkLogicQuery) tupleQuery).setRulesets((SPARQLRuleset)null, null); tupleQuery.setIncludeInferred(false); result = tupleQuery.evaluate(); try { assertThat(result, is(notNullValue())); assertThat(result.hasNext(), is(equalTo(true))); while (result.hasNext()) { BindingSet solution = result.next(); assertThat(solution.hasBinding("totalcount"), is(equalTo(true))); Value count = solution.getValue("totalcount"); Assert.assertEquals(16, Integer.parseInt(count.stringValue())); } } finally { result.close(); } } @Test public void testConstrainingQueries() throws Exception{ testAdminCon.add(micah, lname, micahlname, dirgraph1); testAdminCon.add(micah, fname, micahfname, dirgraph1); testAdminCon.add(john, fname, johnfname); testAdminCon.add(john, lname, johnlname); String query1 = "ASK WHERE {?s ?p \"Micah\" .}"; String query2 = "SELECT ?s ?p ?o WHERE {?s ?p ?o .} ORDER by ?o"; // case one, rawcombined String combinedQuery = "{\"search\":" + "{\"qtext\":\"2222\"}}"; String negCombinedQuery = "{\"search\":" + "{\"qtext\":\"John\"}}"; RawCombinedQueryDefinition rawCombined = qmgr.newRawCombinedQueryDefinition(new StringHandle().with(combinedQuery).withFormat(Format.JSON)); RawCombinedQueryDefinition negRawCombined = qmgr.newRawCombinedQueryDefinition(new StringHandle().with(negCombinedQuery).withFormat(Format.JSON)); MarkLogicBooleanQuery askQuery = (MarkLogicBooleanQuery) testAdminCon.prepareBooleanQuery(QueryLanguage.SPARQL,query1); askQuery.setConstrainingQueryDefinition(rawCombined); Assert.assertEquals(true, askQuery.evaluate()); testAdminCon.setDefaultConstrainingQueryDefinition(negRawCombined); MarkLogicTupleQuery tupleQuery = testAdminCon.prepareTupleQuery(QueryLanguage.SPARQL, query2); TupleQueryResult result = tupleQuery.evaluate(); try { assertThat(result, is(notNullValue())); assertThat(result.hasNext(), is(equalTo(true))); while (result.hasNext()) { BindingSet solution = result.next(); assertThat(solution.hasBinding("s"), is(equalTo(true))); Value fname = solution.getValue("o"); String name = fname.stringValue().toString(); Assert.assertTrue(name.equals("John")|| name.equals("Snelson")); } } finally { result.close(); } QueryDefinition qd = testAdminCon.getDefaultConstrainingQueryDefinition(); testAdminCon.setDefaultConstrainingQueryDefinition(null); testAdminCon.setDefaultConstrainingQueryDefinition(qd); tupleQuery = testAdminCon.prepareTupleQuery(QueryLanguage.SPARQL, query2); result = tupleQuery.evaluate(); try { assertThat(result, is(notNullValue())); assertThat(result.hasNext(), is(equalTo(true))); while (result.hasNext()) { BindingSet solution = result.next(); assertThat(solution.hasBinding("s"), is(equalTo(true))); Value fname = solution.getValue("o"); String name = fname.stringValue().toString(); Assert.assertTrue(name.equals("John")|| name.equals("Snelson")); } } finally { result.close(); } testAdminCon.setDefaultConstrainingQueryDefinition(null); tupleQuery = testAdminCon.prepareTupleQuery(QueryLanguage.SPARQL, query2); result = tupleQuery.evaluate(); try { assertThat(result, is(notNullValue())); assertThat(result.hasNext(), is(equalTo(true))); while (result.hasNext()) { BindingSet solution = result.next(); assertThat(solution.hasBinding("s"), is(equalTo(true))); Value fname = solution.getValue("o"); String name = fname.stringValue().toString(); Assert.assertTrue(name.equals("John")|| name.equals("Snelson")|| name.equals("Micah")|| name.equals("Dubinko")); } } finally { result.close(); } } // ISSUE 124, 142 @Test public void testStructuredQuery() throws Exception { setupData(); StructuredQueryBuilder qb = new StructuredQueryBuilder(); QueryDefinition structuredDef = qb.build(qb.term("Second")); String posQuery = "ASK WHERE {<http://example.org/r9929> ?p ?o .}"; String negQuery = "ASK WHERE {<http://example.org/r9928> ?p ?o .}"; MarkLogicBooleanQuery askQuery = (MarkLogicBooleanQuery) testAdminCon.prepareBooleanQuery(QueryLanguage.SPARQL,posQuery); askQuery.setConstrainingQueryDefinition(structuredDef); Assert.assertEquals(true, askQuery.evaluate()); testAdminCon.setDefaultConstrainingQueryDefinition(structuredDef); MarkLogicBooleanQuery askQuery1 = (MarkLogicBooleanQuery) testAdminCon.prepareBooleanQuery(QueryLanguage.SPARQL,negQuery); Assert.assertEquals(false, askQuery1.evaluate()); QueryDefinition qd = testAdminCon.getDefaultConstrainingQueryDefinition(); testAdminCon.setDefaultConstrainingQueryDefinition(null); askQuery1 = (MarkLogicBooleanQuery) testAdminCon.prepareBooleanQuery(QueryLanguage.SPARQL,negQuery); Assert.assertEquals(true, askQuery1.evaluate()); testAdminCon.setDefaultConstrainingQueryDefinition(qd); askQuery1 = (MarkLogicBooleanQuery) testAdminCon.prepareBooleanQuery(QueryLanguage.SPARQL,negQuery); Assert.assertEquals(false, askQuery1.evaluate()); testAdminCon.setDefaultConstrainingQueryDefinition(null); askQuery = (MarkLogicBooleanQuery) testAdminCon.prepareBooleanQuery(QueryLanguage.SPARQL,posQuery); askQuery.setConstrainingQueryDefinition(null); Assert.assertEquals(true, askQuery.evaluate()); askQuery1 = (MarkLogicBooleanQuery) testAdminCon.prepareBooleanQuery(QueryLanguage.SPARQL,negQuery); askQuery.setConstrainingQueryDefinition(null); Assert.assertEquals(true, askQuery1.evaluate()); } // ISSUE 124 @Test public void testStringQuery() throws Exception { setupData(); StringQueryDefinition stringDef = qmgr.newStringDefinition().withCriteria("First"); String posQuery = "ASK WHERE {<http://example.org/r9928> ?p ?o .}"; String negQuery = "ASK WHERE {<http://example.org/r9929> ?p ?o .}"; MarkLogicBooleanQuery askQuery = (MarkLogicBooleanQuery) testAdminCon.prepareBooleanQuery(QueryLanguage.SPARQL,posQuery); askQuery.setConstrainingQueryDefinition(stringDef); Assert.assertEquals(true, askQuery.evaluate()); MarkLogicBooleanQuery askQuery1 = (MarkLogicBooleanQuery) testAdminCon.prepareBooleanQuery(QueryLanguage.SPARQL,negQuery); askQuery1.setConstrainingQueryDefinition(stringDef); Assert.assertEquals(false, askQuery1.evaluate()); askQuery = (MarkLogicBooleanQuery) testAdminCon.prepareBooleanQuery(QueryLanguage.SPARQL,posQuery); askQuery.setConstrainingQueryDefinition(null); Assert.assertEquals(true, askQuery.evaluate()); askQuery1 = (MarkLogicBooleanQuery) testAdminCon.prepareBooleanQuery(QueryLanguage.SPARQL,negQuery); askQuery1.setConstrainingQueryDefinition(null); Assert.assertEquals(true, askQuery1.evaluate()); } private void setupData() { String tripleDocOne = "<semantic-document>\n" + "<title>First Title</title>\n" + "<size>100</size>\n" + "<sem:triples xmlns:sem=\"http://marklogic.com/semantics\">" + "<sem:triple><sem:subject>http://example.org/r9928</sem:subject>" + "<sem:predicate>http://example.org/p3</sem:predicate>" + "<sem:object datatype=\"http://www.w3.org/2001/XMLSchema#int\">1</sem:object></sem:triple>" + "</sem:triples>\n" + "</semantic-document>"; String tripleDocTwo = "<semantic-document>\n" + "<title>Second Title</title>\n" + "<size>500</size>\n" + "<sem:triples xmlns:sem=\"http://marklogic.com/semantics\">" + "<sem:triple><sem:subject>http://example.org/r9929</sem:subject>" + "<sem:predicate>http://example.org/p3</sem:predicate>" + "<sem:object datatype=\"http://www.w3.org/2001/XMLSchema#int\">2</sem:object></sem:triple>" + "</sem:triples>\n" + "</semantic-document>"; XMLDocumentManager docMgr = databaseClient.newXMLDocumentManager(); docMgr.write("/directory1/doc1.xml", new StringHandle().with(tripleDocOne)); docMgr.write("/directory2/doc2.xml", new StringHandle().with(tripleDocTwo)); } //ISSUE 51 @Test public void testCommitConnClosed() throws Exception { try{ testAdminCon.begin(); testAdminCon.add(micah, lname, micahlname, dirgraph1); testAdminCon.add(micah, fname, micahfname, dirgraph1); testAdminCon.add(micah, homeTel, micahhomeTel, dirgraph1); Assert.assertEquals("Size of dirgraph1",3, testAdminCon.size()); testAdminCon.close(); } catch(Exception e){ e.printStackTrace(); } // initializes repository and creates testAdminCon testAdminRepository.shutDown(); testAdminRepository = null; testAdminCon = null; setUp(); Assert.assertEquals("Size of dirgraph1",0, testAdminCon.size()); } }
marklogic-sesame-functionaltests/src/test/java/com/marklogic/sesame/functionaltests/MarkLogicRepositoryConnectionTest.java
package com.marklogic.sesame.functionaltests; import com.marklogic.client.DatabaseClient; import com.marklogic.client.DatabaseClientFactory; import com.marklogic.client.document.XMLDocumentManager; import com.marklogic.client.io.Format; import com.marklogic.client.io.StringHandle; import com.marklogic.client.query.*; import com.marklogic.client.semantics.Capability; import com.marklogic.client.semantics.GraphManager; import com.marklogic.client.semantics.GraphPermissions; import com.marklogic.client.semantics.SPARQLRuleset; import com.marklogic.semantics.sesame.MarkLogicRepository; import com.marklogic.semantics.sesame.MarkLogicRepositoryConnection; import com.marklogic.semantics.sesame.MarkLogicTransactionException; import com.marklogic.semantics.sesame.config.MarkLogicRepositoryConfig; import com.marklogic.semantics.sesame.config.MarkLogicRepositoryFactory; import com.marklogic.semantics.sesame.query.MarkLogicBooleanQuery; import com.marklogic.semantics.sesame.query.MarkLogicQuery; import com.marklogic.semantics.sesame.query.MarkLogicTupleQuery; import com.marklogic.semantics.sesame.query.MarkLogicUpdateQuery; import com.marklogic.sesame.functionaltests.util.ConnectedRESTQA; import com.marklogic.sesame.functionaltests.util.StatementIterable; import com.marklogic.sesame.functionaltests.util.StatementIterator; import com.marklogic.sesame.functionaltests.util.StatementList; import info.aduna.iteration.CloseableIteration; import info.aduna.iteration.Iteration; import info.aduna.iteration.Iterations; import info.aduna.iteration.IteratorIteration; import org.junit.*; import org.openrdf.IsolationLevels; import org.openrdf.OpenRDFException; import org.openrdf.model.*; import org.openrdf.model.vocabulary.XMLSchema; import org.openrdf.query.*; import org.openrdf.repository.Repository; import org.openrdf.repository.RepositoryConnection; import org.openrdf.repository.RepositoryException; import org.openrdf.repository.RepositoryResult; import org.openrdf.repository.UnknownTransactionStateException; import org.openrdf.repository.config.RepositoryConfigException; import org.openrdf.repository.config.RepositoryFactory; import org.openrdf.repository.config.RepositoryImplConfig; import org.openrdf.rio.RDFFormat; import org.openrdf.rio.RDFHandlerException; import org.openrdf.rio.RDFParseException; import org.openrdf.rio.RioSetting; import org.openrdf.rio.helpers.BasicParserSettings; import org.openrdf.rio.helpers.RDFHandlerBase; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import java.io.*; import java.net.URL; import java.util.*; import java.util.Map.Entry; import static org.hamcrest.core.AnyOf.anyOf; import static org.hamcrest.core.Is.is; import static org.hamcrest.core.IsEqual.equalTo; import static org.hamcrest.core.IsNot.not; import static org.hamcrest.core.IsNull.notNullValue; import static org.hamcrest.core.IsNull.nullValue; import static org.junit.Assert.*; public class MarkLogicRepositoryConnectionTest extends ConnectedRESTQA { private static final String TEST_DIR_PREFIX = "/testdata/"; private static String dbName = "MLSesame"; private static String [] fNames = {"MLSesame-1"}; private static String restServer = "REST-MLSesame-API-Server"; private static int restPort = 8023; protected static DatabaseClient databaseClient ; protected static MarkLogicRepository testAdminRepository; protected static MarkLogicRepository testReaderRepository; protected static MarkLogicRepository testWriterRepository; protected static MarkLogicRepositoryConnection testAdminCon; protected static MarkLogicRepositoryConnection testReaderCon; protected static MarkLogicRepositoryConnection testWriterCon; protected final Logger logger = LoggerFactory.getLogger(this.getClass()); protected ValueFactory vf; protected ValueFactory vfWrite; protected URI graph1; protected URI graph2; protected URI dirgraph; protected URI dirgraph1; protected URI john; protected URI micah; protected URI fei; protected URI fname; protected URI lname; protected URI email; protected URI homeTel; protected Literal johnfname; protected Literal johnlname; protected Literal johnemail; protected Literal johnhomeTel; protected Literal micahfname; protected Literal micahlname; protected Literal micahhomeTel; protected Literal feifname; protected Literal feilname; protected Literal feiemail; protected URI writeFuncSpecOf ; protected URI type ; protected URI worksFor ; protected URI developPrototypeOf ; protected URI ml ; protected URI semantics ; protected URI inference ; protected URI sEngineer ; protected URI lEngineer ; protected URI engineer ; protected URI employee ; protected URI design ; protected URI subClass ; protected URI subProperty ; protected URI eqProperty ; protected URI develop ; protected QueryManager qmgr; private static final String ID = "id"; private static final String ADDRESS = "addressbook"; protected static final String NS = "http://marklogicsparql.com/"; protected static final String RDFS = "http://www.w3.org/2000/01/rdf-schema#"; protected static final String OWL = "http://www.w3.org/2002/07/owl#"; @BeforeClass public static void initialSetup() throws Exception { setupJavaRESTServer(dbName, fNames[0], restServer, restPort); setupAppServicesConstraint(dbName); enableCollectionLexicon(dbName); enableTripleIndex(dbName); createRESTUser("reader", "reader", "rest-reader"); createRESTUser("writer", "writer", "rest-writer"); } @AfterClass public static void tearDownSetup() throws Exception { tearDownJavaRESTServer(dbName, fNames, restServer); deleteUserRole("test-eval"); deleteRESTUser("reader"); deleteRESTUser("writer"); } @Before public void setUp() throws Exception { logger.debug("Initializing repository"); createRepository(); vf = testAdminCon.getValueFactory(); vfWrite = testWriterCon.getValueFactory(); john = vf.createURI(NS+ID+"#1111"); micah = vf.createURI(NS+ID+"#2222"); fei = vf.createURI(NS+ID+"#3333"); fname = vf.createURI(NS+ADDRESS+"#firstName"); lname = vf.createURI(NS+ADDRESS+"#lastName"); email = vf.createURI(NS+ADDRESS+"#email"); homeTel =vf.createURI(NS+ADDRESS+"#homeTel"); writeFuncSpecOf =vf.createURI(NS+"writeFuncSpecOf"); type = vf.createURI("http://www.w3.org/1999/02/22-rdf-syntax-ns#type"); worksFor =vf.createURI(NS+"worksFor"); developPrototypeOf =vf.createURI(NS+"developPrototypeOf"); ml =vf.createURI(NS+"MarkLogic"); semantics = vf.createURI(NS+"Semantics"); inference = vf.createURI(NS+"Inference"); sEngineer = vf.createURI(NS+"SeniorEngineer"); lEngineer = vf.createURI(NS+"LeadEngineer"); engineer = vf.createURI(NS+"Engineer"); employee = vf.createURI(NS+"Employee"); design = vf.createURI(NS+"design"); develop = vf.createURI(NS+"develop"); subClass = vf.createURI(RDFS+"subClassOf"); subProperty = vf.createURI(RDFS+"subPropertyOf"); eqProperty = vf.createURI(OWL+"equivalentProperty"); johnfname = vf.createLiteral("John"); johnlname = vf.createLiteral("Snelson"); johnhomeTel = vf.createLiteral(111111111D); johnemail = vf.createLiteral("[email protected]"); micahfname = vf.createLiteral("Micah"); micahlname = vf.createLiteral("Dubinko"); micahhomeTel = vf.createLiteral(22222222D); feifname = vf.createLiteral("Fei"); feilname = vf.createLiteral("Ling"); feiemail = vf.createLiteral("[email protected]"); } @After public void tearDown() throws Exception { clearDB(restPort); testAdminCon.close(); testAdminRepository.shutDown(); testAdminRepository = null; testAdminCon = null; testReaderRepository.shutDown(); testReaderRepository = null; testReaderCon = null; testWriterCon.close(); testWriterRepository.shutDown(); testWriterCon = null; testWriterRepository = null; logger.info("tearDown complete."); } /** * Gets an (uninitialized) instance of the repository that should be tested. * * @return void * @throws RepositoryConfigException * @throws RepositoryException */ protected void createRepository() throws Exception { //Creating MLSesame Connection object Using MarkLogicRepositoryConfig MarkLogicRepositoryConfig adminconfig = new MarkLogicRepositoryConfig(); adminconfig.setHost("localhost"); adminconfig.setAuth("DIGEST"); adminconfig.setUser("admin"); adminconfig.setPassword("admin"); adminconfig.setPort(restPort); RepositoryFactory factory = new MarkLogicRepositoryFactory(); Assert.assertEquals("marklogic:MarkLogicRepository", factory.getRepositoryType()); try { testAdminRepository = (MarkLogicRepository) factory.getRepository(adminconfig); } catch (RepositoryConfigException e) { // TODO Auto-generated catch block e.printStackTrace(); } try { testAdminRepository.initialize(); testAdminCon = (MarkLogicRepositoryConnection) testAdminRepository.getConnection(); } catch (RepositoryException e) { // TODO Auto-generated catch block e.printStackTrace(); } // Creating testAdminCon with MarkLogicRepositoryConfig constructor testAdminCon.close(); testAdminRepository.shutDown(); testAdminRepository = null; testAdminCon = null; adminconfig = new MarkLogicRepositoryConfig("localhost",restPort,"admin","admin","DIGEST"); Assert.assertEquals("marklogic:MarkLogicRepository", factory.getRepositoryType()); testAdminRepository = (MarkLogicRepository) factory.getRepository(adminconfig); testAdminRepository.initialize(); testAdminCon = testAdminRepository.getConnection(); Assert.assertTrue(testAdminCon instanceof MarkLogicRepositoryConnection); Repository otherrepo = factory.getRepository(adminconfig); try{ //try to get connection without initializing repo, will throw error RepositoryConnection conn = otherrepo.getConnection(); Assert.assertTrue(false); } catch(Exception e){ Assert.assertTrue(e instanceof RepositoryException); otherrepo.shutDown(); } Assert.assertTrue(testAdminCon instanceof MarkLogicRepositoryConnection); graph1 = testAdminCon.getValueFactory().createURI("http://marklogic.com/Graph1"); graph2 = testAdminCon.getValueFactory().createURI("http://marklogic.com/Graph2"); dirgraph = testAdminCon.getValueFactory().createURI("http://marklogic.com/dirgraph"); dirgraph1 = testAdminCon.getValueFactory().createURI("http://marklogic.com/dirgraph1"); //Creating MLSesame Connection object Using MarkLogicRepository overloaded constructor if(testReaderCon == null || testReaderRepository ==null){ testReaderRepository = new MarkLogicRepository("localhost", restPort, "reader", "reader", "DIGEST"); try { testReaderRepository.initialize(); Assert.assertNotNull(testReaderRepository); testReaderCon = (MarkLogicRepositoryConnection) testReaderRepository.getConnection(); } catch (RepositoryException e) { // TODO Auto-generated catch block e.printStackTrace(); } Assert.assertTrue(testReaderCon instanceof MarkLogicRepositoryConnection); } //Creating MLSesame Connection object Using MarkLogicRepository(databaseclient) constructor if (databaseClient == null) databaseClient = DatabaseClientFactory.newClient("localhost", restPort, "writer", "writer", DatabaseClientFactory.Authentication.valueOf("DIGEST")); if(testWriterCon == null || testWriterRepository ==null){ testWriterRepository = new MarkLogicRepository(databaseClient); qmgr = databaseClient.newQueryManager(); try { testWriterRepository.initialize(); Assert.assertNotNull(testWriterRepository); testWriterCon = (MarkLogicRepositoryConnection) testWriterRepository.getConnection(); } catch (RepositoryException e) { // TODO Auto-generated catch block e.printStackTrace(); } } } @Test public void testMultiThreadedAdd() throws Exception{ class MyRunnable implements Runnable { @Override public void run(){ try { testAdminCon.begin(); for (int j =0 ;j < 100; j++){ URI subject = vf.createURI(NS+ID+"/"+Thread.currentThread().getId()+"/"+j+"#1111"); URI predicate = fname = vf.createURI(NS+ADDRESS+"/"+Thread.currentThread().getId()+"/"+"#firstName"); Literal object = vf.createLiteral(Thread.currentThread().getId()+ "-" + j +"-" +"John"); testAdminCon.add(subject, predicate,object, dirgraph); } testAdminCon.commit(); } catch (RepositoryException e1) { // TODO Auto-generated catch block e1.printStackTrace(); } finally{ try { if(testAdminCon.isActive()) testAdminCon.rollback(); } catch (UnknownTransactionStateException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (RepositoryException e) { // TODO Auto-generated catch block e.printStackTrace(); } } } } class MyRunnable1 implements Runnable { @Override public void run(){ try { testWriterCon.begin(); for (int j =0 ;j <100; j++){ URI subject = vf.createURI(NS+ID+"/"+Thread.currentThread().getId()+"/"+j+"#1111"); URI predicate = fname = vf.createURI(NS+ADDRESS+"/"+Thread.currentThread().getId()+"/"+"#firstName"); Literal object = vf.createLiteral(Thread.currentThread().getId()+ "-" + j +"-" +"John"); testWriterCon.add(subject, predicate,object, dirgraph); } testWriterCon.commit(); } catch (RepositoryException e1) { e1.printStackTrace(); } finally{ try { if(testWriterCon.isActive()) testWriterCon.rollback(); } catch (UnknownTransactionStateException e) { e.printStackTrace(); } catch (RepositoryException e) { e.printStackTrace(); } } } } Thread t1,t2; t1 = new Thread(new MyRunnable()); t1.setName("T1"); t2 = new Thread(new MyRunnable1()); t2.setName("T2"); t1.start(); t2.start(); t1.join(); t2.join(); Assert.assertEquals(200, testAdminCon.size()); } @Ignore public void testMultiThreadedAdd1() throws Exception{ class MyRunnable implements Runnable { private final Object lock = new Object(); @Override public void run(){ try { synchronized (lock){ if(! testAdminCon.isActive()) testAdminCon.begin(); } for (int j =0 ;j < 100; j++){ URI subject = vf.createURI(NS+ID+"/"+Thread.currentThread().getId()+"/"+j+"#1111"); URI predicate = fname = vf.createURI(NS+ADDRESS+"/"+Thread.currentThread().getId()+"/"+"#firstName"); Literal object = vf.createLiteral(Thread.currentThread().getId()+ "-" + j +"-" +"John"); testAdminCon.add(subject, predicate,object, dirgraph); } testAdminCon.commit(); } catch (RepositoryException e1) { // TODO Auto-generated catch block e1.printStackTrace(); } finally{ try { if(testAdminCon.isActive()) testAdminCon.rollback(); } catch (UnknownTransactionStateException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (RepositoryException e) { // TODO Auto-generated catch block e.printStackTrace(); } } } } Thread t1,t2,t3,t4; t1 = new Thread(new MyRunnable()); t1.setName("T1"); t2 = new Thread(new MyRunnable()); t2.setName("T2"); t3 = new Thread(new MyRunnable()); t3.setName("T2"); t4 = new Thread(new MyRunnable()); t4.setName("T2"); t1.start(); t2.start(); t3.start(); t4.start(); t1.join(); t2.join(); t3.join(); t4.join(); Assert.assertEquals(400, testAdminCon.size()); } @Test public void testMultiThreadedAdd2() throws Exception{ class MyRunnable implements Runnable { @Override public void run(){ try { for (int j =0 ;j < 100; j++){ URI subject = vf.createURI(NS+ID+"/"+Thread.currentThread().getId()+"/"+j+"#1111"); URI predicate = fname = vf.createURI(NS+ADDRESS+"/"+Thread.currentThread().getId()+"/"+"#firstName"); Literal object = vf.createLiteral(Thread.currentThread().getId()+ "-" + j +"-" +"John"); testAdminCon.add(subject, predicate,object, dirgraph); } } catch (RepositoryException e1) { // TODO Auto-generated catch block e1.printStackTrace(); } } } Thread t1,t2,t3,t4; t1 = new Thread(new MyRunnable()); t1.setName("T1"); t2 = new Thread(new MyRunnable()); t2.setName("T2"); t3 = new Thread(new MyRunnable()); t3.setName("T2"); t4 = new Thread(new MyRunnable()); t4.setName("T2"); t1.start(); t2.start(); t3.start(); t4.start(); t1.join(); t2.join(); t3.join(); t4.join(); Assert.assertEquals(400, testAdminCon.size()); } @Test public void testMultiThreadedAddDuplicate() throws Exception{ class MyRunnable implements Runnable { @Override public void run() { for (int j =0 ;j < 100; j++){ URI subject = vf.createURI(NS+ID+"/"+j+"#1111"); URI predicate = fname = vf.createURI(NS+ADDRESS+"/"+"#firstName"); Literal object = vf.createLiteral(j +"-" +"John"); try { testAdminCon.add(subject, predicate,object, dirgraph); } catch (RepositoryException e) { // TODO Auto-generated catch block e.printStackTrace(); } } } } Thread t1,t2,t3,t4,t5; t1 = new Thread(new MyRunnable()); t2 = new Thread(new MyRunnable()); t3 = new Thread(new MyRunnable()); t4 = new Thread(new MyRunnable()); t5 = new Thread(new MyRunnable()); t1.start(); t2.start(); t3.start(); t4.start(); t5.start(); t1.join(); t2.join(); t3.join(); t4.join(); t5.join(); Assert.assertEquals(100, testAdminCon.size()); } //ISSUE - 19 @Test public void testPrepareBooleanQuery1() throws Exception{ Assert.assertEquals(0L, testAdminCon.size()); InputStream in = MarkLogicRepositoryConnectionTest.class.getResourceAsStream(TEST_DIR_PREFIX + "tigers.ttl"); testAdminCon.add(in, "", RDFFormat.TURTLE); in.close(); Assert.assertEquals(107L, testAdminCon.size()); String query1 = "PREFIX bb: <http://marklogic.com/baseball/players#>"+ " ASK "+ " WHERE"+ " {"+ " ?id bb:lastname ?name ."+ " FILTER EXISTS { ?id bb:country ?countryname }"+ " }"; boolean result1 = testAdminCon.prepareBooleanQuery(QueryLanguage.SPARQL, query1).evaluate(); Assert.assertFalse(result1); String query2 = "PREFIX bb: <http://marklogic.com/baseball/players#>"+ "PREFIX r: <http://marklogic.com/baseball/rules#>"+ " ASK WHERE"+ " {"+ " ?id bb:team r:Tigers."+ " ?id bb:position \"pitcher\"."+ " }"; boolean result2 = testAdminCon.prepareBooleanQuery(QueryLanguage.SPARQL, query2).evaluate(); Assert.assertTrue(result2); } // ISSUE 32, 45 @Test public void testPrepareBooleanQuery2() throws Exception{ InputStream in = MarkLogicRepositoryConnectionTest.class.getResourceAsStream(TEST_DIR_PREFIX + "tigers.ttl"); Reader reader = new InputStreamReader(in); testAdminCon.add(reader, "http://marklogic.com/baseball/", RDFFormat.TURTLE, graph1); reader.close(); Assert.assertEquals(107L, testAdminCon.size(graph1, null)); String query1 = "ASK FROM <http://marklogic.com/Graph1>"+ " WHERE"+ " {"+ " ?player ?team <#Tigers>."+ " }"; boolean result1 = testAdminCon.prepareBooleanQuery(QueryLanguage.SPARQL, query1,"http://marklogic.com/baseball/rules").evaluate(); Assert.assertTrue(result1); String query2 = "PREFIX bb: <http://marklogic.com/baseball/players#>"+ " PREFIX r: <http://marklogic.com/baseball/rules#>"+ " ASK FROM <http://marklogic.com/Graph1> WHERE"+ " {"+ " ?id bb:team r:Tigers."+ " ?id bb:position \"pitcher\"."+ " }"; boolean result2 = testAdminCon.prepareBooleanQuery(QueryLanguage.SPARQL, query2, "").evaluate(); Assert.assertTrue(result2); } @Test public void testPrepareBooleanQuery3() throws Exception{ URL url = MarkLogicRepositoryConnectionTest.class.getResource(TEST_DIR_PREFIX+"tigers.ttl"); testAdminCon.add(url, "", RDFFormat.TURTLE, graph1); Assert.assertEquals(107L, testAdminCon.size()); String query1 = "PREFIX bb: <http://marklogic.com/baseball/players#>"+ "ASK "+ "WHERE"+ "{"+ " ?s bb:position ?o."+ "}"; BooleanQuery bq = testAdminCon.prepareBooleanQuery(query1); bq.setBinding("o", vf.createLiteral("coach")); boolean result1 = bq.evaluate(); Assert.assertTrue(result1); bq.clearBindings(); bq.setBinding("o", vf.createLiteral("pitcher")); boolean result2 = bq.evaluate(); Assert.assertTrue(result2); bq.clearBindings(); bq.setBinding("o", vf.createLiteral("abcd")); boolean result3 = bq.evaluate(); Assert.assertFalse(result3); } @Test public void testPrepareBooleanQuery4() throws Exception{ File file = new File(MarkLogicRepositoryConnectionTest.class.getResource(TEST_DIR_PREFIX+ "tigers.ttl").getFile()); testAdminCon.add(file, "", RDFFormat.TURTLE, graph1); logger.debug(file.getAbsolutePath()); Assert.assertEquals(107L, testAdminCon.size(graph1)); String query1 = "PREFIX bb: <http://marklogic.com/baseball/players#>"+ "ASK FROM <http://marklogic.com/Graph1>"+ "WHERE"+ "{"+ "<#119> <#lastname> \"Verlander\"."+ "<#119> <#team> ?tigers."+ "}"; boolean result1 = testAdminCon.prepareBooleanQuery(query1,"http://marklogic.com/baseball/players").evaluate(); Assert.assertTrue(result1); } // ISSUE 20 , 25 @Test public void testPrepareTupleQuery1() throws Exception{ Assert.assertEquals(0, testAdminCon.size()); Statement st1 = vf.createStatement(john, fname, johnfname, dirgraph); Statement st2 = vf.createStatement(john, lname, johnlname, dirgraph); Statement st3 = vf.createStatement(john, homeTel, johnhomeTel, dirgraph); Statement st4 = vf.createStatement(john, email, johnemail, dirgraph); Statement st5 = vf.createStatement(micah, fname, micahfname, dirgraph); Statement st6 = vf.createStatement(micah, lname, micahlname, dirgraph); Statement st7 = vf.createStatement(micah, homeTel, micahhomeTel, dirgraph); Statement st8 = vf.createStatement(fei, fname, feifname, dirgraph); Statement st9 = vf.createStatement(fei, lname, feilname, dirgraph); Statement st10 = vf.createStatement(fei, email, feiemail, dirgraph); testAdminCon.add(st1, dirgraph); testAdminCon.add(st2, dirgraph); testAdminCon.add(st3, dirgraph); testAdminCon.add(st4, dirgraph); testAdminCon.add(st5, dirgraph); testAdminCon.add(st6, dirgraph); testAdminCon.add(st7, dirgraph); testAdminCon.add(st8, dirgraph); testAdminCon.add(st9, dirgraph); testAdminCon.add(st10, dirgraph); Assert.assertEquals(10, testAdminCon.size(dirgraph)); StringBuilder queryBuilder = new StringBuilder(); queryBuilder.append("PREFIX ad: <http://marklogicsparql.com/addressbook#>"); queryBuilder.append(" PREFIX d: <http://marklogicsparql.com/id#>"); queryBuilder.append(" SELECT DISTINCT ?person"); queryBuilder.append(" FROM <http://marklogic.com/dirgraph>"); queryBuilder.append(" WHERE"); queryBuilder.append(" {?person ad:firstName ?firstname ;"); queryBuilder.append(" ad:lastName ?lastname."); queryBuilder.append(" OPTIONAL {?person ad:homeTel ?phonenumber .}"); queryBuilder.append(" FILTER (?firstname = \"Fei\")}"); TupleQuery query = testAdminCon.prepareTupleQuery(QueryLanguage.SPARQL, queryBuilder.toString()); TupleQueryResult result = query.evaluate(); try { assertThat(result, is(notNullValue())); assertThat(result.hasNext(), is(equalTo(true))); while (result.hasNext()) { BindingSet solution = result.next(); assertThat(solution.hasBinding("person"), is(equalTo(true))); Value nameResult = solution.getValue("person"); Assert.assertEquals(nameResult.stringValue(),fei.stringValue()); } } finally { result.close(); } } @Test public void testPrepareTupleQuery2() throws Exception{ testAdminCon.add(john, fname, johnfname, dirgraph); testAdminCon.add(john, lname, johnlname, dirgraph); testAdminCon.add(john, homeTel, johnhomeTel, dirgraph); testAdminCon.add(john, email, johnemail, dirgraph); testAdminCon.add(micah, fname, micahfname, dirgraph); testAdminCon.add(micah, lname, micahlname, dirgraph); testAdminCon.add(micah, homeTel, micahhomeTel, dirgraph); testAdminCon.add(fei, fname, feifname, dirgraph); testAdminCon.add(fei, lname, feilname, dirgraph); testAdminCon.add(fei, email, feiemail, dirgraph); try{ Assert.assertEquals(10, testAdminCon.size(dirgraph)); } catch(Exception ex){ logger.error("Failed :", ex); } StringBuilder queryBuilder = new StringBuilder(); queryBuilder.append("PREFIX ad: <http://marklogicsparql.com/addressbook#>"); queryBuilder.append(" PREFIX d: <http://marklogicsparql.com/id#>"); queryBuilder.append(" SELECT ?person ?lastname"); queryBuilder.append(" WHERE"); queryBuilder.append(" {?person <#firstName> ?firstname ;"); queryBuilder.append(" <#lastName> ?lastname."); queryBuilder.append(" OPTIONAL {?person <#email> ?email.}"); queryBuilder.append(" FILTER EXISTS {?person <#homeTel> ?tel .}} ORDER BY ?lastname"); TupleQuery query = testAdminCon.prepareTupleQuery(QueryLanguage.SPARQL, queryBuilder.toString(),"http://marklogicsparql.com/addressbook"); TupleQueryResult result = query.evaluate(); String [] expectedPersonresult = {micah.stringValue(), john.stringValue()}; String [] expectedLnameresult = {micahlname.stringValue(), johnlname.stringValue()}; int i = 0; try { assertThat(result, is(notNullValue())); Assert.assertTrue(result.hasNext()); while (result.hasNext()) { BindingSet solution = result.next(); assertThat(solution.hasBinding("person"), is(equalTo(true))); assertThat(solution.hasBinding("lastname"), is(equalTo(true))); Value personResult = solution.getValue("person"); Value nameResult = solution.getValue("lastname"); Assert.assertEquals(personResult.stringValue(),expectedPersonresult[i]); Assert.assertEquals(nameResult.stringValue(),expectedLnameresult[i]); i++; } } finally { result.close(); } } @Test public void testPrepareTupleQuery3() throws Exception{ Statement st1 = vf.createStatement(john, fname, johnfname); Statement st2 = vf.createStatement(john, lname, johnlname); Statement st3 = vf.createStatement(john, homeTel, johnhomeTel); Statement st4 = vf.createStatement(john, email, johnemail); Statement st5 = vf.createStatement(micah, fname, micahfname); Statement st6 = vf.createStatement(micah, lname, micahlname); Statement st7 = vf.createStatement(micah, homeTel, micahhomeTel); Statement st8 = vf.createStatement(fei, fname, feifname); Statement st9 = vf.createStatement(fei, lname, feilname); Statement st10 = vf.createStatement(fei, email, feiemail); testAdminCon.add(st1, dirgraph); testAdminCon.add(st2, dirgraph); testAdminCon.add(st3, dirgraph); testAdminCon.add(st4, dirgraph); testAdminCon.add(st5, dirgraph); testAdminCon.add(st6, dirgraph); testAdminCon.add(st7, dirgraph); testAdminCon.add(st8, dirgraph); testAdminCon.add(st9, dirgraph); testAdminCon.add(st10, dirgraph); try{ Assert.assertEquals(10, testAdminCon.size(dirgraph)); } catch(Exception ex){ logger.error("Failed :", ex); } StringBuilder queryBuilder = new StringBuilder(); queryBuilder.append(" PREFIX ad: <http://marklogicsparql.com/addressbook#> "); queryBuilder.append(" SELECT ?name ?id ?g "); queryBuilder.append(" FROM NAMED "); queryBuilder.append("<").append(dirgraph.stringValue()).append(">"); queryBuilder.append(" WHERE "); queryBuilder.append(" { "); queryBuilder.append(" GRAPH ?g { ?id ad:lastName ?name .} "); queryBuilder.append(" FILTER EXISTS { GRAPH ?g {?id ad:email ?email ; "); queryBuilder.append(" ad:firstName ?fname.}"); queryBuilder.append(" } "); queryBuilder.append(" } "); queryBuilder.append(" ORDER BY ?name "); TupleQuery query = testAdminCon.prepareTupleQuery(queryBuilder.toString()); TupleQueryResult result = query.evaluate(); String [] epectedPersonresult = {fei.stringValue(), john.stringValue()}; String [] expectedLnameresult = {feilname.stringValue(), johnlname.stringValue()}; String [] expectedGraphresult = {dirgraph.stringValue(), dirgraph.stringValue()}; int i = 0; try { assertThat(result, is(notNullValue())); Assert.assertTrue(result.hasNext()); while (result.hasNext()) { BindingSet solution = result.next(); assertThat(solution.hasBinding("name"), is(equalTo(true))); assertThat(solution.hasBinding("id"), is(equalTo(true))); assertThat(solution.hasBinding("g"), is(equalTo(true))); Value idResult = solution.getValue("id"); Value nameResult = solution.getValue("name"); Value graphResult = solution.getValue("g"); Assert.assertEquals(idResult.stringValue(),epectedPersonresult[i]); Assert.assertEquals(nameResult.stringValue(),expectedLnameresult[i]); Assert.assertEquals(graphResult.stringValue(),expectedGraphresult[i]); i++; } } finally { result.close(); } } // ISSSUE 109 @Test public void testPrepareTupleQuery4() throws Exception{ Statement st1 = vf.createStatement(john, fname, johnfname, dirgraph); Statement st2 = vf.createStatement(john, lname, johnlname, dirgraph); Statement st3 = vf.createStatement(john, homeTel, johnhomeTel, dirgraph); Statement st4 = vf.createStatement(john, email, johnemail, dirgraph); Statement st5 = vf.createStatement(micah, fname, micahfname, dirgraph); Statement st6 = vf.createStatement(micah, lname, micahlname, dirgraph); Statement st7 = vf.createStatement(micah, homeTel, micahhomeTel, dirgraph); Statement st8 = vf.createStatement(fei, fname, feifname, dirgraph); Statement st9 = vf.createStatement(fei, lname, feilname, dirgraph); Statement st10 = vf.createStatement(fei, email, feiemail, dirgraph); testAdminCon.add(st1); testAdminCon.add(st2); testAdminCon.add(st3); testAdminCon.add(st4); testAdminCon.add(st5); testAdminCon.add(st6); testAdminCon.add(st7); testAdminCon.add(st8); testAdminCon.add(st9); testAdminCon.add(st10); try{ Assert.assertEquals(10, testAdminCon.size(dirgraph)); } catch(Exception ex){ logger.error("Failed :", ex); } StringBuilder queryBuilder = new StringBuilder(64); queryBuilder.append("PREFIX ad: <http://marklogicsparql.com/addressbook#> "); queryBuilder.append(" SELECT ?person ?firstname ?lastname ?phonenumber"); queryBuilder.append(" FROM <").append(dirgraph.stringValue()).append(">"); queryBuilder.append(" WHERE"); queryBuilder.append(" { "); queryBuilder.append(" ?person <#firstName> ?firstname ;"); queryBuilder.append(" <#lastName> ?lastname. "); queryBuilder.append(" OPTIONAL {?person <#homeTel> ?phonenumber .} "); queryBuilder.append(" VALUES ?firstname { \"Micah\" \"Fei\" }"); queryBuilder.append(" } "); queryBuilder.append(" ORDER BY ?firstname"); TupleQuery query = testAdminCon.prepareTupleQuery(queryBuilder.toString(),"http://marklogicsparql.com/addressbook"); TupleQueryResult result = query.evaluate(); String [] epectedPersonresult = {"http://marklogicsparql.com/id#3333", "http://marklogicsparql.com/id#2222"}; String [] expectedLnameresult = {"Ling", "Dubinko"}; String [] expectedFnameresult = {"Fei", "Micah"}; int i = 0; try { assertThat(result, is(notNullValue())); Assert.assertTrue(result.hasNext()); while (result.hasNext()) { BindingSet solution = result.next(); assertThat(solution.hasBinding("person"), is(equalTo(true))); assertThat(solution.hasBinding("lastname"), is(equalTo(true))); Value personResult = solution.getValue("person"); Value lnameResult = solution.getValue("lastname"); Value fnameResult = solution.getValue("firstname"); Literal phoneResult = (Literal) solution.getValue("phonenumber"); Assert.assertEquals(epectedPersonresult[i], personResult.stringValue()); Assert.assertEquals(expectedLnameresult[i], lnameResult.stringValue()); Assert.assertEquals(expectedFnameresult[i], fnameResult.stringValue()); try{ assertThat(phoneResult.doubleValue(), is(equalTo(new Double(22222222D)))); } catch(NullPointerException e){ } i++; } } finally { result.close(); } } // ISSUE 197 @Test public void testPrepareTupleQuerywithBidings() throws Exception{ Statement st1 = vf.createStatement(john, fname, johnfname, dirgraph); Statement st2 = vf.createStatement(john, lname, johnlname, dirgraph); Statement st3 = vf.createStatement(john, homeTel, johnhomeTel, dirgraph); Statement st4 = vf.createStatement(john, email, johnemail, dirgraph); Statement st5 = vf.createStatement(micah, fname, micahfname, dirgraph); Statement st6 = vf.createStatement(micah, lname, micahlname, dirgraph); Statement st7 = vf.createStatement(micah, homeTel, micahhomeTel, dirgraph); Statement st8 = vf.createStatement(fei, fname, feifname, dirgraph); Statement st9 = vf.createStatement(fei, lname, feilname, dirgraph); Statement st10 = vf.createStatement(fei, email, feiemail, dirgraph); testAdminCon.add(st1); testAdminCon.add(st2); testAdminCon.add(st3); testAdminCon.add(st4); testAdminCon.add(st5); testAdminCon.add(st6); testAdminCon.add(st7); testAdminCon.add(st8); testAdminCon.add(st9); testAdminCon.add(st10); try{ Assert.assertEquals(10, testAdminCon.size(dirgraph)); } catch(Exception ex){ logger.error("Failed :", ex); } StringBuilder queryBuilder = new StringBuilder(64); queryBuilder.append(" SELECT ?person ?firstname ?lastname ?phonenumber"); queryBuilder.append(" FROM <").append(dirgraph.stringValue()).append(">"); queryBuilder.append(" WHERE"); queryBuilder.append(" { "); queryBuilder.append(" ?person <#firstName> ?firstname ;"); queryBuilder.append(" <#lastName> ?lastname ; "); queryBuilder.append(" <#homeTel> ?phonenumber .} "); queryBuilder.append(" ORDER BY ?lastname"); TupleQuery query = testAdminCon.prepareTupleQuery(queryBuilder.toString(),"http://marklogicsparql.com/addressbook"); query.setBinding("firstname", vf.createLiteral("Micah")); TupleQueryResult result = query.evaluate(); String [] epectedPersonresult = {"http://marklogicsparql.com/id#2222"}; String [] expectedLnameresult = {"Dubinko"}; String [] expectedFnameresult = {"Micah"}; int i = 0; try { assertThat(result, is(notNullValue())); Assert.assertTrue(result.hasNext()); while (result.hasNext()) { BindingSet solution = result.next(); assertThat(solution.hasBinding("person"), is(equalTo(true))); assertThat(solution.hasBinding("lastname"), is(equalTo(true))); Value personResult = solution.getValue("person"); Value lnameResult = solution.getValue("lastname"); Value fnameResult = solution.getValue("firstname"); Literal phoneResult = (Literal) solution.getValue("phonenumber"); Assert.assertEquals(epectedPersonresult[i], personResult.stringValue()); Assert.assertEquals(expectedLnameresult[i], lnameResult.stringValue()); Assert.assertEquals(expectedFnameresult[i], fnameResult.stringValue()); assertThat(phoneResult.doubleValue(), is(equalTo(new Double(22222222D)))); i++; } } finally { result.close(); } } @Test public void testPrepareTupleQueryEmptyResult() throws Exception{ Statement st1 = vf.createStatement(john, fname, johnfname, dirgraph); Statement st2 = vf.createStatement(john, homeTel, johnhomeTel, dirgraph); Statement st3 = vf.createStatement(micah, fname, micahfname, dirgraph); Statement st4 = vf.createStatement(micah, homeTel, micahhomeTel, dirgraph); testAdminCon.add(st1); testAdminCon.add(st2); testAdminCon.add(st3); testAdminCon.add(st4); try{ Assert.assertEquals(4, testAdminCon.size(dirgraph)); } catch(Exception ex){ logger.error("Failed :", ex); } StringBuilder queryBuilder = new StringBuilder(64); queryBuilder.append("PREFIX ad: <http://marklogicsparql.com/addressbook#> "); queryBuilder.append(" SELECT ?person ?p ?o"); queryBuilder.append(" FROM <").append(dirgraph.stringValue()).append(">"); queryBuilder.append(" WHERE"); queryBuilder.append(" { "); queryBuilder.append(" ?person <#firstName> ?firstname ;"); queryBuilder.append(" <#lastName> ?lastname. "); queryBuilder.append(" OPTIONAL {?person <#homeTel> ?phonenumber .} "); queryBuilder.append(" FILTER NOT EXISTS {?person ?p ?o .}"); queryBuilder.append(" } "); queryBuilder.append(" ORDER BY ?person"); TupleQuery query = testAdminCon.prepareTupleQuery(queryBuilder.toString(),"http://marklogicsparql.com/addressbook"); TupleQueryResult result = query.evaluate(); assertThat(result, is(notNullValue())); Assert.assertFalse(result.hasNext()); } // ISSUE 230 @Test public void testPrepareGraphQuery1() throws Exception { StringBuilder queryBuilder = new StringBuilder(128); queryBuilder.append(" PREFIX ad: <http://marklogicsparql.com/addressbook#>"); queryBuilder.append(" CONSTRUCT{ ?person ?p ?o .} "); queryBuilder.append(" FROM <http://marklogic.com/dirgraph>"); queryBuilder.append(" WHERE "); queryBuilder.append(" { "); queryBuilder.append(" ?person ad:firstName ?firstname ; "); queryBuilder.append(" ad:lastName ?lastname ; "); queryBuilder.append(" ?p ?o . "); queryBuilder.append(" } "); queryBuilder.append(" order by $person ?p ?o "); GraphQuery emptyQuery = testAdminCon.prepareGraphQuery(QueryLanguage.SPARQL, queryBuilder.toString()); emptyQuery.setBinding("firstname", vf.createLiteral("Micah")); GraphQueryResult emptyResult = emptyQuery.evaluate(); assertThat(emptyResult.hasNext(), is(equalTo(false))); Statement st1 = vf.createStatement(john, fname, johnfname, dirgraph); Statement st2 = vf.createStatement(john, lname, johnlname, dirgraph); Statement st3 = vf.createStatement(john, homeTel, johnhomeTel, dirgraph); Statement st4 = vf.createStatement(john, email, johnemail, dirgraph); Statement st5 = vf.createStatement(micah, fname, micahfname, dirgraph); Statement st6 = vf.createStatement(micah, lname, micahlname, dirgraph); Statement st7 = vf.createStatement(micah, homeTel, micahhomeTel, dirgraph); Statement st8 = vf.createStatement(fei, fname, feifname, dirgraph); Statement st9 = vf.createStatement(fei, lname, feilname, dirgraph); Statement st10 = vf.createStatement(fei, email, feiemail, dirgraph); StatementList<Statement> sL = new StatementList<Statement>(st1); sL.add(st2); sL.add(st3); sL.add(st4); sL.add(st5); sL.add(st6); sL.add(st7); sL.add(st8); sL.add(st9); sL.add(st10); StatementIterator iter = new StatementIterator(sL); testAdminCon.add(new StatementIterable(iter), dirgraph); Assert.assertEquals(10, testAdminCon.size(dirgraph)); GraphQuery query = testAdminCon.prepareGraphQuery(QueryLanguage.SPARQL, queryBuilder.toString()); query.setBinding("firstname", vf.createLiteral("Micah")); GraphQueryResult result = query.evaluate(); Literal [] expectedObjectresult = {micahfname, micahhomeTel, micahlname}; URI [] expectedPredicateresult = {fname, homeTel, lname}; int i = 0; try { assertThat(result, is(notNullValue())); assertThat(result.hasNext(), is(equalTo(true))); while (result.hasNext()) { Statement st = result.next(); URI subject = (URI) st.getSubject(); Assert.assertEquals(subject, micah); URI predicate = st.getPredicate(); Assert.assertEquals(predicate, expectedPredicateresult[i]); Value object = st.getObject(); Assert.assertEquals(object, expectedObjectresult[i]); i++; } } finally { result.close(); } StringBuilder qB = new StringBuilder(128); qB.append(" PREFIX ad: <http://marklogicsparql.com/addressbook#>"); qB.append(" CONSTRUCT{ ?person ?p ?o .} "); qB.append(" FROM <http://marklogic.com/dirgraph>"); qB.append(" WHERE "); qB.append(" { "); qB.append(" ?person ad:firstname ?firstname ; "); qB.append(" ?p ?o . "); qB.append(" VALUES ?firstname { \"Fei\" } "); qB.append(" } "); qB.append(" order by $person ?p ?o "); GraphQuery query1 = testAdminCon.prepareGraphQuery(QueryLanguage.SPARQL, qB.toString()); GraphQueryResult result1 = query1.evaluate(); assertThat(result1, is(notNullValue())); Assert.assertFalse(result1.hasNext()); } // ISSUE 45 @Test public void testPrepareGraphQuery2() throws Exception { Statement st1 = vf.createStatement(john, fname, johnfname, dirgraph); Statement st2 = vf.createStatement(john, lname, johnlname, dirgraph); Statement st3 = vf.createStatement(john, homeTel, johnhomeTel, dirgraph); Statement st4 = vf.createStatement(john, email, johnemail, dirgraph); Statement st5 = vf.createStatement(micah, fname, micahfname, dirgraph); Statement st6 = vf.createStatement(micah, lname, micahlname, dirgraph); Statement st7 = vf.createStatement(micah, homeTel, micahhomeTel, dirgraph); Statement st8 = vf.createStatement(fei, fname, feifname, dirgraph); Statement st9 = vf.createStatement(fei, lname, feilname, dirgraph); Statement st10 = vf.createStatement(fei, email, feiemail, dirgraph); StatementList<Statement> sL = new StatementList<Statement>(st1); sL.add(st2); sL.add(st3); sL.add(st4); sL.add(st5); sL.add(st6); sL.add(st7); sL.add(st8); sL.add(st9); sL.add(st10); StatementIterator iter = new StatementIterator(sL); Iteration<Statement, Exception> it = new IteratorIteration<Statement, Exception> (iter); testAdminCon.add(it, dirgraph); Assert.assertEquals(10, testAdminCon.size(dirgraph)); StringBuilder queryBuilder = new StringBuilder(128); queryBuilder.append(" PREFIX ad: <http://marklogicsparql.com/addressbook#>"); queryBuilder.append(" PREFIX id: <http://marklogicsparql.com/id#> "); queryBuilder.append(" CONSTRUCT{ <#1111> ad:email ?e .} "); queryBuilder.append(" FROM <http://marklogic.com/dirgraph> "); queryBuilder.append(" WHERE "); queryBuilder.append(" { "); queryBuilder.append(" <#1111> ad:lastName ?o; "); queryBuilder.append(" ad:email ?e. "); queryBuilder.append(" } "); GraphQuery query = testAdminCon.prepareGraphQuery(QueryLanguage.SPARQL, queryBuilder.toString(), "http://marklogicsparql.com/id"); GraphQueryResult result = query.evaluate(); Literal [] expectedObjectresult = {johnemail}; URI [] expectedPredicateresult = {email}; int i = 0; try { assertThat(result, is(notNullValue())); while (result.hasNext()) { Statement st = result.next(); URI subject = (URI) st.getSubject(); Assert.assertEquals(subject, john); URI predicate = st.getPredicate(); Assert.assertEquals(predicate, expectedPredicateresult[i]); Value object = st.getObject(); Assert.assertEquals(object, expectedObjectresult[i]); i++; } } finally { result.close(); } } // ISSUE 44, 53, 138, 153, 257 @Test public void testPrepareGraphQuery3() throws Exception { Statement st1 = vf.createStatement(john, fname, johnfname, dirgraph); Statement st2 = vf.createStatement(john, lname, johnlname, dirgraph); Statement st3 = vf.createStatement(john, homeTel, johnhomeTel, dirgraph); Statement st4 = vf.createStatement(john, email, johnemail, dirgraph); Statement st5 = vf.createStatement(micah, fname, micahfname, dirgraph); Statement st6 = vf.createStatement(micah, lname, micahlname, dirgraph); Statement st7 = vf.createStatement(micah, homeTel, micahhomeTel, dirgraph); Statement st8 = vf.createStatement(fei, fname, feifname, dirgraph); Statement st9 = vf.createStatement(fei, lname, feilname, dirgraph); Statement st10 = vf.createStatement(fei, email, feiemail, dirgraph); testWriterCon.add(st1); testWriterCon.add(st2); testWriterCon.add(st3); testWriterCon.add(st4); testWriterCon.add(st5); testWriterCon.add(st6); testWriterCon.add(st7); testWriterCon.add(st8); testWriterCon.add(st9); testWriterCon.add(st10); Assert.assertTrue(testWriterCon.hasStatement(st1, false)); Assert.assertFalse(testWriterCon.hasStatement(st1, false, (Resource)null)); Assert.assertFalse(testWriterCon.hasStatement(st1, false, null)); Assert.assertTrue(testWriterCon.hasStatement(st1, false, dirgraph)); Assert.assertEquals(10, testAdminCon.size(dirgraph)); String query = " DESCRIBE <http://marklogicsparql.com/addressbook#firstName> "; GraphQuery queryObj = testReaderCon.prepareGraphQuery(query); GraphQueryResult result = queryObj.evaluate(); result.hasNext(); try { assertThat(result, is(notNullValue())); assertThat(result.hasNext(), is(equalTo(false))); } finally { result.close(); } } // ISSUE 46 @Test public void testPrepareGraphQuery4() throws Exception{ Statement st1 = vf.createStatement(john, fname, johnfname); Statement st2 = vf.createStatement(john, lname, johnlname); Statement st3 = vf.createStatement(john, homeTel, johnhomeTel); Statement st4 = vf.createStatement(john, email, johnemail); Statement st5 = vf.createStatement(micah, fname, micahfname); Statement st6 = vf.createStatement(micah, lname, micahlname); Statement st7 = vf.createStatement(micah, homeTel, micahhomeTel); Statement st8 = vf.createStatement(fei, fname, feifname); Statement st9 = vf.createStatement(fei, lname, feilname); Statement st10 = vf.createStatement(fei, email, feiemail); testWriterCon.add(st1,dirgraph); testWriterCon.add(st2,dirgraph); testWriterCon.add(st3,dirgraph); testWriterCon.add(st4,dirgraph); testWriterCon.add(st5,dirgraph); testWriterCon.add(st6,dirgraph); testWriterCon.add(st7,dirgraph); testWriterCon.add(st8,dirgraph); testWriterCon.add(st9,dirgraph); testWriterCon.add(st10,dirgraph); Assert.assertEquals(10, testWriterCon.size(dirgraph)); String query = " DESCRIBE <#3333> "; GraphQuery queryObj = testReaderCon.prepareGraphQuery(query, "http://marklogicsparql.com/id"); GraphQueryResult result = queryObj.evaluate(); int i = 0; try { assertThat(result, is(notNullValue())); assertThat(result.hasNext(), is(equalTo(true))); while (result.hasNext()) { Statement st = result.next(); URI subject = (URI) st.getSubject(); Assert.assertNotNull(subject); URI predicate = st.getPredicate(); Assert.assertNotNull(predicate); Value object = st.getObject(); Assert.assertNotNull(object); i++; } } finally { result.close(); } Assert.assertEquals(3, i); } //ISSUE 70 @Test public void testPrepareQuery1() throws Exception { testAdminCon.add(MarkLogicRepositoryConnectionTest.class.getResourceAsStream(TEST_DIR_PREFIX + "companies_100.ttl"), "", RDFFormat.TURTLE, null); Assert.assertEquals(testAdminCon.size(), 1600L); StringBuilder queryBuilder = new StringBuilder(128); queryBuilder.append("PREFIX demor: <http://demo/resource#>"); queryBuilder.append(" PREFIX demov: <http://demo/verb#>"); queryBuilder.append(" PREFIX vcard: <http://www.w3.org/2006/vcard/ns#>"); queryBuilder.append(" SELECT (COUNT(?company) AS ?total)"); queryBuilder.append(" WHERE { "); queryBuilder.append(" ?company a vcard:Organization ."); queryBuilder.append(" ?company demov:industry ?industry ."); queryBuilder.append(" ?company vcard:hasAddress/vcard:postal-code ?zip ."); queryBuilder.append(" ?company vcard:hasAddress/vcard:postal-code ?whatcode "); queryBuilder.append(" } "); Query query = testAdminCon.prepareQuery(QueryLanguage.SPARQL, queryBuilder.toString()); query.setBinding("whatcode", vf.createLiteral("33333")); TupleQueryResult result = null; if (query instanceof TupleQuery) { result = ((TupleQuery) query).evaluate(); } try { assertThat(result, is(notNullValue())); while (result.hasNext()) { BindingSet solution = result.next(); assertThat(solution.hasBinding("total"), is(equalTo(true))); Value totalResult = solution.getValue("total"); Assert.assertEquals(vf.createLiteral("12",XMLSchema.UNSIGNED_LONG),totalResult); } } finally { result.close(); } } // ISSUE 70 @Test public void testPrepareQuery2() throws Exception{ Reader ir = new BufferedReader(new InputStreamReader(MarkLogicRepositoryConnectionTest.class.getResourceAsStream(TEST_DIR_PREFIX + "property-paths.ttl"))); testAdminCon.add(ir, "", RDFFormat.TURTLE, null); StringBuilder queryBuilder = new StringBuilder(128); queryBuilder.append(" prefix : <http://learningsparql.com/ns/papers#> "); queryBuilder.append(" prefix c: <http://learningsparql.com/ns/citations#>"); queryBuilder.append(" SELECT ?s"); queryBuilder.append(" WHERE { "); queryBuilder.append(" ?s ^c:cites :paperK2 . "); queryBuilder.append(" FILTER (?s != :paperK2)"); queryBuilder.append(" } "); queryBuilder.append(" ORDER BY ?s "); Query query = testAdminCon.prepareQuery(queryBuilder.toString()); query.setBinding("whatcode", vf.createLiteral("33333")); TupleQueryResult result = null; if (query instanceof TupleQuery) { result = ((TupleQuery) query).evaluate(); } try { assertThat(result, is(notNullValue())); while (result.hasNext()) { BindingSet solution = result.next(); assertThat(solution.hasBinding("s"), is(equalTo(true))); Value totalResult = solution.getValue("s"); Assert.assertEquals(vf.createURI("http://learningsparql.com/ns/papers#paperJ"),totalResult); } } finally { result.close(); } } @Test public void testPrepareQuery3() throws Exception{ Statement st1 = vf.createStatement(john, fname, johnfname); Statement st2 = vf.createStatement(john, lname, johnlname); Statement st3 = vf.createStatement(john, homeTel, johnhomeTel); testWriterCon.add(st1,dirgraph); testWriterCon.add(st2,dirgraph); testWriterCon.add(st3,dirgraph); Assert.assertEquals(3, testWriterCon.size(dirgraph)); String query = " DESCRIBE <http://marklogicsparql.com/id#1111> "; Query queryObj = testReaderCon.prepareQuery(query, "http://marklogicsparql.com/id"); GraphQueryResult result = null; if (queryObj instanceof GraphQuery) { result = ((GraphQuery) queryObj).evaluate(); } Literal [] expectedObjectresult = {johnfname, johnlname, johnhomeTel}; URI [] expectedPredicateresult = {fname, lname, homeTel}; int i = 0; try { assertThat(result, is(notNullValue())); assertThat(result.hasNext(), is(equalTo(true))); while (result.hasNext()) { Statement st = result.next(); URI subject = (URI) st.getSubject(); Assert.assertEquals(subject, john); URI predicate = st.getPredicate(); Assert.assertEquals(predicate, expectedPredicateresult[i]); Value object = st.getObject(); Assert.assertEquals(object, expectedObjectresult[i]); i++; } } finally { result.close(); } } //ISSUE 70 @Test public void testPrepareQuery4() throws Exception{ URL url = MarkLogicRepositoryConnectionTest.class.getResource(TEST_DIR_PREFIX+"tigers.ttl"); testAdminCon.add(url, "", RDFFormat.TURTLE); Assert.assertEquals(107L, testAdminCon.size()); String query1 = "ASK "+ "WHERE"+ "{"+ " ?s <#position> ?o."+ "}"; Query bq = testAdminCon.prepareQuery(query1, "http://marklogic.com/baseball/players"); bq.setBinding("o", vf.createLiteral("pitcher")); boolean result1 = ((BooleanQuery)bq).evaluate(); Assert.assertTrue(result1); } //Bug 35241 @Ignore public void testPrepareMultipleBaseURI1() throws Exception{ testAdminCon.add(john, fname, johnfname, dirgraph); testAdminCon.add(john, lname, johnlname, dirgraph); testAdminCon.add(john, homeTel, johnhomeTel, dirgraph); testAdminCon.add(john, email, johnemail, dirgraph); testAdminCon.add(micah, fname, micahfname, dirgraph); testAdminCon.add(micah, lname, micahlname, dirgraph); testAdminCon.add(micah, homeTel, micahhomeTel, dirgraph); testAdminCon.add(fei, fname, feifname, dirgraph); testAdminCon.add(fei, lname, feilname, dirgraph); testAdminCon.add(fei, email, feiemail, dirgraph); try{ Assert.assertEquals(10, testAdminCon.size(dirgraph)); } catch(Exception ex){ logger.error("Failed :", ex); } StringBuilder queryBuilder = new StringBuilder(); queryBuilder.append("PREFIX ad: <http://marklogicsparql.com/addressbook#>"); queryBuilder.append(" PREFIX d: <http://marklogicsparql.com/id#>"); queryBuilder.append(" BASE <http://marklogicsparql.com/addressbook>"); queryBuilder.append(" BASE <http://marklogicsparql.com/id>"); queryBuilder.append(" SELECT ?person ?lastname"); queryBuilder.append(" WHERE"); queryBuilder.append(" {?person <#firstName> ?firstname ;"); queryBuilder.append(" <#lastName> ?lastname."); queryBuilder.append(" OPTIONAL {<#1111> <#email> ?email.}"); queryBuilder.append(" FILTER EXISTS {?person <#homeTel> ?tel .}} ORDER BY ?lastname"); TupleQuery query = testAdminCon.prepareTupleQuery(QueryLanguage.SPARQL, queryBuilder.toString()); TupleQueryResult result = query.evaluate(); String [] expectedPersonresult = {micah.stringValue(), john.stringValue()}; String [] expectedLnameresult = {micahlname.stringValue(), johnlname.stringValue()}; int i = 0; try { assertThat(result, is(notNullValue())); Assert.assertTrue(result.hasNext()); while (result.hasNext()) { BindingSet solution = result.next(); assertThat(solution.hasBinding("person"), is(equalTo(true))); assertThat(solution.hasBinding("lastname"), is(equalTo(true))); Value personResult = solution.getValue("person"); Value nameResult = solution.getValue("lastname"); Assert.assertEquals(personResult.stringValue(),expectedPersonresult[i]); Assert.assertEquals(nameResult.stringValue(),expectedLnameresult[i]); i++; } } finally { result.close(); } } // ISSUE 106, 133, 183 @Test public void testCommit() throws Exception { try{ testAdminCon.begin(); testAdminCon.add(john, email, johnemail,dirgraph); assertTrue("Uncommitted update should be visible to own connection", testAdminCon.hasStatement(john, email, johnemail, false, dirgraph)); assertFalse("Uncommitted update should only be visible to own connection", testReaderCon.hasStatement(john, email, johnemail, false, dirgraph)); assertThat(testWriterCon.size(), is(equalTo(0L))); testAdminCon.commit(); } catch(Exception e){ logger.debug(e.getMessage()); } finally{ if(testAdminCon.isActive()) testAdminCon.rollback(); } assertThat(testWriterCon.size(), is(equalTo(1L))); assertTrue("Repository should contain statement after commit", testAdminCon.hasStatement(john, email, johnemail, false, dirgraph)); assertTrue("Committed update will be visible to all connection", testReaderCon.hasStatement(john, email, johnemail, false, dirgraph)); } // ISSUE 183 @Test public void testSizeRollback() throws Exception { testAdminCon.setIsolationLevel(IsolationLevels.SNAPSHOT); assertThat(testAdminCon.size(), is(equalTo(0L))); assertThat(testWriterCon.size(), is(equalTo(0L))); try{ testAdminCon.begin(); testAdminCon.add(john, fname, johnfname,dirgraph); assertThat(testAdminCon.size(), is(equalTo(1L))); assertThat(testWriterCon.size(), is(equalTo(0L))); testAdminCon.add(john, fname, feifname); assertThat(testAdminCon.size(), is(equalTo(2L))); assertThat(testWriterCon.size(), is(equalTo(0L))); testAdminCon.rollback(); } catch (Exception e){ } finally{ if (testAdminCon.isActive()) testAdminCon.rollback(); } assertThat(testAdminCon.size(), is(equalTo(0L))); assertThat(testWriterCon.size(), is(equalTo(0L))); } // ISSUE 133, 183 @Test public void testSizeCommit() throws Exception { testAdminCon.setIsolationLevel(IsolationLevels.SNAPSHOT); assertThat(testAdminCon.size(), is(equalTo(0L))); assertThat(testWriterCon.size(), is(equalTo(0L))); try{ testAdminCon.begin(); testAdminCon.add(john, fname, johnfname,dirgraph); assertThat(testAdminCon.size(), is(equalTo(1L))); assertThat(testWriterCon.size(), is(equalTo(0L))); testAdminCon.add(john, fname, feifname); assertThat(testAdminCon.size(), is(equalTo(2L))); assertThat(testWriterCon.size(), is(equalTo(0L))); testAdminCon.commit(); } catch (Exception e){ } finally{ if (testAdminCon.isActive()) testAdminCon.rollback(); } assertThat(testAdminCon.size(), is(equalTo(2L))); assertThat(testWriterCon.size(), is(equalTo(2L))); } //ISSUE 121, 174 @Test public void testTransaction() throws Exception{ testAdminCon.begin(); testAdminCon.commit(); try{ testAdminCon.commit(); Assert.assertFalse("Exception was not thrown, when it should have been", 1<2); } catch (Exception e){ Assert.assertTrue(e instanceof MarkLogicTransactionException); } finally{ if (testAdminCon.isActive()) testAdminCon.rollback(); } try{ testAdminCon.rollback(); Assert.assertFalse("Exception was not thrown, when it should have been", 1<2); } catch (Exception e2){ Assert.assertTrue(e2 instanceof MarkLogicTransactionException); } finally{ if (testAdminCon.isActive()) testAdminCon.rollback(); } testAdminCon.begin(); testAdminCon.prepareUpdate(QueryLanguage.SPARQL, "DELETE DATA {GRAPH <" + dirgraph.stringValue()+ "> { <" + micah.stringValue() + "> <" + homeTel.stringValue() + "> \"" + micahhomeTel.doubleValue() + "\"^^<http://www.w3.org/2001/XMLSchema#double>} }").execute(); testAdminCon.commit(); Assert.assertTrue(testAdminCon.size()==0); try{ testAdminCon.begin(); testAdminCon.begin(); Assert.assertFalse("Exception was not thrown, when it should have been", 1<2); } catch (Exception e){ Assert.assertTrue(e instanceof MarkLogicTransactionException); } finally{ if (testAdminCon.isActive()) testAdminCon.rollback(); } } // ISSUE 123, 122, 175, 185 @Test public void testGraphPerms1() throws Exception { GraphManager gmgr = databaseClient.newGraphManager(); createUserRolesWithPrevilages("test-role"); GraphPermissions gr = testAdminCon.getDefaultGraphPerms(); // ISSUE # 175 uncomment after issue is fixed Assert.assertEquals(0L, gr.size()); testAdminCon.setDefaultGraphPerms(gmgr.permission("test-role", Capability.READ, Capability.UPDATE)); String defGraphQuery = "CREATE GRAPH <http://marklogic.com/test/graph/permstest> "; MarkLogicUpdateQuery updateQuery = testAdminCon.prepareUpdate(QueryLanguage.SPARQL, defGraphQuery); updateQuery.execute(); String defGraphQuery1 = "INSERT DATA { GRAPH <http://marklogic.com/test/graph/permstest> { <http://marklogic.com/test1> <pp2> \"test\" } }"; String checkQuery = "ASK WHERE { GRAPH <http://marklogic.com/test/graph/permstest> {<http://marklogic.com/test> <pp2> \"test\" }}"; MarkLogicUpdateQuery updateQuery1 = testAdminCon.prepareUpdate(QueryLanguage.SPARQL, defGraphQuery1); updateQuery1.execute(); BooleanQuery booleanQuery = testAdminCon.prepareBooleanQuery(QueryLanguage.SPARQL, checkQuery); boolean results = booleanQuery.evaluate(); Assert.assertEquals(false, results); gr = testAdminCon.getDefaultGraphPerms(); Assert.assertEquals(1L, gr.size()); Iterator<Entry<String, Set<Capability>>> resultPerm = gr.entrySet().iterator(); while(resultPerm.hasNext()){ Entry<String, Set<Capability>> perms = resultPerm.next(); Assert.assertTrue("test-role" == perms.getKey()); Iterator<Capability> capability = perms.getValue().iterator(); while (capability.hasNext()) assertThat(capability.next().toString(), anyOf(equalTo("UPDATE"), is(equalTo("READ")))); } String defGraphQuery2 = "CREATE GRAPH <http://marklogic.com/test/graph/permstest1> "; testAdminCon.setDefaultGraphPerms(null); updateQuery = testAdminCon.prepareUpdate(QueryLanguage.SPARQL, defGraphQuery2); updateQuery.execute(); gr = testAdminCon.getDefaultGraphPerms(); Assert.assertEquals(0L, gr.size()); createUserRolesWithPrevilages("multitest-role"); testAdminCon.setDefaultGraphPerms(gmgr.permission("multitest-role", Capability.READ).permission("test-role", Capability.UPDATE)); defGraphQuery = "CREATE GRAPH <http://marklogic.com/test/graph/permstest2> "; updateQuery = testAdminCon.prepareUpdate(QueryLanguage.SPARQL, defGraphQuery); updateQuery.execute(); gr = testAdminCon.getDefaultGraphPerms(); Assert.assertEquals(2L, gr.size()); testAdminCon.setDefaultGraphPerms(null); testAdminCon.setDefaultGraphPerms(null); // ISSUE 180 //testAdminCon.setDefaultGraphPerms((GraphPermissions)null); gr = testAdminCon.getDefaultGraphPerms(); Assert.assertEquals(0L, gr.size()); } //ISSUE 108 @Test public void testAddDelete() throws OpenRDFException { final Statement st1 = vf.createStatement(john, fname, johnfname); testWriterCon.begin(); testWriterCon.add(st1); testWriterCon.prepareUpdate(QueryLanguage.SPARQL, "DELETE DATA {<" + john.stringValue() + "> <" + fname.stringValue() + "> \"" + johnfname.stringValue() + "\"}").execute(); testWriterCon.commit(); testWriterCon.exportStatements(null, null, null, false, new RDFHandlerBase() { @Override public void handleStatement(Statement st) throws RDFHandlerException { assertThat(st, is(not(equalTo(st1)))); } }); } //ISSUE 108, 250 @Test public final void testInsertRemove() throws OpenRDFException { Statement st = null; try{ testAdminCon.begin(); testAdminCon.prepareUpdate( "INSERT DATA {GRAPH <" + dirgraph.stringValue()+"> { <" + john.stringValue() + "> <" + homeTel.stringValue() + "> \"" + johnhomeTel.doubleValue() + "\"^^<http://www.w3.org/2001/XMLSchema#double>}}").execute(); RepositoryResult<Statement> result = testAdminCon.getStatements(null, null, null, false); try { assertNotNull("Iterator should not be null", result); assertTrue("Iterator should not be empty", result.hasNext()); Assert.assertEquals("There should be only one statement in repository",1L, testAdminCon.size()); while (result.hasNext()) { st = result.next(); assertNotNull("Statement should not be in a context ", st.getContext()); assertTrue("Statement predicate should be equal to homeTel ", st.getPredicate().equals(homeTel)); } } finally { result.close(); } testAdminCon.remove(st,dirgraph); testAdminCon.commit(); } catch(Exception e){ } finally{ if (testAdminCon.isActive()) testAdminCon.rollback(); } Assert.assertEquals(0L, testAdminCon.size()); testAdminCon.exportStatements(null, null, null, false, new RDFHandlerBase() { @Override public void handleStatement(Statement st1) throws RDFHandlerException { assertThat(st1, is((equalTo(null)))); } },dirgraph); } //ISSUE 108, 45 @Test public void testInsertDeleteInsertWhere() throws Exception { Assert.assertEquals(0L, testAdminCon.size()); final Statement st1 = vf.createStatement(john, email, johnemail, dirgraph); final Statement st2 = vf.createStatement(john, lname, johnlname); testAdminCon.add(st1); testAdminCon.add(st2,dirgraph); try{ testAdminCon.begin(); testAdminCon.prepareUpdate(QueryLanguage.SPARQL, "INSERT DATA {GRAPH <" + dirgraph.stringValue()+ "> { <" + john.stringValue() + "> <" + fname.stringValue() + "> \"" + johnfname.stringValue() + "\"} }").execute(); testAdminCon.prepareUpdate( "DELETE DATA {GRAPH <" + dirgraph.stringValue()+ "> { <" + john.stringValue() + "> <" + email.stringValue() + "> \"" + johnemail.stringValue() + "\"} }").execute(); String query1 ="PREFIX ad: <http://marklogicsparql.com/addressbook#>" +" INSERT {GRAPH <" + dirgraph.stringValue() + "> { <#1111> ad:email \"[email protected]\"}}" + " where { GRAPH <"+ dirgraph.stringValue()+">{<#1111> ad:lastName ?name .} } " ; testAdminCon.prepareUpdate(QueryLanguage.SPARQL,query1, "http://marklogicsparql.com/id").execute(); testAdminCon.commit(); } catch(Exception e){ logger.debug(e.getMessage()); } finally{ if(testAdminCon.isActive()) testAdminCon.rollback(); } final Statement expSt = vf.createStatement(john, email, vf.createLiteral("[email protected]")); Assert.assertEquals("Dirgraph's size must be 3",3L, testAdminCon.size(dirgraph)); testAdminCon.exportStatements(null, email, null, false, new RDFHandlerBase() { @Override public void handleStatement(Statement st) throws RDFHandlerException { assertThat(st, equalTo(expSt)); } }, dirgraph); } @Test public void testAddRemoveAdd() throws OpenRDFException { Statement st = vf.createStatement(john, lname, johnlname, dirgraph); testAdminCon.add(st); Assert.assertEquals(1L, testAdminCon.size()); testAdminCon.begin(); testAdminCon.remove(st, dirgraph); testAdminCon.add(st); testAdminCon.commit(); Assert.assertFalse(testAdminCon.isEmpty()); } @Test public void testAddDeleteAdd() throws OpenRDFException { Statement stmt = vf.createStatement(micah, homeTel, micahhomeTel, dirgraph); testAdminCon.add(stmt); testAdminCon.begin(); testAdminCon.prepareUpdate(QueryLanguage.SPARQL, "DELETE DATA {GRAPH <" + dirgraph.stringValue()+ "> { <" + micah.stringValue() + "> <" + homeTel.stringValue() + "> \"" + micahhomeTel.doubleValue() + "\"^^<http://www.w3.org/2001/XMLSchema#double>} }").execute(); Assert.assertTrue(testAdminCon.isEmpty()); testAdminCon.add(stmt); testAdminCon.commit(); Assert.assertFalse(testAdminCon.isEmpty()); } // ISSUE 133 @Test public void testAddRemoveInsert() throws OpenRDFException { Statement stmt = vf.createStatement(micah, homeTel, micahhomeTel); testAdminCon.add(stmt); try{ testAdminCon.begin(); testAdminCon.remove(stmt); Assert.assertEquals("The size of repository must be zero",0, testAdminCon.size()); testAdminCon.prepareUpdate( "INSERT DATA "+" { <" + micah.stringValue() + "> <#homeTel> \"" + micahhomeTel.doubleValue() + "\"^^<http://www.w3.org/2001/XMLSchema#double>} ","http://marklogicsparql.com/addressbook").execute(); testAdminCon.commit(); } catch (Exception e){ if (testAdminCon.isActive()) testAdminCon.rollback(); Assert.assertTrue("Failed within transaction", 1>2); } finally{ if (testAdminCon.isActive()) testAdminCon.rollback(); } Assert.assertFalse(testAdminCon.isEmpty()); Assert.assertEquals(1L, testAdminCon.size()); } // ISSSUE 106, 133 @Test public void testAddDeleteInsertWhere() throws OpenRDFException { testAdminCon.add(fei,lname,feilname); testAdminCon.add(fei, email, feiemail); try{ testAdminCon.begin(); testAdminCon.prepareUpdate( " DELETE { <" + fei.stringValue() + "> <#email> \"" + feiemail.stringValue() + "\"} "+ " INSERT { <" + fei.stringValue() + "> <#email> \"[email protected]\"} where{ ?s <#email> ?o}" ,"http://marklogicsparql.com/addressbook").execute(); Assert.assertTrue("The value of email should be updated", testAdminCon.hasStatement(vf.createStatement(fei, email, vf.createLiteral("[email protected]")), false)); testAdminCon.commit(); } catch(Exception e){ } finally{ if(testAdminCon.isActive()) testAdminCon.rollback(); } Assert.assertTrue(testAdminCon.hasStatement(vf.createStatement(fei, email, vf.createLiteral("[email protected]")), false)); Assert.assertFalse(testAdminCon.isEmpty()); } @Test public void testGraphOps() throws Exception { URI gr1 = vf.createURI("http://marklogic.com"); URI gr2 = vf.createURI("http://ml.com"); testAdminCon.add(fei,lname,feilname); testAdminCon.add(fei, email, feiemail); try{ testAdminCon.begin(); testAdminCon.prepareUpdate( " CREATE GRAPH <http://marklogic.com> ").execute(); testAdminCon.prepareUpdate( " CREATE GRAPH <http://ml.com> ").execute(); Assert.assertTrue("The graph should be empty", (testAdminCon.size(gr1) == 0)); Assert.assertTrue("The graph should be empty", (testAdminCon.size(gr2) == 0)); testAdminCon.commit(); } catch(Exception e){ } finally{ if(testAdminCon.isActive()) testAdminCon.rollback(); } testAdminCon.prepareUpdate( " COPY DEFAULT TO <http://marklogic.com> ").execute(); Assert.assertFalse(testAdminCon.isEmpty()); Assert.assertTrue("The graph gr1 should not be empty", (testAdminCon.size(gr1) == 2)); testWriterCon.prepareUpdate( " MOVE DEFAULT TO <http://ml.com> ").execute(); Assert.assertFalse(testWriterCon.isEmpty()); Assert.assertTrue("The graph gr2 should not be empty", (testWriterCon.size(gr2) == 2)); Assert.assertTrue("The graph gr2 should not be empty", (testAdminCon.size(gr2) == 2)); Assert.assertTrue("The default graph should be empty", (testAdminCon.size(null) == 0)); testWriterCon.prepareUpdate( " DROP GRAPH <http://ml.com> ").execute(); testWriterCon.prepareUpdate( " DROP GRAPH <http://marklogic.com> ").execute(); Assert.assertTrue("The default graph should be empty", (testAdminCon.size() == 0)); } @Test public void testAddDifferentFormats() throws Exception { testAdminCon.add(MarkLogicRepositoryConnectionTest.class.getResourceAsStream(TEST_DIR_PREFIX + "journal.nt"), "", RDFFormat.NTRIPLES, dirgraph); Assert.assertEquals(36L,testAdminCon.size()); testAdminCon.clear(); testAdminCon.add(new InputStreamReader(MarkLogicRepositoryConnectionTest.class.getResourceAsStream(TEST_DIR_PREFIX + "little.nq")), "", RDFFormat.NQUADS); Assert.assertEquals( 9L,testAdminCon.size()); testAdminCon.clear(); URL url = MarkLogicRepositoryConnectionTest.class.getResource(TEST_DIR_PREFIX+"semantics.trig"); testAdminCon.add(url, "",RDFFormat.TRIG); Assert.assertEquals(15L,testAdminCon.size()); testAdminCon.clear(); File file = new File(MarkLogicRepositoryConnectionTest.class.getResource(TEST_DIR_PREFIX+ "dir.json").getFile()); testAdminCon.add(file, "", RDFFormat.RDFJSON); Assert.assertEquals(12L, testAdminCon.size()); testAdminCon.clear(); Reader fr = new FileReader(new File(MarkLogicRepositoryConnectionTest.class.getResource(TEST_DIR_PREFIX+ "dir.xml").getFile())); testAdminCon.add(fr, "", RDFFormat.RDFXML); Assert.assertEquals(12L, testAdminCon.size()); testAdminCon.clear(); } //ISSUE 110 @Test public void testOpen() throws Exception { Statement stmt = vf.createStatement(micah, homeTel, micahhomeTel, dirgraph); try{ testAdminCon.begin(); assertThat("testAdminCon should be open",testAdminCon.isOpen(), is(equalTo(true))); assertThat("testWriterCon should be open",testWriterCon.isOpen(), is(equalTo(true))); testAdminCon.add(stmt); testAdminCon.commit(); } catch(Exception e){ } finally{ if(testAdminCon.isActive()) testAdminCon.rollback(); } testAdminCon.remove(stmt, dirgraph); testAdminCon.close(); Assert.assertFalse(testAdminCon.hasStatement(stmt, false, dirgraph)); try{ testAdminCon.add(stmt); fail("Adding triples after close should not be allowed"); } catch(Exception e){ Assert.assertTrue(e instanceof RepositoryException); } Assert.assertEquals("testAdminCon size should be zero",testAdminCon.size(),0); assertThat("testAdminCon should not be open",testAdminCon.isOpen(), is(equalTo(false))); assertThat("testWriterCon should be open",testWriterCon.isOpen(), is(equalTo(true))); testAdminRepository.shutDown(); testAdminRepository = null; testAdminCon = null; setUp(); assertThat(testAdminCon.isOpen(), is(equalTo(true))); } // ISSUE 126, 33 @Test public void testClear() throws Exception { testAdminCon.add(john, fname, johnfname,dirgraph); testAdminCon.add(john, fname, feifname); assertThat(testAdminCon.hasStatement(null, null, null, false), is(equalTo(true))); testAdminCon.clear(dirgraph); Assert.assertFalse(testAdminCon.isEmpty()); assertThat(testAdminCon.hasStatement(john, fname, johnfname, false), is(equalTo(false))); testAdminCon.clear(); Assert.assertTrue(testAdminCon.isEmpty()); assertThat(testAdminCon.hasStatement(null, null, null, false), is(equalTo(false))); } @Ignore public void testAddNullStatements() throws Exception{ Statement st1 = vf.createStatement(john, fname, null, dirgraph); Statement st2 = vf.createStatement(null, lname, johnlname, dirgraph); Statement st3 = vf.createStatement(john, homeTel, null ); Statement st4 = vf.createStatement(john, email, johnemail, null); Statement st5 = vf.createStatement(null, null , null, null); try{ testAdminCon.add(st1); Assert.assertFalse("Exception was not thrown, when it should have been", 1<2); } catch(Exception e){ e.printStackTrace(); Assert.assertTrue(e instanceof UnsupportedOperationException); } try{ testAdminCon.add(st2); Assert.assertFalse("Exception was not thrown, when it should have been", 1<2); } catch(Exception e){ Assert.assertTrue(e instanceof UnsupportedOperationException); } try{ testAdminCon.add(st3); Assert.assertFalse("Exception was not thrown, when it should have been", 1<2); } catch(Exception e){ Assert.assertTrue(e instanceof UnsupportedOperationException); } try{ testAdminCon.add(st5); Assert.assertFalse("Exception was not thrown, when it should have been", 1<2); } catch(Exception e){ Assert.assertTrue(e instanceof UnsupportedOperationException); } testAdminCon.add(st4); Assert.assertEquals(1L,testAdminCon.size()); } //ISSUE 65 @Test public void testAddMalformedLiteralsDefaultConfig() throws Exception { try { testAdminCon.add( MarkLogicRepositoryConnectionTest.class.getResourceAsStream(TEST_DIR_PREFIX + "malformed-literals.ttl"), "", RDFFormat.TURTLE); fail("upload of malformed literals should fail with error in default configuration"); } catch (Exception e) { Assert.assertTrue(e instanceof RDFParseException); } } @Test public void testAddMalformedLiteralsStrictConfig() throws Exception { Assert.assertEquals(0L, testAdminCon.size()); Set<RioSetting<?>> empty = Collections.emptySet(); testAdminCon.getParserConfig().setNonFatalErrors(empty); try { testAdminCon.add( MarkLogicRepositoryConnectionTest.class.getResourceAsStream(TEST_DIR_PREFIX + "malformed-literals.ttl"), "", RDFFormat.TURTLE); fail("upload of malformed literals should fail with error in strict configuration"); } catch (Exception e) { Assert.assertTrue(e instanceof RDFParseException); } } //ISSUE 106, 132, 61, 126 @Test public void testRemoveStatements() throws Exception { testAdminCon.begin(); testAdminCon.add(john, lname, johnlname, dirgraph); testAdminCon.add(john, fname, johnfname, dirgraph); testAdminCon.add(john, email, johnemail, dirgraph); testAdminCon.add(john, homeTel, johnhomeTel, dirgraph); testAdminCon.add(micah, lname, micahlname); testAdminCon.add(micah, fname, micahfname); testAdminCon.add(micah, homeTel, micahhomeTel); testAdminCon.commit(); testAdminCon.setDefaultRulesets(null); Statement st1 = vf.createStatement(john, fname, johnlname); testAdminCon.remove(st1); Assert.assertEquals("There is no triple st1 in the repository, so it shouldn't be deleted",7L, testAdminCon.size()); Statement st2 = vf.createStatement(john, lname, johnlname); assertThat(testAdminCon.hasStatement(st2, false, dirgraph), is(equalTo(true))); assertThat(testAdminCon.hasStatement(st2, true, null, dirgraph), is(equalTo(true))); assertThat(testAdminCon.hasStatement(st2, true, null), is(equalTo(false))); assertThat(testAdminCon.hasStatement(john, lname, johnlname, true, null), is(equalTo(false))); assertThat(testAdminCon.hasStatement(john, lname, johnlname, true, (Resource)null, dirgraph, dirgraph1), is(equalTo(true))); assertThat(testAdminCon.hasStatement(st2, true), is(equalTo(true))); testAdminCon.remove(st2, dirgraph); assertThat(testAdminCon.hasStatement(st2, true, null, dirgraph), is(equalTo(false))); Assert.assertEquals(6L, testAdminCon.size()); testAdminCon.remove(john,email, null); assertThat(testAdminCon.hasStatement(john, fname, johnfname, false, dirgraph), is(equalTo(true))); assertThat(testAdminCon.hasStatement(john, fname, johnfname, false), is(equalTo(true))); assertThat(testAdminCon.hasStatement(john, fname, johnfname, false, null), is(equalTo(false))); assertThat(testAdminCon.hasStatement(john, fname, johnfname, false, null, dirgraph), is(equalTo(true))); assertThat(testAdminCon.hasStatement(john, lname, johnlname, false, dirgraph), is(equalTo(false))); testAdminCon.remove(john,null,null); assertThat(testAdminCon.hasStatement(john, lname, johnlname, false, dirgraph), is(equalTo(false))); assertThat(testAdminCon.hasStatement(john, fname, johnfname, false, dirgraph), is(equalTo(false))); assertThat(testAdminCon.hasStatement(john, fname, johnfname, false, null, dirgraph), is(equalTo(false))); assertThat(testAdminCon.hasStatement(john, lname, johnlname, false, (Resource)null, dirgraph), is(equalTo(false))); assertThat(testAdminCon.hasStatement(micah, homeTel, johnhomeTel, false, null), is(equalTo(false))); assertThat(testAdminCon.hasStatement(micah, homeTel, micahhomeTel, false, (Resource)null), is(equalTo(true))); assertThat(testAdminCon.hasStatement(micah, homeTel, micahhomeTel, false, null), is(equalTo(true))); testAdminCon.remove((Resource)null, homeTel,(Value) null); testAdminCon.remove((Resource)null, homeTel, (Value)null); testAdminCon.remove(vf.createStatement(john, lname, johnlname), dirgraph); assertThat(testAdminCon.hasStatement(john, lname, johnlname, false), is(equalTo(false))); assertThat(testAdminCon.hasStatement(john, lname, johnlname, false, dirgraph), is(equalTo(false))); testAdminCon.add(john, fname, johnfname, dirgraph); assertThat(testAdminCon.hasStatement(john, homeTel, johnhomeTel, false, dirgraph), is(equalTo(false))); assertThat(testAdminCon.hasStatement(micah, homeTel, micahhomeTel, false), is(equalTo(false))); assertThat(testAdminCon.hasStatement(john, fname, johnfname, false, dirgraph), is(equalTo(true))); testAdminCon.remove(john, (URI)null, (Value)null); assertThat(testAdminCon.hasStatement(john, fname, johnfname, false, dirgraph), is(equalTo(false))); assertThat(testAdminCon.isEmpty(), is(equalTo(false))); testAdminCon.remove(null, null, micahlname); assertThat(testAdminCon.hasStatement(micah, fname, micahfname, false), is(equalTo(true))); assertThat(testAdminCon.hasStatement(micah, fname, micahfname, false, null, dirgraph), is(equalTo(true))); assertThat(testAdminCon.hasStatement(null, null, null, false, null), is(equalTo(true))); assertThat(testAdminCon.hasStatement(null, null, null, false), is(equalTo(true))); assertThat(testAdminCon.hasStatement(null, null, null, false, dirgraph), is(equalTo(false))); assertThat(testAdminCon.hasStatement(micah, fname, micahfname, false, dirgraph1, dirgraph), is(equalTo(false))); testAdminCon.remove((URI)null, null, null); assertThat(testAdminCon.isEmpty(), is(equalTo(true))); assertThat(testAdminCon.hasStatement((URI)null, (URI)null, (Literal)null, false,(Resource) null), is(equalTo(false))); } //ISSUE 130 @Test public void testRemoveStatementCollection() throws Exception { testAdminCon.begin(); testAdminCon.add(john, lname, johnlname); testAdminCon.add(john, fname, johnfname); testAdminCon.add(john, email, johnemail); testAdminCon.add(john, homeTel, johnhomeTel); testAdminCon.add(micah, lname, micahlname, dirgraph); testAdminCon.add(micah, fname, micahfname, dirgraph); testAdminCon.add(micah, homeTel, micahhomeTel, dirgraph); testAdminCon.commit(); assertThat(testAdminCon.hasStatement(john, lname, johnlname, false, dirgraph), is(equalTo(false))); assertThat(testAdminCon.hasStatement(john, lname, johnlname, false, null, dirgraph), is(equalTo(true))); assertThat(testAdminCon.hasStatement(micah, homeTel, micahhomeTel, false, dirgraph), is(equalTo(true))); Collection<Statement> c = Iterations.addAll(testAdminCon.getStatements(null, null, null, false), new ArrayList<Statement>()); testAdminCon.remove(c); assertThat(testAdminCon.hasStatement(john, lname, johnlname, false), is(equalTo(false))); assertThat(testAdminCon.hasStatement(micah, homeTel, micahhomeTel, false, dirgraph), is(equalTo(false))); assertThat(testAdminCon.isEmpty(), is(equalTo(true))); } // ISSUE 130 @Test public void testRemoveStatementIterable() throws Exception { testAdminCon.add(john,fname, johnfname); Statement st1 = vf.createStatement(fei, fname, feifname,dirgraph); Statement st2 = vf.createStatement(fei, lname, feilname, dirgraph); Statement st3 = vf.createStatement(fei, email, feiemail, dirgraph); StatementList<Statement> sL = new StatementList<Statement>(st1); sL.add(st2); sL.add(st3); StatementIterator iter = new StatementIterator(sL); Iterable<? extends Statement> iterable = new StatementIterable(iter); testAdminCon.add(iterable); Assert.assertEquals(4L,testAdminCon.size()); StatementList<Statement> sL1 = new StatementList<Statement>(st1); sL1.add(st2); sL1.add(st3); StatementIterator iter1 = new StatementIterator(sL1); Iterable<? extends Statement> iterable1 = new StatementIterable(iter1); Assert.assertTrue(iterable1.iterator().hasNext()); testAdminCon.remove(iterable1, dirgraph); Assert.assertEquals(1L,testAdminCon.size()); } // ISSUE 66 @Test public void testRemoveStatementIteration() throws Exception { testAdminCon.begin(); testAdminCon.add(john,fname, johnfname); testAdminCon.add(fei, fname, feifname, dirgraph); testAdminCon.add(fei, lname, feilname, dirgraph); testAdminCon.add(fei, email, feiemail, dirgraph); testAdminCon.commit(); Assert.assertEquals(4L,testAdminCon.size()); Statement st1 = vf.createStatement(fei, fname, feifname,dirgraph); Statement st2 = vf.createStatement(fei, lname, feilname, dirgraph); Statement st3 = vf.createStatement(fei, email, feiemail, dirgraph); StatementList<Statement> sL = new StatementList<Statement>(st1); sL.add(st2); sL.add(st3); StatementIterator iter = new StatementIterator(sL); Iteration<Statement, Exception> it = new IteratorIteration<Statement, Exception> (iter); Assert.assertTrue(it.hasNext()); testAdminCon.remove(it); Assert.assertEquals(1L,testAdminCon.size()); } // ISSUE 118, 129 @Test public void testGetStatements() throws Exception { testAdminCon.add(john, fname, johnfname); testAdminCon.add(john, lname, johnlname); testAdminCon.add(john, homeTel, johnhomeTel); testAdminCon.add(john, email, johnemail); try{ assertTrue("Repository should contain statement", testAdminCon.hasStatement(john, homeTel, johnhomeTel, false)); } catch (Exception e){ logger.debug(e.getMessage()); } RepositoryResult<Statement> result = testAdminCon.getStatements(null, homeTel, null, false); try { assertNotNull("Iterator should not be null", result); assertTrue("Iterator should not be empty", result.hasNext()); while (result.hasNext()) { Statement st = result.next(); // clarify with Charles if context is null or http://... Assert.assertNull("Statement should not be in a context ", st.getContext()); assertTrue("Statement predicate should be equal to name ", st.getPredicate().equals(homeTel)); } } finally { result.close(); } List<Statement> list = Iterations.addAll(testAdminCon.getStatements(null, john, null,false,dirgraph), new ArrayList<Statement>()); assertTrue("List should be empty", list.isEmpty()); } // ISSUE 131 @Test public void testGetStatementsMalformedTypedLiteral() throws Exception { testAdminCon.getParserConfig().addNonFatalError(BasicParserSettings.VERIFY_DATATYPE_VALUES); Literal invalidIntegerLiteral = vf.createLiteral("four", XMLSchema.INTEGER); try { testAdminCon.add(micah, homeTel, invalidIntegerLiteral, dirgraph); RepositoryResult<Statement> statements = testAdminCon.getStatements(micah, homeTel, null, true); assertNotNull(statements); assertTrue(statements.hasNext()); Statement st = statements.next(); assertTrue(st.getObject() instanceof Literal); assertTrue(st.getObject().equals(invalidIntegerLiteral)); } catch (RepositoryException e) { // shouldn't happen fail(e.getMessage()); } } // ISSUE 131, 178 @Test public void testGetStatementsLanguageLiteral() throws Exception { Literal validLanguageLiteral = vf.createLiteral("the number four", "en"); try { testAdminCon.add(micah, homeTel, validLanguageLiteral,dirgraph); RepositoryResult<Statement> statements = testAdminCon.getStatements(null, null, null, true,dirgraph); assertNotNull(statements); assertTrue(statements.hasNext()); Statement st = statements.next(); assertTrue(st.getObject() instanceof Literal); assertTrue(st.getObject().equals(validLanguageLiteral)); } catch (RepositoryException e) { // shouldn't happen fail(e.getMessage()); } // Uncomment after 178 is fixed. /* testAdminCon.clear(); Literal invalidLanguageLiteral = vf.createLiteral("the number four", "en_us"); try { testAdminCon.add(micah, homeTel, invalidLanguageLiteral,dirgraph); RepositoryResult<Statement> statements = testAdminCon.getStatements(null, null, null, true,dirgraph); assertNotNull(statements); assertTrue(statements.hasNext()); Statement st = statements.next(); assertTrue(st.getObject() instanceof Literal); assertTrue(st.getObject().equals(invalidLanguageLiteral)); } catch (RepositoryException e) { // shouldn't happen fail(e.getMessage()); }*/ } //ISSUE 26 , 83, 90, 106, 107, 120, 81 @Test public void testGetStatementsInSingleContext() throws Exception { try{ testAdminCon.begin(); testAdminCon.add(micah, lname, micahlname, dirgraph1); testAdminCon.add(micah, fname, micahfname, dirgraph1); testAdminCon.add(micah, homeTel, micahhomeTel, dirgraph1); testAdminCon.add(john, fname, johnfname,dirgraph); testAdminCon.add(john, lname, johnlname,dirgraph); testAdminCon.add(john, homeTel, johnhomeTel,dirgraph); Assert.assertEquals("Size of dirgraph1 must be 3",3, testAdminCon.size(dirgraph1)); Assert.assertEquals("Size of unknown context must be 0",0L, testAdminCon.size(vf.createURI(":asd"))); Assert.assertEquals("Size of dirgraph must be 3",3, testAdminCon.size(dirgraph)); Assert.assertEquals("Size of repository must be 6",6, testAdminCon.size()); Assert.assertEquals("Size of repository must be 6",6, testAdminCon.size(dirgraph,dirgraph1,null)); Assert.assertEquals("Size of repository must be 6",6, testAdminCon.size(dirgraph,dirgraph1)); Assert.assertEquals("Size of repository must be 3",3, testAdminCon.size(dirgraph,null)); Assert.assertEquals("Size of repository must be 3",3, testAdminCon.size(dirgraph1,null)); Assert.assertEquals("Size of default graph must be 0",0, testAdminCon.size(null)); testAdminCon.add(dirgraph, vf.createURI("http://TYPE"), vf.createLiteral("Directory Graph")); Assert.assertEquals("Size of default graph must be 1",1, testAdminCon.size((Resource)null)); Assert.assertEquals("Size of repository must be 4",4, testAdminCon.size(dirgraph,null)); testAdminCon.commit(); } catch(Exception e){ } finally{ if (testAdminCon.isActive()) testAdminCon.rollback(); } Assert.assertEquals("Size of repository must be 4",4, testAdminCon.size(dirgraph1,null)); Assert.assertEquals(1, testAdminCon.size(null)); Assert.assertEquals(1, testAdminCon.size(null, null)); Assert.assertEquals(3, testAdminCon.size(dirgraph, dirgraph)); assertTrue("Repository should contain statement", testAdminCon.hasStatement(john, homeTel, johnhomeTel, false)); assertTrue("Repository should contain statement in dirgraph1", testAdminCon.hasStatement(micah, lname, micahlname, false, dirgraph1)); assertFalse("Repository should not contain statement in context2", testAdminCon.hasStatement(micah, lname, micahlname, false, dirgraph)); // Check handling of getStatements without context IDs RepositoryResult<Statement> result = testAdminCon.getStatements(micah, lname, null, false); try { while (result.hasNext()) { Statement st = result.next(); assertThat(st.getSubject(), is(equalTo((Resource)micah))); assertThat(st.getPredicate(), is(equalTo(lname))); assertThat(st.getObject(), is(equalTo((Value)micahlname))); assertThat(st.getContext(), is(equalTo((Resource)dirgraph1))); } } finally { result.close(); } // Check handling of getStatements with a known context ID result = testAdminCon.getStatements(null, null, null, false, dirgraph); try { while (result.hasNext()) { Statement st = result.next(); assertThat(st.getContext(), is(equalTo((Resource)dirgraph))); } } finally { result.close(); } // Check handling of getStatements with null context result = testAdminCon.getStatements(null, null, null, false, null); assertThat(result, is(notNullValue())); try { while (result.hasNext()) { Statement st = result.next(); assertThat(st.getContext(), is(equalTo((Resource)null))); } } finally { result.close(); } // Check handling of getStatements with an unknown context ID result = testAdminCon.getStatements(null, null, null, false, vf.createURI(":unknownContext")); try { assertThat(result, is(notNullValue())); assertThat(result.hasNext(), is(equalTo(false))); } finally { result.close(); } List<Statement> list = Iterations.addAll(testAdminCon.getStatements(null, lname, null, false, dirgraph1), new ArrayList<Statement>()); assertNotNull("List should not be null", list); assertFalse("List should not be empty", list.isEmpty()); List<Statement> list1 = Iterations.addAll(testAdminCon.getStatements(dirgraph, null, null, false, null), new ArrayList<Statement>()); assertNotNull("List should not be null", list1); assertFalse("List should not be empty", list1.isEmpty()); } //ISSUE 82, 127, 129, 140 @Test public void testGetStatementsInMultipleContexts() throws Exception { URI ur = vf.createURI("http://abcd"); CloseableIteration<? extends Statement, RepositoryException> iter1 = testAdminCon.getStatements(null, null, null, false, null); try { int count = 0; while (iter1.hasNext()) { iter1.next(); count++; } assertEquals("there should be 0 statements", 0 , count); } finally { iter1.close(); iter1 = null; } testAdminCon.begin(); testAdminCon.add(micah, lname, micahlname, dirgraph1); testAdminCon.add(micah, fname, micahfname, dirgraph1); testAdminCon.add(micah, homeTel, micahhomeTel, dirgraph1); testAdminCon.add(dirgraph1, ur, vf.createLiteral("test")); testAdminCon.commit(); // get statements with either no context or dirgraph1 CloseableIteration<? extends Statement, RepositoryException> iter = testAdminCon.getStatements(null, null, null, false, null , dirgraph1); try { int count = 0; while (iter.hasNext()) { count++; Statement st = iter.next(); assertThat(st.getContext(), anyOf(is(nullValue(Resource.class)), is(equalTo((Resource)dirgraph1)))); } assertEquals("there should be four statements", 4, count); } finally { iter.close(); iter = null; } iter = testAdminCon.getStatements(null, null, null, false, dirgraph1, dirgraph); try { int count = 0; while (iter.hasNext()) { count++; Statement st = iter.next(); assertThat(st.getContext(), is(equalTo((Resource)dirgraph1))); } assertEquals("there should be three statements", 3 , count); } finally { iter.close(); iter = null; } // get all statements with unknownContext or context2. URI unknownContext = testAdminCon.getValueFactory().createURI("http://unknownContext"); iter = testAdminCon.getStatements(null, null, null, false, unknownContext, dirgraph1); try { int count = 0; while (iter.hasNext()) { Statement st = iter.next(); count++; assertThat(st.getContext(), is(equalTo((Resource)dirgraph1))); } assertEquals("there should be three statements", 3, count); } finally { iter.close(); iter = null; } // add statements to dirgraph try{ testAdminCon.begin(); testAdminCon.add(john, fname, johnfname, dirgraph); testAdminCon.add(john, lname, johnlname, dirgraph); testAdminCon.add(john, homeTel, johnhomeTel, dirgraph); testAdminCon.commit(); } catch(Exception e){ e.printStackTrace(); } finally{ if(testAdminCon.isActive()) testAdminCon.rollback(); } // get statements with either no context or dirgraph iter = testAdminCon.getStatements(null, null, null, false, null, dirgraph); try { assertThat(iter, is(notNullValue())); assertThat(iter.hasNext(), is(equalTo(true))); int count = 0; while (iter.hasNext()) { count++; Statement st = iter.next(); System.out.println("Context is "+st.getContext()); assertThat(st.getContext(), anyOf(is(nullValue(Resource.class)), is(equalTo((Resource)dirgraph)) )); } assertEquals("there should be four statements", 4, count); } finally { iter.close(); iter = null; } // get all statements with dirgraph or dirgraph1 iter = testAdminCon.getStatements(null, null, null, false, null, dirgraph, dirgraph1); try { int count = 0; while (iter.hasNext()) { count++; Statement st = iter.next(); assertThat(st.getContext(), anyOf(is(nullValue(Resource.class)),is(equalTo((Resource)dirgraph)), is(equalTo((Resource)dirgraph1)))); } assertEquals("there should be 7 statements", 7, count); } finally { iter.close(); iter = null; } // get all statements with dirgraph or dirgraph1 iter = testAdminCon.getStatements(null, null, null, false, dirgraph, dirgraph1); try { int count = 0; while (iter.hasNext()) { count++; Statement st = iter.next(); assertThat(st.getContext(), anyOf(is(equalTo((Resource)dirgraph)), is(equalTo((Resource)dirgraph1)))); } assertEquals("there should be 6 statements", 6, count); } finally { iter.close(); iter = null; } } @Test public void testPagination() throws Exception{ URL url = MarkLogicRepositoryConnectionTest.class.getResource(TEST_DIR_PREFIX+"tigers.ttl"); testAdminCon.add(url, "", RDFFormat.TURTLE, graph1); StringBuilder queryBuilder = new StringBuilder(128); queryBuilder.append(" PREFIX bb: <http://marklogic.com/baseball/players#> "); queryBuilder.append(" PREFIX r: <http://marklogic.com/baseball/rules#> "); queryBuilder.append(" SELECT ?id ?lastname "); queryBuilder.append(" { "); queryBuilder.append(" ?id bb:lastname ?lastname. "); queryBuilder.append(" } "); queryBuilder.append(" ORDER BY ?lastname"); Query query = testAdminCon.prepareQuery(queryBuilder.toString()); TupleQueryResult result1 = ((MarkLogicTupleQuery) query).evaluate(1,2); String [] expLname = {"Ausmus","Avila","Bernard","Cabrera","Carrera","Castellanos","Holaday","Joyner","Lamont","Nathan","Verlander"}; String [] expID ={"http://marklogic.com/baseball/players#157", "http://marklogic.com/baseball/players#120", "http://marklogic.com/baseball/players#130", "http://marklogic.com/baseball/players#123", "http://marklogic.com/baseball/players#131", "http://marklogic.com/baseball/players#124", "http://marklogic.com/baseball/players#121", "http://marklogic.com/baseball/players#159", "http://marklogic.com/baseball/players#158", "http://marklogic.com/baseball/players#107","http://marklogic.com/baseball/players#119"}; int i =0; while (result1.hasNext()) { BindingSet solution = result1.next(); assertThat(solution.hasBinding("lastname"), is(equalTo(true))); Value totalResult = solution.getValue("lastname"); Assert.assertEquals(expLname[i],totalResult.stringValue()); i++; } Assert.assertEquals(2, i); i=0; TupleQueryResult result2 = ((MarkLogicTupleQuery) query).evaluate(1,0); while (result2.hasNext()) { BindingSet solution = result2.next(); assertThat(solution.hasBinding("lastname"), is(equalTo(true))); Value totalResult = solution.getValue("lastname"); Assert.assertEquals(expLname[i],totalResult.stringValue()); logger.debug("String values : "+ expLname[i] ); i++; } try{ TupleQueryResult result3 = ((MarkLogicTupleQuery) query).evaluate(0,0); Assert.assertTrue(2>1); } catch(Exception e){ logger.debug(e.getMessage()); Assert.assertTrue(e instanceof IllegalArgumentException); } try{ TupleQueryResult result3 = ((MarkLogicTupleQuery) query).evaluate(-1,-1); Assert.assertTrue(2>1); } catch(Exception e){ logger.debug(e.getMessage()); Assert.assertTrue(e instanceof IllegalArgumentException); } try{ TupleQueryResult result3 = ((MarkLogicTupleQuery) query).evaluate(2,-1); Assert.assertTrue(2>1); } catch(Exception e){ logger.debug(e.getMessage()); Assert.assertTrue(e instanceof IllegalArgumentException); } try{ TupleQueryResult result3 = ((MarkLogicTupleQuery) query).evaluate(-2,2); Assert.assertTrue(2>1); } catch(Exception e){ logger.debug(e.getMessage()); Assert.assertTrue(e instanceof IllegalArgumentException); } i = 0; TupleQueryResult result4 = ((MarkLogicTupleQuery) query).evaluate(11,2); while (result4.hasNext()) { BindingSet solution = result4.next(); assertThat(solution.hasBinding("lastname"), is(equalTo(true))); Value totalResult = solution.getValue("lastname"); Assert.assertEquals(expLname[11-i-1],totalResult.stringValue()); i++; } Assert.assertEquals(1L, i); } // ISSUE 72 @Test public void testPrepareNonSparql() throws Exception{ URL url = MarkLogicRepositoryConnectionTest.class.getResource(TEST_DIR_PREFIX+"tigers.ttl"); testAdminCon.add(url, "", RDFFormat.TURTLE, graph1); Assert.assertEquals(107L, testAdminCon.size()); String query1 = "ASK "+ "WHERE"+ "{"+ " ?s <#position> ?o."+ "}"; try{ testAdminCon.prepareGraphQuery(QueryLanguage.SERQL, query1, "http://marklogic.com/baseball/players").evaluate(); Assert.assertFalse("Exception was not thrown, when it should have been", 1<2); } catch(UnsupportedQueryLanguageException ex){ Assert.assertEquals("Unsupported query language SeRQL", ex.getMessage()); } try{ testAdminCon.prepareTupleQuery(QueryLanguage.SERQO, query1).evaluate(1,2); Assert.assertFalse("Exception was not thrown, when it should have been", 1<2); } catch(UnsupportedQueryLanguageException ex1){ Assert.assertEquals("Unsupported query language SeRQO", ex1.getMessage()); } try{ testAdminCon.prepareBooleanQuery(QueryLanguage.SERQL, query1).evaluate(); Assert.assertFalse("Exception was not thrown, when it should have been", 1<2); } catch(UnsupportedQueryLanguageException ex1){ Assert.assertEquals("Unsupported query language SeRQL", ex1.getMessage()); } try{ testAdminCon.prepareUpdate(QueryLanguage.SERQO, query1); Assert.assertFalse("Exception was not thrown, when it should have been", 1<2); } catch(UnsupportedQueryLanguageException ex1){ Assert.assertEquals("Unsupported query language SeRQO", ex1.getMessage()); } try{ testAdminCon.prepareQuery(QueryLanguage.SERQL, query1); Assert.assertFalse("Exception was not thrown, when it should have been", 1<2); } catch(UnsupportedQueryLanguageException ex1){ Assert.assertEquals("Unsupported query language SeRQL", ex1.getMessage()); } } // ISSUE 73 @Test public void testPrepareInvalidSparql() throws Exception{ Assert.assertEquals(0L, testWriterCon.size()); Assert.assertTrue(testAdminCon.isEmpty()); Statement st1 = vf.createStatement(john, fname, johnfname); testWriterCon.add(st1,dirgraph); Assert.assertEquals(1L, testWriterCon.size(dirgraph)); String query = " DESCRIBE <http://marklogicsparql.com/id#1111> "; try{ boolean tq = testReaderCon.prepareBooleanQuery(query, "http://marklogicsparql.com/id").evaluate(); Assert.assertEquals(0L, 1L); } // Change exception IIlegalArgumentException catch(Exception ex1){ Assert.assertTrue(ex1 instanceof Exception); } String query1 = "ASK {"+ "{"+ " ?s <#position> ?o."+ "}"; try{ boolean tq = testReaderCon.prepareBooleanQuery(query1, "http://marklogicsparql.com/id").evaluate(); Assert.assertEquals(0L, 1L); } // Should be MalformedQueryException catch(Exception ex){ ex.printStackTrace(); Assert.assertTrue(ex instanceof Exception); } } //ISSUE # 133, 183 @Test public void testUnsupportedIsolationLevel() throws Exception{ Assert.assertEquals(IsolationLevels.SNAPSHOT, testAdminCon.getIsolationLevel()); try{ testAdminCon.begin(); testAdminCon.add(john, fname, johnfname); assertThat(testAdminCon.hasStatement(john, fname, johnfname, false), is(equalTo(true))); assertThat(testWriterCon.hasStatement(john, fname, johnfname, false), is(equalTo(false))); testAdminCon.commit(); } catch (Exception e){ logger.debug(e.getMessage()); } finally{ if(testAdminCon.isActive()) testAdminCon.rollback(); } assertThat(testAdminCon.hasStatement(john, fname, johnfname, false), is(equalTo(true))); assertThat(testWriterCon.hasStatement(john, fname, johnfname, false), is(equalTo(true))); try{ testAdminCon.setIsolationLevel(IsolationLevels.SNAPSHOT_READ); Assert.assertTrue(1>2); } catch(Exception e){ Assert.assertTrue(e instanceof IllegalStateException); } } //ISSUE # 252 @Test public void testIsolationLevel() throws Exception { RepositoryConnection repConn = null; Repository tempRep1 = null; try{ MarkLogicRepositoryConfig tempConfig1 = new MarkLogicRepositoryConfig(); tempConfig1.setHost("localhost"); tempConfig1.setAuth("DIGEST"); tempConfig1.setUser("admin"); tempConfig1.setPassword("admin"); tempConfig1.setPort(restPort); tempRep1 = new MarkLogicRepositoryFactory().getRepository(tempConfig1); tempRep1.initialize(); repConn = tempRep1.getConnection(); repConn.begin(); repConn.add(john, fname, johnfname); createRepconn(); assertThat(repConn.hasStatement(john, fname, johnfname, false), is(equalTo(true))); repConn.commit(); } catch (Exception e){ logger.debug(e.getMessage()); } finally{ if(repConn.isActive()) repConn.rollback(); tempRep1.shutDown(); repConn.close(); repConn = null; tempRep1 = null; } } private void createRepconn() throws Exception { RepositoryConnection repConn1 = null; Repository tempRep2 = null; try{ MarkLogicRepositoryConfig tempConfig2 = new MarkLogicRepositoryConfig(); tempConfig2.setHost("localhost"); tempConfig2.setAuth("DIGEST"); tempConfig2.setUser("admin"); tempConfig2.setPassword("admin"); tempConfig2.setPort(restPort); tempRep2 = new MarkLogicRepositoryFactory().getRepository(tempConfig2); tempRep2.initialize(); repConn1 = tempRep2.getConnection(); assertThat(repConn1.hasStatement(john, fname, johnfname, false), is(equalTo(false))); } catch (Exception e){ logger.debug(e.getMessage()); } finally{ if(repConn1.isActive()) repConn1.rollback(); tempRep2.shutDown(); repConn1.close(); repConn1 = null; tempRep2 = null; } } // ISSUE - 84 @Test public void testNoUpdateRole() throws Exception{ try{ testAdminCon.prepareUpdate("DROP GRAPH <abc>").execute(); Assert.assertTrue(false); } catch(Exception e){ Assert.assertTrue(e instanceof UpdateExecutionException); } try{ testReaderCon.prepareUpdate("CREATE GRAPH <abc>").execute(); Assert.assertTrue(false); } catch(Exception e){ Assert.assertTrue(e instanceof UpdateExecutionException); } testAdminCon.prepareUpdate("CREATE GRAPH <http://abc>").execute(); final Statement st1 = vf.createStatement(john, fname, johnfname); try{ testReaderCon.add(st1, vf.createURI("http://abc")); } catch(Exception e){ } try{ testReaderCon.begin(); testReaderCon.add(st1, vf.createURI("http://abc")); testReaderCon.commit(); } catch(Exception e){ } finally{ if(testReaderCon.isActive()) testReaderCon.rollback(); } } //ISSUE 112, 104 @Test public void testRuleSets1() throws Exception{ Assert.assertEquals(0L, testAdminCon.size()); testAdminCon.add(micah, lname, micahlname, dirgraph1); testAdminCon.add(micah, fname, micahfname, dirgraph1); testAdminCon.add(micah, developPrototypeOf, semantics, dirgraph1); testAdminCon.add(micah, type, sEngineer, dirgraph1); testAdminCon.add(micah, worksFor, ml, dirgraph1); testAdminCon.add(john, fname, johnfname, dirgraph1); testAdminCon.add(john, lname, johnlname, dirgraph1); testAdminCon.add(john, writeFuncSpecOf, inference, dirgraph1); testAdminCon.add(john, type, lEngineer, dirgraph1); testAdminCon.add(john, worksFor, ml, dirgraph1); testAdminCon.add(writeFuncSpecOf, eqProperty, design, dirgraph1); testAdminCon.add(developPrototypeOf, eqProperty, design, dirgraph1); testAdminCon.add(design, eqProperty, develop, dirgraph1); // String query = "select (count (?s) as ?totalcount) where {?s ?p ?o .} "; TupleQuery tupleQuery = testAdminCon.prepareTupleQuery(QueryLanguage.SPARQL, query); ((MarkLogicQuery) tupleQuery).setRulesets(SPARQLRuleset.EQUIVALENT_CLASS); TupleQueryResult result = tupleQuery.evaluate(); try { assertThat(result, is(notNullValue())); assertThat(result.hasNext(), is(equalTo(true))); while (result.hasNext()) { BindingSet solution = result.next(); assertThat(solution.hasBinding("totalcount"), is(equalTo(true))); Value count = solution.getValue("totalcount"); Assert.assertEquals(15, Integer.parseInt(count.stringValue())); } } finally { result.close(); } testAdminCon.setDefaultRulesets(SPARQLRuleset.EQUIVALENT_PROPERTY, null); TupleQuery tupleQuery1 = testAdminCon.prepareTupleQuery(QueryLanguage.SPARQL, query); TupleQueryResult result1 = tupleQuery1.evaluate(); try { assertThat(result1, is(notNullValue())); assertThat(result1.hasNext(), is(equalTo(true))); while (result1.hasNext()) { BindingSet solution = result1.next(); assertThat(solution.hasBinding("totalcount"), is(equalTo(true))); Value count = solution.getValue("totalcount"); Assert.assertEquals(23,Integer.parseInt(count.stringValue())); } } finally { result1.close(); } SPARQLRuleset [] ruleset = testAdminCon.getDefaultRulesets(); Assert.assertEquals(2, ruleset.length); Assert.assertEquals(ruleset[0],SPARQLRuleset.EQUIVALENT_PROPERTY ); Assert.assertEquals(ruleset[1],null ); testAdminCon.setDefaultRulesets(null); TupleQuery tupleQuery2 = testAdminCon.prepareTupleQuery(QueryLanguage.SPARQL, query); ((MarkLogicQuery) tupleQuery2).setRulesets(null); tupleQuery2.setIncludeInferred(false); TupleQueryResult result2 = tupleQuery2.evaluate(); try { assertThat(result2, is(notNullValue())); assertThat(result2.hasNext(), is(equalTo(true))); while (result2.hasNext()) { BindingSet solution = result2.next(); assertThat(solution.hasBinding("totalcount"), is(equalTo(true))); Value count = solution.getValue("totalcount"); Assert.assertEquals(13, Integer.parseInt(count.stringValue())); } } finally { result2.close(); } } // ISSUE 128, 163, 111, 112 (closed) @Test public void testRuleSets2() throws Exception{ Assert.assertEquals(0L, testAdminCon.size()); testAdminCon.add(micah, lname, micahlname, dirgraph1); testAdminCon.add(micah, fname, micahfname, dirgraph1); testAdminCon.add(micah, developPrototypeOf, semantics, dirgraph1); testAdminCon.add(micah, type, sEngineer, dirgraph1); testAdminCon.add(micah, worksFor, ml, dirgraph1); testAdminCon.add(john, fname, johnfname,dirgraph); testAdminCon.add(john, lname, johnlname,dirgraph); testAdminCon.add(john, writeFuncSpecOf, inference, dirgraph); testAdminCon.add(john, type, lEngineer, dirgraph); testAdminCon.add(john, worksFor, ml, dirgraph); testAdminCon.add(writeFuncSpecOf, subProperty, design, dirgraph1); testAdminCon.add(developPrototypeOf, subProperty, design, dirgraph1); testAdminCon.add(design, subProperty, develop, dirgraph1); testAdminCon.add(lEngineer, subClass, engineer, dirgraph1); testAdminCon.add(sEngineer, subClass, engineer, dirgraph1); testAdminCon.add(engineer, subClass, employee, dirgraph1); String query = "select (count (?s) as ?totalcount) where {?s ?p ?o .} "; TupleQuery tupleQuery = testAdminCon.prepareTupleQuery(QueryLanguage.SPARQL, query); ((MarkLogicQuery) tupleQuery).setRulesets(SPARQLRuleset.RDFS_PLUS_FULL); TupleQueryResult result = tupleQuery.evaluate(); try { assertThat(result, is(notNullValue())); assertThat(result.hasNext(), is(equalTo(true))); while (result.hasNext()) { BindingSet solution = result.next(); assertThat(solution.hasBinding("totalcount"), is(equalTo(true))); Value count = solution.getValue("totalcount"); Assert.assertEquals(374, Integer.parseInt(count.stringValue())); } } finally { result.close(); } RepositoryResult<Statement> resultg = testAdminCon.getStatements(null, null, null, true, dirgraph, dirgraph1); assertNotNull("Iterator should not be null", resultg); assertTrue("Iterator should not be empty", resultg.hasNext()); tupleQuery = testAdminCon.prepareTupleQuery(QueryLanguage.SPARQL, query); ((MarkLogicQuery) tupleQuery).setRulesets(SPARQLRuleset.EQUIVALENT_CLASS); result = tupleQuery.evaluate(); try { assertThat(result, is(notNullValue())); assertThat(result.hasNext(), is(equalTo(true))); while (result.hasNext()) { BindingSet solution = result.next(); assertThat(solution.hasBinding("totalcount"), is(equalTo(true))); Value count = solution.getValue("totalcount"); Assert.assertEquals(18, Integer.parseInt(count.stringValue())); } } finally { result.close(); } tupleQuery = testAdminCon.prepareTupleQuery(QueryLanguage.SPARQL, query); ((MarkLogicQuery) tupleQuery).setRulesets(SPARQLRuleset.RDFS,SPARQLRuleset.INVERSE_OF); result = tupleQuery.evaluate(); try { assertThat(result, is(notNullValue())); assertThat(result.hasNext(), is(equalTo(true))); while (result.hasNext()) { BindingSet solution = result.next(); assertThat(solution.hasBinding("totalcount"), is(equalTo(true))); Value count = solution.getValue("totalcount"); Assert.assertEquals(86, Integer.parseInt(count.stringValue())); } } finally { result.close(); } tupleQuery = testAdminCon.prepareTupleQuery(QueryLanguage.SPARQL, query); ((MarkLogicQuery) tupleQuery).setRulesets(null,SPARQLRuleset.INVERSE_OF); result = tupleQuery.evaluate(); try { assertThat(result, is(notNullValue())); assertThat(result.hasNext(), is(equalTo(true))); while (result.hasNext()) { BindingSet solution = result.next(); assertThat(solution.hasBinding("totalcount"), is(equalTo(true))); Value count = solution.getValue("totalcount"); Assert.assertEquals(18, Integer.parseInt(count.stringValue())); } } finally { result.close(); } tupleQuery = testAdminCon.prepareTupleQuery(QueryLanguage.SPARQL, query); ((MarkLogicQuery) tupleQuery).setRulesets((SPARQLRuleset)null, null); tupleQuery.setIncludeInferred(false); result = tupleQuery.evaluate(); try { assertThat(result, is(notNullValue())); assertThat(result.hasNext(), is(equalTo(true))); while (result.hasNext()) { BindingSet solution = result.next(); assertThat(solution.hasBinding("totalcount"), is(equalTo(true))); Value count = solution.getValue("totalcount"); Assert.assertEquals(16, Integer.parseInt(count.stringValue())); } } finally { result.close(); } } @Test public void testConstrainingQueries() throws Exception{ testAdminCon.add(micah, lname, micahlname, dirgraph1); testAdminCon.add(micah, fname, micahfname, dirgraph1); testAdminCon.add(john, fname, johnfname); testAdminCon.add(john, lname, johnlname); String query1 = "ASK WHERE {?s ?p \"Micah\" .}"; String query2 = "SELECT ?s ?p ?o WHERE {?s ?p ?o .} ORDER by ?o"; // case one, rawcombined String combinedQuery = "{\"search\":" + "{\"qtext\":\"2222\"}}"; String negCombinedQuery = "{\"search\":" + "{\"qtext\":\"John\"}}"; RawCombinedQueryDefinition rawCombined = qmgr.newRawCombinedQueryDefinition(new StringHandle().with(combinedQuery).withFormat(Format.JSON)); RawCombinedQueryDefinition negRawCombined = qmgr.newRawCombinedQueryDefinition(new StringHandle().with(negCombinedQuery).withFormat(Format.JSON)); MarkLogicBooleanQuery askQuery = (MarkLogicBooleanQuery) testAdminCon.prepareBooleanQuery(QueryLanguage.SPARQL,query1); askQuery.setConstrainingQueryDefinition(rawCombined); Assert.assertEquals(true, askQuery.evaluate()); testAdminCon.setDefaultConstrainingQueryDefinition(negRawCombined); MarkLogicTupleQuery tupleQuery = testAdminCon.prepareTupleQuery(QueryLanguage.SPARQL, query2); TupleQueryResult result = tupleQuery.evaluate(); try { assertThat(result, is(notNullValue())); assertThat(result.hasNext(), is(equalTo(true))); while (result.hasNext()) { BindingSet solution = result.next(); assertThat(solution.hasBinding("s"), is(equalTo(true))); Value fname = solution.getValue("o"); String name = fname.stringValue().toString(); Assert.assertTrue(name.equals("John")|| name.equals("Snelson")); } } finally { result.close(); } QueryDefinition qd = testAdminCon.getDefaultConstrainingQueryDefinition(); testAdminCon.setDefaultConstrainingQueryDefinition(null); testAdminCon.setDefaultConstrainingQueryDefinition(qd); tupleQuery = testAdminCon.prepareTupleQuery(QueryLanguage.SPARQL, query2); result = tupleQuery.evaluate(); try { assertThat(result, is(notNullValue())); assertThat(result.hasNext(), is(equalTo(true))); while (result.hasNext()) { BindingSet solution = result.next(); assertThat(solution.hasBinding("s"), is(equalTo(true))); Value fname = solution.getValue("o"); String name = fname.stringValue().toString(); Assert.assertTrue(name.equals("John")|| name.equals("Snelson")); } } finally { result.close(); } testAdminCon.setDefaultConstrainingQueryDefinition(null); tupleQuery = testAdminCon.prepareTupleQuery(QueryLanguage.SPARQL, query2); result = tupleQuery.evaluate(); try { assertThat(result, is(notNullValue())); assertThat(result.hasNext(), is(equalTo(true))); while (result.hasNext()) { BindingSet solution = result.next(); assertThat(solution.hasBinding("s"), is(equalTo(true))); Value fname = solution.getValue("o"); String name = fname.stringValue().toString(); Assert.assertTrue(name.equals("John")|| name.equals("Snelson")|| name.equals("Micah")|| name.equals("Dubinko")); } } finally { result.close(); } } // ISSUE 124, 142 @Test public void testStructuredQuery() throws Exception { setupData(); StructuredQueryBuilder qb = new StructuredQueryBuilder(); QueryDefinition structuredDef = qb.build(qb.term("Second")); String posQuery = "ASK WHERE {<http://example.org/r9929> ?p ?o .}"; String negQuery = "ASK WHERE {<http://example.org/r9928> ?p ?o .}"; MarkLogicBooleanQuery askQuery = (MarkLogicBooleanQuery) testAdminCon.prepareBooleanQuery(QueryLanguage.SPARQL,posQuery); askQuery.setConstrainingQueryDefinition(structuredDef); Assert.assertEquals(true, askQuery.evaluate()); testAdminCon.setDefaultConstrainingQueryDefinition(structuredDef); MarkLogicBooleanQuery askQuery1 = (MarkLogicBooleanQuery) testAdminCon.prepareBooleanQuery(QueryLanguage.SPARQL,negQuery); Assert.assertEquals(false, askQuery1.evaluate()); QueryDefinition qd = testAdminCon.getDefaultConstrainingQueryDefinition(); testAdminCon.setDefaultConstrainingQueryDefinition(null); askQuery1 = (MarkLogicBooleanQuery) testAdminCon.prepareBooleanQuery(QueryLanguage.SPARQL,negQuery); Assert.assertEquals(true, askQuery1.evaluate()); testAdminCon.setDefaultConstrainingQueryDefinition(qd); askQuery1 = (MarkLogicBooleanQuery) testAdminCon.prepareBooleanQuery(QueryLanguage.SPARQL,negQuery); Assert.assertEquals(false, askQuery1.evaluate()); testAdminCon.setDefaultConstrainingQueryDefinition(null); askQuery = (MarkLogicBooleanQuery) testAdminCon.prepareBooleanQuery(QueryLanguage.SPARQL,posQuery); askQuery.setConstrainingQueryDefinition(null); Assert.assertEquals(true, askQuery.evaluate()); askQuery1 = (MarkLogicBooleanQuery) testAdminCon.prepareBooleanQuery(QueryLanguage.SPARQL,negQuery); askQuery.setConstrainingQueryDefinition(null); Assert.assertEquals(true, askQuery1.evaluate()); } // ISSUE 124 @Test public void testStringQuery() throws Exception { setupData(); StringQueryDefinition stringDef = qmgr.newStringDefinition().withCriteria("First"); String posQuery = "ASK WHERE {<http://example.org/r9928> ?p ?o .}"; String negQuery = "ASK WHERE {<http://example.org/r9929> ?p ?o .}"; MarkLogicBooleanQuery askQuery = (MarkLogicBooleanQuery) testAdminCon.prepareBooleanQuery(QueryLanguage.SPARQL,posQuery); askQuery.setConstrainingQueryDefinition(stringDef); Assert.assertEquals(true, askQuery.evaluate()); MarkLogicBooleanQuery askQuery1 = (MarkLogicBooleanQuery) testAdminCon.prepareBooleanQuery(QueryLanguage.SPARQL,negQuery); askQuery1.setConstrainingQueryDefinition(stringDef); Assert.assertEquals(false, askQuery1.evaluate()); askQuery = (MarkLogicBooleanQuery) testAdminCon.prepareBooleanQuery(QueryLanguage.SPARQL,posQuery); askQuery.setConstrainingQueryDefinition(null); Assert.assertEquals(true, askQuery.evaluate()); askQuery1 = (MarkLogicBooleanQuery) testAdminCon.prepareBooleanQuery(QueryLanguage.SPARQL,negQuery); askQuery1.setConstrainingQueryDefinition(null); Assert.assertEquals(true, askQuery1.evaluate()); } private void setupData() { String tripleDocOne = "<semantic-document>\n" + "<title>First Title</title>\n" + "<size>100</size>\n" + "<sem:triples xmlns:sem=\"http://marklogic.com/semantics\">" + "<sem:triple><sem:subject>http://example.org/r9928</sem:subject>" + "<sem:predicate>http://example.org/p3</sem:predicate>" + "<sem:object datatype=\"http://www.w3.org/2001/XMLSchema#int\">1</sem:object></sem:triple>" + "</sem:triples>\n" + "</semantic-document>"; String tripleDocTwo = "<semantic-document>\n" + "<title>Second Title</title>\n" + "<size>500</size>\n" + "<sem:triples xmlns:sem=\"http://marklogic.com/semantics\">" + "<sem:triple><sem:subject>http://example.org/r9929</sem:subject>" + "<sem:predicate>http://example.org/p3</sem:predicate>" + "<sem:object datatype=\"http://www.w3.org/2001/XMLSchema#int\">2</sem:object></sem:triple>" + "</sem:triples>\n" + "</semantic-document>"; XMLDocumentManager docMgr = databaseClient.newXMLDocumentManager(); docMgr.write("/directory1/doc1.xml", new StringHandle().with(tripleDocOne)); docMgr.write("/directory2/doc2.xml", new StringHandle().with(tripleDocTwo)); } //ISSUE 51 @Test public void testCommitConnClosed() throws Exception { try{ testAdminCon.begin(); testAdminCon.add(micah, lname, micahlname, dirgraph1); testAdminCon.add(micah, fname, micahfname, dirgraph1); testAdminCon.add(micah, homeTel, micahhomeTel, dirgraph1); Assert.assertEquals("Size of dirgraph1",3, testAdminCon.size()); testAdminCon.close(); } catch(Exception e){ e.printStackTrace(); } // initializes repository and creates testAdminCon testAdminRepository.shutDown(); testAdminRepository = null; testAdminCon = null; setUp(); Assert.assertEquals("Size of dirgraph1",0, testAdminCon.size()); } }
Adding another test
marklogic-sesame-functionaltests/src/test/java/com/marklogic/sesame/functionaltests/MarkLogicRepositoryConnectionTest.java
Adding another test
<ide><path>arklogic-sesame-functionaltests/src/test/java/com/marklogic/sesame/functionaltests/MarkLogicRepositoryConnectionTest.java <ide> <ide> } <ide> <del> @Ignore <add> @Test <ide> public void testMultiThreadedAdd1() throws Exception{ <ide> <ide> class MyRunnable implements Runnable { <del> private final Object lock = new Object(); <del> @Override <add> @Override <ide> public void run(){ <add> MarkLogicRepositoryConnection tempConn = null; <ide> try { <del> synchronized (lock){ <del> if(! testAdminCon.isActive()) <del> testAdminCon.begin(); <del> } <del> <del> for (int j =0 ;j < 100; j++){ <add> if(! testAdminRepository.isInitialized()) <add> testAdminRepository.initialize(); <add> tempConn= testAdminRepository.getConnection(); <add> tempConn.begin(); <add> for (int j =0 ;j < 100; j++){ <ide> URI subject = vf.createURI(NS+ID+"/"+Thread.currentThread().getId()+"/"+j+"#1111"); <ide> URI predicate = fname = vf.createURI(NS+ADDRESS+"/"+Thread.currentThread().getId()+"/"+"#firstName"); <ide> Literal object = vf.createLiteral(Thread.currentThread().getId()+ "-" + j +"-" +"John"); <del> testAdminCon.add(subject, predicate,object, dirgraph); <del> } <del> testAdminCon.commit(); <add> tempConn.add(subject, predicate,object, dirgraph); <add> } <add> tempConn.commit(); <ide> <ide> } catch (RepositoryException e1) { <ide> // TODO Auto-generated catch block <ide> } <ide> finally{ <ide> try { <del> if(testAdminCon.isActive()) <del> testAdminCon.rollback(); <add> if(tempConn.isActive()) <add> tempConn.rollback(); <ide> } catch (UnknownTransactionStateException e) { <ide> // TODO Auto-generated catch block <ide> e.printStackTrace(); <ide> t2 = new Thread(new MyRunnable()); <ide> t2.setName("T2"); <ide> t3 = new Thread(new MyRunnable()); <del> t3.setName("T2"); <add> t3.setName("T3"); <ide> t4 = new Thread(new MyRunnable()); <del> t4.setName("T2"); <add> t4.setName("T4"); <ide> <ide> t1.start(); <ide> t2.start();
Java
apache-2.0
04ba04dfe6ac82aed37df0a28698d23b90569f20
0
kishorejangid/manifoldcf,kishorejangid/manifoldcf,apache/manifoldcf,kishorejangid/manifoldcf,kishorejangid/manifoldcf,apache/manifoldcf,apache/manifoldcf,apache/manifoldcf,apache/manifoldcf,apache/manifoldcf,kishorejangid/manifoldcf,kishorejangid/manifoldcf
/* $Id: JDBCConnector.java 988245 2010-08-23 18:39:35Z kwright $ */ /** * 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.manifoldcf.crawler.connectors.jdbc; import org.apache.manifoldcf.core.interfaces.*; import org.apache.manifoldcf.agents.interfaces.*; import org.apache.manifoldcf.crawler.interfaces.*; import org.apache.manifoldcf.crawler.system.Logging; import org.apache.manifoldcf.core.database.*; import org.apache.manifoldcf.connectorcommon.interfaces.*; import org.apache.manifoldcf.jdbc.JDBCConnection; import org.apache.manifoldcf.jdbc.JDBCConstants; import org.apache.manifoldcf.jdbc.IDynamicResultSet; import org.apache.manifoldcf.jdbc.IDynamicResultRow; import java.nio.charset.StandardCharsets; import java.sql.*; import javax.naming.*; import javax.sql.*; import java.io.*; import java.util.*; /** JDBC repository connector. */ public class JDBCConnector extends org.apache.manifoldcf.crawler.connectors.BaseRepositoryConnector { public static final String _rcsid = "@(#)$Id: JDBCConnector.java 988245 2010-08-23 18:39:35Z kwright $"; // Activities that we know about protected final static String ACTIVITY_EXTERNAL_QUERY = "external query"; protected final static String ACTIVITY_FETCH = "fetch"; // Activities list protected static final String[] activitiesList = new String[]{ACTIVITY_EXTERNAL_QUERY, ACTIVITY_FETCH}; /** Deny access token for default authority */ private final static String defaultAuthorityDenyToken = "DEAD_AUTHORITY"; protected JDBCConnection connection = null; protected String jdbcProvider = null; protected String accessMethod = null; protected String host = null; protected String databaseName = null; protected String rawDriverString = null; protected String userName = null; protected String password = null; /** Constructor. */ public JDBCConnector() { } /** Set up a session */ protected void getSession() throws ManifoldCFException { if (connection == null) { if (jdbcProvider == null || jdbcProvider.length() == 0) throw new ManifoldCFException("Missing parameter '"+JDBCConstants.providerParameter+"'"); if ((host == null || host.length() == 0) && (rawDriverString == null || rawDriverString.length() == 0)) throw new ManifoldCFException("Missing parameter '"+JDBCConstants.hostParameter+"' or '"+JDBCConstants.driverStringParameter+"'"); connection = new JDBCConnection(jdbcProvider,(accessMethod==null || accessMethod.equals("name")),host,databaseName,rawDriverString,userName,password); } } /** Return the list of activities that this connector supports (i.e. writes into the log). *@return the list. */ @Override public String[] getActivitiesList() { return activitiesList; } /** Model. Depending on what people enter for the seeding query, this could be either ALL or * could be less than that. So, I've decided it will be at least the adds and changes, and * won't include the deletes. */ @Override public int getConnectorModel() { return MODEL_ADD_CHANGE; } /** Connect. The configuration parameters are included. *@param configParams are the configuration parameters for this connection. */ @Override public void connect(ConfigParams configParams) { super.connect(configParams); jdbcProvider = configParams.getParameter(JDBCConstants.providerParameter); accessMethod = configParams.getParameter(JDBCConstants.methodParameter); host = configParams.getParameter(JDBCConstants.hostParameter); databaseName = configParams.getParameter(JDBCConstants.databaseNameParameter); rawDriverString = configParams.getParameter(JDBCConstants.driverStringParameter); userName= configParams.getParameter(JDBCConstants.databaseUserName); password = configParams.getObfuscatedParameter(JDBCConstants.databasePassword); } /** Check status of connection. */ @Override public String check() throws ManifoldCFException { try { getSession(); // Attempt to fetch a connection; if this succeeds we pass connection.testConnection(); return super.check(); } catch (ServiceInterruption e) { if (Logging.connectors.isDebugEnabled()) Logging.connectors.debug("Service interruption in check(): "+e.getMessage(),e); return "Transient error: "+e.getMessage(); } } /** Close the connection. Call this before discarding the repository connector. */ @Override public void disconnect() throws ManifoldCFException { connection = null; host = null; jdbcProvider = null; accessMethod = null; databaseName = null; rawDriverString = null; userName = null; password = null; super.disconnect(); } /** Get the bin name string for a document identifier. The bin name describes the queue to which the * document will be assigned for throttling purposes. Throttling controls the rate at which items in a * given queue are fetched; it does not say anything about the overall fetch rate, which may operate on * multiple queues or bins. * For example, if you implement a web crawler, a good choice of bin name would be the server name, since * that is likely to correspond to a real resource that will need real throttle protection. *@param documentIdentifier is the document identifier. *@return the bin name. */ @Override public String[] getBinNames(String documentIdentifier) { return new String[]{(rawDriverString==null||rawDriverString.length()==0)?host:rawDriverString}; } /** Queue "seed" documents. Seed documents are the starting places for crawling activity. Documents * are seeded when this method calls appropriate methods in the passed in ISeedingActivity object. * * This method can choose to find repository changes that happen only during the specified time interval. * The seeds recorded by this method will be viewed by the framework based on what the * getConnectorModel() method returns. * * It is not a big problem if the connector chooses to create more seeds than are * strictly necessary; it is merely a question of overall work required. * * The end time and seeding version string passed to this method may be interpreted for greatest efficiency. * For continuous crawling jobs, this method will * be called once, when the job starts, and at various periodic intervals as the job executes. * * When a job's specification is changed, the framework automatically resets the seeding version string to null. The * seeding version string may also be set to null on each job run, depending on the connector model returned by * getConnectorModel(). * * Note that it is always ok to send MORE documents rather than less to this method. * The connector will be connected before this method can be called. *@param activities is the interface this method should use to perform whatever framework actions are desired. *@param spec is a document specification (that comes from the job). *@param seedTime is the end of the time range of documents to consider, exclusive. *@param lastSeedVersionString is the last seeding version string for this job, or null if the job has no previous seeding version string. *@param jobMode is an integer describing how the job is being run, whether continuous or once-only. *@return an updated seeding version string, to be stored with the job. */ @Override public String addSeedDocuments(ISeedingActivity activities, Specification spec, String lastSeedVersion, long seedTime, int jobMode) throws ManifoldCFException, ServiceInterruption { long startTime; if (lastSeedVersion == null) startTime = 0L; else { // Unpack seed time from seed version string startTime = new Long(lastSeedVersion).longValue(); } getSession(); // Set up the query TableSpec ts = new TableSpec(spec); VariableMap vm = new VariableMap(); addConstant(vm,JDBCConstants.idReturnVariable,JDBCConstants.idReturnColumnName); addVariable(vm,JDBCConstants.startTimeVariable,startTime); addVariable(vm,JDBCConstants.endTimeVariable,seedTime); // Do the substitution ArrayList paramList = new ArrayList(); StringBuilder sb = new StringBuilder(); substituteQuery(ts.idQuery,vm,sb,paramList); IDynamicResultSet idSet; String queryText = sb.toString(); long startQueryTime = System.currentTimeMillis(); // Contract for IDynamicResultset indicates that if successfully obtained, it MUST // be closed. try { idSet = connection.executeUncachedQuery(queryText,paramList,-1); } catch (ServiceInterruption e) { // If failure, record the failure. activities.recordActivity(new Long(startQueryTime), ACTIVITY_EXTERNAL_QUERY, null, createQueryString(queryText,paramList), "ERROR", e.getMessage(), null); throw e; } catch (ManifoldCFException e) { // If failure, record the failure. activities.recordActivity(new Long(startQueryTime), ACTIVITY_EXTERNAL_QUERY, null, createQueryString(queryText,paramList), "ERROR", e.getMessage(), null); throw e; } try { // If success, record that too. activities.recordActivity(new Long(startQueryTime), ACTIVITY_EXTERNAL_QUERY, null, createQueryString(queryText,paramList), "OK", null, null); while (true) { IDynamicResultRow row = idSet.getNextRow(); if (row == null) break; try { Object o = row.getValue(JDBCConstants.idReturnColumnName); if (o == null) throw new ManifoldCFException("Bad seed query; doesn't return $(IDCOLUMN) column. Try using quotes around $(IDCOLUMN) variable, e.g. \"$(IDCOLUMN)\", or, for MySQL, select \"by label\" in your repository connection."); String idValue = JDBCConnection.readAsString(o); activities.addSeedDocument(idValue); } finally { row.close(); } } } finally { idSet.close(); } return new Long(seedTime).toString(); } /** Process a set of documents. * This is the method that should cause each document to be fetched, processed, and the results either added * to the queue of documents for the current job, and/or entered into the incremental ingestion manager. * The document specification allows this class to filter what is done based on the job. * The connector will be connected before this method can be called. *@param documentIdentifiers is the set of document identifiers to process. *@param statuses are the currently-stored document versions for each document in the set of document identifiers * passed in above. *@param activities is the interface this method should use to queue up new document references * and ingest documents. *@param jobMode is an integer describing how the job is being run, whether continuous or once-only. *@param usesDefaultAuthority will be true only if the authority in use for these documents is the default one. */ @Override public void processDocuments(String[] documentIdentifiers, IExistingVersions statuses, Specification spec, IProcessActivity activities, int jobMode, boolean usesDefaultAuthority) throws ManifoldCFException, ServiceInterruption { TableSpec ts = new TableSpec(spec); Set<String> acls = ts.getAcls(); String[] versionsReturned = new String[documentIdentifiers.length]; // If there is no version query, then always return empty string for all documents. // This will mean that processDocuments will be called // for all. ProcessDocuments will then be responsible for doing document deletes itself, // based on the query results. Map<String,String> documentVersions = new HashMap<String,String>(); if (ts.versionQuery != null && ts.versionQuery.length() > 0) { // If there IS a versions query, do it. First set up the variables, then do the substitution. VariableMap vm = new VariableMap(); addConstant(vm,JDBCConstants.idReturnVariable,JDBCConstants.idReturnColumnName); addConstant(vm,JDBCConstants.versionReturnVariable,JDBCConstants.versionReturnColumnName); if (addIDList(vm,JDBCConstants.idListVariable,documentIdentifiers,null)) { // Do the substitution ArrayList paramList = new ArrayList(); StringBuilder sb = new StringBuilder(); substituteQuery(ts.versionQuery,vm,sb,paramList); // Now, build a result return, and a hash table so we can correlate the returned values with the place to put them. // We presume that if the row is missing, the document is gone. // Fire off the query! getSession(); IDynamicResultSet result; String queryText = sb.toString(); long startTime = System.currentTimeMillis(); // Get a dynamic resultset. Contract for dynamic resultset is that if // one is returned, it MUST be closed, or a connection will leak. try { result = connection.executeUncachedQuery(queryText,paramList,-1); } catch (ManifoldCFException e) { // If failure, record the failure. if (e.getErrorCode() != ManifoldCFException.INTERRUPTED) activities.recordActivity(new Long(startTime), ACTIVITY_EXTERNAL_QUERY, null, createQueryString(queryText,paramList), "ERROR", e.getMessage(), null); throw e; } try { // If success, record that too. activities.recordActivity(new Long(startTime), ACTIVITY_EXTERNAL_QUERY, null, createQueryString(queryText,paramList), "OK", null, null); // Now, go through resultset while (true) { IDynamicResultRow row = result.getNextRow(); if (row == null) break; try { Object o = row.getValue(JDBCConstants.idReturnColumnName); if (o == null) throw new ManifoldCFException("Bad version query; doesn't return $(IDCOLUMN) column. Try using quotes around $(IDCOLUMN) variable, e.g. \"$(IDCOLUMN)\", or, for MySQL, select \"by label\" in your repository connection."); String idValue = JDBCConnection.readAsString(o); o = row.getValue(JDBCConstants.versionReturnColumnName); String versionValue; // Null version is OK; make it a "" if (o == null) versionValue = ""; else versionValue = JDBCConnection.readAsString(o); documentVersions.put(idValue,versionValue); } finally { row.close(); } } } finally { result.close(); } } } else { for (String documentIdentifier : documentIdentifiers) { documentVersions.put(documentIdentifier,""); } } // Delete the documents that had no version, and work only on ones that did Set<String> fetchDocuments = documentVersions.keySet(); for (String documentIdentifier : documentIdentifiers) { String documentVersion = documentVersions.get(documentIdentifier); if (documentVersion == null) { activities.deleteDocument(documentIdentifier); continue; } } // Pick up document acls Map<String,Set<String>> documentAcls = new HashMap<String,Set<String>>(); if (ts.securityOn) { if (acls.size() == 0 && ts.aclQuery != null && ts.aclQuery.length() > 0) { // If there IS an acls query, do it. First set up the variables, then do the substitution. VariableMap vm = new VariableMap(); addConstant(vm,JDBCConstants.idReturnVariable,JDBCConstants.idReturnColumnName); addConstant(vm,JDBCConstants.tokenReturnVariable,JDBCConstants.tokenReturnColumnName); if (addIDList(vm,JDBCConstants.idListVariable,documentIdentifiers,fetchDocuments)) { // Do the substitution ArrayList paramList = new ArrayList(); StringBuilder sb = new StringBuilder(); substituteQuery(ts.aclQuery,vm,sb,paramList); // Fire off the query! getSession(); IDynamicResultSet result; String queryText = sb.toString(); long startTime = System.currentTimeMillis(); // Get a dynamic resultset. Contract for dynamic resultset is that if // one is returned, it MUST be closed, or a connection will leak. try { result = connection.executeUncachedQuery(queryText,paramList,-1); } catch (ManifoldCFException e) { // If failure, record the failure. if (e.getErrorCode() != ManifoldCFException.INTERRUPTED) activities.recordActivity(new Long(startTime), ACTIVITY_EXTERNAL_QUERY, null, createQueryString(queryText,paramList), "ERROR", e.getMessage(), null); throw e; } try { // If success, record that too. activities.recordActivity(new Long(startTime), ACTIVITY_EXTERNAL_QUERY, null, createQueryString(queryText,paramList), "OK", null, null); // Now, go through resultset while (true) { IDynamicResultRow row = result.getNextRow(); if (row == null) break; try { Object o = row.getValue(JDBCConstants.idReturnColumnName); if (o == null) throw new ManifoldCFException("Bad acl query; doesn't return $(IDCOLUMN) column. Try using quotes around $(IDCOLUMN) variable, e.g. \"$(IDCOLUMN)\", or, for MySQL, select \"by label\" in your repository connection."); String idValue = JDBCConnection.readAsString(o); o = row.getValue(JDBCConstants.tokenReturnColumnName); String tokenValue; if (o == null) tokenValue = ""; else tokenValue = JDBCConnection.readAsString(o); // Versions that are "", when processed, will have their acls fetched at that time... Set<String> dcs = documentAcls.get(idValue); if (dcs == null) { dcs = new HashSet<String>(); documentAcls.put(idValue,dcs); } dcs.add(tokenValue); } finally { row.close(); } } } finally { result.close(); } } } else { for (String documentIdentifier : fetchDocuments) { documentAcls.put(documentIdentifier,acls); } } } Map<String,String> map = new HashMap<String,String>(); for (String documentIdentifier : fetchDocuments) { String documentVersion = documentVersions.get(documentIdentifier); if (documentVersion.length() == 0) { map.put(documentIdentifier,documentVersion); } else { // Compute a full version string StringBuilder sb = new StringBuilder(); Set<String> dAcls = documentAcls.get(documentIdentifier); if (dAcls == null) sb.append('-'); else { sb.append('+'); String[] aclValues = new String[dAcls.size()]; int k = 0; for (String acl : dAcls) { aclValues[k++] = acl; } java.util.Arrays.sort(aclValues); packList(sb,aclValues,'+'); } sb.append(documentVersion).append("=").append(ts.dataQuery); String versionValue = sb.toString(); if (activities.checkDocumentNeedsReindexing(documentIdentifier,versionValue)) { map.put(documentIdentifier,versionValue); } } } // For all the documents not marked "scan only", form a query and pick up the contents. // If the contents is not found, then explicitly call the delete action method. VariableMap vm = new VariableMap(); addConstant(vm,JDBCConstants.idReturnVariable,JDBCConstants.idReturnColumnName); addConstant(vm,JDBCConstants.urlReturnVariable,JDBCConstants.urlReturnColumnName); addConstant(vm,JDBCConstants.dataReturnVariable,JDBCConstants.dataReturnColumnName); addConstant(vm,JDBCConstants.contentTypeReturnVariable,JDBCConstants.contentTypeReturnColumnName); if (!addIDList(vm,JDBCConstants.idListVariable,documentIdentifiers,map.keySet())) return; // Do the substitution ArrayList paramList = new ArrayList(); StringBuilder sb = new StringBuilder(); substituteQuery(ts.dataQuery,vm,sb,paramList); // Execute the query getSession(); IDynamicResultSet result; String queryText = sb.toString(); long startTime = System.currentTimeMillis(); // Get a dynamic resultset. Contract for dynamic resultset is that if // one is returned, it MUST be closed, or a connection will leak. try { result = connection.executeUncachedQuery(queryText,paramList,-1); } catch (ManifoldCFException e) { // If failure, record the failure. activities.recordActivity(new Long(startTime), ACTIVITY_EXTERNAL_QUERY, null, createQueryString(queryText,paramList), "ERROR", e.getMessage(), null); throw e; } try { // If success, record that too. activities.recordActivity(new Long(startTime), ACTIVITY_EXTERNAL_QUERY, null, createQueryString(queryText,paramList), "OK", null, null); while (true) { IDynamicResultRow row = result.getNextRow(); if (row == null) break; try { Object o = row.getValue(JDBCConstants.idReturnColumnName); if (o == null) throw new ManifoldCFException("Bad document query; doesn't return $(IDCOLUMN) column. Try using quotes around $(IDCOLUMN) variable, e.g. \"$(IDCOLUMN)\", or, for MySQL, select \"by label\" in your repository connection."); String id = JDBCConnection.readAsString(o); String errorCode = null; String errorDesc = null; Long fileLengthLong = null; long fetchStartTime = System.currentTimeMillis(); try { String version = map.get(id); if (version == null) // Does not need refetching continue; // This document was marked as "not scan only", so we expect to find it. if (Logging.connectors.isDebugEnabled()) Logging.connectors.debug("JDBC: Document data result found for '"+id+"'"); o = row.getValue(JDBCConstants.urlReturnColumnName); if (o == null) { Logging.connectors.debug("JDBC: Document '"+id+"' has a null url - skipping"); errorCode = activities.NULL_URL; errorDesc = "Excluded because document had a null URL"; activities.noDocument(id,version); continue; } // This is not right - url can apparently be a BinaryInput String url = JDBCConnection.readAsString(o); boolean validURL; try { // Check to be sure url is valid new java.net.URI(url); validURL = true; } catch (java.net.URISyntaxException e) { validURL = false; } if (!validURL) { Logging.connectors.debug("JDBC: Document '"+id+"' has an illegal url: '"+url+"' - skipping"); errorCode = activities.BAD_URL; errorDesc = "Excluded because document had illegal URL ('"+url+"')"; activities.noDocument(id,version); continue; } // Process the document itself Object contents = row.getValue(JDBCConstants.dataReturnColumnName); // Null data is allowed; we just ignore these if (contents == null) { Logging.connectors.debug("JDBC: Document '"+id+"' seems to have null data - skipping"); errorCode = "NULLDATA"; errorDesc = "Excluded because document had null data"; activities.noDocument(id,version); continue; } // We will ingest something, so remove this id from the map in order that we know what we still // need to delete when all done. map.remove(id); String contentType; o = row.getValue(JDBCConstants.contentTypeReturnColumnName); if (o != null) contentType = JDBCConnection.readAsString(o); else { if (contents instanceof BinaryInput) contentType = "application/octet-stream"; else if (contents instanceof CharacterInput) contentType = "text/plain; charset=utf-8"; else contentType = "text/plain"; } if (!activities.checkMimeTypeIndexable(contentType)) { Logging.connectors.debug("JDBC: Document '"+id+"' excluded because of mime type - skipping"); errorCode = activities.EXCLUDED_MIMETYPE; errorDesc = "Excluded because of mime type ("+contentType+")"; activities.noDocument(id,version); continue; } if (!activities.checkURLIndexable(url)) { Logging.connectors.debug("JDBC: Document '"+id+"' excluded because of url - skipping"); errorCode = activities.EXCLUDED_URL; errorDesc = "Excluded because of URL ('"+url+"')"; activities.noDocument(id,version); continue; } // An ingestion will take place for this document. RepositoryDocument rd = new RepositoryDocument(); rd.setMimeType(contentType); applyAccessTokens(rd,documentAcls.get(id)); applyMetadata(rd,row); if (contents instanceof BinaryInput) { BinaryInput bi = (BinaryInput)contents; long fileLength = bi.getLength(); if (!activities.checkLengthIndexable(fileLength)) { Logging.connectors.debug("JDBC: Document '"+id+"' excluded because of length - skipping"); errorCode = activities.EXCLUDED_LENGTH; errorDesc = "Excluded because of length ("+fileLength+")"; activities.noDocument(id, version); continue; } try { // Read the stream InputStream is = bi.getStream(); try { rd.setBinary(is,fileLength); activities.ingestDocumentWithException(id, version, url, rd); errorCode = "OK"; fileLengthLong = new Long(fileLength); } finally { is.close(); } } catch (IOException e) { errorCode = e.getClass().getSimpleName().toUpperCase(Locale.ROOT); errorDesc = e.getMessage(); handleIOException(id,e); } } else if (contents instanceof CharacterInput) { CharacterInput ci = (CharacterInput)contents; long fileLength = ci.getUtf8StreamLength(); if (!activities.checkLengthIndexable(fileLength)) { Logging.connectors.debug("JDBC: Document '"+id+"' excluded because of length - skipping"); errorCode = activities.EXCLUDED_LENGTH; errorDesc = "Excluded because of length ("+fileLength+")"; activities.noDocument(id, version); continue; } try { // Read the stream InputStream is = ci.getUtf8Stream(); try { rd.setBinary(is,fileLength); activities.ingestDocumentWithException(id, version, url, rd); errorCode = "OK"; fileLengthLong = new Long(fileLength); } finally { is.close(); } } catch (IOException e) { errorCode = e.getClass().getSimpleName().toUpperCase(Locale.ROOT); errorDesc = e.getMessage(); handleIOException(id,e); } } else { // Turn it into a string, and then into a stream String value = contents.toString(); byte[] bytes = value.getBytes(StandardCharsets.UTF_8); long fileLength = bytes.length; if (!activities.checkLengthIndexable(fileLength)) { Logging.connectors.debug("JDBC: Document '"+id+"' excluded because of length - skipping"); errorCode = activities.EXCLUDED_LENGTH; errorDesc = "Excluded because of length ("+fileLength+")"; activities.noDocument(id, version); continue; } try { InputStream is = new ByteArrayInputStream(bytes); try { rd.setBinary(is,fileLength); activities.ingestDocumentWithException(id, version, url, rd); errorCode = "OK"; fileLengthLong = new Long(fileLength); } finally { is.close(); } } catch (IOException e) { errorCode = e.getClass().getSimpleName().toUpperCase(Locale.ROOT); errorDesc = e.getMessage(); handleIOException(id,e); } } } catch (ManifoldCFException e) { if (e.getErrorCode() == ManifoldCFException.INTERRUPTED) errorCode = null; throw e; } finally { if (errorCode != null) activities.recordActivity(new Long(fetchStartTime), ACTIVITY_FETCH, fileLengthLong, id, errorCode, errorDesc, null); } } finally { row.close(); } } } finally { result.close(); } // Now, go through the original id's, and see which ones are still in the map. These // did not appear in the result and are presumed to be gone from the database, and thus must be deleted. for (String documentIdentifier : documentIdentifiers) { if (fetchDocuments.contains(documentIdentifier)) { String documentVersion = map.get(documentIdentifier); if (documentVersion != null) { // This means we did not see it (or data for it) in the result set. Delete it! activities.noDocument(documentIdentifier,documentVersion); activities.recordActivity(null, ACTIVITY_FETCH, null, documentIdentifier, "NOTFETCHED", "Document was not seen by processing query", null); } } } } protected static void handleIOException(String id, IOException e) throws ManifoldCFException, ServiceInterruption { if (e instanceof java.net.SocketTimeoutException) { throw new ManifoldCFException("Socket timeout reading database data: "+e.getMessage(),e); } if (e instanceof InterruptedIOException) { throw new ManifoldCFException("Interrupted: "+e.getMessage(),e,ManifoldCFException.INTERRUPTED); } throw new ManifoldCFException("Error reading database data: "+e.getMessage(),e); } // UI support methods. // // These support methods come in two varieties. The first bunch is involved in setting up connection configuration information. The second bunch // is involved in presenting and editing document specification information for a job. The two kinds of methods are accordingly treated differently, // in that the first bunch cannot assume that the current connector object is connected, while the second bunch can. That is why the first bunch // receives a thread context argument for all UI methods, while the second bunch does not need one (since it has already been applied via the connect() // method, above). /** Output the configuration header section. * This method is called in the head section of the connector's configuration page. Its purpose is to add the required tabs to the list, and to output any * javascript methods that might be needed by the configuration editing HTML. *@param threadContext is the local thread context. *@param out is the output to which any HTML should be sent. *@param parameters are the configuration parameters, as they currently exist, for this connection being configured. *@param tabsArray is an array of tab names. Add to this array any tab names that are specific to the connector. */ @Override public void outputConfigurationHeader(IThreadContext threadContext, IHTTPOutput out, Locale locale, ConfigParams parameters, List<String> tabsArray) throws ManifoldCFException, IOException { tabsArray.add(Messages.getString(locale,"JDBCConnector.DatabaseType")); tabsArray.add(Messages.getString(locale,"JDBCConnector.Server")); tabsArray.add(Messages.getString(locale,"JDBCConnector.Credentials")); out.print( "<script type=\"text/javascript\">\n"+ "<!--\n"+ "function checkConfigForSave()\n"+ "{\n"+ " if (editconnection.databasehost.value == \"\" && editconnection.rawjdbcstring.value == \"\")\n"+ " {\n"+ " alert(\"" + Messages.getBodyJavascriptString(locale,"JDBCConnector.PleaseFillInADatabaseServerName") + "\");\n"+ " SelectTab(\"" + Messages.getBodyJavascriptString(locale,"JDBCConnector.Server") + "\");\n"+ " editconnection.databasehost.focus();\n"+ " return false;\n"+ " }\n"+ " if (editconnection.databasename.value == \"\" && editconnection.rawjdbcstring.value == \"\")\n"+ " {\n"+ " alert(\"" + Messages.getBodyJavascriptString(locale,"JDBCConnector.PleaseFillInTheNameOfTheDatabase") + "\");\n"+ " SelectTab(\"" + Messages.getBodyJavascriptString(locale,"JDBCConnector.Server") + "\");\n"+ " editconnection.databasename.focus();\n"+ " return false;\n"+ " }\n"+ " if (editconnection.username.value == \"\")\n"+ " {\n"+ " alert(\"" + Messages.getBodyJavascriptString(locale,"JDBCConnector.PleaseSupplyTheDatabaseUsernameForThisConnection") + "\");\n"+ " SelectTab(\"" + Messages.getBodyJavascriptString(locale,"JDBCConnector.Credentials") + "\");\n"+ " editconnection.username.focus();\n"+ " return false;\n"+ " }\n"+ " return true;\n"+ "}\n"+ "\n"+ "//-->\n"+ "</script>\n" ); } /** Output the configuration body section. * This method is called in the body section of the connector's configuration page. Its purpose is to present the required form elements for editing. * The coder can presume that the HTML that is output from this configuration will be within appropriate <html>, <body>, and <form> tags. The name of the * form is "editconnection". *@param threadContext is the local thread context. *@param out is the output to which any HTML should be sent. *@param parameters are the configuration parameters, as they currently exist, for this connection being configured. *@param tabName is the current tab name. */ @Override public void outputConfigurationBody(IThreadContext threadContext, IHTTPOutput out, Locale locale, ConfigParams parameters, String tabName) throws ManifoldCFException, IOException { String jdbcProvider = parameters.getParameter(JDBCConstants.providerParameter); if (jdbcProvider == null) jdbcProvider = "oracle:thin:@"; String accessMethod = parameters.getParameter(JDBCConstants.methodParameter); if (accessMethod == null) accessMethod = "name"; String host = parameters.getParameter(JDBCConstants.hostParameter); if (host == null) host = "localhost"; String databaseName = parameters.getParameter(JDBCConstants.databaseNameParameter); if (databaseName == null) databaseName = "database"; String rawJDBCString = parameters.getParameter(JDBCConstants.driverStringParameter); if (rawJDBCString == null) rawJDBCString = ""; String databaseUser = parameters.getParameter(JDBCConstants.databaseUserName); if (databaseUser == null) databaseUser = ""; String databasePassword = parameters.getObfuscatedParameter(JDBCConstants.databasePassword); if (databasePassword == null) databasePassword = ""; else databasePassword = out.mapPasswordToKey(databasePassword); // "Database Type" tab if (tabName.equals(Messages.getString(locale,"JDBCConnector.DatabaseType"))) { out.print( "<table class=\"displaytable\">\n"+ " <tr><td class=\"separator\" colspan=\"2\"><hr/></td></tr>\n"+ " <tr>\n"+ " <td class=\"description\"><nobr>" + Messages.getBodyString(locale,"JDBCConnector.DatabaseType2") + "</nobr></td><td class=\"value\">\n"+ " <select multiple=\"false\" name=\"databasetype\" size=\"2\">\n"+ " <option value=\"oracle:thin:@\" "+(jdbcProvider.equals("oracle:thin:@")?"selected=\"selected\"":"")+">Oracle</option>\n"+ " <option value=\"postgresql:\" "+(jdbcProvider.equals("postgresql:")?"selected=\"selected\"":"")+">Postgres SQL</option>\n"+ " <option value=\"jtds:sqlserver:\" "+(jdbcProvider.equals("jtds:sqlserver:")?"selected=\"selected\"":"")+">MS SQL Server (&gt; V6.5)</option>\n"+ " <option value=\"jtds:sybase:\" "+(jdbcProvider.equals("jtds:sybase:")?"selected=\"selected\"":"")+">Sybase (&gt;= V10)</option>\n"+ " <option value=\"mysql:\" "+(jdbcProvider.equals("mysql:")?"selected=\"selected\"":"")+">MySQL (&gt;= V5)</option>\n"+ " </select>\n"+ " </td>\n"+ " </tr>\n"+ " <tr><td class=\"separator\" colspan=\"2\"><hr/></td></tr>\n"+ " <tr>\n"+ " <td class=\"description\"><nobr>" + Messages.getBodyString(locale,"JDBCConnector.AccessMethod") + "</nobr></td><td class=\"value\">\n"+ " <select multiple=\"false\" name=\"accessmethod\" size=\"2\">\n"+ " <option value=\"name\" "+(accessMethod.equals("name")?"selected=\"selected\"":"")+">"+Messages.getBodyString(locale,"JDBCConnector.ByName")+"</option>\n"+ " <option value=\"label\" "+(accessMethod.equals("label")?"selected=\"selected\"":"")+">"+Messages.getBodyString(locale,"JDBCConnector.ByLabel")+"</option>\n"+ " </select>\n"+ " </td>\n"+ " </tr>\n"+ "</table>\n" ); } else { out.print( "<input type=\"hidden\" name=\"databasetype\" value=\""+jdbcProvider+"\"/>\n"+ "<input type=\"hidden\" name=\"accessmethod\" value=\""+accessMethod+"\"/>\n" ); } // "Server" tab if (tabName.equals(Messages.getString(locale,"JDBCConnector.Server"))) { out.print( "<table class=\"displaytable\">\n"+ " <tr><td class=\"separator\" colspan=\"2\"><hr/></td></tr>\n"+ " <tr>\n"+ " <td class=\"description\"><nobr>" + Messages.getBodyString(locale,"JDBCConnector.DatabaseHostAndPort") + "</nobr></td><td class=\"value\"><input type=\"text\" size=\"64\" name=\"databasehost\" value=\""+org.apache.manifoldcf.ui.util.Encoder.attributeEscape(host)+"\"/></td>\n"+ " </tr>\n"+ " <tr>\n"+ " <td class=\"description\"><nobr>" + Messages.getBodyString(locale,"JDBCConnector.DatabaseServiceNameOrInstanceDatabase") + "</nobr></td><td class=\"value\"><input type=\"text\" size=\"32\" name=\"databasename\" value=\""+org.apache.manifoldcf.ui.util.Encoder.attributeEscape(databaseName)+"\"/></td>\n"+ " </tr>\n"+ " <tr>\n"+ " <td class=\"description\"><nobr>" + Messages.getBodyString(locale,"JDBCConnector.RawDatabaseConnectString") + "</nobr></td><td class=\"value\"><input type=\"text\" size=\"80\" name=\"rawjdbcstring\" value=\""+org.apache.manifoldcf.ui.util.Encoder.attributeEscape(rawJDBCString)+"\"/></td>\n"+ " </tr>\n"+ "</table>\n" ); } else { out.print( "<input type=\"hidden\" name=\"databasehost\" value=\""+org.apache.manifoldcf.ui.util.Encoder.attributeEscape(host)+"\"/>\n"+ "<input type=\"hidden\" name=\"databasename\" value=\""+org.apache.manifoldcf.ui.util.Encoder.attributeEscape(databaseName)+"\"/>\n"+ "<input type=\"hidden\" name=\"rawjdbcstring\" value=\""+org.apache.manifoldcf.ui.util.Encoder.attributeEscape(rawJDBCString)+"\"/>\n" ); } // "Credentials" tab if (tabName.equals(Messages.getString(locale,"JDBCConnector.Credentials"))) { out.print( "<table class=\"displaytable\">\n"+ " <tr><td class=\"separator\" colspan=\"2\"><hr/></td></tr>\n"+ " <tr>\n"+ " <td class=\"description\"><nobr>" + Messages.getBodyString(locale,"JDBCConnector.UserName") + "</nobr></td><td class=\"value\"><input type=\"text\" size=\"32\" name=\"username\" value=\""+org.apache.manifoldcf.ui.util.Encoder.attributeEscape(databaseUser)+"\"/></td>\n"+ " </tr>\n"+ " <tr>\n"+ " <td class=\"description\"><nobr>" + Messages.getBodyString(locale,"JDBCConnector.Password") + "</nobr></td><td class=\"value\"><input type=\"password\" size=\"32\" name=\"password\" value=\""+org.apache.manifoldcf.ui.util.Encoder.attributeEscape(databasePassword)+"\"/></td>\n"+ " </tr>\n"+ "</table>\n" ); } else { out.print( "<input type=\"hidden\" name=\"username\" value=\""+org.apache.manifoldcf.ui.util.Encoder.attributeEscape(databaseUser)+"\"/>\n"+ "<input type=\"hidden\" name=\"password\" value=\""+org.apache.manifoldcf.ui.util.Encoder.attributeEscape(databasePassword)+"\"/>\n" ); } } /** Process a configuration post. * This method is called at the start of the connector's configuration page, whenever there is a possibility that form data for a connection has been * posted. Its purpose is to gather form information and modify the configuration parameters accordingly. * The name of the posted form is "editconnection". *@param threadContext is the local thread context. *@param variableContext is the set of variables available from the post, including binary file post information. *@param parameters are the configuration parameters, as they currently exist, for this connection being configured. *@return null if all is well, or a string error message if there is an error that should prevent saving of the connection (and cause a redirection to an error page). */ @Override public String processConfigurationPost(IThreadContext threadContext, IPostParameters variableContext, Locale locale, ConfigParams parameters) throws ManifoldCFException { String type = variableContext.getParameter("databasetype"); if (type != null) parameters.setParameter(JDBCConstants.providerParameter,type); String accessMethod = variableContext.getParameter("accessmethod"); if (accessMethod != null) parameters.setParameter(JDBCConstants.methodParameter,accessMethod); String host = variableContext.getParameter("databasehost"); if (host != null) parameters.setParameter(JDBCConstants.hostParameter,host); String databaseName = variableContext.getParameter("databasename"); if (databaseName != null) parameters.setParameter(JDBCConstants.databaseNameParameter,databaseName); String rawJDBCString = variableContext.getParameter("rawjdbcstring"); if (rawJDBCString != null) parameters.setParameter(JDBCConstants.driverStringParameter,rawJDBCString); String userName = variableContext.getParameter("username"); if (userName != null) parameters.setParameter(JDBCConstants.databaseUserName,userName); String password = variableContext.getParameter("password"); if (password != null) parameters.setObfuscatedParameter(JDBCConstants.databasePassword,variableContext.mapKeyToPassword(password)); return null; } /** View configuration. * This method is called in the body section of the connector's view configuration page. Its purpose is to present the connection information to the user. * The coder can presume that the HTML that is output from this configuration will be within appropriate <html> and <body> tags. *@param threadContext is the local thread context. *@param out is the output to which any HTML should be sent. *@param parameters are the configuration parameters, as they currently exist, for this connection being configured. */ @Override public void viewConfiguration(IThreadContext threadContext, IHTTPOutput out, Locale locale, ConfigParams parameters) throws ManifoldCFException, IOException { out.print( "<table class=\"displaytable\">\n"+ " <tr>\n"+ " <td class=\"description\" colspan=\"1\"><nobr>" + Messages.getBodyString(locale,"JDBCConnector.Parameters") + "</nobr></td>\n"+ " <td class=\"value\" colspan=\"3\">\n" ); Iterator iter = parameters.listParameters(); while (iter.hasNext()) { String param = (String)iter.next(); String value = parameters.getParameter(param); if (param.length() >= "password".length() && param.substring(param.length()-"password".length()).equalsIgnoreCase("password")) { out.print( " <nobr>"+org.apache.manifoldcf.ui.util.Encoder.bodyEscape(param)+"=********</nobr><br/>\n" ); } else if (param.length() >="keystore".length() && param.substring(param.length()-"keystore".length()).equalsIgnoreCase("keystore")) { IKeystoreManager kmanager = KeystoreManagerFactory.make("",value); out.print( " <nobr>"+org.apache.manifoldcf.ui.util.Encoder.bodyEscape(param)+"=&lt;"+Integer.toString(kmanager.getContents().length)+" certificate(s)&gt;</nobr><br/>\n" ); } else { out.print( " <nobr>"+org.apache.manifoldcf.ui.util.Encoder.bodyEscape(param)+"="+org.apache.manifoldcf.ui.util.Encoder.bodyEscape(value)+"</nobr><br/>\n" ); } } out.print( " </td>\n"+ " </tr>\n"+ "</table>\n" ); } /** Output the specification header section. * This method is called in the head section of a job page which has selected a repository connection of the * current type. Its purpose is to add the required tabs to the list, and to output any javascript methods * that might be needed by the job editing HTML. * The connector will be connected before this method can be called. *@param out is the output to which any HTML should be sent. *@param locale is the locale the output is preferred to be in. *@param ds is the current document specification for this job. *@param connectionSequenceNumber is the unique number of this connection within the job. *@param tabsArray is an array of tab names. Add to this array any tab names that are specific to the connector. */ @Override public void outputSpecificationHeader(IHTTPOutput out, Locale locale, Specification ds, int connectionSequenceNumber, List<String> tabsArray) throws ManifoldCFException, IOException { tabsArray.add(Messages.getString(locale,"JDBCConnector.Queries")); tabsArray.add(Messages.getString(locale,"JDBCConnector.Security")); String seqPrefix = "s"+connectionSequenceNumber+"_"; out.print( "<script type=\"text/javascript\">\n"+ "<!--\n"+ "\n"+ "function "+seqPrefix+"SpecOp(n, opValue, anchorvalue)\n"+ "{\n"+ " eval(\"editjob.\"+n+\".value = \\\"\"+opValue+\"\\\"\");\n"+ " postFormSetAnchor(anchorvalue);\n"+ "}\n"+ "\n"+ "function "+seqPrefix+"DeleteAttr(index)\n"+ "{\n"+ " "+seqPrefix+"SpecOp(\""+seqPrefix+"attr_\"+index+\"_op\", \"Delete\", \""+seqPrefix+"attr_\" + index);\n"+ "}\n"+ "\n"+ "function "+seqPrefix+"AddAttr()\n"+ "{\n"+ " if (editjob."+seqPrefix+"attr_name.value == \"\")\n"+ " {\n"+ " alert(\"" + Messages.getBodyJavascriptString(locale,"JDBCConnector.TypeInAnAttributeName") + "\");\n"+ " editjob."+seqPrefix+"attr_name.focus();\n"+ " return;\n"+ " }\n"+ " if (editjob."+seqPrefix+"attr_query.value == \"\")\n"+ " {\n"+ " alert(\"" + Messages.getBodyJavascriptString(locale,"JDBCConnector.AttributeQueryCannotBeNull") + "\");\n"+ " editjob."+seqPrefix+"attr_query.focus();\n"+ " return;\n"+ " }\n"+ " if (editjob."+seqPrefix+"attr_query.value.indexOf(\"$(IDCOLUMN)\") == -1)\n"+ " {\n"+ " alert(\"" + Messages.getBodyJavascriptString(locale,"JDBCConnector.MustReturnIDCOLUMNInTheResult") + "\");\n"+ " editjob."+seqPrefix+"attr_query.focus();\n"+ " return;\n"+ " }\n"+ " if (editjob."+seqPrefix+"attr_query.value.indexOf(\"$(DATACOLUMN)\") == -1)\n"+ " {\n"+ " alert(\"" + Messages.getBodyJavascriptString(locale,"JDBCConnector.MustReturnDATACOLUMNInTheResult") + "\");\n"+ " editjob."+seqPrefix+"attr_query.focus();\n"+ " return;\n"+ " }\n"+ " if (editjob."+seqPrefix+"attr_query.value.indexOf(\"$(IDLIST)\") == -1)\n"+ " {\n"+ " alert(\"" + Messages.getBodyJavascriptString(locale,"JDBCConnector.MustUseIDLISTInWHEREClause") + "\");\n"+ " editjob."+seqPrefix+"attr_query.focus();\n"+ " return;\n"+ " }\n"+ " "+seqPrefix+"SpecOp(\""+seqPrefix+"attr_op\", \"Add\", \""+seqPrefix+"attr\");\n"+ "}\n"+ "\n"+ "function "+seqPrefix+"SpecAddToken(anchorvalue)\n"+ "{\n"+ " if (editjob."+seqPrefix+"spectoken.value == \"\")\n"+ " {\n"+ " alert(\"" + Messages.getBodyJavascriptString(locale,"JDBCConnector.TypeInAnAccessToken") + "\");\n"+ " editjob."+seqPrefix+"spectoken.focus();\n"+ " return;\n"+ " }\n"+ " "+seqPrefix+"SpecOp(\""+seqPrefix+"accessop\",\"Add\",anchorvalue);\n"+ "}\n"+ "\n"+ "function "+seqPrefix+"checkSpecification()\n"+ "{\n"+ " if (editjob."+seqPrefix+"idquery.value == \"\")\n"+ " {\n"+ " alert(\"" + Messages.getBodyJavascriptString(locale,"JDBCConnector.EnterASeedingQuery") + "\");\n"+ " editjob."+seqPrefix+"idquery.focus();\n"+ " return false;\n"+ " }\n"+ " if (editjob."+seqPrefix+"idquery.value.indexOf(\"$(IDCOLUMN)\") == -1)\n"+ " {\n"+ " alert(\"" + Messages.getBodyJavascriptString(locale,"JDBCConnector.MustReturnIDCOLUMNInTheResult") + "\");\n"+ " editjob."+seqPrefix+"idquery.focus();\n"+ " return false;\n"+ " }\n"+ " if (editjob."+seqPrefix+"versionquery.value != \"\")\n"+ " {\n"+ " if (editjob."+seqPrefix+"versionquery.value.indexOf(\"$(IDCOLUMN)\") == -1)\n"+ " {\n"+ " alert(\"" + Messages.getBodyJavascriptString(locale,"JDBCConnector.MustReturnIDCOLUMNInTheResult") + "\");\n"+ " editjob."+seqPrefix+"versionquery.focus();\n"+ " return false;\n"+ " }\n"+ " if (editjob."+seqPrefix+"versionquery.value.indexOf(\"$(VERSIONCOLUMN)\") == -1)\n"+ " {\n"+ " alert(\"" + Messages.getBodyJavascriptString(locale,"JDBCConnector.MustReturnVERSIONCOLUMNInTheResult") + "\");\n"+ " editjob."+seqPrefix+"versionquery.focus();\n"+ " return false;\n"+ " }\n"+ " if (editjob."+seqPrefix+"versionquery.value.indexOf(\"$(IDLIST)\") == -1)\n"+ " {\n"+ " alert(\"" + Messages.getBodyJavascriptString(locale,"JDBCConnector.MustUseIDLISTInWHEREClause") + "\");\n"+ " editjob."+seqPrefix+"versionquery.focus();\n"+ " return false;\n"+ " }\n"+ " }\n"+ " if (editjob."+seqPrefix+"aclquery.value != \"\")\n"+ " {\n"+ " if (editjob."+seqPrefix+"aclquery.value.indexOf(\"$(IDCOLUMN)\") == -1)\n"+ " {\n"+ " alert(\"" + Messages.getBodyJavascriptString(locale,"JDBCConnector.MustReturnIDCOLUMNInTheResult") + "\");\n"+ " editjob."+seqPrefix+"aclquery.focus();\n"+ " return false;\n"+ " }\n"+ " if (editjob."+seqPrefix+"aclquery.value.indexOf(\"$(TOKENCOLUMN)\") == -1)\n"+ " {\n"+ " alert(\"" + Messages.getBodyJavascriptString(locale,"JDBCConnector.MustReturnTOKENCOLUMNInTheResult") + "\");\n"+ " editjob."+seqPrefix+"aclquery.focus();\n"+ " return false;\n"+ " }\n"+ " if (editjob."+seqPrefix+"aclquery.value.indexOf(\"$(IDLIST)\") == -1)\n"+ " {\n"+ " alert(\"" + Messages.getBodyJavascriptString(locale,"JDBCConnector.MustUseIDLISTInWHEREClause") + "\");\n"+ " editjob."+seqPrefix+"aclquery.focus();\n"+ " return false;\n"+ " }\n"+ " }\n"+ " if (editjob."+seqPrefix+"dataquery.value == \"\")\n"+ " {\n"+ " alert(\"" + Messages.getBodyJavascriptString(locale,"JDBCConnector.EnterADataQuery") + "\");\n"+ " editjob."+seqPrefix+"dataquery.focus();\n"+ " return false;\n"+ " }\n"+ " if (editjob."+seqPrefix+"dataquery.value.indexOf(\"$(IDCOLUMN)\") == -1)\n"+ " {\n"+ " alert(\"" + Messages.getBodyJavascriptString(locale,"JDBCConnector.MustReturnIDCOLUMNInTheResult2") + "\");\n"+ " editjob."+seqPrefix+"dataquery.focus();\n"+ " return false;\n"+ " }\n"+ " if (editjob."+seqPrefix+"dataquery.value.indexOf(\"$(URLCOLUMN)\") == -1)\n"+ " {\n"+ " alert(\"" + Messages.getBodyJavascriptString(locale,"JDBCConnector.MustReturnURLCOLUMNInTheResult") + "\");\n"+ " editjob."+seqPrefix+"dataquery.focus();\n"+ " return false;\n"+ " }\n"+ " if (editjob."+seqPrefix+"dataquery.value.indexOf(\"$(DATACOLUMN)\") == -1)\n"+ " {\n"+ " alert(\"" + Messages.getBodyJavascriptString(locale,"JDBCConnector.MustReturnDATACOLUMNInTheResult") + "\");\n"+ " editjob."+seqPrefix+"dataquery.focus();\n"+ " return false;\n"+ " }\n"+ " if (editjob."+seqPrefix+"dataquery.value.indexOf(\"$(IDLIST)\") == -1)\n"+ " {\n"+ " alert(\"" + Messages.getBodyJavascriptString(locale,"JDBCConnector.MustUseIDLISTInWHEREClause") + "\");\n"+ " editjob."+seqPrefix+"dataquery.focus();\n"+ " return false;\n"+ " }\n"+ "\n"+ " return true;\n"+ "}\n"+ "\n"+ "//-->\n"+ "</script>\n" ); } /** Output the specification body section. * This method is called in the body section of a job page which has selected a repository connection of the * current type. Its purpose is to present the required form elements for editing. * The coder can presume that the HTML that is output from this configuration will be within appropriate * <html>, <body>, and <form> tags. The name of the form is always "editjob". * The connector will be connected before this method can be called. *@param out is the output to which any HTML should be sent. *@param locale is the locale the output is preferred to be in. *@param ds is the current document specification for this job. *@param connectionSequenceNumber is the unique number of this connection within the job. *@param actualSequenceNumber is the connection within the job that has currently been selected. *@param tabName is the current tab name. (actualSequenceNumber, tabName) form a unique tuple within * the job. */ @Override public void outputSpecificationBody(IHTTPOutput out, Locale locale, Specification ds, int connectionSequenceNumber, int actualSequenceNumber, String tabName) throws ManifoldCFException, IOException { String seqPrefix = "s"+connectionSequenceNumber+"_"; String idQuery = "SELECT idfield AS $(IDCOLUMN) FROM documenttable WHERE modifydatefield > $(STARTTIME) AND modifydatefield <= $(ENDTIME)"; String versionQuery = "SELECT idfield AS $(IDCOLUMN), versionfield AS $(VERSIONCOLUMN) FROM documenttable WHERE idfield IN $(IDLIST)"; String dataQuery = "SELECT idfield AS $(IDCOLUMN), urlfield AS $(URLCOLUMN), datafield AS $(DATACOLUMN) FROM documenttable WHERE idfield IN $(IDLIST)"; String aclQuery = "SELECT docidfield AS $(IDCOLUMN), aclfield AS $(TOKENCOLUMN) FROM acltable WHERE docidfield IN $(IDLIST)"; final Map<String, String> attributeQueryMap = new HashMap<String, String>(); int i = 0; while (i < ds.getChildCount()) { SpecificationNode sn = ds.getChild(i++); if (sn.getType().equals(JDBCConstants.idQueryNode)) { idQuery = sn.getValue(); if (idQuery == null) idQuery = ""; } else if (sn.getType().equals(JDBCConstants.versionQueryNode)) { versionQuery = sn.getValue(); if (versionQuery == null) versionQuery = ""; } else if (sn.getType().equals(JDBCConstants.dataQueryNode)) { dataQuery = sn.getValue(); if (dataQuery == null) dataQuery = ""; } else if (sn.getType().equals(JDBCConstants.aclQueryNode)) { aclQuery = sn.getValue(); if (aclQuery == null) aclQuery = ""; } else if (sn.getType().equals(JDBCConstants.attributeQueryNode)) { String attributeName = sn.getAttributeValue(JDBCConstants.attributeName); String attributeQuery = sn.getValue(); attributeQueryMap.put(attributeName, attributeQuery); } } // Sort the attribute query list final String[] attributeNames = attributeQueryMap.keySet().toArray(new String[0]); java.util.Arrays.sort(attributeNames); // The Queries tab if (tabName.equals(Messages.getString(locale,"JDBCConnector.Queries")) && connectionSequenceNumber == actualSequenceNumber) { out.print( "<table class=\"displaytable\">\n"+ " <tr><td class=\"separator\" colspan=\"2\"><hr/></td></tr>\n"+ " <tr>\n"+ " <td class=\"description\"><nobr>" + Messages.getBodyString(locale,"JDBCConnector.SeedingQuery") + "</nobr><br/><nobr>" + Messages.getBodyString(locale,"JDBCConnector.returnIdsThatNeedToBeChecked") + "</nobr></td>\n"+ " <td class=\"value\"><textarea name=\""+seqPrefix+"idquery\" cols=\"64\" rows=\"6\">"+org.apache.manifoldcf.ui.util.Encoder.bodyEscape(idQuery)+"</textarea></td>\n"+ " </tr>\n"+ " <tr>\n"+ " <td class=\"description\"><nobr>" + Messages.getBodyString(locale,"JDBCConnector.VersionCheckQuery") + "</nobr><br/><nobr>" + Messages.getBodyString(locale,"JDBCConnector.returnIdsAndVersionsForASetOfDocuments") + "</nobr><br/><nobr>" + Messages.getBodyString(locale,"JDBCConnector.leaveBlankIfNoVersioningCapability") + "</nobr></td>\n"+ " <td class=\"value\"><textarea name=\""+seqPrefix+"versionquery\" cols=\"64\" rows=\"6\">"+org.apache.manifoldcf.ui.util.Encoder.bodyEscape(versionQuery)+"</textarea></td>\n"+ " </tr>\n"+ " <tr>\n"+ " <td class=\"description\"><nobr>" + Messages.getBodyString(locale,"JDBCConnector.AccessTokenQuery") + "</nobr><br/><nobr>" + Messages.getBodyString(locale,"JDBCConnector.returnIdsAndAccessTokensForASetOfDocuments") + "</nobr><br/><nobr>" + Messages.getBodyString(locale,"JDBCConnector.leaveBlankIfNoSecurityCapability") + "</nobr></td>\n"+ " <td class=\"value\"><textarea name=\""+seqPrefix+"aclquery\" cols=\"64\" rows=\"6\">"+org.apache.manifoldcf.ui.util.Encoder.bodyEscape(aclQuery)+"</textarea></td>\n"+ " </tr>\n"+ " <tr>\n"+ " <td class=\"description\"><nobr>" + Messages.getBodyString(locale,"JDBCConnector.DataQuery") + "</nobr><br/><nobr>" + Messages.getBodyString(locale,"JDBCConnector.returnIdsUrlsAndDataForASetOfDocuments") + "</nobr></td>\n"+ " <td class=\"value\"><textarea name=\""+seqPrefix+"dataquery\" cols=\"64\" rows=\"6\">"+org.apache.manifoldcf.ui.util.Encoder.bodyEscape(dataQuery)+"</textarea></td>\n"+ " </tr>\n"); out.print( " <tr><td class=\"separator\" colspan=\"2\"><hr/></td></tr>\n"+ " <tr>"+ " <td class=\"description\"><nobr>" + Messages.getBodyString(locale,"JDBCConnector.AttributeQueries") + "</nobr></td>\n"+ " <td class=\"boxcell\">\n"+ " <table class=\"formtable\">\n"+ " <tr class=\"formheaderrow\">\n"+ " <td class=\"formcolumnheader\"></td>\n"+ " <td class=\"formcolumnheader\"><nobr>" + Messages.getBodyString(locale,"JDBCConnector.AttributeName") + "</nobr></td>\n"+ " <td class=\"formcolumnheader\"><nobr>" + Messages.getBodyString(locale,"JDBCConnector.AttributeQuery") + "</nobr></td>\n"+ " </tr>\n" ); int attributeIndex = 0; for (final String attributeName : attributeNames) { final String attributeQuery = attributeQueryMap.get(attributeName); if (attributeIndex % 2 == 0) { out.print( " <tr class=\"evenformrow\">\n" ); } else { out.print( " <tr class=\"oddformrow\">\n" ); } // Delete button out.print( " <td class=\"formcolumncell\">\n"+ " <a name=\""+seqPrefix+"attr_"+attributeIndex+"\">\n"+ " <nobr>\n"+ " <input type=\"button\" value=\""+Messages.getAttributeString(locale,"JDBCConnector.Delete")+"\"\n"+ " alt=\""+Messages.getAttributeString(locale,"JDBCConnector.DeleteAttributeQueryNumber")+attributeIndex+"\" onclick=\"javascript:"+seqPrefix+"DeleteAttr("+attributeIndex+");\"/>\n"+ " </nobr>\n"+ " </a>\n"+ " <input type=\"hidden\" name=\""+seqPrefix+"attr_"+attributeIndex+"_op"+"\" value=\"Continue\"/>\n"+ " <input type=\"hidden\" name=\""+seqPrefix+"attr_"+attributeIndex+"_name\" value=\""+org.apache.manifoldcf.ui.util.Encoder.attributeEscape(attributeName)+"\"/>\n"+ " </td>\n" ); // Attribute name out.print( " <td class=\"formcolumncell\">\n"+ " "+org.apache.manifoldcf.ui.util.Encoder.bodyEscape(attributeName)+"\n"+ " </td>\n" ); // Query out.print( " <td class=\"formcolumncell\">\n"+ " <textarea name=\""+seqPrefix+"attr_"+attributeIndex+"_query\" cols=\"64\" rows=\"6\">"+org.apache.manifoldcf.ui.util.Encoder.bodyEscape(dataQuery)+"</textarea>\n"+ " </td>\n" ); out.print( " </tr>\n" ); attributeIndex++; } if (attributeIndex == 0) { out.print( " <tr><td class=\"formmessage\" colspan=\"3\">"+Messages.getBodyString(locale,"JDBCConnector.NoAttributeQueries")+"</td></tr>\n" ); } // Add button out.print( " <tr><td class=\"formseparator\" colspan=\"3\"><hr/></td></tr>\n"+ " <tr class=\"formrow\">\n"+ " <td class=\"formcolumncell\">\n"+ " <a name=\""+seqPrefix+"attr_"+attributeIndex+"\">\n"+ " <input type=\"button\" value=\""+Messages.getAttributeString(locale,"JDBCConnector.Add")+"\"\n"+ " alt=\""+Messages.getAttributeString(locale,"JDBCConnector.AddAttribute")+"\" onclick=\"javascript:"+seqPrefix+"AddAttr();\"/>\n"+ " </a>\n"+ " <input type=\"hidden\" name=\""+seqPrefix+"attr_count\" value=\""+attributeIndex+"\"/>\n"+ " <input type=\"hidden\" name=\""+seqPrefix+"attr_op\" value=\"Continue\"/>\n"+ " </td>\n"+ " <td class=\"formcolumncell\"><nobr><input name=\""+seqPrefix+"attr_name\" type=\"text\" size=\"32\" value=\"\"/></nobr></td>\n"+ " <td class=\"formcolumncell\">\n"+ " <textarea name=\""+seqPrefix+"attr_query\" cols=\"64\" rows=\"6\"></textarea>\n"+ " </td>\n"+ " </tr>\n" ); out.print( " </table>\n"+ " </td>\n"+ " </tr>\n"+ "</table>\n" ); } else { out.print( "<input type=\"hidden\" name=\""+seqPrefix+"idquery\" value=\""+org.apache.manifoldcf.ui.util.Encoder.attributeEscape(idQuery)+"\"/>\n"+ "<input type=\"hidden\" name=\""+seqPrefix+"versionquery\" value=\""+org.apache.manifoldcf.ui.util.Encoder.attributeEscape(versionQuery)+"\"/>\n"+ "<input type=\"hidden\" name=\""+seqPrefix+"aclquery\" value=\""+org.apache.manifoldcf.ui.util.Encoder.attributeEscape(aclQuery)+"\"/>\n"+ "<input type=\"hidden\" name=\""+seqPrefix+"dataquery\" value=\""+org.apache.manifoldcf.ui.util.Encoder.attributeEscape(dataQuery)+"\"/>\n" ); int attributeIndex = 0; for (final String attributeName : attributeNames) { final String attributeQuery = attributeQueryMap.get(attributeName); out.print( "<input type=\"hidden\" name=\""+seqPrefix+"attr_"+attributeIndex+"_name\" value=\""+org.apache.manifoldcf.ui.util.Encoder.attributeEscape(attributeName)+"\"/>\n"+ "<input type=\"hidden\" name=\""+seqPrefix+"attr_"+attributeIndex+"_query\" value=\""+org.apache.manifoldcf.ui.util.Encoder.attributeEscape(attributeQuery)+"\"/>\n" ); attributeIndex++; } out.print( "<input type=\"hidden\" name=\""+seqPrefix+"attr_count\" value=\""+attributeIndex+"\"/>\n" ); } // Security tab // There is no native security, so all we care about are the tokens. i = 0; boolean securityOn = true; while (i < ds.getChildCount()) { SpecificationNode sn = ds.getChild(i++); if (sn.getType().equals("security")) { String securityValue = sn.getAttributeValue("value"); if (securityValue.equals("off")) securityOn = false; else if (securityValue.equals("on")) securityOn = true; } } if (tabName.equals(Messages.getString(locale,"JDBCConnector.Security")) && connectionSequenceNumber == actualSequenceNumber) { out.print( "<table class=\"displaytable\">\n"+ " <tr><td class=\"separator\" colspan=\"2\"><hr/></td></tr>\n"+ " <tr>\n"+ " <td class=\"description\"><nobr>"+Messages.getBodyString(locale,"JDBCConnector.SecurityColon")+"</nobr></td>\n"+ " <td class=\"value\">\n"+ " <input type=\"radio\" name=\""+seqPrefix+"specsecurity\" value=\"on\" "+(securityOn?"checked=\"true\"":"")+" />"+Messages.getBodyString(locale,"JDBCConnector.Enabled")+"\n"+ " <input type=\"radio\" name=\""+seqPrefix+"specsecurity\" value=\"off\" "+((securityOn==false)?"checked=\"true\"":"")+" />"+Messages.getBodyString(locale,"JDBCConnector.Disabled")+"\n"+ " </td>\n"+ " </tr>\n"+ " <tr><td class=\"separator\" colspan=\"2\"><hr/></td></tr>\n" ); // Go through forced ACL i = 0; int k = 0; while (i < ds.getChildCount()) { SpecificationNode sn = ds.getChild(i++); if (sn.getType().equals("access")) { String accessDescription = "_"+Integer.toString(k); String accessOpName = seqPrefix+"accessop"+accessDescription; String token = sn.getAttributeValue("token"); out.print( " <tr>\n"+ " <td class=\"description\">\n"+ " <input type=\"hidden\" name=\""+accessOpName+"\" value=\"\"/>\n"+ " <input type=\"hidden\" name=\""+seqPrefix+"spectoken"+accessDescription+"\" value=\""+org.apache.manifoldcf.ui.util.Encoder.attributeEscape(token)+"\"/>\n"+ " <a name=\""+seqPrefix+"token_"+Integer.toString(k)+"\">\n"+ " <input type=\"button\" value=\"Delete\" onClick='Javascript:"+seqPrefix+"SpecOp(\""+accessOpName+"\",\"Delete\",\""+seqPrefix+"token_"+Integer.toString(k)+"\")' alt=\"" + Messages.getAttributeString(locale,"JDBCConnector.DeleteToken") + "\""+Integer.toString(k)+"\"/>\n"+ " </a>&nbsp;\n"+ " </td>\n"+ " <td class=\"value\">\n"+ " "+org.apache.manifoldcf.ui.util.Encoder.bodyEscape(token)+"\n"+ " </td>\n"+ " </tr>\n" ); k++; } } if (k == 0) { out.print( " <tr>\n"+ " <td class=\"message\" colspan=\"2\">" + Messages.getBodyString(locale,"JDBCConnector.NoAccessTokensPresent") + "</td>\n"+ " </tr>\n" ); } out.print( " <tr><td class=\"lightseparator\" colspan=\"2\"><hr/></td></tr>\n"+ " <tr>\n"+ " <td class=\"description\">\n"+ " <input type=\"hidden\" name=\""+seqPrefix+"tokencount\" value=\""+Integer.toString(k)+"\"/>\n"+ " <input type=\"hidden\" name=\""+seqPrefix+"accessop\" value=\"\"/>\n"+ " <a name=\""+seqPrefix+"token_"+Integer.toString(k)+"\">\n"+ " <input type=\"button\" value=\"Add\" onClick='Javascript:"+seqPrefix+"SpecAddToken(\""+seqPrefix+"token_"+Integer.toString(k+1)+"\")' alt=\"" + Messages.getAttributeString(locale,"JDBCConnector.AddAccessToken") + "\"/>\n"+ " </a>&nbsp;\n"+ " </td>\n"+ " <td class=\"value\">\n"+ " <input type=\"text\" size=\"30\" name=\""+seqPrefix+"spectoken\" value=\"\"/>\n"+ " </td>\n"+ " </tr>\n"+ "</table>\n" ); } else { out.print( "<input type=\"hidden\" name=\""+seqPrefix+"specsecurity\" value=\""+(securityOn?"on":"off")+"\"/>\n" ); // Finally, go through forced ACL i = 0; int k = 0; while (i < ds.getChildCount()) { SpecificationNode sn = ds.getChild(i++); if (sn.getType().equals("access")) { String accessDescription = "_"+Integer.toString(k); String token = sn.getAttributeValue("token"); out.print( "<input type=\"hidden\" name=\""+seqPrefix+"spectoken"+accessDescription+"\" value=\""+org.apache.manifoldcf.ui.util.Encoder.attributeEscape(token)+"\"/>\n" ); k++; } } out.print( "<input type=\"hidden\" name=\""+seqPrefix+"tokencount\" value=\""+Integer.toString(k)+"\"/>\n" ); } } /** Process a specification post. * This method is called at the start of job's edit or view page, whenever there is a possibility that form * data for a connection has been posted. Its purpose is to gather form information and modify the * document specification accordingly. The name of the posted form is always "editjob". * The connector will be connected before this method can be called. *@param variableContext contains the post data, including binary file-upload information. *@param locale is the locale the output is preferred to be in. *@param ds is the current document specification for this job. *@param connectionSequenceNumber is the unique number of this connection within the job. *@return null if all is well, or a string error message if there is an error that should prevent saving of * the job (and cause a redirection to an error page). */ @Override public String processSpecificationPost(IPostParameters variableContext, Locale locale, Specification ds, int connectionSequenceNumber) throws ManifoldCFException { String seqPrefix = "s"+connectionSequenceNumber+"_"; String idQuery = variableContext.getParameter(seqPrefix+"idquery"); String versionQuery = variableContext.getParameter(seqPrefix+"versionquery"); String dataQuery = variableContext.getParameter(seqPrefix+"dataquery"); String aclQuery = variableContext.getParameter(seqPrefix+"aclquery"); SpecificationNode sn; if (idQuery != null) { int i = 0; while (i < ds.getChildCount()) { if (ds.getChild(i).getType().equals(JDBCConstants.idQueryNode)) ds.removeChild(i); else i++; } sn = new SpecificationNode(JDBCConstants.idQueryNode); sn.setValue(idQuery); ds.addChild(ds.getChildCount(),sn); } if (versionQuery != null) { int i = 0; while (i < ds.getChildCount()) { if (ds.getChild(i).getType().equals(JDBCConstants.versionQueryNode)) ds.removeChild(i); else i++; } sn = new SpecificationNode(JDBCConstants.versionQueryNode); sn.setValue(versionQuery); ds.addChild(ds.getChildCount(),sn); } if (aclQuery != null) { int i = 0; while (i < ds.getChildCount()) { if (ds.getChild(i).getType().equals(JDBCConstants.aclQueryNode)) ds.removeChild(i); else i++; } sn = new SpecificationNode(JDBCConstants.aclQueryNode); sn.setValue(aclQuery); ds.addChild(ds.getChildCount(),sn); } if (dataQuery != null) { int i = 0; while (i < ds.getChildCount()) { if (ds.getChild(i).getType().equals(JDBCConstants.dataQueryNode)) ds.removeChild(i); else i++; } sn = new SpecificationNode(JDBCConstants.dataQueryNode); sn.setValue(dataQuery); ds.addChild(ds.getChildCount(),sn); } String xc; xc = variableContext.getParameter(seqPrefix+"attr_count"); if (xc != null) { // Delete all attribute queries first int i = 0; while (i < ds.getChildCount()) { sn = ds.getChild(i); if (sn.getType().equals(JDBCConstants.attributeQueryNode)) ds.removeChild(i); else i++; } int attributeCount = Integer.parseInt(xc); for (int attributeIndex = 0; i < attributeCount; i++) { final String attributeOp = variableContext.getParameter(seqPrefix+"attr_"+attributeIndex+"_op"); if (!(attributeOp != null && attributeOp.equals("Delete"))) { // Include this!! final String attributeName = variableContext.getParameter(seqPrefix+"attr_"+attributeIndex+"_name"); final String attributeQuery = variableContext.getParameter(seqPrefix+"attr_"+attributeIndex+"_query"); SpecificationNode node = new SpecificationNode(JDBCConstants.attributeQueryNode); node.setAttribute(JDBCConstants.attributeName, attributeName); node.setValue(attributeQuery); ds.addChild(ds.getChildCount(),node); } } // Now, maybe do add final String newAttributeOp = variableContext.getParameter(seqPrefix+"attr_op"); if (newAttributeOp.equals("Add")) { final String attributeName = variableContext.getParameter(seqPrefix+"attr_name"); final String attributeQuery = variableContext.getParameter(seqPrefix+"attr_query"); SpecificationNode node = new SpecificationNode(JDBCConstants.attributeQueryNode); node.setAttribute(JDBCConstants.attributeName, attributeName); node.setValue(attributeQuery); ds.addChild(ds.getChildCount(),node); } } xc = variableContext.getParameter(seqPrefix+"specsecurity"); if (xc != null) { // Delete all security entries first int i = 0; while (i < ds.getChildCount()) { sn = ds.getChild(i); if (sn.getType().equals("security")) ds.removeChild(i); else i++; } SpecificationNode node = new SpecificationNode("security"); node.setAttribute("value",xc); ds.addChild(ds.getChildCount(),node); } xc = variableContext.getParameter(seqPrefix+"tokencount"); if (xc != null) { // Delete all tokens first int i = 0; while (i < ds.getChildCount()) { sn = ds.getChild(i); if (sn.getType().equals("access")) ds.removeChild(i); else i++; } int accessCount = Integer.parseInt(xc); i = 0; while (i < accessCount) { String accessDescription = "_"+Integer.toString(i); String accessOpName = seqPrefix+"accessop"+accessDescription; xc = variableContext.getParameter(accessOpName); if (xc != null && xc.equals("Delete")) { // Next row i++; continue; } // Get the stuff we need String accessSpec = variableContext.getParameter(seqPrefix+"spectoken"+accessDescription); SpecificationNode node = new SpecificationNode("access"); node.setAttribute("token",accessSpec); ds.addChild(ds.getChildCount(),node); i++; } String op = variableContext.getParameter(seqPrefix+"accessop"); if (op != null && op.equals("Add")) { String accessspec = variableContext.getParameter(seqPrefix+"spectoken"); SpecificationNode node = new SpecificationNode("access"); node.setAttribute("token",accessspec); ds.addChild(ds.getChildCount(),node); } } return null; } /** View specification. * This method is called in the body section of a job's view page. Its purpose is to present the document * specification information to the user. The coder can presume that the HTML that is output from * this configuration will be within appropriate <html> and <body> tags. * The connector will be connected before this method can be called. *@param out is the output to which any HTML should be sent. *@param locale is the locale the output is preferred to be in. *@param ds is the current document specification for this job. *@param connectionSequenceNumber is the unique number of this connection within the job. */ @Override public void viewSpecification(IHTTPOutput out, Locale locale, Specification ds, int connectionSequenceNumber) throws ManifoldCFException, IOException { String idQuery = ""; String versionQuery = ""; String dataQuery = ""; String aclQuery = ""; int i = 0; while (i < ds.getChildCount()) { SpecificationNode sn = ds.getChild(i++); if (sn.getType().equals(JDBCConstants.idQueryNode)) { idQuery = sn.getValue(); if (idQuery == null) idQuery = ""; } else if (sn.getType().equals(JDBCConstants.versionQueryNode)) { versionQuery = sn.getValue(); if (versionQuery == null) versionQuery = ""; } else if (sn.getType().equals(JDBCConstants.dataQueryNode)) { dataQuery = sn.getValue(); if (dataQuery == null) dataQuery = ""; } else if (sn.getType().equals(JDBCConstants.aclQueryNode)) { aclQuery = sn.getValue(); if (aclQuery == null) aclQuery = ""; } } out.print( "<table class=\"displaytable\">\n"+ " <tr>\n"+ " <td class=\"description\"><nobr>" + Messages.getBodyString(locale,"JDBCConnector.SeedingQuery") + "</nobr></td>\n"+ " <td class=\"value\">"+org.apache.manifoldcf.ui.util.Encoder.bodyEscape(idQuery)+"</td>\n"+ " </tr>\n"+ " <tr>\n"+ " <td class=\"description\"><nobr>" + Messages.getBodyString(locale,"JDBCConnector.VersionCheckQuery") + "</nobr></td>\n"+ " <td class=\"value\">"+org.apache.manifoldcf.ui.util.Encoder.bodyEscape(versionQuery)+"</td>\n"+ " </tr>\n"+ " <tr>\n"+ " <td class=\"description\"><nobr>" + Messages.getBodyString(locale,"JDBCConnector.AccessTokenQuery") + "</nobr></td>\n"+ " <td class=\"value\">"+org.apache.manifoldcf.ui.util.Encoder.bodyEscape(aclQuery)+"</td>\n"+ " </tr>\n"+ " <tr>\n"+ " <td class=\"description\"><nobr>" + Messages.getBodyString(locale,"JDBCConnector.DataQuery") + "</nobr></td>\n"+ " <td class=\"value\">"+org.apache.manifoldcf.ui.util.Encoder.bodyEscape(dataQuery)+"</td>\n"+ " </tr>\n"+ "\n"+ " <tr><td class=\"separator\" colspan=\"2\"><hr/></td></tr>\n" ); // Find whether security is on or off i = 0; boolean securityOn = true; while (i < ds.getChildCount()) { SpecificationNode sn = ds.getChild(i++); if (sn.getType().equals("security")) { String securityValue = sn.getAttributeValue("value"); if (securityValue.equals("off")) securityOn = false; else if (securityValue.equals("on")) securityOn = true; } } out.print( " <tr>\n"+ " <td class=\"description\">"+Messages.getBodyString(locale,"JDBCConnector.SecurityColon")+"</td>\n"+ " <td class=\"value\">"+(securityOn?Messages.getBodyString(locale,"JDBCConnector.Enabled"):Messages.getBodyString(locale,"JDBCConnector.Disabled"))+"</td>\n"+ " </tr>\n"+ "\n"+ " <tr><td class=\"separator\" colspan=\"2\"><hr/></td></tr>\n" ); // Go through looking for access tokens boolean seenAny = false; i = 0; while (i < ds.getChildCount()) { SpecificationNode sn = ds.getChild(i++); if (sn.getType().equals("access")) { if (seenAny == false) { out.print( " <tr><td class=\"description\"><nobr>" + Messages.getBodyString(locale,"JDBCConnector.AccessTokens") + "</nobr></td>\n"+ " <td class=\"value\">\n" ); seenAny = true; } String token = sn.getAttributeValue("token"); out.print( " "+org.apache.manifoldcf.ui.util.Encoder.bodyEscape(token)+"<br/>\n" ); } } if (seenAny) { out.print( " </td>\n"+ " </tr>\n" ); } else { out.print( " <tr><td class=\"message\" colspan=\"2\"><nobr>" + Messages.getBodyString(locale,"JDBCConnector.NoAccessTokensSpecified") + "</nobr></td></tr>\n" ); } out.print( "</table>\n" ); } /** Special column names, as far as document queries are concerned */ protected static HashMap documentKnownColumns; static { documentKnownColumns = new HashMap(); documentKnownColumns.put(JDBCConstants.idReturnColumnName,""); documentKnownColumns.put(JDBCConstants.urlReturnColumnName,""); documentKnownColumns.put(JDBCConstants.dataReturnColumnName,""); documentKnownColumns.put(JDBCConstants.contentTypeReturnColumnName,""); } /** Apply metadata to a repository document. *@param rd is the repository document to apply the metadata to. *@param row is the resultset row to use to get the metadata. All non-special columns from this row will be considered to be metadata. */ protected void applyMetadata(RepositoryDocument rd, IResultRow row) throws ManifoldCFException { // Cycle through the row's columns Iterator iter = row.getColumns(); while (iter.hasNext()) { String columnName = (String)iter.next(); if (documentKnownColumns.get(columnName) == null) { // Consider this column to contain metadata. // We can only accept non-binary metadata at this time. Object metadata = row.getValue(columnName); rd.addField(columnName,JDBCConnection.readAsString(metadata)); } } } /** Apply access tokens to a repository document. *@param rd is the repository document to apply the access tokens to. *@param version is the version string. *@param spec is the document specification. */ protected void applyAccessTokens(RepositoryDocument rd, Set<String> accessTokens) throws ManifoldCFException { if (accessTokens == null) return; String[] accessAcls = new String[accessTokens.size()]; int i = 0; for (String accessToken : accessTokens) { accessAcls[i++] = accessToken; } java.util.Arrays.sort(accessAcls); String[] denyAcls = new String[]{defaultAuthorityDenyToken}; rd.setSecurity(RepositoryDocument.SECURITY_TYPE_DOCUMENT,accessAcls,denyAcls); } /** Get the maximum number of documents to amalgamate together into one batch, for this connector. *@return the maximum number. 0 indicates "unlimited". */ @Override public int getMaxDocumentRequest() { // This is a number that is comfortably processed by the query processor as part of an IN clause. return 100; } // These are protected helper methods /** Add starttime and endtime query variables */ protected static void addVariable(VariableMap map, String varName, long variable) { ArrayList params = new ArrayList(); params.add(new Long(variable)); map.addVariable(varName,"?",params); } /** Add string query variables */ protected static void addVariable(VariableMap map, String varName, String variable) { ArrayList params = new ArrayList(); params.add(variable); map.addVariable(varName,"?",params); } /** Add string query constants */ protected static void addConstant(VariableMap map, String varName, String value) { map.addVariable(varName,value,null); } /** Build an idlist variable, and add it to the specified variable map. */ protected static boolean addIDList(VariableMap map, String varName, String[] documentIdentifiers, Set<String> fetchDocuments) { ArrayList params = new ArrayList(); StringBuilder sb = new StringBuilder(" ("); int k = 0; for (String documentIdentifier : documentIdentifiers) { if (fetchDocuments == null || fetchDocuments.contains(documentIdentifier)) { if (k > 0) sb.append(","); sb.append("?"); params.add(documentIdentifier); k++; } } sb.append(") "); map.addVariable(varName,sb.toString(),params); return (k > 0); } /** Given a query, and a parameter map, substitute it. * Each variable substitutes the string, and it also substitutes zero or more query parameters. */ protected static void substituteQuery(String inputString, VariableMap inputMap, StringBuilder outputQuery, ArrayList outputParams) throws ManifoldCFException { // We are looking for strings that look like this: $(something) // Right at the moment we don't care even about quotes, so we just want to look for $(. int startIndex = 0; while (true) { int nextIndex = inputString.indexOf("$(",startIndex); if (nextIndex == -1) { outputQuery.append(inputString.substring(startIndex)); break; } int endIndex = inputString.indexOf(")",nextIndex); if (endIndex == -1) { outputQuery.append(inputString.substring(startIndex)); break; } String variableName = inputString.substring(nextIndex+2,endIndex); VariableMapItem item = inputMap.getVariable(variableName); if (item == null) throw new ManifoldCFException("No such substitution variable: $("+variableName+")"); outputQuery.append(inputString.substring(startIndex,nextIndex)); outputQuery.append(item.getValue()); ArrayList inputParams = item.getParameters(); if (inputParams != null) { int i = 0; while (i < inputParams.size()) { Object x = inputParams.get(i++); outputParams.add(x); } } startIndex = endIndex+1; } } /** Create an entity identifier from a querystring and a parameter list. */ protected static String createQueryString(String queryText, ArrayList paramList) { StringBuilder sb = new StringBuilder(queryText); sb.append("; arguments = ("); int i = 0; while (i < paramList.size()) { if (i > 0) sb.append(","); Object parameter = paramList.get(i++); if (parameter instanceof String) sb.append(quoteSQLString((String)parameter)); else sb.append(parameter.toString()); } sb.append(")"); return sb.toString(); } /** Quote a sql string. */ protected static String quoteSQLString(String input) { StringBuilder sb = new StringBuilder("\'"); int i = 0; while (i < input.length()) { char x = input.charAt(i++); if (x == '\'') sb.append('\'').append(x); else if (x >= 0 && x < ' ') sb.append(' '); else sb.append(x); } sb.append("\'"); return sb.toString(); } /** Variable map entry. */ protected static class VariableMapItem { protected String value; protected ArrayList params; /** Constructor. */ public VariableMapItem(String value, ArrayList params) { this.value = value; this.params = params; } /** Get value. */ public String getValue() { return value; } /** Get parameters. */ public ArrayList getParameters() { return params; } } /** Variable map. */ protected static class VariableMap { protected Map variableMap = new HashMap(); /** Constructor */ public VariableMap() { } /** Add a variable map entry */ public void addVariable(String variableName, String value, ArrayList parameters) { VariableMapItem e = new VariableMapItem(value,parameters); variableMap.put(variableName,e); } /** Get a variable map entry */ public VariableMapItem getVariable(String variableName) { return (VariableMapItem)variableMap.get(variableName); } } /** This class represents data gleaned from a document specification, in a more usable form. */ protected static class TableSpec { public final String idQuery; public final String versionQuery; public final String dataQuery; public final String aclQuery; public final boolean securityOn; public final Set<String> aclMap = new HashSet<String>(); public TableSpec(Specification ds) { String idQuery = null; String versionQuery = null; String dataQuery = null; String aclQuery = null; boolean securityOn = false; for (int i = 0; i < ds.getChildCount(); i++) { SpecificationNode sn = ds.getChild(i); if (sn.getType().equals(JDBCConstants.idQueryNode)) { idQuery = sn.getValue(); if (idQuery == null) idQuery = ""; } else if (sn.getType().equals(JDBCConstants.versionQueryNode)) { versionQuery = sn.getValue(); if (versionQuery == null) versionQuery = ""; } else if (sn.getType().equals(JDBCConstants.dataQueryNode)) { dataQuery = sn.getValue(); if (dataQuery == null) dataQuery = ""; } else if (sn.getType().equals(JDBCConstants.aclQueryNode)) { aclQuery = sn.getValue(); if (aclQuery == null) aclQuery = ""; } else if (sn.getType().equals("access")) { String token = sn.getAttributeValue("token"); aclMap.add(token); } else if (sn.getType().equals("security")) { String value = sn.getAttributeValue("value"); securityOn = value.equals("on"); } } this.idQuery = idQuery; this.versionQuery = versionQuery; this.dataQuery = dataQuery; this.aclQuery = aclQuery; this.securityOn = securityOn; } public Set<String> getAcls() { return aclMap; } public boolean isSecurityOn() { return securityOn; } } }
connectors/jdbc/connector/src/main/java/org/apache/manifoldcf/crawler/connectors/jdbc/JDBCConnector.java
/* $Id: JDBCConnector.java 988245 2010-08-23 18:39:35Z kwright $ */ /** * 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.manifoldcf.crawler.connectors.jdbc; import org.apache.manifoldcf.core.interfaces.*; import org.apache.manifoldcf.agents.interfaces.*; import org.apache.manifoldcf.crawler.interfaces.*; import org.apache.manifoldcf.crawler.system.Logging; import org.apache.manifoldcf.core.database.*; import org.apache.manifoldcf.connectorcommon.interfaces.*; import org.apache.manifoldcf.jdbc.JDBCConnection; import org.apache.manifoldcf.jdbc.JDBCConstants; import org.apache.manifoldcf.jdbc.IDynamicResultSet; import org.apache.manifoldcf.jdbc.IDynamicResultRow; import java.nio.charset.StandardCharsets; import java.sql.*; import javax.naming.*; import javax.sql.*; import java.io.*; import java.util.*; /** JDBC repository connector. */ public class JDBCConnector extends org.apache.manifoldcf.crawler.connectors.BaseRepositoryConnector { public static final String _rcsid = "@(#)$Id: JDBCConnector.java 988245 2010-08-23 18:39:35Z kwright $"; // Activities that we know about protected final static String ACTIVITY_EXTERNAL_QUERY = "external query"; protected final static String ACTIVITY_FETCH = "fetch"; // Activities list protected static final String[] activitiesList = new String[]{ACTIVITY_EXTERNAL_QUERY, ACTIVITY_FETCH}; /** Deny access token for default authority */ private final static String defaultAuthorityDenyToken = "DEAD_AUTHORITY"; protected JDBCConnection connection = null; protected String jdbcProvider = null; protected String accessMethod = null; protected String host = null; protected String databaseName = null; protected String rawDriverString = null; protected String userName = null; protected String password = null; /** Constructor. */ public JDBCConnector() { } /** Set up a session */ protected void getSession() throws ManifoldCFException { if (connection == null) { if (jdbcProvider == null || jdbcProvider.length() == 0) throw new ManifoldCFException("Missing parameter '"+JDBCConstants.providerParameter+"'"); if ((host == null || host.length() == 0) && (rawDriverString == null || rawDriverString.length() == 0)) throw new ManifoldCFException("Missing parameter '"+JDBCConstants.hostParameter+"' or '"+JDBCConstants.driverStringParameter+"'"); connection = new JDBCConnection(jdbcProvider,(accessMethod==null || accessMethod.equals("name")),host,databaseName,rawDriverString,userName,password); } } /** Return the list of activities that this connector supports (i.e. writes into the log). *@return the list. */ @Override public String[] getActivitiesList() { return activitiesList; } /** Model. Depending on what people enter for the seeding query, this could be either ALL or * could be less than that. So, I've decided it will be at least the adds and changes, and * won't include the deletes. */ @Override public int getConnectorModel() { return MODEL_ADD_CHANGE; } /** Connect. The configuration parameters are included. *@param configParams are the configuration parameters for this connection. */ @Override public void connect(ConfigParams configParams) { super.connect(configParams); jdbcProvider = configParams.getParameter(JDBCConstants.providerParameter); accessMethod = configParams.getParameter(JDBCConstants.methodParameter); host = configParams.getParameter(JDBCConstants.hostParameter); databaseName = configParams.getParameter(JDBCConstants.databaseNameParameter); rawDriverString = configParams.getParameter(JDBCConstants.driverStringParameter); userName= configParams.getParameter(JDBCConstants.databaseUserName); password = configParams.getObfuscatedParameter(JDBCConstants.databasePassword); } /** Check status of connection. */ @Override public String check() throws ManifoldCFException { try { getSession(); // Attempt to fetch a connection; if this succeeds we pass connection.testConnection(); return super.check(); } catch (ServiceInterruption e) { if (Logging.connectors.isDebugEnabled()) Logging.connectors.debug("Service interruption in check(): "+e.getMessage(),e); return "Transient error: "+e.getMessage(); } } /** Close the connection. Call this before discarding the repository connector. */ @Override public void disconnect() throws ManifoldCFException { connection = null; host = null; jdbcProvider = null; accessMethod = null; databaseName = null; rawDriverString = null; userName = null; password = null; super.disconnect(); } /** Get the bin name string for a document identifier. The bin name describes the queue to which the * document will be assigned for throttling purposes. Throttling controls the rate at which items in a * given queue are fetched; it does not say anything about the overall fetch rate, which may operate on * multiple queues or bins. * For example, if you implement a web crawler, a good choice of bin name would be the server name, since * that is likely to correspond to a real resource that will need real throttle protection. *@param documentIdentifier is the document identifier. *@return the bin name. */ @Override public String[] getBinNames(String documentIdentifier) { return new String[]{(rawDriverString==null||rawDriverString.length()==0)?host:rawDriverString}; } /** Queue "seed" documents. Seed documents are the starting places for crawling activity. Documents * are seeded when this method calls appropriate methods in the passed in ISeedingActivity object. * * This method can choose to find repository changes that happen only during the specified time interval. * The seeds recorded by this method will be viewed by the framework based on what the * getConnectorModel() method returns. * * It is not a big problem if the connector chooses to create more seeds than are * strictly necessary; it is merely a question of overall work required. * * The end time and seeding version string passed to this method may be interpreted for greatest efficiency. * For continuous crawling jobs, this method will * be called once, when the job starts, and at various periodic intervals as the job executes. * * When a job's specification is changed, the framework automatically resets the seeding version string to null. The * seeding version string may also be set to null on each job run, depending on the connector model returned by * getConnectorModel(). * * Note that it is always ok to send MORE documents rather than less to this method. * The connector will be connected before this method can be called. *@param activities is the interface this method should use to perform whatever framework actions are desired. *@param spec is a document specification (that comes from the job). *@param seedTime is the end of the time range of documents to consider, exclusive. *@param lastSeedVersionString is the last seeding version string for this job, or null if the job has no previous seeding version string. *@param jobMode is an integer describing how the job is being run, whether continuous or once-only. *@return an updated seeding version string, to be stored with the job. */ @Override public String addSeedDocuments(ISeedingActivity activities, Specification spec, String lastSeedVersion, long seedTime, int jobMode) throws ManifoldCFException, ServiceInterruption { long startTime; if (lastSeedVersion == null) startTime = 0L; else { // Unpack seed time from seed version string startTime = new Long(lastSeedVersion).longValue(); } getSession(); // Set up the query TableSpec ts = new TableSpec(spec); VariableMap vm = new VariableMap(); addConstant(vm,JDBCConstants.idReturnVariable,JDBCConstants.idReturnColumnName); addVariable(vm,JDBCConstants.startTimeVariable,startTime); addVariable(vm,JDBCConstants.endTimeVariable,seedTime); // Do the substitution ArrayList paramList = new ArrayList(); StringBuilder sb = new StringBuilder(); substituteQuery(ts.idQuery,vm,sb,paramList); IDynamicResultSet idSet; String queryText = sb.toString(); long startQueryTime = System.currentTimeMillis(); // Contract for IDynamicResultset indicates that if successfully obtained, it MUST // be closed. try { idSet = connection.executeUncachedQuery(queryText,paramList,-1); } catch (ServiceInterruption e) { // If failure, record the failure. activities.recordActivity(new Long(startQueryTime), ACTIVITY_EXTERNAL_QUERY, null, createQueryString(queryText,paramList), "ERROR", e.getMessage(), null); throw e; } catch (ManifoldCFException e) { // If failure, record the failure. activities.recordActivity(new Long(startQueryTime), ACTIVITY_EXTERNAL_QUERY, null, createQueryString(queryText,paramList), "ERROR", e.getMessage(), null); throw e; } try { // If success, record that too. activities.recordActivity(new Long(startQueryTime), ACTIVITY_EXTERNAL_QUERY, null, createQueryString(queryText,paramList), "OK", null, null); while (true) { IDynamicResultRow row = idSet.getNextRow(); if (row == null) break; try { Object o = row.getValue(JDBCConstants.idReturnColumnName); if (o == null) throw new ManifoldCFException("Bad seed query; doesn't return $(IDCOLUMN) column. Try using quotes around $(IDCOLUMN) variable, e.g. \"$(IDCOLUMN)\", or, for MySQL, select \"by label\" in your repository connection."); String idValue = JDBCConnection.readAsString(o); activities.addSeedDocument(idValue); } finally { row.close(); } } } finally { idSet.close(); } return new Long(seedTime).toString(); } /** Process a set of documents. * This is the method that should cause each document to be fetched, processed, and the results either added * to the queue of documents for the current job, and/or entered into the incremental ingestion manager. * The document specification allows this class to filter what is done based on the job. * The connector will be connected before this method can be called. *@param documentIdentifiers is the set of document identifiers to process. *@param statuses are the currently-stored document versions for each document in the set of document identifiers * passed in above. *@param activities is the interface this method should use to queue up new document references * and ingest documents. *@param jobMode is an integer describing how the job is being run, whether continuous or once-only. *@param usesDefaultAuthority will be true only if the authority in use for these documents is the default one. */ @Override public void processDocuments(String[] documentIdentifiers, IExistingVersions statuses, Specification spec, IProcessActivity activities, int jobMode, boolean usesDefaultAuthority) throws ManifoldCFException, ServiceInterruption { TableSpec ts = new TableSpec(spec); Set<String> acls = ts.getAcls(); String[] versionsReturned = new String[documentIdentifiers.length]; // If there is no version query, then always return empty string for all documents. // This will mean that processDocuments will be called // for all. ProcessDocuments will then be responsible for doing document deletes itself, // based on the query results. Map<String,String> documentVersions = new HashMap<String,String>(); if (ts.versionQuery != null && ts.versionQuery.length() > 0) { // If there IS a versions query, do it. First set up the variables, then do the substitution. VariableMap vm = new VariableMap(); addConstant(vm,JDBCConstants.idReturnVariable,JDBCConstants.idReturnColumnName); addConstant(vm,JDBCConstants.versionReturnVariable,JDBCConstants.versionReturnColumnName); if (addIDList(vm,JDBCConstants.idListVariable,documentIdentifiers,null)) { // Do the substitution ArrayList paramList = new ArrayList(); StringBuilder sb = new StringBuilder(); substituteQuery(ts.versionQuery,vm,sb,paramList); // Now, build a result return, and a hash table so we can correlate the returned values with the place to put them. // We presume that if the row is missing, the document is gone. // Fire off the query! getSession(); IDynamicResultSet result; String queryText = sb.toString(); long startTime = System.currentTimeMillis(); // Get a dynamic resultset. Contract for dynamic resultset is that if // one is returned, it MUST be closed, or a connection will leak. try { result = connection.executeUncachedQuery(queryText,paramList,-1); } catch (ManifoldCFException e) { // If failure, record the failure. if (e.getErrorCode() != ManifoldCFException.INTERRUPTED) activities.recordActivity(new Long(startTime), ACTIVITY_EXTERNAL_QUERY, null, createQueryString(queryText,paramList), "ERROR", e.getMessage(), null); throw e; } try { // If success, record that too. activities.recordActivity(new Long(startTime), ACTIVITY_EXTERNAL_QUERY, null, createQueryString(queryText,paramList), "OK", null, null); // Now, go through resultset while (true) { IDynamicResultRow row = result.getNextRow(); if (row == null) break; try { Object o = row.getValue(JDBCConstants.idReturnColumnName); if (o == null) throw new ManifoldCFException("Bad version query; doesn't return $(IDCOLUMN) column. Try using quotes around $(IDCOLUMN) variable, e.g. \"$(IDCOLUMN)\", or, for MySQL, select \"by label\" in your repository connection."); String idValue = JDBCConnection.readAsString(o); o = row.getValue(JDBCConstants.versionReturnColumnName); String versionValue; // Null version is OK; make it a "" if (o == null) versionValue = ""; else versionValue = JDBCConnection.readAsString(o); documentVersions.put(idValue,versionValue); } finally { row.close(); } } } finally { result.close(); } } } else { for (String documentIdentifier : documentIdentifiers) { documentVersions.put(documentIdentifier,""); } } // Delete the documents that had no version, and work only on ones that did Set<String> fetchDocuments = documentVersions.keySet(); for (String documentIdentifier : documentIdentifiers) { String documentVersion = documentVersions.get(documentIdentifier); if (documentVersion == null) { activities.deleteDocument(documentIdentifier); continue; } } // Pick up document acls Map<String,Set<String>> documentAcls = new HashMap<String,Set<String>>(); if (ts.securityOn) { if (acls.size() == 0 && ts.aclQuery != null && ts.aclQuery.length() > 0) { // If there IS an acls query, do it. First set up the variables, then do the substitution. VariableMap vm = new VariableMap(); addConstant(vm,JDBCConstants.idReturnVariable,JDBCConstants.idReturnColumnName); addConstant(vm,JDBCConstants.tokenReturnVariable,JDBCConstants.tokenReturnColumnName); if (addIDList(vm,JDBCConstants.idListVariable,documentIdentifiers,fetchDocuments)) { // Do the substitution ArrayList paramList = new ArrayList(); StringBuilder sb = new StringBuilder(); substituteQuery(ts.aclQuery,vm,sb,paramList); // Fire off the query! getSession(); IDynamicResultSet result; String queryText = sb.toString(); long startTime = System.currentTimeMillis(); // Get a dynamic resultset. Contract for dynamic resultset is that if // one is returned, it MUST be closed, or a connection will leak. try { result = connection.executeUncachedQuery(queryText,paramList,-1); } catch (ManifoldCFException e) { // If failure, record the failure. if (e.getErrorCode() != ManifoldCFException.INTERRUPTED) activities.recordActivity(new Long(startTime), ACTIVITY_EXTERNAL_QUERY, null, createQueryString(queryText,paramList), "ERROR", e.getMessage(), null); throw e; } try { // If success, record that too. activities.recordActivity(new Long(startTime), ACTIVITY_EXTERNAL_QUERY, null, createQueryString(queryText,paramList), "OK", null, null); // Now, go through resultset while (true) { IDynamicResultRow row = result.getNextRow(); if (row == null) break; try { Object o = row.getValue(JDBCConstants.idReturnColumnName); if (o == null) throw new ManifoldCFException("Bad acl query; doesn't return $(IDCOLUMN) column. Try using quotes around $(IDCOLUMN) variable, e.g. \"$(IDCOLUMN)\", or, for MySQL, select \"by label\" in your repository connection."); String idValue = JDBCConnection.readAsString(o); o = row.getValue(JDBCConstants.tokenReturnColumnName); String tokenValue; if (o == null) tokenValue = ""; else tokenValue = JDBCConnection.readAsString(o); // Versions that are "", when processed, will have their acls fetched at that time... Set<String> dcs = documentAcls.get(idValue); if (dcs == null) { dcs = new HashSet<String>(); documentAcls.put(idValue,dcs); } dcs.add(tokenValue); } finally { row.close(); } } } finally { result.close(); } } } else { for (String documentIdentifier : fetchDocuments) { documentAcls.put(documentIdentifier,acls); } } } Map<String,String> map = new HashMap<String,String>(); for (String documentIdentifier : fetchDocuments) { String documentVersion = documentVersions.get(documentIdentifier); if (documentVersion.length() == 0) { map.put(documentIdentifier,documentVersion); } else { // Compute a full version string StringBuilder sb = new StringBuilder(); Set<String> dAcls = documentAcls.get(documentIdentifier); if (dAcls == null) sb.append('-'); else { sb.append('+'); String[] aclValues = new String[dAcls.size()]; int k = 0; for (String acl : dAcls) { aclValues[k++] = acl; } java.util.Arrays.sort(aclValues); packList(sb,aclValues,'+'); } sb.append(documentVersion).append("=").append(ts.dataQuery); String versionValue = sb.toString(); if (activities.checkDocumentNeedsReindexing(documentIdentifier,versionValue)) { map.put(documentIdentifier,versionValue); } } } // For all the documents not marked "scan only", form a query and pick up the contents. // If the contents is not found, then explicitly call the delete action method. VariableMap vm = new VariableMap(); addConstant(vm,JDBCConstants.idReturnVariable,JDBCConstants.idReturnColumnName); addConstant(vm,JDBCConstants.urlReturnVariable,JDBCConstants.urlReturnColumnName); addConstant(vm,JDBCConstants.dataReturnVariable,JDBCConstants.dataReturnColumnName); addConstant(vm,JDBCConstants.contentTypeReturnVariable,JDBCConstants.contentTypeReturnColumnName); if (!addIDList(vm,JDBCConstants.idListVariable,documentIdentifiers,map.keySet())) return; // Do the substitution ArrayList paramList = new ArrayList(); StringBuilder sb = new StringBuilder(); substituteQuery(ts.dataQuery,vm,sb,paramList); // Execute the query getSession(); IDynamicResultSet result; String queryText = sb.toString(); long startTime = System.currentTimeMillis(); // Get a dynamic resultset. Contract for dynamic resultset is that if // one is returned, it MUST be closed, or a connection will leak. try { result = connection.executeUncachedQuery(queryText,paramList,-1); } catch (ManifoldCFException e) { // If failure, record the failure. activities.recordActivity(new Long(startTime), ACTIVITY_EXTERNAL_QUERY, null, createQueryString(queryText,paramList), "ERROR", e.getMessage(), null); throw e; } try { // If success, record that too. activities.recordActivity(new Long(startTime), ACTIVITY_EXTERNAL_QUERY, null, createQueryString(queryText,paramList), "OK", null, null); while (true) { IDynamicResultRow row = result.getNextRow(); if (row == null) break; try { Object o = row.getValue(JDBCConstants.idReturnColumnName); if (o == null) throw new ManifoldCFException("Bad document query; doesn't return $(IDCOLUMN) column. Try using quotes around $(IDCOLUMN) variable, e.g. \"$(IDCOLUMN)\", or, for MySQL, select \"by label\" in your repository connection."); String id = JDBCConnection.readAsString(o); String errorCode = null; String errorDesc = null; Long fileLengthLong = null; long fetchStartTime = System.currentTimeMillis(); try { String version = map.get(id); if (version == null) // Does not need refetching continue; // This document was marked as "not scan only", so we expect to find it. if (Logging.connectors.isDebugEnabled()) Logging.connectors.debug("JDBC: Document data result found for '"+id+"'"); o = row.getValue(JDBCConstants.urlReturnColumnName); if (o == null) { Logging.connectors.debug("JDBC: Document '"+id+"' has a null url - skipping"); errorCode = activities.NULL_URL; errorDesc = "Excluded because document had a null URL"; activities.noDocument(id,version); continue; } // This is not right - url can apparently be a BinaryInput String url = JDBCConnection.readAsString(o); boolean validURL; try { // Check to be sure url is valid new java.net.URI(url); validURL = true; } catch (java.net.URISyntaxException e) { validURL = false; } if (!validURL) { Logging.connectors.debug("JDBC: Document '"+id+"' has an illegal url: '"+url+"' - skipping"); errorCode = activities.BAD_URL; errorDesc = "Excluded because document had illegal URL ('"+url+"')"; activities.noDocument(id,version); continue; } // Process the document itself Object contents = row.getValue(JDBCConstants.dataReturnColumnName); // Null data is allowed; we just ignore these if (contents == null) { Logging.connectors.debug("JDBC: Document '"+id+"' seems to have null data - skipping"); errorCode = "NULLDATA"; errorDesc = "Excluded because document had null data"; activities.noDocument(id,version); continue; } // We will ingest something, so remove this id from the map in order that we know what we still // need to delete when all done. map.remove(id); String contentType; o = row.getValue(JDBCConstants.contentTypeReturnColumnName); if (o != null) contentType = JDBCConnection.readAsString(o); else { if (contents instanceof BinaryInput) contentType = "application/octet-stream"; else if (contents instanceof CharacterInput) contentType = "text/plain; charset=utf-8"; else contentType = "text/plain"; } if (!activities.checkMimeTypeIndexable(contentType)) { Logging.connectors.debug("JDBC: Document '"+id+"' excluded because of mime type - skipping"); errorCode = activities.EXCLUDED_MIMETYPE; errorDesc = "Excluded because of mime type ("+contentType+")"; activities.noDocument(id,version); continue; } if (!activities.checkURLIndexable(url)) { Logging.connectors.debug("JDBC: Document '"+id+"' excluded because of url - skipping"); errorCode = activities.EXCLUDED_URL; errorDesc = "Excluded because of URL ('"+url+"')"; activities.noDocument(id,version); continue; } // An ingestion will take place for this document. RepositoryDocument rd = new RepositoryDocument(); rd.setMimeType(contentType); applyAccessTokens(rd,documentAcls.get(id)); applyMetadata(rd,row); if (contents instanceof BinaryInput) { BinaryInput bi = (BinaryInput)contents; long fileLength = bi.getLength(); if (!activities.checkLengthIndexable(fileLength)) { Logging.connectors.debug("JDBC: Document '"+id+"' excluded because of length - skipping"); errorCode = activities.EXCLUDED_LENGTH; errorDesc = "Excluded because of length ("+fileLength+")"; activities.noDocument(id, version); continue; } try { // Read the stream InputStream is = bi.getStream(); try { rd.setBinary(is,fileLength); activities.ingestDocumentWithException(id, version, url, rd); errorCode = "OK"; fileLengthLong = new Long(fileLength); } finally { is.close(); } } catch (IOException e) { errorCode = e.getClass().getSimpleName().toUpperCase(Locale.ROOT); errorDesc = e.getMessage(); handleIOException(id,e); } } else if (contents instanceof CharacterInput) { CharacterInput ci = (CharacterInput)contents; long fileLength = ci.getUtf8StreamLength(); if (!activities.checkLengthIndexable(fileLength)) { Logging.connectors.debug("JDBC: Document '"+id+"' excluded because of length - skipping"); errorCode = activities.EXCLUDED_LENGTH; errorDesc = "Excluded because of length ("+fileLength+")"; activities.noDocument(id, version); continue; } try { // Read the stream InputStream is = ci.getUtf8Stream(); try { rd.setBinary(is,fileLength); activities.ingestDocumentWithException(id, version, url, rd); errorCode = "OK"; fileLengthLong = new Long(fileLength); } finally { is.close(); } } catch (IOException e) { errorCode = e.getClass().getSimpleName().toUpperCase(Locale.ROOT); errorDesc = e.getMessage(); handleIOException(id,e); } } else { // Turn it into a string, and then into a stream String value = contents.toString(); byte[] bytes = value.getBytes(StandardCharsets.UTF_8); long fileLength = bytes.length; if (!activities.checkLengthIndexable(fileLength)) { Logging.connectors.debug("JDBC: Document '"+id+"' excluded because of length - skipping"); errorCode = activities.EXCLUDED_LENGTH; errorDesc = "Excluded because of length ("+fileLength+")"; activities.noDocument(id, version); continue; } try { InputStream is = new ByteArrayInputStream(bytes); try { rd.setBinary(is,fileLength); activities.ingestDocumentWithException(id, version, url, rd); errorCode = "OK"; fileLengthLong = new Long(fileLength); } finally { is.close(); } } catch (IOException e) { errorCode = e.getClass().getSimpleName().toUpperCase(Locale.ROOT); errorDesc = e.getMessage(); handleIOException(id,e); } } } catch (ManifoldCFException e) { if (e.getErrorCode() == ManifoldCFException.INTERRUPTED) errorCode = null; throw e; } finally { if (errorCode != null) activities.recordActivity(new Long(fetchStartTime), ACTIVITY_FETCH, fileLengthLong, id, errorCode, errorDesc, null); } } finally { row.close(); } } } finally { result.close(); } // Now, go through the original id's, and see which ones are still in the map. These // did not appear in the result and are presumed to be gone from the database, and thus must be deleted. for (String documentIdentifier : documentIdentifiers) { if (fetchDocuments.contains(documentIdentifier)) { String documentVersion = map.get(documentIdentifier); if (documentVersion != null) { // This means we did not see it (or data for it) in the result set. Delete it! activities.noDocument(documentIdentifier,documentVersion); activities.recordActivity(null, ACTIVITY_FETCH, null, documentIdentifier, "NOTFETCHED", "Document was not seen by processing query", null); } } } } protected static void handleIOException(String id, IOException e) throws ManifoldCFException, ServiceInterruption { if (e instanceof java.net.SocketTimeoutException) { throw new ManifoldCFException("Socket timeout reading database data: "+e.getMessage(),e); } if (e instanceof InterruptedIOException) { throw new ManifoldCFException("Interrupted: "+e.getMessage(),e,ManifoldCFException.INTERRUPTED); } throw new ManifoldCFException("Error reading database data: "+e.getMessage(),e); } // UI support methods. // // These support methods come in two varieties. The first bunch is involved in setting up connection configuration information. The second bunch // is involved in presenting and editing document specification information for a job. The two kinds of methods are accordingly treated differently, // in that the first bunch cannot assume that the current connector object is connected, while the second bunch can. That is why the first bunch // receives a thread context argument for all UI methods, while the second bunch does not need one (since it has already been applied via the connect() // method, above). /** Output the configuration header section. * This method is called in the head section of the connector's configuration page. Its purpose is to add the required tabs to the list, and to output any * javascript methods that might be needed by the configuration editing HTML. *@param threadContext is the local thread context. *@param out is the output to which any HTML should be sent. *@param parameters are the configuration parameters, as they currently exist, for this connection being configured. *@param tabsArray is an array of tab names. Add to this array any tab names that are specific to the connector. */ @Override public void outputConfigurationHeader(IThreadContext threadContext, IHTTPOutput out, Locale locale, ConfigParams parameters, List<String> tabsArray) throws ManifoldCFException, IOException { tabsArray.add(Messages.getString(locale,"JDBCConnector.DatabaseType")); tabsArray.add(Messages.getString(locale,"JDBCConnector.Server")); tabsArray.add(Messages.getString(locale,"JDBCConnector.Credentials")); out.print( "<script type=\"text/javascript\">\n"+ "<!--\n"+ "function checkConfigForSave()\n"+ "{\n"+ " if (editconnection.databasehost.value == \"\" && editconnection.rawjdbcstring.value == \"\")\n"+ " {\n"+ " alert(\"" + Messages.getBodyJavascriptString(locale,"JDBCConnector.PleaseFillInADatabaseServerName") + "\");\n"+ " SelectTab(\"" + Messages.getBodyJavascriptString(locale,"JDBCConnector.Server") + "\");\n"+ " editconnection.databasehost.focus();\n"+ " return false;\n"+ " }\n"+ " if (editconnection.databasename.value == \"\" && editconnection.rawjdbcstring.value == \"\")\n"+ " {\n"+ " alert(\"" + Messages.getBodyJavascriptString(locale,"JDBCConnector.PleaseFillInTheNameOfTheDatabase") + "\");\n"+ " SelectTab(\"" + Messages.getBodyJavascriptString(locale,"JDBCConnector.Server") + "\");\n"+ " editconnection.databasename.focus();\n"+ " return false;\n"+ " }\n"+ " if (editconnection.username.value == \"\")\n"+ " {\n"+ " alert(\"" + Messages.getBodyJavascriptString(locale,"JDBCConnector.PleaseSupplyTheDatabaseUsernameForThisConnection") + "\");\n"+ " SelectTab(\"" + Messages.getBodyJavascriptString(locale,"JDBCConnector.Credentials") + "\");\n"+ " editconnection.username.focus();\n"+ " return false;\n"+ " }\n"+ " return true;\n"+ "}\n"+ "\n"+ "//-->\n"+ "</script>\n" ); } /** Output the configuration body section. * This method is called in the body section of the connector's configuration page. Its purpose is to present the required form elements for editing. * The coder can presume that the HTML that is output from this configuration will be within appropriate <html>, <body>, and <form> tags. The name of the * form is "editconnection". *@param threadContext is the local thread context. *@param out is the output to which any HTML should be sent. *@param parameters are the configuration parameters, as they currently exist, for this connection being configured. *@param tabName is the current tab name. */ @Override public void outputConfigurationBody(IThreadContext threadContext, IHTTPOutput out, Locale locale, ConfigParams parameters, String tabName) throws ManifoldCFException, IOException { String jdbcProvider = parameters.getParameter(JDBCConstants.providerParameter); if (jdbcProvider == null) jdbcProvider = "oracle:thin:@"; String accessMethod = parameters.getParameter(JDBCConstants.methodParameter); if (accessMethod == null) accessMethod = "name"; String host = parameters.getParameter(JDBCConstants.hostParameter); if (host == null) host = "localhost"; String databaseName = parameters.getParameter(JDBCConstants.databaseNameParameter); if (databaseName == null) databaseName = "database"; String rawJDBCString = parameters.getParameter(JDBCConstants.driverStringParameter); if (rawJDBCString == null) rawJDBCString = ""; String databaseUser = parameters.getParameter(JDBCConstants.databaseUserName); if (databaseUser == null) databaseUser = ""; String databasePassword = parameters.getObfuscatedParameter(JDBCConstants.databasePassword); if (databasePassword == null) databasePassword = ""; else databasePassword = out.mapPasswordToKey(databasePassword); // "Database Type" tab if (tabName.equals(Messages.getString(locale,"JDBCConnector.DatabaseType"))) { out.print( "<table class=\"displaytable\">\n"+ " <tr><td class=\"separator\" colspan=\"2\"><hr/></td></tr>\n"+ " <tr>\n"+ " <td class=\"description\"><nobr>" + Messages.getBodyString(locale,"JDBCConnector.DatabaseType2") + "</nobr></td><td class=\"value\">\n"+ " <select multiple=\"false\" name=\"databasetype\" size=\"2\">\n"+ " <option value=\"oracle:thin:@\" "+(jdbcProvider.equals("oracle:thin:@")?"selected=\"selected\"":"")+">Oracle</option>\n"+ " <option value=\"postgresql:\" "+(jdbcProvider.equals("postgresql:")?"selected=\"selected\"":"")+">Postgres SQL</option>\n"+ " <option value=\"jtds:sqlserver:\" "+(jdbcProvider.equals("jtds:sqlserver:")?"selected=\"selected\"":"")+">MS SQL Server (&gt; V6.5)</option>\n"+ " <option value=\"jtds:sybase:\" "+(jdbcProvider.equals("jtds:sybase:")?"selected=\"selected\"":"")+">Sybase (&gt;= V10)</option>\n"+ " <option value=\"mysql:\" "+(jdbcProvider.equals("mysql:")?"selected=\"selected\"":"")+">MySQL (&gt;= V5)</option>\n"+ " </select>\n"+ " </td>\n"+ " </tr>\n"+ " <tr><td class=\"separator\" colspan=\"2\"><hr/></td></tr>\n"+ " <tr>\n"+ " <td class=\"description\"><nobr>" + Messages.getBodyString(locale,"JDBCConnector.AccessMethod") + "</nobr></td><td class=\"value\">\n"+ " <select multiple=\"false\" name=\"accessmethod\" size=\"2\">\n"+ " <option value=\"name\" "+(accessMethod.equals("name")?"selected=\"selected\"":"")+">"+Messages.getBodyString(locale,"JDBCConnector.ByName")+"</option>\n"+ " <option value=\"label\" "+(accessMethod.equals("label")?"selected=\"selected\"":"")+">"+Messages.getBodyString(locale,"JDBCConnector.ByLabel")+"</option>\n"+ " </select>\n"+ " </td>\n"+ " </tr>\n"+ "</table>\n" ); } else { out.print( "<input type=\"hidden\" name=\"databasetype\" value=\""+jdbcProvider+"\"/>\n"+ "<input type=\"hidden\" name=\"accessmethod\" value=\""+accessMethod+"\"/>\n" ); } // "Server" tab if (tabName.equals(Messages.getString(locale,"JDBCConnector.Server"))) { out.print( "<table class=\"displaytable\">\n"+ " <tr><td class=\"separator\" colspan=\"2\"><hr/></td></tr>\n"+ " <tr>\n"+ " <td class=\"description\"><nobr>" + Messages.getBodyString(locale,"JDBCConnector.DatabaseHostAndPort") + "</nobr></td><td class=\"value\"><input type=\"text\" size=\"64\" name=\"databasehost\" value=\""+org.apache.manifoldcf.ui.util.Encoder.attributeEscape(host)+"\"/></td>\n"+ " </tr>\n"+ " <tr>\n"+ " <td class=\"description\"><nobr>" + Messages.getBodyString(locale,"JDBCConnector.DatabaseServiceNameOrInstanceDatabase") + "</nobr></td><td class=\"value\"><input type=\"text\" size=\"32\" name=\"databasename\" value=\""+org.apache.manifoldcf.ui.util.Encoder.attributeEscape(databaseName)+"\"/></td>\n"+ " </tr>\n"+ " <tr>\n"+ " <td class=\"description\"><nobr>" + Messages.getBodyString(locale,"JDBCConnector.RawDatabaseConnectString") + "</nobr></td><td class=\"value\"><input type=\"text\" size=\"80\" name=\"rawjdbcstring\" value=\""+org.apache.manifoldcf.ui.util.Encoder.attributeEscape(rawJDBCString)+"\"/></td>\n"+ " </tr>\n"+ "</table>\n" ); } else { out.print( "<input type=\"hidden\" name=\"databasehost\" value=\""+org.apache.manifoldcf.ui.util.Encoder.attributeEscape(host)+"\"/>\n"+ "<input type=\"hidden\" name=\"databasename\" value=\""+org.apache.manifoldcf.ui.util.Encoder.attributeEscape(databaseName)+"\"/>\n"+ "<input type=\"hidden\" name=\"rawjdbcstring\" value=\""+org.apache.manifoldcf.ui.util.Encoder.attributeEscape(rawJDBCString)+"\"/>\n" ); } // "Credentials" tab if (tabName.equals(Messages.getString(locale,"JDBCConnector.Credentials"))) { out.print( "<table class=\"displaytable\">\n"+ " <tr><td class=\"separator\" colspan=\"2\"><hr/></td></tr>\n"+ " <tr>\n"+ " <td class=\"description\"><nobr>" + Messages.getBodyString(locale,"JDBCConnector.UserName") + "</nobr></td><td class=\"value\"><input type=\"text\" size=\"32\" name=\"username\" value=\""+org.apache.manifoldcf.ui.util.Encoder.attributeEscape(databaseUser)+"\"/></td>\n"+ " </tr>\n"+ " <tr>\n"+ " <td class=\"description\"><nobr>" + Messages.getBodyString(locale,"JDBCConnector.Password") + "</nobr></td><td class=\"value\"><input type=\"password\" size=\"32\" name=\"password\" value=\""+org.apache.manifoldcf.ui.util.Encoder.attributeEscape(databasePassword)+"\"/></td>\n"+ " </tr>\n"+ "</table>\n" ); } else { out.print( "<input type=\"hidden\" name=\"username\" value=\""+org.apache.manifoldcf.ui.util.Encoder.attributeEscape(databaseUser)+"\"/>\n"+ "<input type=\"hidden\" name=\"password\" value=\""+org.apache.manifoldcf.ui.util.Encoder.attributeEscape(databasePassword)+"\"/>\n" ); } } /** Process a configuration post. * This method is called at the start of the connector's configuration page, whenever there is a possibility that form data for a connection has been * posted. Its purpose is to gather form information and modify the configuration parameters accordingly. * The name of the posted form is "editconnection". *@param threadContext is the local thread context. *@param variableContext is the set of variables available from the post, including binary file post information. *@param parameters are the configuration parameters, as they currently exist, for this connection being configured. *@return null if all is well, or a string error message if there is an error that should prevent saving of the connection (and cause a redirection to an error page). */ @Override public String processConfigurationPost(IThreadContext threadContext, IPostParameters variableContext, Locale locale, ConfigParams parameters) throws ManifoldCFException { String type = variableContext.getParameter("databasetype"); if (type != null) parameters.setParameter(JDBCConstants.providerParameter,type); String accessMethod = variableContext.getParameter("accessmethod"); if (accessMethod != null) parameters.setParameter(JDBCConstants.methodParameter,accessMethod); String host = variableContext.getParameter("databasehost"); if (host != null) parameters.setParameter(JDBCConstants.hostParameter,host); String databaseName = variableContext.getParameter("databasename"); if (databaseName != null) parameters.setParameter(JDBCConstants.databaseNameParameter,databaseName); String rawJDBCString = variableContext.getParameter("rawjdbcstring"); if (rawJDBCString != null) parameters.setParameter(JDBCConstants.driverStringParameter,rawJDBCString); String userName = variableContext.getParameter("username"); if (userName != null) parameters.setParameter(JDBCConstants.databaseUserName,userName); String password = variableContext.getParameter("password"); if (password != null) parameters.setObfuscatedParameter(JDBCConstants.databasePassword,variableContext.mapKeyToPassword(password)); return null; } /** View configuration. * This method is called in the body section of the connector's view configuration page. Its purpose is to present the connection information to the user. * The coder can presume that the HTML that is output from this configuration will be within appropriate <html> and <body> tags. *@param threadContext is the local thread context. *@param out is the output to which any HTML should be sent. *@param parameters are the configuration parameters, as they currently exist, for this connection being configured. */ @Override public void viewConfiguration(IThreadContext threadContext, IHTTPOutput out, Locale locale, ConfigParams parameters) throws ManifoldCFException, IOException { out.print( "<table class=\"displaytable\">\n"+ " <tr>\n"+ " <td class=\"description\" colspan=\"1\"><nobr>" + Messages.getBodyString(locale,"JDBCConnector.Parameters") + "</nobr></td>\n"+ " <td class=\"value\" colspan=\"3\">\n" ); Iterator iter = parameters.listParameters(); while (iter.hasNext()) { String param = (String)iter.next(); String value = parameters.getParameter(param); if (param.length() >= "password".length() && param.substring(param.length()-"password".length()).equalsIgnoreCase("password")) { out.print( " <nobr>"+org.apache.manifoldcf.ui.util.Encoder.bodyEscape(param)+"=********</nobr><br/>\n" ); } else if (param.length() >="keystore".length() && param.substring(param.length()-"keystore".length()).equalsIgnoreCase("keystore")) { IKeystoreManager kmanager = KeystoreManagerFactory.make("",value); out.print( " <nobr>"+org.apache.manifoldcf.ui.util.Encoder.bodyEscape(param)+"=&lt;"+Integer.toString(kmanager.getContents().length)+" certificate(s)&gt;</nobr><br/>\n" ); } else { out.print( " <nobr>"+org.apache.manifoldcf.ui.util.Encoder.bodyEscape(param)+"="+org.apache.manifoldcf.ui.util.Encoder.bodyEscape(value)+"</nobr><br/>\n" ); } } out.print( " </td>\n"+ " </tr>\n"+ "</table>\n" ); } /** Output the specification header section. * This method is called in the head section of a job page which has selected a repository connection of the * current type. Its purpose is to add the required tabs to the list, and to output any javascript methods * that might be needed by the job editing HTML. * The connector will be connected before this method can be called. *@param out is the output to which any HTML should be sent. *@param locale is the locale the output is preferred to be in. *@param ds is the current document specification for this job. *@param connectionSequenceNumber is the unique number of this connection within the job. *@param tabsArray is an array of tab names. Add to this array any tab names that are specific to the connector. */ @Override public void outputSpecificationHeader(IHTTPOutput out, Locale locale, Specification ds, int connectionSequenceNumber, List<String> tabsArray) throws ManifoldCFException, IOException { tabsArray.add(Messages.getString(locale,"JDBCConnector.Queries")); tabsArray.add(Messages.getString(locale,"JDBCConnector.Security")); String seqPrefix = "s"+connectionSequenceNumber+"_"; out.print( "<script type=\"text/javascript\">\n"+ "<!--\n"+ "\n"+ "function "+seqPrefix+"SpecOp(n, opValue, anchorvalue)\n"+ "{\n"+ " eval(\"editjob.\"+n+\".value = \\\"\"+opValue+\"\\\"\");\n"+ " postFormSetAnchor(anchorvalue);\n"+ "}\n"+ "\n"+ "function "+seqPrefix+"DeleteAttr(index)\n"+ "{\n"+ " var tag;\n"+ " if (index == 0)\n"+ " tag = \""+seqPrefix+"attr\";\n"+ " else\n"+ " tag = \""+seqPrefix+"attr_\" + (index-1);\n"+ " "+seqPrefix+"SpecOp(\""+seqPrefix+"attr_\"+index+\"_op\", \"Delete\", tag);\n"+ "}\n"+ "\n"+ "function "+seqPrefix+"AddAttr()\n"+ "{\n"+ " if (editjob."+seqPrefix+"attr_name.value == \"\")\n"+ " {\n"+ " alert(\"" + Messages.getBodyJavascriptString(locale,"JDBCConnector.TypeInAnAttributeName") + "\");\n"+ " editjob."+seqPrefix+"attr_name.focus();\n"+ " return;\n"+ " }\n"+ " if (editjob."+seqPrefix+"attr_query.value == \"\")\n"+ " {\n"+ " alert(\"" + Messages.getBodyJavascriptString(locale,"JDBCConnector.AttributeQueryCannotBeNull") + "\");\n"+ " editjob."+seqPrefix+"attr_query.focus();\n"+ " return;\n"+ " }\n"+ " if (editjob."+seqPrefix+"attr_query.value.indexOf(\"$(IDCOLUMN)\") == -1)\n"+ " {\n"+ " alert(\"" + Messages.getBodyJavascriptString(locale,"JDBCConnector.MustReturnIDCOLUMNInTheResult") + "\");\n"+ " editjob."+seqPrefix+"attr_query.focus();\n"+ " return;\n"+ " }\n"+ " if (editjob."+seqPrefix+"attr_query.value.indexOf(\"$(DATACOLUMN)\") == -1)\n"+ " {\n"+ " alert(\"" + Messages.getBodyJavascriptString(locale,"JDBCConnector.MustReturnDATACOLUMNInTheResult") + "\");\n"+ " editjob."+seqPrefix+"attr_query.focus();\n"+ " return;\n"+ " }\n"+ " if (editjob."+seqPrefix+"aclquery.value.indexOf(\"$(IDLIST)\") == -1)\n"+ " {\n"+ " alert(\"" + Messages.getBodyJavascriptString(locale,"JDBCConnector.MustUseIDLISTInWHEREClause") + "\");\n"+ " editjob."+seqPrefix+"attr_query.focus();\n"+ " return;\n"+ " }\n"+ " "+seqPrefix+"SpecOp(\""+seqPrefix+"attr_op\", \"Add\", \""+seqPrefix+"attr\");\n"+ "}\n"+ "\n"+ "function "+seqPrefix+"SpecAddToken(anchorvalue)\n"+ "{\n"+ " if (editjob."+seqPrefix+"spectoken.value == \"\")\n"+ " {\n"+ " alert(\"" + Messages.getBodyJavascriptString(locale,"JDBCConnector.TypeInAnAccessToken") + "\");\n"+ " editjob."+seqPrefix+"spectoken.focus();\n"+ " return;\n"+ " }\n"+ " "+seqPrefix+"SpecOp(\""+seqPrefix+"accessop\",\"Add\",anchorvalue);\n"+ "}\n"+ "\n"+ "function "+seqPrefix+"checkSpecification()\n"+ "{\n"+ " if (editjob."+seqPrefix+"idquery.value == \"\")\n"+ " {\n"+ " alert(\"" + Messages.getBodyJavascriptString(locale,"JDBCConnector.EnterASeedingQuery") + "\");\n"+ " editjob."+seqPrefix+"idquery.focus();\n"+ " return false;\n"+ " }\n"+ " if (editjob."+seqPrefix+"idquery.value.indexOf(\"$(IDCOLUMN)\") == -1)\n"+ " {\n"+ " alert(\"" + Messages.getBodyJavascriptString(locale,"JDBCConnector.MustReturnIDCOLUMNInTheResult") + "\");\n"+ " editjob."+seqPrefix+"idquery.focus();\n"+ " return false;\n"+ " }\n"+ " if (editjob."+seqPrefix+"versionquery.value != \"\")\n"+ " {\n"+ " if (editjob."+seqPrefix+"versionquery.value.indexOf(\"$(IDCOLUMN)\") == -1)\n"+ " {\n"+ " alert(\"" + Messages.getBodyJavascriptString(locale,"JDBCConnector.MustReturnIDCOLUMNInTheResult") + "\");\n"+ " editjob."+seqPrefix+"versionquery.focus();\n"+ " return false;\n"+ " }\n"+ " if (editjob."+seqPrefix+"versionquery.value.indexOf(\"$(VERSIONCOLUMN)\") == -1)\n"+ " {\n"+ " alert(\"" + Messages.getBodyJavascriptString(locale,"JDBCConnector.MustReturnVERSIONCOLUMNInTheResult") + "\");\n"+ " editjob."+seqPrefix+"versionquery.focus();\n"+ " return false;\n"+ " }\n"+ " if (editjob."+seqPrefix+"versionquery.value.indexOf(\"$(IDLIST)\") == -1)\n"+ " {\n"+ " alert(\"" + Messages.getBodyJavascriptString(locale,"JDBCConnector.MustUseIDLISTInWHEREClause") + "\");\n"+ " editjob."+seqPrefix+"versionquery.focus();\n"+ " return false;\n"+ " }\n"+ " }\n"+ " if (editjob."+seqPrefix+"aclquery.value != \"\")\n"+ " {\n"+ " if (editjob."+seqPrefix+"aclquery.value.indexOf(\"$(IDCOLUMN)\") == -1)\n"+ " {\n"+ " alert(\"" + Messages.getBodyJavascriptString(locale,"JDBCConnector.MustReturnIDCOLUMNInTheResult") + "\");\n"+ " editjob."+seqPrefix+"aclquery.focus();\n"+ " return false;\n"+ " }\n"+ " if (editjob."+seqPrefix+"aclquery.value.indexOf(\"$(TOKENCOLUMN)\") == -1)\n"+ " {\n"+ " alert(\"" + Messages.getBodyJavascriptString(locale,"JDBCConnector.MustReturnTOKENCOLUMNInTheResult") + "\");\n"+ " editjob."+seqPrefix+"aclquery.focus();\n"+ " return false;\n"+ " }\n"+ " if (editjob."+seqPrefix+"aclquery.value.indexOf(\"$(IDLIST)\") == -1)\n"+ " {\n"+ " alert(\"" + Messages.getBodyJavascriptString(locale,"JDBCConnector.MustUseIDLISTInWHEREClause") + "\");\n"+ " editjob."+seqPrefix+"aclquery.focus();\n"+ " return false;\n"+ " }\n"+ " }\n"+ " if (editjob."+seqPrefix+"dataquery.value == \"\")\n"+ " {\n"+ " alert(\"" + Messages.getBodyJavascriptString(locale,"JDBCConnector.EnterADataQuery") + "\");\n"+ " editjob."+seqPrefix+"dataquery.focus();\n"+ " return false;\n"+ " }\n"+ " if (editjob."+seqPrefix+"dataquery.value.indexOf(\"$(IDCOLUMN)\") == -1)\n"+ " {\n"+ " alert(\"" + Messages.getBodyJavascriptString(locale,"JDBCConnector.MustReturnIDCOLUMNInTheResult2") + "\");\n"+ " editjob."+seqPrefix+"dataquery.focus();\n"+ " return false;\n"+ " }\n"+ " if (editjob."+seqPrefix+"dataquery.value.indexOf(\"$(URLCOLUMN)\") == -1)\n"+ " {\n"+ " alert(\"" + Messages.getBodyJavascriptString(locale,"JDBCConnector.MustReturnURLCOLUMNInTheResult") + "\");\n"+ " editjob."+seqPrefix+"dataquery.focus();\n"+ " return false;\n"+ " }\n"+ " if (editjob."+seqPrefix+"dataquery.value.indexOf(\"$(DATACOLUMN)\") == -1)\n"+ " {\n"+ " alert(\"" + Messages.getBodyJavascriptString(locale,"JDBCConnector.MustReturnDATACOLUMNInTheResult") + "\");\n"+ " editjob."+seqPrefix+"dataquery.focus();\n"+ " return false;\n"+ " }\n"+ " if (editjob."+seqPrefix+"dataquery.value.indexOf(\"$(IDLIST)\") == -1)\n"+ " {\n"+ " alert(\"" + Messages.getBodyJavascriptString(locale,"JDBCConnector.MustUseIDLISTInWHEREClause") + "\");\n"+ " editjob."+seqPrefix+"dataquery.focus();\n"+ " return false;\n"+ " }\n"+ "\n"+ " return true;\n"+ "}\n"+ "\n"+ "//-->\n"+ "</script>\n" ); } /** Output the specification body section. * This method is called in the body section of a job page which has selected a repository connection of the * current type. Its purpose is to present the required form elements for editing. * The coder can presume that the HTML that is output from this configuration will be within appropriate * <html>, <body>, and <form> tags. The name of the form is always "editjob". * The connector will be connected before this method can be called. *@param out is the output to which any HTML should be sent. *@param locale is the locale the output is preferred to be in. *@param ds is the current document specification for this job. *@param connectionSequenceNumber is the unique number of this connection within the job. *@param actualSequenceNumber is the connection within the job that has currently been selected. *@param tabName is the current tab name. (actualSequenceNumber, tabName) form a unique tuple within * the job. */ @Override public void outputSpecificationBody(IHTTPOutput out, Locale locale, Specification ds, int connectionSequenceNumber, int actualSequenceNumber, String tabName) throws ManifoldCFException, IOException { String seqPrefix = "s"+connectionSequenceNumber+"_"; String idQuery = "SELECT idfield AS $(IDCOLUMN) FROM documenttable WHERE modifydatefield > $(STARTTIME) AND modifydatefield <= $(ENDTIME)"; String versionQuery = "SELECT idfield AS $(IDCOLUMN), versionfield AS $(VERSIONCOLUMN) FROM documenttable WHERE idfield IN $(IDLIST)"; String dataQuery = "SELECT idfield AS $(IDCOLUMN), urlfield AS $(URLCOLUMN), datafield AS $(DATACOLUMN) FROM documenttable WHERE idfield IN $(IDLIST)"; String aclQuery = "SELECT docidfield AS $(IDCOLUMN), aclfield AS $(TOKENCOLUMN) FROM acltable WHERE docidfield IN $(IDLIST)"; final Map<String, String> attributeQueryMap = new HashMap<String, String>(); int i = 0; while (i < ds.getChildCount()) { SpecificationNode sn = ds.getChild(i++); if (sn.getType().equals(JDBCConstants.idQueryNode)) { idQuery = sn.getValue(); if (idQuery == null) idQuery = ""; } else if (sn.getType().equals(JDBCConstants.versionQueryNode)) { versionQuery = sn.getValue(); if (versionQuery == null) versionQuery = ""; } else if (sn.getType().equals(JDBCConstants.dataQueryNode)) { dataQuery = sn.getValue(); if (dataQuery == null) dataQuery = ""; } else if (sn.getType().equals(JDBCConstants.aclQueryNode)) { aclQuery = sn.getValue(); if (aclQuery == null) aclQuery = ""; } else if (sn.getType().equals(JDBCConstants.attributeQueryNode)) { String attributeName = sn.getAttributeValue(JDBCConstants.attributeName); String attributeQuery = sn.getValue(); attributeQueryMap.put(attributeName, attributeQuery); } } // Sort the attribute query list final String[] attributeNames = attributeQueryMap.keySet().toArray(new String[0]); java.util.Arrays.sort(attributeNames); // The Queries tab if (tabName.equals(Messages.getString(locale,"JDBCConnector.Queries")) && connectionSequenceNumber == actualSequenceNumber) { out.print( "<table class=\"displaytable\">\n"+ " <tr><td class=\"separator\" colspan=\"2\"><hr/></td></tr>\n"+ " <tr>\n"+ " <td class=\"description\"><nobr>" + Messages.getBodyString(locale,"JDBCConnector.SeedingQuery") + "</nobr><br/><nobr>" + Messages.getBodyString(locale,"JDBCConnector.returnIdsThatNeedToBeChecked") + "</nobr></td>\n"+ " <td class=\"value\"><textarea name=\""+seqPrefix+"idquery\" cols=\"64\" rows=\"6\">"+org.apache.manifoldcf.ui.util.Encoder.bodyEscape(idQuery)+"</textarea></td>\n"+ " </tr>\n"+ " <tr>\n"+ " <td class=\"description\"><nobr>" + Messages.getBodyString(locale,"JDBCConnector.VersionCheckQuery") + "</nobr><br/><nobr>" + Messages.getBodyString(locale,"JDBCConnector.returnIdsAndVersionsForASetOfDocuments") + "</nobr><br/><nobr>" + Messages.getBodyString(locale,"JDBCConnector.leaveBlankIfNoVersioningCapability") + "</nobr></td>\n"+ " <td class=\"value\"><textarea name=\""+seqPrefix+"versionquery\" cols=\"64\" rows=\"6\">"+org.apache.manifoldcf.ui.util.Encoder.bodyEscape(versionQuery)+"</textarea></td>\n"+ " </tr>\n"+ " <tr>\n"+ " <td class=\"description\"><nobr>" + Messages.getBodyString(locale,"JDBCConnector.AccessTokenQuery") + "</nobr><br/><nobr>" + Messages.getBodyString(locale,"JDBCConnector.returnIdsAndAccessTokensForASetOfDocuments") + "</nobr><br/><nobr>" + Messages.getBodyString(locale,"JDBCConnector.leaveBlankIfNoSecurityCapability") + "</nobr></td>\n"+ " <td class=\"value\"><textarea name=\""+seqPrefix+"aclquery\" cols=\"64\" rows=\"6\">"+org.apache.manifoldcf.ui.util.Encoder.bodyEscape(aclQuery)+"</textarea></td>\n"+ " </tr>\n"+ " <tr>\n"+ " <td class=\"description\"><nobr>" + Messages.getBodyString(locale,"JDBCConnector.DataQuery") + "</nobr><br/><nobr>" + Messages.getBodyString(locale,"JDBCConnector.returnIdsUrlsAndDataForASetOfDocuments") + "</nobr></td>\n"+ " <td class=\"value\"><textarea name=\""+seqPrefix+"dataquery\" cols=\"64\" rows=\"6\">"+org.apache.manifoldcf.ui.util.Encoder.bodyEscape(dataQuery)+"</textarea></td>\n"+ " </tr>\n"); out.print( " <tr><td class=\"separator\" colspan=\"2\"><hr/></td></tr>\n"+ " <tr>"+ " <td class=\"description\"><nobr>" + Messages.getBodyString(locale,"JDBCConnector.AttributeQueries") + "</nobr></td>\n"+ " <td class=\"boxcell\">\n"+ " <table class=\"formtable\">\n"+ " <tr class=\"formheaderrow\">\n"+ " <td class=\"formcolumnheader\"></td>\n"+ " <td class=\"formcolumnheader\"><nobr>" + Messages.getBodyString(locale,"JDBCConnector.AttributeName") + "</nobr></td>\n"+ " <td class=\"formcolumnheader\"><nobr>" + Messages.getBodyString(locale,"JDBCConnector.AttributeQuery") + "</nobr></td>\n"+ " </tr>\n" ); int attributeIndex = 0; for (final String attributeName : attributeNames) { final String attributeQuery = attributeQueryMap.get(attributeName); if (attributeIndex % 2 == 0) { out.print( " <tr class=\"evenformrow\">\n" ); } else { out.print( " <tr class=\"oddformrow\">\n" ); } // Delete button out.print( " <td class=\"formcolumncell\">\n"+ " <a name=\""+seqPrefix+"attr_"+attributeIndex+"\">\n"+ " <nobr>\n"+ " <input type=\"button\" value=\""+Messages.getAttributeString(locale,"JDBCConnector.Delete")+"\"\n"+ " alt=\""+Messages.getAttributeString(locale,"JDBCConnector.DeleteAttributeQueryNumber")+attributeIndex+"\" onclick=\"javascript:"+seqPrefix+"DeleteAttr("+attributeIndex+");\"/>\n"+ " </nobr>\n"+ " </a>\n"+ " <input type=\"hidden\" name=\""+seqPrefix+"attr_"+attributeIndex+"_op"+"\" value=\"Continue\"/>\n"+ " <input type=\"hidden\" name=\""+seqPrefix+"attr_"+attributeIndex+"_name\" value=\""+org.apache.manifoldcf.ui.util.Encoder.attributeEscape(attributeName)+"\"/>\n"+ " </td>\n" ); // Attribute name out.print( " <td class=\"formcolumncell\">\n"+ " "+org.apache.manifoldcf.ui.util.Encoder.bodyEscape(attributeName)+"\n"+ " </td>\n" ); // Query out.print( " <td class=\"formcolumncell\">\n"+ " <textarea name=\""+seqPrefix+"attr_"+attributeIndex+"_query\" cols=\"64\" rows=\"6\">"+org.apache.manifoldcf.ui.util.Encoder.bodyEscape(dataQuery)+"</textarea>\n"+ " </td>\n" ); out.print( " </tr>\n" ); attributeIndex++; } if (attributeIndex == 0) { out.print( " <tr><td class=\"formmessage\" colspan=\"3\">"+Messages.getBodyString(locale,"JDBCConnector.NoAttributeQueries")+"</td></tr>\n" ); } // Add button out.print( " <tr><td class=\"formseparator\" colspan=\"3\"><hr/></td></tr>\n"+ " <tr class=\"formrow\">\n"+ " <td class=\"formcolumncell\">\n"+ " <a name=\""+seqPrefix+"attr\">\n"+ " <input type=\"button\" value=\""+Messages.getAttributeString(locale,"JDBCConnector.Add")+"\"\n"+ " alt=\""+Messages.getAttributeString(locale,"JDBCConnector.AddAttribute")+"\" onclick=\"javascript:"+seqPrefix+"AddAttr();\"/>\n"+ " </a>\n"+ " <input type=\"hidden\" name=\""+seqPrefix+"attr_count\" value=\""+attributeIndex+"\"/>\n"+ " <input type=\"hidden\" name=\""+seqPrefix+"attr_op\" value=\"Continue\"/>\n"+ " </td>\n"+ " <td class=\"formcolumncell\"><nobr><input name=\""+seqPrefix+"attr_name\" type=\"text\" size=\"32\" value=\"\"/></nobr></td>\n"+ " <td class=\"formcolumncell\">\n"+ " <textarea name=\""+seqPrefix+"attr_query\" cols=\"64\" rows=\"6\"></textarea>\n"+ " </td>\n"+ " </tr>\n" ); out.print( " </table>\n"+ " </td>\n"+ " </tr>\n"+ "</table>\n" ); } else { out.print( "<input type=\"hidden\" name=\""+seqPrefix+"idquery\" value=\""+org.apache.manifoldcf.ui.util.Encoder.attributeEscape(idQuery)+"\"/>\n"+ "<input type=\"hidden\" name=\""+seqPrefix+"versionquery\" value=\""+org.apache.manifoldcf.ui.util.Encoder.attributeEscape(versionQuery)+"\"/>\n"+ "<input type=\"hidden\" name=\""+seqPrefix+"aclquery\" value=\""+org.apache.manifoldcf.ui.util.Encoder.attributeEscape(aclQuery)+"\"/>\n"+ "<input type=\"hidden\" name=\""+seqPrefix+"dataquery\" value=\""+org.apache.manifoldcf.ui.util.Encoder.attributeEscape(dataQuery)+"\"/>\n" ); int attributeIndex = 0; for (final String attributeName : attributeNames) { final String attributeQuery = attributeQueryMap.get(attributeName); out.print( "<input type=\"hidden\" name=\""+seqPrefix+"attr_"+attributeIndex+"_name\" value=\""+org.apache.manifoldcf.ui.util.Encoder.attributeEscape(attributeName)+"\"/>\n"+ "<input type=\"hidden\" name=\""+seqPrefix+"attr_"+attributeIndex+"_query\" value=\""+org.apache.manifoldcf.ui.util.Encoder.attributeEscape(attributeQuery)+"\"/>\n" ); attributeIndex++; } out.print( "<input type=\"hidden\" name=\""+seqPrefix+"attr_count\" value=\""+attributeIndex+"\"/>\n" ); } // Security tab // There is no native security, so all we care about are the tokens. i = 0; boolean securityOn = true; while (i < ds.getChildCount()) { SpecificationNode sn = ds.getChild(i++); if (sn.getType().equals("security")) { String securityValue = sn.getAttributeValue("value"); if (securityValue.equals("off")) securityOn = false; else if (securityValue.equals("on")) securityOn = true; } } if (tabName.equals(Messages.getString(locale,"JDBCConnector.Security")) && connectionSequenceNumber == actualSequenceNumber) { out.print( "<table class=\"displaytable\">\n"+ " <tr><td class=\"separator\" colspan=\"2\"><hr/></td></tr>\n"+ " <tr>\n"+ " <td class=\"description\"><nobr>"+Messages.getBodyString(locale,"JDBCConnector.SecurityColon")+"</nobr></td>\n"+ " <td class=\"value\">\n"+ " <input type=\"radio\" name=\""+seqPrefix+"specsecurity\" value=\"on\" "+(securityOn?"checked=\"true\"":"")+" />"+Messages.getBodyString(locale,"JDBCConnector.Enabled")+"\n"+ " <input type=\"radio\" name=\""+seqPrefix+"specsecurity\" value=\"off\" "+((securityOn==false)?"checked=\"true\"":"")+" />"+Messages.getBodyString(locale,"JDBCConnector.Disabled")+"\n"+ " </td>\n"+ " </tr>\n"+ " <tr><td class=\"separator\" colspan=\"2\"><hr/></td></tr>\n" ); // Go through forced ACL i = 0; int k = 0; while (i < ds.getChildCount()) { SpecificationNode sn = ds.getChild(i++); if (sn.getType().equals("access")) { String accessDescription = "_"+Integer.toString(k); String accessOpName = seqPrefix+"accessop"+accessDescription; String token = sn.getAttributeValue("token"); out.print( " <tr>\n"+ " <td class=\"description\">\n"+ " <input type=\"hidden\" name=\""+accessOpName+"\" value=\"\"/>\n"+ " <input type=\"hidden\" name=\""+seqPrefix+"spectoken"+accessDescription+"\" value=\""+org.apache.manifoldcf.ui.util.Encoder.attributeEscape(token)+"\"/>\n"+ " <a name=\""+seqPrefix+"token_"+Integer.toString(k)+"\">\n"+ " <input type=\"button\" value=\"Delete\" onClick='Javascript:"+seqPrefix+"SpecOp(\""+accessOpName+"\",\"Delete\",\""+seqPrefix+"token_"+Integer.toString(k)+"\")' alt=\"" + Messages.getAttributeString(locale,"JDBCConnector.DeleteToken") + "\""+Integer.toString(k)+"\"/>\n"+ " </a>&nbsp;\n"+ " </td>\n"+ " <td class=\"value\">\n"+ " "+org.apache.manifoldcf.ui.util.Encoder.bodyEscape(token)+"\n"+ " </td>\n"+ " </tr>\n" ); k++; } } if (k == 0) { out.print( " <tr>\n"+ " <td class=\"message\" colspan=\"2\">" + Messages.getBodyString(locale,"JDBCConnector.NoAccessTokensPresent") + "</td>\n"+ " </tr>\n" ); } out.print( " <tr><td class=\"lightseparator\" colspan=\"2\"><hr/></td></tr>\n"+ " <tr>\n"+ " <td class=\"description\">\n"+ " <input type=\"hidden\" name=\""+seqPrefix+"tokencount\" value=\""+Integer.toString(k)+"\"/>\n"+ " <input type=\"hidden\" name=\""+seqPrefix+"accessop\" value=\"\"/>\n"+ " <a name=\""+seqPrefix+"token_"+Integer.toString(k)+"\">\n"+ " <input type=\"button\" value=\"Add\" onClick='Javascript:"+seqPrefix+"SpecAddToken(\""+seqPrefix+"token_"+Integer.toString(k+1)+"\")' alt=\"" + Messages.getAttributeString(locale,"JDBCConnector.AddAccessToken") + "\"/>\n"+ " </a>&nbsp;\n"+ " </td>\n"+ " <td class=\"value\">\n"+ " <input type=\"text\" size=\"30\" name=\""+seqPrefix+"spectoken\" value=\"\"/>\n"+ " </td>\n"+ " </tr>\n"+ "</table>\n" ); } else { out.print( "<input type=\"hidden\" name=\""+seqPrefix+"specsecurity\" value=\""+(securityOn?"on":"off")+"\"/>\n" ); // Finally, go through forced ACL i = 0; int k = 0; while (i < ds.getChildCount()) { SpecificationNode sn = ds.getChild(i++); if (sn.getType().equals("access")) { String accessDescription = "_"+Integer.toString(k); String token = sn.getAttributeValue("token"); out.print( "<input type=\"hidden\" name=\""+seqPrefix+"spectoken"+accessDescription+"\" value=\""+org.apache.manifoldcf.ui.util.Encoder.attributeEscape(token)+"\"/>\n" ); k++; } } out.print( "<input type=\"hidden\" name=\""+seqPrefix+"tokencount\" value=\""+Integer.toString(k)+"\"/>\n" ); } } /** Process a specification post. * This method is called at the start of job's edit or view page, whenever there is a possibility that form * data for a connection has been posted. Its purpose is to gather form information and modify the * document specification accordingly. The name of the posted form is always "editjob". * The connector will be connected before this method can be called. *@param variableContext contains the post data, including binary file-upload information. *@param locale is the locale the output is preferred to be in. *@param ds is the current document specification for this job. *@param connectionSequenceNumber is the unique number of this connection within the job. *@return null if all is well, or a string error message if there is an error that should prevent saving of * the job (and cause a redirection to an error page). */ @Override public String processSpecificationPost(IPostParameters variableContext, Locale locale, Specification ds, int connectionSequenceNumber) throws ManifoldCFException { String seqPrefix = "s"+connectionSequenceNumber+"_"; String idQuery = variableContext.getParameter(seqPrefix+"idquery"); String versionQuery = variableContext.getParameter(seqPrefix+"versionquery"); String dataQuery = variableContext.getParameter(seqPrefix+"dataquery"); String aclQuery = variableContext.getParameter(seqPrefix+"aclquery"); SpecificationNode sn; if (idQuery != null) { int i = 0; while (i < ds.getChildCount()) { if (ds.getChild(i).getType().equals(JDBCConstants.idQueryNode)) ds.removeChild(i); else i++; } sn = new SpecificationNode(JDBCConstants.idQueryNode); sn.setValue(idQuery); ds.addChild(ds.getChildCount(),sn); } if (versionQuery != null) { int i = 0; while (i < ds.getChildCount()) { if (ds.getChild(i).getType().equals(JDBCConstants.versionQueryNode)) ds.removeChild(i); else i++; } sn = new SpecificationNode(JDBCConstants.versionQueryNode); sn.setValue(versionQuery); ds.addChild(ds.getChildCount(),sn); } if (aclQuery != null) { int i = 0; while (i < ds.getChildCount()) { if (ds.getChild(i).getType().equals(JDBCConstants.aclQueryNode)) ds.removeChild(i); else i++; } sn = new SpecificationNode(JDBCConstants.aclQueryNode); sn.setValue(aclQuery); ds.addChild(ds.getChildCount(),sn); } if (dataQuery != null) { int i = 0; while (i < ds.getChildCount()) { if (ds.getChild(i).getType().equals(JDBCConstants.dataQueryNode)) ds.removeChild(i); else i++; } sn = new SpecificationNode(JDBCConstants.dataQueryNode); sn.setValue(dataQuery); ds.addChild(ds.getChildCount(),sn); } String xc = variableContext.getParameter(seqPrefix+"specsecurity"); if (xc != null) { // Delete all security entries first int i = 0; while (i < ds.getChildCount()) { sn = ds.getChild(i); if (sn.getType().equals("security")) ds.removeChild(i); else i++; } SpecificationNode node = new SpecificationNode("security"); node.setAttribute("value",xc); ds.addChild(ds.getChildCount(),node); } xc = variableContext.getParameter(seqPrefix+"tokencount"); if (xc != null) { // Delete all tokens first int i = 0; while (i < ds.getChildCount()) { sn = ds.getChild(i); if (sn.getType().equals("access")) ds.removeChild(i); else i++; } int accessCount = Integer.parseInt(xc); i = 0; while (i < accessCount) { String accessDescription = "_"+Integer.toString(i); String accessOpName = seqPrefix+"accessop"+accessDescription; xc = variableContext.getParameter(accessOpName); if (xc != null && xc.equals("Delete")) { // Next row i++; continue; } // Get the stuff we need String accessSpec = variableContext.getParameter(seqPrefix+"spectoken"+accessDescription); SpecificationNode node = new SpecificationNode("access"); node.setAttribute("token",accessSpec); ds.addChild(ds.getChildCount(),node); i++; } String op = variableContext.getParameter(seqPrefix+"accessop"); if (op != null && op.equals("Add")) { String accessspec = variableContext.getParameter(seqPrefix+"spectoken"); SpecificationNode node = new SpecificationNode("access"); node.setAttribute("token",accessspec); ds.addChild(ds.getChildCount(),node); } } return null; } /** View specification. * This method is called in the body section of a job's view page. Its purpose is to present the document * specification information to the user. The coder can presume that the HTML that is output from * this configuration will be within appropriate <html> and <body> tags. * The connector will be connected before this method can be called. *@param out is the output to which any HTML should be sent. *@param locale is the locale the output is preferred to be in. *@param ds is the current document specification for this job. *@param connectionSequenceNumber is the unique number of this connection within the job. */ @Override public void viewSpecification(IHTTPOutput out, Locale locale, Specification ds, int connectionSequenceNumber) throws ManifoldCFException, IOException { String idQuery = ""; String versionQuery = ""; String dataQuery = ""; String aclQuery = ""; int i = 0; while (i < ds.getChildCount()) { SpecificationNode sn = ds.getChild(i++); if (sn.getType().equals(JDBCConstants.idQueryNode)) { idQuery = sn.getValue(); if (idQuery == null) idQuery = ""; } else if (sn.getType().equals(JDBCConstants.versionQueryNode)) { versionQuery = sn.getValue(); if (versionQuery == null) versionQuery = ""; } else if (sn.getType().equals(JDBCConstants.dataQueryNode)) { dataQuery = sn.getValue(); if (dataQuery == null) dataQuery = ""; } else if (sn.getType().equals(JDBCConstants.aclQueryNode)) { aclQuery = sn.getValue(); if (aclQuery == null) aclQuery = ""; } } out.print( "<table class=\"displaytable\">\n"+ " <tr>\n"+ " <td class=\"description\"><nobr>" + Messages.getBodyString(locale,"JDBCConnector.SeedingQuery") + "</nobr></td>\n"+ " <td class=\"value\">"+org.apache.manifoldcf.ui.util.Encoder.bodyEscape(idQuery)+"</td>\n"+ " </tr>\n"+ " <tr>\n"+ " <td class=\"description\"><nobr>" + Messages.getBodyString(locale,"JDBCConnector.VersionCheckQuery") + "</nobr></td>\n"+ " <td class=\"value\">"+org.apache.manifoldcf.ui.util.Encoder.bodyEscape(versionQuery)+"</td>\n"+ " </tr>\n"+ " <tr>\n"+ " <td class=\"description\"><nobr>" + Messages.getBodyString(locale,"JDBCConnector.AccessTokenQuery") + "</nobr></td>\n"+ " <td class=\"value\">"+org.apache.manifoldcf.ui.util.Encoder.bodyEscape(aclQuery)+"</td>\n"+ " </tr>\n"+ " <tr>\n"+ " <td class=\"description\"><nobr>" + Messages.getBodyString(locale,"JDBCConnector.DataQuery") + "</nobr></td>\n"+ " <td class=\"value\">"+org.apache.manifoldcf.ui.util.Encoder.bodyEscape(dataQuery)+"</td>\n"+ " </tr>\n"+ "\n"+ " <tr><td class=\"separator\" colspan=\"2\"><hr/></td></tr>\n" ); // Find whether security is on or off i = 0; boolean securityOn = true; while (i < ds.getChildCount()) { SpecificationNode sn = ds.getChild(i++); if (sn.getType().equals("security")) { String securityValue = sn.getAttributeValue("value"); if (securityValue.equals("off")) securityOn = false; else if (securityValue.equals("on")) securityOn = true; } } out.print( " <tr>\n"+ " <td class=\"description\">"+Messages.getBodyString(locale,"JDBCConnector.SecurityColon")+"</td>\n"+ " <td class=\"value\">"+(securityOn?Messages.getBodyString(locale,"JDBCConnector.Enabled"):Messages.getBodyString(locale,"JDBCConnector.Disabled"))+"</td>\n"+ " </tr>\n"+ "\n"+ " <tr><td class=\"separator\" colspan=\"2\"><hr/></td></tr>\n" ); // Go through looking for access tokens boolean seenAny = false; i = 0; while (i < ds.getChildCount()) { SpecificationNode sn = ds.getChild(i++); if (sn.getType().equals("access")) { if (seenAny == false) { out.print( " <tr><td class=\"description\"><nobr>" + Messages.getBodyString(locale,"JDBCConnector.AccessTokens") + "</nobr></td>\n"+ " <td class=\"value\">\n" ); seenAny = true; } String token = sn.getAttributeValue("token"); out.print( " "+org.apache.manifoldcf.ui.util.Encoder.bodyEscape(token)+"<br/>\n" ); } } if (seenAny) { out.print( " </td>\n"+ " </tr>\n" ); } else { out.print( " <tr><td class=\"message\" colspan=\"2\"><nobr>" + Messages.getBodyString(locale,"JDBCConnector.NoAccessTokensSpecified") + "</nobr></td></tr>\n" ); } out.print( "</table>\n" ); } /** Special column names, as far as document queries are concerned */ protected static HashMap documentKnownColumns; static { documentKnownColumns = new HashMap(); documentKnownColumns.put(JDBCConstants.idReturnColumnName,""); documentKnownColumns.put(JDBCConstants.urlReturnColumnName,""); documentKnownColumns.put(JDBCConstants.dataReturnColumnName,""); documentKnownColumns.put(JDBCConstants.contentTypeReturnColumnName,""); } /** Apply metadata to a repository document. *@param rd is the repository document to apply the metadata to. *@param row is the resultset row to use to get the metadata. All non-special columns from this row will be considered to be metadata. */ protected void applyMetadata(RepositoryDocument rd, IResultRow row) throws ManifoldCFException { // Cycle through the row's columns Iterator iter = row.getColumns(); while (iter.hasNext()) { String columnName = (String)iter.next(); if (documentKnownColumns.get(columnName) == null) { // Consider this column to contain metadata. // We can only accept non-binary metadata at this time. Object metadata = row.getValue(columnName); rd.addField(columnName,JDBCConnection.readAsString(metadata)); } } } /** Apply access tokens to a repository document. *@param rd is the repository document to apply the access tokens to. *@param version is the version string. *@param spec is the document specification. */ protected void applyAccessTokens(RepositoryDocument rd, Set<String> accessTokens) throws ManifoldCFException { if (accessTokens == null) return; String[] accessAcls = new String[accessTokens.size()]; int i = 0; for (String accessToken : accessTokens) { accessAcls[i++] = accessToken; } java.util.Arrays.sort(accessAcls); String[] denyAcls = new String[]{defaultAuthorityDenyToken}; rd.setSecurity(RepositoryDocument.SECURITY_TYPE_DOCUMENT,accessAcls,denyAcls); } /** Get the maximum number of documents to amalgamate together into one batch, for this connector. *@return the maximum number. 0 indicates "unlimited". */ @Override public int getMaxDocumentRequest() { // This is a number that is comfortably processed by the query processor as part of an IN clause. return 100; } // These are protected helper methods /** Add starttime and endtime query variables */ protected static void addVariable(VariableMap map, String varName, long variable) { ArrayList params = new ArrayList(); params.add(new Long(variable)); map.addVariable(varName,"?",params); } /** Add string query variables */ protected static void addVariable(VariableMap map, String varName, String variable) { ArrayList params = new ArrayList(); params.add(variable); map.addVariable(varName,"?",params); } /** Add string query constants */ protected static void addConstant(VariableMap map, String varName, String value) { map.addVariable(varName,value,null); } /** Build an idlist variable, and add it to the specified variable map. */ protected static boolean addIDList(VariableMap map, String varName, String[] documentIdentifiers, Set<String> fetchDocuments) { ArrayList params = new ArrayList(); StringBuilder sb = new StringBuilder(" ("); int k = 0; for (String documentIdentifier : documentIdentifiers) { if (fetchDocuments == null || fetchDocuments.contains(documentIdentifier)) { if (k > 0) sb.append(","); sb.append("?"); params.add(documentIdentifier); k++; } } sb.append(") "); map.addVariable(varName,sb.toString(),params); return (k > 0); } /** Given a query, and a parameter map, substitute it. * Each variable substitutes the string, and it also substitutes zero or more query parameters. */ protected static void substituteQuery(String inputString, VariableMap inputMap, StringBuilder outputQuery, ArrayList outputParams) throws ManifoldCFException { // We are looking for strings that look like this: $(something) // Right at the moment we don't care even about quotes, so we just want to look for $(. int startIndex = 0; while (true) { int nextIndex = inputString.indexOf("$(",startIndex); if (nextIndex == -1) { outputQuery.append(inputString.substring(startIndex)); break; } int endIndex = inputString.indexOf(")",nextIndex); if (endIndex == -1) { outputQuery.append(inputString.substring(startIndex)); break; } String variableName = inputString.substring(nextIndex+2,endIndex); VariableMapItem item = inputMap.getVariable(variableName); if (item == null) throw new ManifoldCFException("No such substitution variable: $("+variableName+")"); outputQuery.append(inputString.substring(startIndex,nextIndex)); outputQuery.append(item.getValue()); ArrayList inputParams = item.getParameters(); if (inputParams != null) { int i = 0; while (i < inputParams.size()) { Object x = inputParams.get(i++); outputParams.add(x); } } startIndex = endIndex+1; } } /** Create an entity identifier from a querystring and a parameter list. */ protected static String createQueryString(String queryText, ArrayList paramList) { StringBuilder sb = new StringBuilder(queryText); sb.append("; arguments = ("); int i = 0; while (i < paramList.size()) { if (i > 0) sb.append(","); Object parameter = paramList.get(i++); if (parameter instanceof String) sb.append(quoteSQLString((String)parameter)); else sb.append(parameter.toString()); } sb.append(")"); return sb.toString(); } /** Quote a sql string. */ protected static String quoteSQLString(String input) { StringBuilder sb = new StringBuilder("\'"); int i = 0; while (i < input.length()) { char x = input.charAt(i++); if (x == '\'') sb.append('\'').append(x); else if (x >= 0 && x < ' ') sb.append(' '); else sb.append(x); } sb.append("\'"); return sb.toString(); } /** Variable map entry. */ protected static class VariableMapItem { protected String value; protected ArrayList params; /** Constructor. */ public VariableMapItem(String value, ArrayList params) { this.value = value; this.params = params; } /** Get value. */ public String getValue() { return value; } /** Get parameters. */ public ArrayList getParameters() { return params; } } /** Variable map. */ protected static class VariableMap { protected Map variableMap = new HashMap(); /** Constructor */ public VariableMap() { } /** Add a variable map entry */ public void addVariable(String variableName, String value, ArrayList parameters) { VariableMapItem e = new VariableMapItem(value,parameters); variableMap.put(variableName,e); } /** Get a variable map entry */ public VariableMapItem getVariable(String variableName) { return (VariableMapItem)variableMap.get(variableName); } } /** This class represents data gleaned from a document specification, in a more usable form. */ protected static class TableSpec { public final String idQuery; public final String versionQuery; public final String dataQuery; public final String aclQuery; public final boolean securityOn; public final Set<String> aclMap = new HashSet<String>(); public TableSpec(Specification ds) { String idQuery = null; String versionQuery = null; String dataQuery = null; String aclQuery = null; boolean securityOn = false; for (int i = 0; i < ds.getChildCount(); i++) { SpecificationNode sn = ds.getChild(i); if (sn.getType().equals(JDBCConstants.idQueryNode)) { idQuery = sn.getValue(); if (idQuery == null) idQuery = ""; } else if (sn.getType().equals(JDBCConstants.versionQueryNode)) { versionQuery = sn.getValue(); if (versionQuery == null) versionQuery = ""; } else if (sn.getType().equals(JDBCConstants.dataQueryNode)) { dataQuery = sn.getValue(); if (dataQuery == null) dataQuery = ""; } else if (sn.getType().equals(JDBCConstants.aclQueryNode)) { aclQuery = sn.getValue(); if (aclQuery == null) aclQuery = ""; } else if (sn.getType().equals("access")) { String token = sn.getAttributeValue("token"); aclMap.add(token); } else if (sn.getType().equals("security")) { String value = sn.getAttributeValue("value"); securityOn = value.equals("on"); } } this.idQuery = idQuery; this.versionQuery = versionQuery; this.dataQuery = dataQuery; this.aclQuery = aclQuery; this.securityOn = securityOn; } public Set<String> getAcls() { return aclMap; } public boolean isSecurityOn() { return securityOn; } } }
Finish UI code git-svn-id: 68355f031c8ccd748d2cfd4e7c897bcc8651a4d7@1742935 13f79535-47bb-0310-9956-ffa450edef68
connectors/jdbc/connector/src/main/java/org/apache/manifoldcf/crawler/connectors/jdbc/JDBCConnector.java
Finish UI code
<ide><path>onnectors/jdbc/connector/src/main/java/org/apache/manifoldcf/crawler/connectors/jdbc/JDBCConnector.java <ide> "\n"+ <ide> "function "+seqPrefix+"DeleteAttr(index)\n"+ <ide> "{\n"+ <del>" var tag;\n"+ <del>" if (index == 0)\n"+ <del>" tag = \""+seqPrefix+"attr\";\n"+ <del>" else\n"+ <del>" tag = \""+seqPrefix+"attr_\" + (index-1);\n"+ <del>" "+seqPrefix+"SpecOp(\""+seqPrefix+"attr_\"+index+\"_op\", \"Delete\", tag);\n"+ <add>" "+seqPrefix+"SpecOp(\""+seqPrefix+"attr_\"+index+\"_op\", \"Delete\", \""+seqPrefix+"attr_\" + index);\n"+ <ide> "}\n"+ <ide> "\n"+ <ide> "function "+seqPrefix+"AddAttr()\n"+ <ide> " editjob."+seqPrefix+"attr_query.focus();\n"+ <ide> " return;\n"+ <ide> " }\n"+ <del>" if (editjob."+seqPrefix+"aclquery.value.indexOf(\"$(IDLIST)\") == -1)\n"+ <add>" if (editjob."+seqPrefix+"attr_query.value.indexOf(\"$(IDLIST)\") == -1)\n"+ <ide> " {\n"+ <ide> " alert(\"" + Messages.getBodyJavascriptString(locale,"JDBCConnector.MustUseIDLISTInWHEREClause") + "\");\n"+ <ide> " editjob."+seqPrefix+"attr_query.focus();\n"+ <ide> " <tr><td class=\"formseparator\" colspan=\"3\"><hr/></td></tr>\n"+ <ide> " <tr class=\"formrow\">\n"+ <ide> " <td class=\"formcolumncell\">\n"+ <del>" <a name=\""+seqPrefix+"attr\">\n"+ <add>" <a name=\""+seqPrefix+"attr_"+attributeIndex+"\">\n"+ <ide> " <input type=\"button\" value=\""+Messages.getAttributeString(locale,"JDBCConnector.Add")+"\"\n"+ <ide> " alt=\""+Messages.getAttributeString(locale,"JDBCConnector.AddAttribute")+"\" onclick=\"javascript:"+seqPrefix+"AddAttr();\"/>\n"+ <ide> " </a>\n"+ <ide> ds.addChild(ds.getChildCount(),sn); <ide> } <ide> <del> String xc = variableContext.getParameter(seqPrefix+"specsecurity"); <add> String xc; <add> xc = variableContext.getParameter(seqPrefix+"attr_count"); <add> if (xc != null) <add> { <add> // Delete all attribute queries first <add> int i = 0; <add> while (i < ds.getChildCount()) <add> { <add> sn = ds.getChild(i); <add> if (sn.getType().equals(JDBCConstants.attributeQueryNode)) <add> ds.removeChild(i); <add> else <add> i++; <add> } <add> <add> int attributeCount = Integer.parseInt(xc); <add> for (int attributeIndex = 0; i < attributeCount; i++) <add> { <add> final String attributeOp = variableContext.getParameter(seqPrefix+"attr_"+attributeIndex+"_op"); <add> if (!(attributeOp != null && attributeOp.equals("Delete"))) <add> { <add> // Include this!! <add> final String attributeName = variableContext.getParameter(seqPrefix+"attr_"+attributeIndex+"_name"); <add> final String attributeQuery = variableContext.getParameter(seqPrefix+"attr_"+attributeIndex+"_query"); <add> SpecificationNode node = new SpecificationNode(JDBCConstants.attributeQueryNode); <add> node.setAttribute(JDBCConstants.attributeName, attributeName); <add> node.setValue(attributeQuery); <add> ds.addChild(ds.getChildCount(),node); <add> } <add> } <add> <add> // Now, maybe do add <add> final String newAttributeOp = variableContext.getParameter(seqPrefix+"attr_op"); <add> if (newAttributeOp.equals("Add")) <add> { <add> final String attributeName = variableContext.getParameter(seqPrefix+"attr_name"); <add> final String attributeQuery = variableContext.getParameter(seqPrefix+"attr_query"); <add> SpecificationNode node = new SpecificationNode(JDBCConstants.attributeQueryNode); <add> node.setAttribute(JDBCConstants.attributeName, attributeName); <add> node.setValue(attributeQuery); <add> ds.addChild(ds.getChildCount(),node); <add> } <add> } <add> <add> xc = variableContext.getParameter(seqPrefix+"specsecurity"); <ide> if (xc != null) <ide> { <ide> // Delete all security entries first
Java
apache-2.0
error: pathspec 'src/ext/wyone/io/SpecLexer.java' did not match any file(s) known to git
aaa9f6956f4e36468f28d5b34f8a3ab3d42bc840
1
Whiley/WhileyCompiler,hjwylde/whiley-compiler,hjwylde/whiley-compiler,hjwylde/whiley-compiler,hjwylde/whiley-compiler,hjwylde/whiley-compiler
// This file is part of the Whiley-to-Java Compiler (wyjc). // // The Whiley-to-Java Compiler 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. // // The Whiley-to-Java Compiler 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 the Whiley-to-Java Compiler. If not, see // <http://www.gnu.org/licenses/> // // Copyright 2010, David James Pearce. package wyone.io; import java.io.*; import java.math.BigInteger; import java.util.*; import wyil.jvm.rt.BigRational; import wyone.util.SyntaxError; public class SpecLexer { private String filename; private StringBuffer input; private int pos; public SpecLexer(String filename) throws IOException { this(new InputStreamReader(new FileInputStream(filename),"UTF8")); this.filename = filename; } public SpecLexer(InputStream instream) throws IOException { this(new InputStreamReader(instream,"UTF8")); } public SpecLexer(Reader reader) throws IOException { BufferedReader in = new BufferedReader(reader); StringBuffer text = new StringBuffer(); String tmp; while ((tmp = in.readLine()) != null) { text.append(tmp); text.append("\n"); } input = text; } public List<Token> scan() { ArrayList<Token> tokens = new ArrayList<Token>(); pos = 0; while(pos < input.length()) { char c = input.charAt(pos); if(Character.isDigit(c)) { tokens.add(scanDigits()); } else if(c == '"') { tokens.add(scanString()); } else if(c == '\'') { tokens.add(scanChar()); } else if(isOperatorStart(c)) { tokens.add(scanOperator()); } else if(isIdentifierStart(c)) { tokens.add(scanIdentifier()); } else if(c == '\n') { tokens.add(new NewLine(pos++)); } else if(c == '\t') { tokens.add(scanTabs()); } else if(Character.isWhitespace(c)) { skipWhitespace(tokens); } else { syntaxError("syntax error"); } } return tokens; } public Token scanComment() { int start = pos; while(pos < input.length() && input.charAt(pos) != '\n') { pos++; } return new Comment(input.substring(start,pos),start); } public Token scanDigits() { int start = pos; while (pos < input.length() && Character.isDigit(input.charAt(pos))) { pos = pos + 1; } if(pos < input.length() && input.charAt(pos) == '.') { pos = pos + 1; if(pos < input.length() && input.charAt(pos) == '.') { // this is case for range e.g. 0..1 pos = pos - 1; BigInteger r = new BigInteger(input.substring(start, pos)); return new Int(r,input.substring(start,pos),start); } while (pos < input.length() && Character.isDigit(input.charAt(pos))) { pos = pos + 1; } BigRational r = new BigRational(input.substring(start, pos)); return new Real(r,input.substring(start,pos),start); } else { BigInteger r = new BigInteger(input.substring(start, pos)); return new Int(r,input.substring(start,pos),start); } } public Token scanChar() { int start = pos; pos++; char c = input.charAt(pos++); if(c == '\\') { // escape code switch(input.charAt(pos++)) { case 't': c = '\t'; break; case 'n': c = '\n'; break; default: syntaxError("unrecognised escape character",pos); } } if(input.charAt(pos) != '\'') { syntaxError("unexpected end-of-character",pos); } pos = pos + 1; return new Int(BigInteger.valueOf(c),input.substring(start,pos),start); } public Token scanString() { int start = pos; pos ++; while(pos < input.length()) { char c = input.charAt(pos); if (c == '"') { String v = input.substring(start,++pos); return new Strung(parseString(v),v, start); } pos = pos + 1; } syntaxError("unexpected end-of-string",pos-1); return null; } protected String parseString(String v) { /* * Parsing a string requires several steps to be taken. First, we need * to strip quotes from the ends of the string. */ v = v.substring(1, v.length() - 1); int start = pos - v.length(); // Second, step through the string and replace escaped characters for (int i = 0; i < v.length(); i++) { if (v.charAt(i) == '\\') { if (v.length() <= i + 1) { syntaxError("unexpected end-of-string",start+i); } else { char replace = 0; int len = 2; switch (v.charAt(i + 1)) { case 'b' : replace = '\b'; break; case 't' : replace = '\t'; break; case 'n' : replace = '\n'; break; case 'f' : replace = '\f'; break; case 'r' : replace = '\r'; break; case '"' : replace = '\"'; break; case '\'' : replace = '\''; break; case '\\' : replace = '\\'; break; case 'u' : len = 6; // unicode escapes are six digits long, // including "slash u" String unicode = v.substring(i + 2, i + 6); replace = (char) Integer.parseInt(unicode, 16); // unicode break; default : syntaxError("unknown escape character",start+i); } v = v.substring(0, i) + replace + v.substring(i + len); } } } return v; } static final char UC_FORALL = '\u2200'; static final char UC_EXISTS = '\u2203'; static final char UC_EMPTYSET = '\u2205'; static final char UC_SUBSET = '\u2282'; static final char UC_SUBSETEQ = '\u2286'; static final char UC_SUPSET = '\u2283'; static final char UC_SUPSETEQ = '\u2287'; static final char UC_SETUNION = '\u222A'; static final char UC_SETINTERSECTION = '\u2229'; static final char UC_LESSEQUALS = '\u2264'; static final char UC_GREATEREQUALS = '\u2265'; static final char UC_ELEMENTOF = '\u2208'; static final char UC_LOGICALAND = '\u2227'; static final char UC_LOGICALOR = '\u2228'; static final char[] opStarts = { ',', '(', ')', '[', ']', '{', '}', '+', '-', '*', '/', '!', '?', '=', '<', '>', ':', ';', '&', '|', '.','~', UC_FORALL, UC_EXISTS, UC_EMPTYSET, UC_SUBSET, UC_SUBSETEQ, UC_SUPSET, UC_SUPSETEQ, UC_SETUNION, UC_SETINTERSECTION, UC_LESSEQUALS, UC_GREATEREQUALS, UC_ELEMENTOF }; public boolean isOperatorStart(char c) { for(char o : opStarts) { if(c == o) { return true; } } return false; } public Token scanOperator() { char c = input.charAt(pos); if(c == '.') { if((pos+1) < input.length() && input.charAt(pos+1) == '.') { pos += 2; return new DotDot(pos-2); } else { return new Dot(pos++); } } else if(c == ',') { return new Comma(pos++); } else if(c == ':') { return new Colon(pos++); } else if(c == ';') { return new SemiColon(pos++); } else if(c == '(') { return new LeftBrace(pos++); } else if(c == ')') { return new RightBrace(pos++); } else if(c == '[') { return new LeftSquare(pos++); } else if(c == ']') { return new RightSquare(pos++); } else if(c == '{') { return new LeftCurly(pos++); } else if(c == '}') { return new RightCurly(pos++); } else if(c == '+') { return new Plus(pos++); } else if(c == '-') { if((pos+1) < input.length() && input.charAt(pos+1) == '>') { pos += 2; return new Arrow("->",pos-2); } else { return new Minus(pos++); } } else if(c == '*') { return new Star(pos++); } else if(c == '&') { if((pos+1) < input.length() && input.charAt(pos+1) == '&') { pos += 2; return new LogicalAnd("&&",pos-2); } else { return new AddressOf("&",pos++); } } else if(c == '|') { if((pos+1) < input.length() && input.charAt(pos+1) == '|') { pos += 2; return new LogicalOr("||",pos-2); } else { return new Bar(pos++); } } else if(c == '/') { if((pos+1) < input.length() && input.charAt(pos+1) == '/') { return scanComment(); } else { return new RightSlash(pos++); } } else if(c == '!') { if((pos+1) < input.length() && input.charAt(pos+1) == '=') { pos += 2; return new NotEquals("!=",pos-2); } else { return new Shreak(pos++); } } else if(c == '?') { return new Question(pos++); } else if(c == '=') { if((pos+1) < input.length() && input.charAt(pos+1) == '=') { pos += 2; return new EqualsEquals(pos-2); } else { return new Equals(pos++); } } else if(c == '<') { if((pos+1) < input.length() && input.charAt(pos+1) == '=') { pos += 2; return new LessEquals("<=",pos-2); } else { return new LeftAngle(pos++); } } else if(c == '>') { if((pos+1) < input.length() && input.charAt(pos+1) == '=') { pos += 2; return new GreaterEquals(">=",pos - 2); } else { return new RightAngle(pos++); } } else if (c == '~' && (pos + 1) < input.length() && input.charAt(pos + 1) == '=') { pos += 2; return new TypeEquals(pos - 2); } else if(c == UC_LESSEQUALS) { return new LessEquals(""+UC_LESSEQUALS,pos++); } else if(c == UC_GREATEREQUALS) { return new GreaterEquals(""+UC_GREATEREQUALS,pos++); } else if(c == UC_SETUNION) { return new Union(""+UC_SETUNION,pos++); } else if(c == UC_SETINTERSECTION) { return new Intersection(""+UC_SETINTERSECTION,pos++); } else if(c == UC_ELEMENTOF) { return new ElemOf(""+UC_ELEMENTOF,pos++); } else if(c == UC_SUBSET) { return new Subset(""+UC_SUBSET,pos++); } else if(c == UC_SUBSETEQ) { return new SubsetEquals(""+UC_SUBSETEQ,pos++); } else if(c == UC_SUPSET) { return new Supset(""+UC_SUPSET,pos++); } else if(c == UC_SUPSETEQ) { return new SupsetEquals(""+UC_SUPSETEQ,pos++); } else if(c == UC_EMPTYSET) { return new EmptySet(""+UC_EMPTYSET,pos++); } else if(c == UC_LOGICALOR) { return new LogicalOr(""+UC_LOGICALOR,pos++); } else if(c == UC_LOGICALAND) { return new LogicalAnd(""+UC_LOGICALAND,pos++); } syntaxError("unknown operator encountered: " + c); return null; } public boolean isIdentifierStart(char c) { return Character.isJavaIdentifierStart(c); } public static final String[] keywords = { "true", "false", "null", "int", "real", "bool", "process", "void", "if", "while", "else", "where", "requires", "ensures", "as", "for", "assert", "debug", "print", "return", "define", "function", "import", "package", "public", "extern", "spawn" }; public Token scanIdentifier() { int start = pos; while (pos < input.length() && Character.isJavaIdentifierPart(input.charAt(pos))) { pos++; } String text = input.substring(start,pos); // now, check for keywords for(String keyword : keywords) { if(keyword.equals(text)) { return new Keyword(text,start); } } // now, check for text operators if(text.equals("in")) { return new ElemOf(text,start); } else if(text.equals("no")) { return new None(text,start); } else if(text.equals("some")) { return new Some(text,start); } // otherwise, must be identifier return new Identifier(text,start); } public Token scanTabs() { int start = pos; int ntabs = 0; while (pos < input.length() && input.charAt(pos) == '\t') { pos++; ntabs++; } return new Tabs(input.substring(start, pos), ntabs, start); } public void skipWhitespace(List<Token> tokens) { int start = pos; while (pos < input.length() && input.charAt(pos) != '\n' && input.charAt(pos) == ' ') { pos++; } int ts = (pos - start) / 4; if(ts > 0) { tokens.add(new Tabs(input.substring(start,pos),ts,start)); } while (pos < input.length() && input.charAt(pos) != '\n' && Character.isWhitespace(input.charAt(pos))) { pos++; } } private void syntaxError(String msg, int index) { throw new SyntaxError(msg, filename, index, index); } private void syntaxError(String msg) { throw new SyntaxError(msg, filename, pos, pos); } public static abstract class Token { public final String text; public final int start; public Token(String text, int pos) { this.text = text; this.start = pos; } public int end() { return start + text.length() - 1; } } public static class Real extends Token { public final BigRational value; public Real(BigRational r, String text, int pos) { super(text,pos); value = r; } } public static class Int extends Token { public final BigInteger value; public Int(BigInteger r, String text, int pos) { super(text,pos); value = r; } } public static class Identifier extends Token { public Identifier(String text, int pos) { super(text,pos); } } public static class Strung extends Token { public final String string; public Strung(String string, String text, int pos) { super(text,pos); this.string = string; } } public static class Keyword extends Token { public Keyword(String text, int pos) { super(text,pos); } } public static class NewLine extends Token { public NewLine(int pos) { super("\n",pos); } } public static class Tabs extends Token { public int ntabs; public Tabs(String text, int ntabs, int pos) { super(text,pos); this.ntabs = ntabs; } } public static class Comment extends Token { public Comment(String text, int pos) { super(text,pos); } } public static class Comma extends Token { public Comma(int pos) { super(",",pos); } } public static class Colon extends Token { public Colon(int pos) { super(":",pos); } } public static class SemiColon extends Token { public SemiColon(int pos) { super(";",pos); } } public static class LeftBrace extends Token { public LeftBrace(int pos) { super("(",pos); } } public static class RightBrace extends Token { public RightBrace(int pos) { super(")",pos); } } public static class LeftSquare extends Token { public LeftSquare(int pos) { super("[",pos); } } public static class RightSquare extends Token { public RightSquare(int pos) { super("]",pos); } } public static class LeftAngle extends Token { public LeftAngle(int pos) { super("<",pos); } } public static class RightAngle extends Token { public RightAngle(int pos) { super(">",pos); } } public static class LeftCurly extends Token { public LeftCurly(int pos) { super("{",pos); } } public static class RightCurly extends Token { public RightCurly(int pos) { super("}",pos); } } public static class Plus extends Token { public Plus(int pos) { super("+",pos); } } public static class Minus extends Token { public Minus(int pos) { super("-",pos); } } public static class Star extends Token { public Star(int pos) { super("*",pos); } } public static class LeftSlash extends Token { public LeftSlash(int pos) { super("\\",pos); } } public static class RightSlash extends Token { public RightSlash(int pos) { super("/",pos); } } public static class Shreak extends Token { public Shreak(int pos) { super("!",pos); } } public static class Question extends Token { public Question(int pos) { super("?",pos); } } public static class Dot extends Token { public Dot(int pos) { super(".",pos); } } public static class DotDot extends Token { public DotDot(int pos) { super("..",pos); } } public static class Bar extends Token { public Bar(int pos) { super("|",pos); } } public static class Equals extends Token { public Equals(int pos) { super("=",pos); } } public static class EqualsEquals extends Token { public EqualsEquals(int pos) { super("==",pos); } } public static class NotEquals extends Token { public NotEquals(String text, int pos) { super(text,pos); } } public static class LessEquals extends Token { public LessEquals(String text, int pos) { super(text,pos); } } public static class GreaterEquals extends Token { public GreaterEquals(String text, int pos) { super(text,pos); } } public static class TypeEquals extends Token { public TypeEquals(int pos) { super("~=",pos); } } public static class None extends Token { public None(String text, int pos) { super(text,pos); } } public static class Some extends Token { public Some(String text, int pos) { super(text,pos); } } public static class ElemOf extends Token { public ElemOf(String text, int pos) { super(text,pos); } } public static class Union extends Token { public Union(String text, int pos) { super(text,pos); } } public static class Intersection extends Token { public Intersection(String text, int pos) { super(text,pos); } } public static class EmptySet extends Token { public EmptySet(String text, int pos) { super(text,pos); } } public static class Subset extends Token { public Subset(String text, int pos) { super(text,pos); } } public static class Supset extends Token { public Supset(String text, int pos) { super(text,pos); } } public static class SubsetEquals extends Token { public SubsetEquals(String text, int pos) { super(text,pos); } } public static class SupsetEquals extends Token { public SupsetEquals(String text, int pos) { super(text,pos); } } public static class LogicalAnd extends Token { public LogicalAnd(String text, int pos) { super(text,pos); } } public static class LogicalOr extends Token { public LogicalOr(String text, int pos) { super(text,pos); } } public static class LogicalNot extends Token { public LogicalNot(String text, int pos) { super(text,pos); } } public static class AddressOf extends Token { public AddressOf(String text, int pos) { super(text,pos); } } public static class BitwiseOr extends Token { public BitwiseOr(String text, int pos) { super(text,pos); } } public static class BitwiseNot extends Token { public BitwiseNot(String text, int pos) { super(text,pos); } } public static class Arrow extends Token { public Arrow(String text, int pos) { super(text,pos); } } }
src/ext/wyone/io/SpecLexer.java
Kind of not making much progress ...
src/ext/wyone/io/SpecLexer.java
Kind of not making much progress ...
<ide><path>rc/ext/wyone/io/SpecLexer.java <add>// This file is part of the Whiley-to-Java Compiler (wyjc). <add>// <add>// The Whiley-to-Java Compiler is free software; you can redistribute <add>// it and/or modify it under the terms of the GNU General Public <add>// License as published by the Free Software Foundation; either <add>// version 3 of the License, or (at your option) any later version. <add>// <add>// The Whiley-to-Java Compiler is distributed in the hope that it <add>// will be useful, but WITHOUT ANY WARRANTY; without even the <add>// implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR <add>// PURPOSE. See the GNU General Public License for more details. <add>// <add>// You should have received a copy of the GNU General Public <add>// License along with the Whiley-to-Java Compiler. If not, see <add>// <http://www.gnu.org/licenses/> <add>// <add>// Copyright 2010, David James Pearce. <add> <add>package wyone.io; <add> <add>import java.io.*; <add>import java.math.BigInteger; <add>import java.util.*; <add> <add>import wyil.jvm.rt.BigRational; <add>import wyone.util.SyntaxError; <add> <add>public class SpecLexer { <add> private String filename; <add> private StringBuffer input; <add> private int pos; <add> <add> public SpecLexer(String filename) throws IOException { <add> this(new InputStreamReader(new FileInputStream(filename),"UTF8")); <add> this.filename = filename; <add> } <add> <add> public SpecLexer(InputStream instream) throws IOException { <add> this(new InputStreamReader(instream,"UTF8")); <add> } <add> <add> public SpecLexer(Reader reader) throws IOException { <add> BufferedReader in = new BufferedReader(reader); <add> <add> StringBuffer text = new StringBuffer(); <add> String tmp; <add> while ((tmp = in.readLine()) != null) { <add> text.append(tmp); <add> text.append("\n"); <add> } <add> <add> input = text; <add> } <add> <add> public List<Token> scan() { <add> ArrayList<Token> tokens = new ArrayList<Token>(); <add> pos = 0; <add> <add> while(pos < input.length()) { <add> char c = input.charAt(pos); <add> <add> if(Character.isDigit(c)) { <add> tokens.add(scanDigits()); <add> } else if(c == '"') { <add> tokens.add(scanString()); <add> } else if(c == '\'') { <add> tokens.add(scanChar()); <add> } else if(isOperatorStart(c)) { <add> tokens.add(scanOperator()); <add> } else if(isIdentifierStart(c)) { <add> tokens.add(scanIdentifier()); <add> } else if(c == '\n') { <add> tokens.add(new NewLine(pos++)); <add> } else if(c == '\t') { <add> tokens.add(scanTabs()); <add> } else if(Character.isWhitespace(c)) { <add> skipWhitespace(tokens); <add> } else { <add> syntaxError("syntax error"); <add> } <add> } <add> <add> return tokens; <add> } <add> <add> public Token scanComment() { <add> int start = pos; <add> while(pos < input.length() && input.charAt(pos) != '\n') { <add> pos++; <add> } <add> return new Comment(input.substring(start,pos),start); <add> } <add> <add> public Token scanDigits() { <add> int start = pos; <add> while (pos < input.length() && Character.isDigit(input.charAt(pos))) { <add> pos = pos + 1; <add> } <add> if(pos < input.length() && input.charAt(pos) == '.') { <add> pos = pos + 1; <add> if(pos < input.length() && input.charAt(pos) == '.') { <add> // this is case for range e.g. 0..1 <add> pos = pos - 1; <add> BigInteger r = new BigInteger(input.substring(start, pos)); <add> return new Int(r,input.substring(start,pos),start); <add> } <add> while (pos < input.length() && Character.isDigit(input.charAt(pos))) { <add> pos = pos + 1; <add> } <add> BigRational r = new BigRational(input.substring(start, pos)); <add> return new Real(r,input.substring(start,pos),start); <add> } else { <add> BigInteger r = new BigInteger(input.substring(start, pos)); <add> return new Int(r,input.substring(start,pos),start); <add> } <add> } <add> <add> public Token scanChar() { <add> int start = pos; <add> pos++; <add> char c = input.charAt(pos++); <add> if(c == '\\') { <add> // escape code <add> switch(input.charAt(pos++)) { <add> case 't': <add> c = '\t'; <add> break; <add> case 'n': <add> c = '\n'; <add> break; <add> default: <add> syntaxError("unrecognised escape character",pos); <add> } <add> } <add> if(input.charAt(pos) != '\'') { <add> syntaxError("unexpected end-of-character",pos); <add> } <add> pos = pos + 1; <add> return new Int(BigInteger.valueOf(c),input.substring(start,pos),start); <add> } <add> <add> public Token scanString() { <add> int start = pos; <add> pos ++; <add> while(pos < input.length()) { <add> char c = input.charAt(pos); <add> if (c == '"') { <add> String v = input.substring(start,++pos); <add> return new Strung(parseString(v),v, start); <add> } <add> pos = pos + 1; <add> } <add> syntaxError("unexpected end-of-string",pos-1); <add> return null; <add> } <add> <add> protected String parseString(String v) { <add> /* <add> * Parsing a string requires several steps to be taken. First, we need <add> * to strip quotes from the ends of the string. <add> */ <add> v = v.substring(1, v.length() - 1); <add> int start = pos - v.length(); <add> // Second, step through the string and replace escaped characters <add> for (int i = 0; i < v.length(); i++) { <add> if (v.charAt(i) == '\\') { <add> if (v.length() <= i + 1) { <add> syntaxError("unexpected end-of-string",start+i); <add> } else { <add> char replace = 0; <add> int len = 2; <add> switch (v.charAt(i + 1)) { <add> case 'b' : <add> replace = '\b'; <add> break; <add> case 't' : <add> replace = '\t'; <add> break; <add> case 'n' : <add> replace = '\n'; <add> break; <add> case 'f' : <add> replace = '\f'; <add> break; <add> case 'r' : <add> replace = '\r'; <add> break; <add> case '"' : <add> replace = '\"'; <add> break; <add> case '\'' : <add> replace = '\''; <add> break; <add> case '\\' : <add> replace = '\\'; <add> break; <add> case 'u' : <add> len = 6; // unicode escapes are six digits long, <add> // including "slash u" <add> String unicode = v.substring(i + 2, i + 6); <add> replace = (char) Integer.parseInt(unicode, 16); // unicode <add> break; <add> default : <add> syntaxError("unknown escape character",start+i); <add> } <add> v = v.substring(0, i) + replace + v.substring(i + len); <add> } <add> } <add> } <add> return v; <add> } <add> <add> static final char UC_FORALL = '\u2200'; <add> static final char UC_EXISTS = '\u2203'; <add> static final char UC_EMPTYSET = '\u2205'; <add> static final char UC_SUBSET = '\u2282'; <add> static final char UC_SUBSETEQ = '\u2286'; <add> static final char UC_SUPSET = '\u2283'; <add> static final char UC_SUPSETEQ = '\u2287'; <add> static final char UC_SETUNION = '\u222A'; <add> static final char UC_SETINTERSECTION = '\u2229'; <add> static final char UC_LESSEQUALS = '\u2264'; <add> static final char UC_GREATEREQUALS = '\u2265'; <add> static final char UC_ELEMENTOF = '\u2208'; <add> static final char UC_LOGICALAND = '\u2227'; <add> static final char UC_LOGICALOR = '\u2228'; <add> <add> static final char[] opStarts = { ',', '(', ')', '[', ']', '{', '}', '+', '-', <add> '*', '/', '!', '?', '=', '<', '>', ':', ';', '&', '|', '.','~', <add> UC_FORALL, <add> UC_EXISTS, <add> UC_EMPTYSET, <add> UC_SUBSET, <add> UC_SUBSETEQ, <add> UC_SUPSET, <add> UC_SUPSETEQ, <add> UC_SETUNION, <add> UC_SETINTERSECTION, <add> UC_LESSEQUALS, <add> UC_GREATEREQUALS, <add> UC_ELEMENTOF <add> }; <add> <add> public boolean isOperatorStart(char c) { <add> for(char o : opStarts) { <add> if(c == o) { <add> return true; <add> } <add> } <add> return false; <add> } <add> <add> public Token scanOperator() { <add> char c = input.charAt(pos); <add> <add> if(c == '.') { <add> if((pos+1) < input.length() && input.charAt(pos+1) == '.') { <add> pos += 2; <add> return new DotDot(pos-2); <add> } else { <add> return new Dot(pos++); <add> } <add> } else if(c == ',') { <add> return new Comma(pos++); <add> } else if(c == ':') { <add> return new Colon(pos++); <add> } else if(c == ';') { <add> return new SemiColon(pos++); <add> } else if(c == '(') { <add> return new LeftBrace(pos++); <add> } else if(c == ')') { <add> return new RightBrace(pos++); <add> } else if(c == '[') { <add> return new LeftSquare(pos++); <add> } else if(c == ']') { <add> return new RightSquare(pos++); <add> } else if(c == '{') { <add> return new LeftCurly(pos++); <add> } else if(c == '}') { <add> return new RightCurly(pos++); <add> } else if(c == '+') { <add> return new Plus(pos++); <add> } else if(c == '-') { <add> if((pos+1) < input.length() && input.charAt(pos+1) == '>') { <add> pos += 2; <add> return new Arrow("->",pos-2); <add> } else { <add> return new Minus(pos++); <add> } <add> } else if(c == '*') { <add> return new Star(pos++); <add> } else if(c == '&') { <add> if((pos+1) < input.length() && input.charAt(pos+1) == '&') { <add> pos += 2; <add> return new LogicalAnd("&&",pos-2); <add> } else { <add> return new AddressOf("&",pos++); <add> } <add> } else if(c == '|') { <add> if((pos+1) < input.length() && input.charAt(pos+1) == '|') { <add> pos += 2; <add> return new LogicalOr("||",pos-2); <add> } else { <add> return new Bar(pos++); <add> } <add> } else if(c == '/') { <add> if((pos+1) < input.length() && input.charAt(pos+1) == '/') { <add> return scanComment(); <add> } else { <add> return new RightSlash(pos++); <add> } <add> } else if(c == '!') { <add> if((pos+1) < input.length() && input.charAt(pos+1) == '=') { <add> pos += 2; <add> return new NotEquals("!=",pos-2); <add> } else { <add> return new Shreak(pos++); <add> } <add> } else if(c == '?') { <add> return new Question(pos++); <add> } else if(c == '=') { <add> if((pos+1) < input.length() && input.charAt(pos+1) == '=') { <add> pos += 2; <add> return new EqualsEquals(pos-2); <add> } else { <add> return new Equals(pos++); <add> } <add> } else if(c == '<') { <add> if((pos+1) < input.length() && input.charAt(pos+1) == '=') { <add> pos += 2; <add> return new LessEquals("<=",pos-2); <add> } else { <add> return new LeftAngle(pos++); <add> } <add> } else if(c == '>') { <add> if((pos+1) < input.length() && input.charAt(pos+1) == '=') { <add> pos += 2; <add> return new GreaterEquals(">=",pos - 2); <add> } else { <add> return new RightAngle(pos++); <add> } <add> } else if (c == '~' && (pos + 1) < input.length() <add> && input.charAt(pos + 1) == '=') { <add> pos += 2; <add> return new TypeEquals(pos - 2); <add> } else if(c == UC_LESSEQUALS) { <add> return new LessEquals(""+UC_LESSEQUALS,pos++); <add> } else if(c == UC_GREATEREQUALS) { <add> return new GreaterEquals(""+UC_GREATEREQUALS,pos++); <add> } else if(c == UC_SETUNION) { <add> return new Union(""+UC_SETUNION,pos++); <add> } else if(c == UC_SETINTERSECTION) { <add> return new Intersection(""+UC_SETINTERSECTION,pos++); <add> } else if(c == UC_ELEMENTOF) { <add> return new ElemOf(""+UC_ELEMENTOF,pos++); <add> } else if(c == UC_SUBSET) { <add> return new Subset(""+UC_SUBSET,pos++); <add> } else if(c == UC_SUBSETEQ) { <add> return new SubsetEquals(""+UC_SUBSETEQ,pos++); <add> } else if(c == UC_SUPSET) { <add> return new Supset(""+UC_SUPSET,pos++); <add> } else if(c == UC_SUPSETEQ) { <add> return new SupsetEquals(""+UC_SUPSETEQ,pos++); <add> } else if(c == UC_EMPTYSET) { <add> return new EmptySet(""+UC_EMPTYSET,pos++); <add> } else if(c == UC_LOGICALOR) { <add> return new LogicalOr(""+UC_LOGICALOR,pos++); <add> } else if(c == UC_LOGICALAND) { <add> return new LogicalAnd(""+UC_LOGICALAND,pos++); <add> } <add> <add> syntaxError("unknown operator encountered: " + c); <add> return null; <add> } <add> <add> public boolean isIdentifierStart(char c) { <add> return Character.isJavaIdentifierStart(c); <add> } <add> <add> public static final String[] keywords = { <add> "true", <add> "false", <add> "null", <add> "int", <add> "real", <add> "bool", <add> "process", <add> "void", <add> "if", <add> "while", <add> "else", <add> "where", <add> "requires", <add> "ensures", <add> "as", <add> "for", <add> "assert", <add> "debug", <add> "print", <add> "return", <add> "define", <add> "function", <add> "import", <add> "package", <add> "public", <add> "extern", <add> "spawn" <add> }; <add> <add> public Token scanIdentifier() { <add> int start = pos; <add> while (pos < input.length() && <add> Character.isJavaIdentifierPart(input.charAt(pos))) { <add> pos++; <add> } <add> String text = input.substring(start,pos); <add> <add> // now, check for keywords <add> for(String keyword : keywords) { <add> if(keyword.equals(text)) { <add> return new Keyword(text,start); <add> } <add> } <add> <add> // now, check for text operators <add> if(text.equals("in")) { <add> return new ElemOf(text,start); <add> } else if(text.equals("no")) { <add> return new None(text,start); <add> } else if(text.equals("some")) { <add> return new Some(text,start); <add> } <add> <add> // otherwise, must be identifier <add> return new Identifier(text,start); <add> } <add> <add> public Token scanTabs() { <add> int start = pos; <add> int ntabs = 0; <add> while (pos < input.length() && input.charAt(pos) == '\t') { <add> pos++; <add> ntabs++; <add> } <add> return new Tabs(input.substring(start, pos), ntabs, start); <add> } <add> <add> public void skipWhitespace(List<Token> tokens) { <add> int start = pos; <add> while (pos < input.length() && input.charAt(pos) != '\n' <add> && input.charAt(pos) == ' ') { <add> pos++; <add> } <add> int ts = (pos - start) / 4; <add> if(ts > 0) { <add> tokens.add(new Tabs(input.substring(start,pos),ts,start)); <add> } <add> while (pos < input.length() && input.charAt(pos) != '\n' <add> && Character.isWhitespace(input.charAt(pos))) { <add> pos++; <add> } <add> } <add> <add> private void syntaxError(String msg, int index) { <add> throw new SyntaxError(msg, filename, index, index); <add> } <add> <add> private void syntaxError(String msg) { <add> throw new SyntaxError(msg, filename, pos, pos); <add> } <add> <add> public static abstract class Token { <add> public final String text; <add> public final int start; <add> <add> public Token(String text, int pos) { <add> this.text = text; <add> this.start = pos; <add> } <add> <add> public int end() { <add> return start + text.length() - 1; <add> } <add> } <add> <add> public static class Real extends Token { <add> public final BigRational value; <add> public Real(BigRational r, String text, int pos) { <add> super(text,pos); <add> value = r; <add> } <add> } <add> public static class Int extends Token { <add> public final BigInteger value; <add> public Int(BigInteger r, String text, int pos) { <add> super(text,pos); <add> value = r; <add> } <add> } <add> public static class Identifier extends Token { <add> public Identifier(String text, int pos) { super(text,pos); } <add> } <add> public static class Strung extends Token { <add> public final String string; <add> public Strung(String string, String text, int pos) { <add> super(text,pos); <add> this.string = string; <add> } <add> } <add> public static class Keyword extends Token { <add> public Keyword(String text, int pos) { super(text,pos); } <add> } <add> public static class NewLine extends Token { <add> public NewLine(int pos) { super("\n",pos); } <add> } <add> public static class Tabs extends Token { <add> public int ntabs; <add> public Tabs(String text, int ntabs, int pos) { <add> super(text,pos); <add> this.ntabs = ntabs; <add> } <add> } <add> public static class Comment extends Token { <add> public Comment(String text, int pos) { super(text,pos); } <add> } <add> public static class Comma extends Token { <add> public Comma(int pos) { super(",",pos); } <add> } <add> public static class Colon extends Token { <add> public Colon(int pos) { super(":",pos); } <add> } <add> public static class SemiColon extends Token { <add> public SemiColon(int pos) { super(";",pos); } <add> } <add> public static class LeftBrace extends Token { <add> public LeftBrace(int pos) { super("(",pos); } <add> } <add> public static class RightBrace extends Token { <add> public RightBrace(int pos) { super(")",pos); } <add> } <add> public static class LeftSquare extends Token { <add> public LeftSquare(int pos) { super("[",pos); } <add> } <add> public static class RightSquare extends Token { <add> public RightSquare(int pos) { super("]",pos); } <add> } <add> public static class LeftAngle extends Token { <add> public LeftAngle(int pos) { super("<",pos); } <add> } <add> public static class RightAngle extends Token { <add> public RightAngle(int pos) { super(">",pos); } <add> } <add> public static class LeftCurly extends Token { <add> public LeftCurly(int pos) { super("{",pos); } <add> } <add> public static class RightCurly extends Token { <add> public RightCurly(int pos) { super("}",pos); } <add> } <add> public static class Plus extends Token { <add> public Plus(int pos) { super("+",pos); } <add> } <add> public static class Minus extends Token { <add> public Minus(int pos) { super("-",pos); } <add> } <add> public static class Star extends Token { <add> public Star(int pos) { super("*",pos); } <add> } <add> public static class LeftSlash extends Token { <add> public LeftSlash(int pos) { super("\\",pos); } <add> } <add> public static class RightSlash extends Token { <add> public RightSlash(int pos) { super("/",pos); } <add> } <add> public static class Shreak extends Token { <add> public Shreak(int pos) { super("!",pos); } <add> } <add> public static class Question extends Token { <add> public Question(int pos) { super("?",pos); } <add> } <add> public static class Dot extends Token { <add> public Dot(int pos) { super(".",pos); } <add> } <add> public static class DotDot extends Token { <add> public DotDot(int pos) { super("..",pos); } <add> } <add> public static class Bar extends Token { <add> public Bar(int pos) { super("|",pos); } <add> } <add> public static class Equals extends Token { <add> public Equals(int pos) { super("=",pos); } <add> } <add> public static class EqualsEquals extends Token { <add> public EqualsEquals(int pos) { super("==",pos); } <add> } <add> public static class NotEquals extends Token { <add> public NotEquals(String text, int pos) { super(text,pos); } <add> } <add> public static class LessEquals extends Token { <add> public LessEquals(String text, int pos) { super(text,pos); } <add> } <add> public static class GreaterEquals extends Token { <add> public GreaterEquals(String text, int pos) { super(text,pos); } <add> } <add> public static class TypeEquals extends Token { <add> public TypeEquals(int pos) { super("~=",pos); } <add> } <add> public static class None extends Token { <add> public None(String text, int pos) { super(text,pos); } <add> } <add> public static class Some extends Token { <add> public Some(String text, int pos) { super(text,pos); } <add> } <add> public static class ElemOf extends Token { <add> public ElemOf(String text, int pos) { super(text,pos); } <add> } <add> public static class Union extends Token { <add> public Union(String text, int pos) { super(text,pos); } <add> } <add> public static class Intersection extends Token { <add> public Intersection(String text, int pos) { super(text,pos); } <add> } <add> public static class EmptySet extends Token { <add> public EmptySet(String text, int pos) { super(text,pos); } <add> } <add> public static class Subset extends Token { <add> public Subset(String text, int pos) { super(text,pos); } <add> } <add> public static class Supset extends Token { <add> public Supset(String text, int pos) { super(text,pos); } <add> } <add> public static class SubsetEquals extends Token { <add> public SubsetEquals(String text, int pos) { super(text,pos); } <add> } <add> public static class SupsetEquals extends Token { <add> public SupsetEquals(String text, int pos) { super(text,pos); } <add> } <add> public static class LogicalAnd extends Token { <add> public LogicalAnd(String text, int pos) { super(text,pos); } <add> } <add> public static class LogicalOr extends Token { <add> public LogicalOr(String text, int pos) { super(text,pos); } <add> } <add> public static class LogicalNot extends Token { <add> public LogicalNot(String text, int pos) { super(text,pos); } <add> } <add> public static class AddressOf extends Token { <add> public AddressOf(String text, int pos) { super(text,pos); } <add> } <add> public static class BitwiseOr extends Token { <add> public BitwiseOr(String text, int pos) { super(text,pos); } <add> } <add> public static class BitwiseNot extends Token { <add> public BitwiseNot(String text, int pos) { super(text,pos); } <add> } <add> public static class Arrow extends Token { <add> public Arrow(String text, int pos) { super(text,pos); } <add> } <add>}
Java
apache-2.0
error: pathspec 'DNSLookup.java' did not match any file(s) known to git
970e0f2d49e6290bdf90de85b72eae9a35ad74f3
1
timjinx/Sample-Repo,timjinx/Sample-Repo,timjinx/Sample-Repo,timjinx/Sample-Repo,timjinx/Sample-Repo,timjinx/Sample-Repo,timjinx/Sample-Repo,timjinx/Sample-Repo,timjinx/Sample-Repo,timjinx/Sample-Repo,timjinx/Sample-Repo
import javax.naming.directory.Attributes; import javax.naming.directory.DirContext; import javax.naming.directory.InitialDirContext; import javax.naming.Context; import javax.naming.NamingEnumeration; import javax.naming.NamingException; import java.net.InetAddress; import java.net.UnknownHostException; import java.util.Hashtable; import java.util.Scanner; public class DNSLookup { public static void main(String args[]) { Scanner scan = new Scanner(System.in); String host = scan.nextLine(); try { InetAddress inetAddress = InetAddress.getByName(host); // show the Internet Address as name/address System.out.println(inetAddress.getHostName() + " " + inetAddress.getHostAddress()); Hashtable<String, String> env = new Hashtable<String, String>(); //env.put(Context.INITIAL_CONTEXT_FACTORY,"com.sun.jndi.ldap.LdapCtxFactory"); //env.put(Context.PROVIDER_URL, "ldap://localhost:389/o=JNDITutorial"); env.put(Context.INITIAL_CONTEXT_FACTORY,"com.sun.jndi.dns.DnsContextFactory"); //env.put(Context.PROVIDER_URL, "dns://google.com"); // get the default initial Directory Context InitialDirContext iDirC = new InitialDirContext(env); // get the DNS records for inetAddress Attributes attributes = iDirC.getAttributes("dns:/"+inetAddress.getHostName()); // get an enumeration of the attributes and print them out NamingEnumeration<?> attributeEnumeration = attributes.getAll(); System.out.println(""); while (attributeEnumeration.hasMore()) { System.out.println("" + attributeEnumeration.next()); } attributeEnumeration.close(); } catch (UnknownHostException exception) { System.err.println("ERROR: Cannot access '" + host + "'"); } catch (NamingException exception) { System.err.println("ERROR: No DNS record for '" + host + "'"); exception.printStackTrace(); } } }
DNSLookup.java
Create DNSLookup.java A simple example of how to perform a DNS lookup in Java
DNSLookup.java
Create DNSLookup.java
<ide><path>NSLookup.java <add>import javax.naming.directory.Attributes; <add>import javax.naming.directory.DirContext; <add>import javax.naming.directory.InitialDirContext; <add>import javax.naming.Context; <add>import javax.naming.NamingEnumeration; <add>import javax.naming.NamingException; <add>import java.net.InetAddress; <add>import java.net.UnknownHostException; <add>import java.util.Hashtable; <add>import java.util.Scanner; <add> <add>public class DNSLookup <add>{ <add> public static void main(String args[]) <add> { <add> Scanner scan = new Scanner(System.in); <add> String host = scan.nextLine(); <add> try <add> { <add> InetAddress inetAddress = InetAddress.getByName(host); <add> // show the Internet Address as name/address <add> System.out.println(inetAddress.getHostName() + " " + inetAddress.getHostAddress()); <add> <add> Hashtable<String, String> env = new Hashtable<String, String>(); <add> //env.put(Context.INITIAL_CONTEXT_FACTORY,"com.sun.jndi.ldap.LdapCtxFactory"); <add> //env.put(Context.PROVIDER_URL, "ldap://localhost:389/o=JNDITutorial"); <add> <add> env.put(Context.INITIAL_CONTEXT_FACTORY,"com.sun.jndi.dns.DnsContextFactory"); <add> //env.put(Context.PROVIDER_URL, "dns://google.com"); <add> <add> // get the default initial Directory Context <add> InitialDirContext iDirC = new InitialDirContext(env); <add> // get the DNS records for inetAddress <add> Attributes attributes = iDirC.getAttributes("dns:/"+inetAddress.getHostName()); <add> // get an enumeration of the attributes and print them out <add> NamingEnumeration<?> attributeEnumeration = attributes.getAll(); <add> System.out.println(""); <add> while (attributeEnumeration.hasMore()) <add> { <add> System.out.println("" + attributeEnumeration.next()); <add> } <add> attributeEnumeration.close(); <add> } <add> catch (UnknownHostException exception) <add> { <add> System.err.println("ERROR: Cannot access '" + host + "'"); <add> } <add> catch (NamingException exception) <add> { <add> System.err.println("ERROR: No DNS record for '" + host + "'"); <add> exception.printStackTrace(); <add> } <add> } <add>}
JavaScript
mpl-2.0
1f55438932810fe56d5220ade6b6db3e6984c88f
0
asamuzaK/sidebarTabs,asamuzaK/sidebarTabs
/** * color.js * * Ref: CSS Color Module Level 4 * §17. Sample code for Color Conversions * https://w3c.github.io/csswg-drafts/css-color-4/#color-conversion-code * * NOTE: 'currentColor' keyword is not supported */ /* shared */ import { getType, isString, logWarn } from './common.js'; /* constants */ const HALF = 0.5; const DOUBLE = 2; const TRIPLE = 3; const QUAD = 4; const DEC = 10; const HEX = 16; const DEG = 360; const DEG_INTERVAL = 60; const MAX_PCT = 100; const MAX_RGB = 255; const POW_SQUARE = 2; const POW_CUBE = 3; const POW_LINEAR = 2.4; const LINEAR_COEF = 12.92; const LINEAR_OFFSET = 0.055; const LAB_L = 116; const LAB_A = 500; const LAB_B = 200; const LAB_EPSILON = 216 / 24389; const LAB_KAPPA = 24389 / 27; /* white points */ const D50 = [0.3457 / 0.3585, 1, (1 - 0.3457 - 0.3585) / 0.3585]; const D65 = [0.3127 / 0.3290, 1, (1 - 0.3127 - 0.3290) / 0.3290]; const MATRIX_D50_TO_D65 = [ [0.9554734527042182, -0.023098536874261423, 0.0632593086610217], [-0.028369706963208136, 1.0099954580058226, 0.021041398966943008], [0.012314001688319899, -0.020507696433477912, 1.3303659366080753] ]; const MATRIX_D65_TO_D50 = [ [1.0479298208405488, 0.022946793341019088, -0.05019222954313557], [0.029627815688159344, 0.990434484573249, -0.01707382502938514], [-0.009243058152591178, 0.015055144896577895, 0.7518742899580008] ]; /* color spaces */ const MATRIX_RGB_TO_XYZ = [ [506752 / 1228815, 87881 / 245763, 12673 / 70218], [87098 / 409605, 175762 / 245763, 12673 / 175545], [7918 / 409605, 87881 / 737289, 1001167 / 1053270] ]; const MATRIX_XYZ_TO_RGB = [ [12831 / 3959, -329 / 214, -1974 / 3959], [-851781 / 878810, 1648619 / 878810, 36519 / 878810], [705 / 12673, -2585 / 12673, 705 / 667] ]; const MATRIX_XYZ_TO_LMS = [ [0.8190224432164319, 0.3619062562801221, -0.12887378261216414], [0.0329836671980271, 0.9292868468965546, 0.03614466816999844], [0.048177199566046255, 0.26423952494422764, 0.6335478258136937] ]; const MATRIX_LMS_TO_XYZ = [ [1.2268798733741557, -0.5578149965554813, 0.28139105017721583], [-0.04057576262431372, 1.1122868293970594, -0.07171106666151701], [-0.07637294974672142, -0.4214933239627914, 1.5869240244272418] ]; const MATRIX_OKLAB_TO_LMS = [ [0.9999999984505196, 0.39633779217376774, 0.2158037580607588], [1.0000000088817607, -0.10556134232365633, -0.0638541747717059], [1.0000000546724108, -0.08948418209496574, -1.2914855378640917] ]; const MATRIX_LMS_TO_OKLAB = [ [0.2104542553, 0.7936177850, -0.0040720468], [1.9779984951, -2.4285922050, 0.4505937099], [0.0259040371, 0.7827717662, -0.8086757660] ]; const MATRIX_P3_TO_XYZ = [ [608311 / 1250200, 189793 / 714400, 198249 / 1000160], [35783 / 156275, 247089 / 357200, 198249 / 2500400], [0, 32229 / 714400, 5220557 / 5000800] ]; const MATRIX_REC2020_TO_XYZ = [ [63426534 / 99577255, 20160776 / 139408157, 47086771 / 278816314], [26158966 / 99577255, 472592308 / 697040785, 8267143 / 139408157], [0, 19567812 / 697040785, 295819943 / 278816314] ]; const MATRIX_A98_TO_XYZ = [ [573536 / 994567, 263643 / 1420810, 187206 / 994567], [591459 / 1989134, 6239551 / 9945670, 374412 / 4972835], [53769 / 1989134, 351524 / 4972835, 4929758 / 4972835] ]; const MATRIX_PROPHOTO_TO_XYZ_D50 = [ [0.7977604896723027, 0.13518583717574031, 0.0313493495815248], [0.2880711282292934, 0.7118432178101014, 0.00008565396060525902], [0, 0, 0.8251046025104601] ]; /* regexp */ const NONE = 'none'; const REG_ANGLE = 'deg|g?rad|turn'; const REG_COLOR_SPACE_COLOR_MIX = '(?:ok)?l(?:ab|ch)|h(?:sl|wb)|srgb(?:-linear)?|xyz(?:-d(?:50|65))?'; const REG_COLOR_SPACE_RGB = '(?:a98|prophoto)-rgb|display-p3|rec2020|srgb(?:-linear)?'; const REG_COLOR_SPACE_XYZ = 'xyz(?:-d(?:50|65))?'; const REG_NUM = '-?(?:(?:0|[1-9]\\d*)(?:\\.\\d*)?|\\.\\d+)(?:[Ee]-?(?:(?:0|[1-9]\\d*)))?'; const REG_PCT = `${REG_NUM}%`; const REG_HSL_HWB = `(?:${REG_NUM}(?:${REG_ANGLE})?|${NONE})(?:\\s+(?:${REG_PCT}|${NONE})){2}(?:\\s*\\/\\s*(?:${REG_NUM}|${REG_PCT}|${NONE}))?`; const REG_HSL_LV3 = `${REG_NUM}(?:${REG_ANGLE})?(?:\\s*,\\s*${REG_PCT}){2}(?:\\s*,\\s*(?:${REG_NUM}|${REG_PCT}))?`; const REG_RGB = `(?:(?:${REG_NUM}|${NONE})(?:\\s+(?:${REG_NUM}|${NONE})){2}|(?:${REG_PCT}|${NONE})(?:\\s+(?:${REG_PCT}|${NONE})){2})(?:\\s*\\/\\s*(?:${REG_NUM}|${REG_PCT}|${NONE}))?`; const REG_RGB_LV3 = `(?:${REG_NUM}(?:\\s*,\\s*${REG_NUM}){2}|${REG_PCT}(?:\\s*,\\s*${REG_PCT}){2})(?:\\s*,\\s*(?:${REG_NUM}|${REG_PCT}))?`; const REG_LAB = `(?:${REG_NUM}|${REG_PCT}|${NONE})(?:\\s+(?:${REG_NUM}|${REG_PCT}|${NONE})){2}(?:\\s*\\/\\s*(?:${REG_NUM}|${REG_PCT}|${NONE}))?`; const REG_LCH = `(?:(?:${REG_NUM}|${REG_PCT}|${NONE})\\s+){2}(?:${REG_NUM}(?:${REG_ANGLE})?|${NONE})(?:\\s*\\/\\s*(?:${REG_NUM}|${REG_PCT}|${NONE}))?`; const REG_COLOR_FUNC = `(?:${REG_COLOR_SPACE_RGB}|${REG_COLOR_SPACE_XYZ})(?:\\s+(?:${REG_NUM}|${REG_PCT}|${NONE})){3}(?:\\s*\\/\\s*(?:${REG_NUM}|${REG_PCT}|${NONE}))?`; const REG_COLOR_TYPE = `[a-z]+|#(?:[\\da-f]{3}|[\\da-f]{4}|[\\da-f]{6}|[\\da-f]{8})|hsla?\\(\\s*(?:${REG_HSL_HWB}|${REG_HSL_LV3})\\s*\\)|hwb\\(\\s*${REG_HSL_HWB}\\s*\\)|rgba?\\(\\s*(?:${REG_RGB}|${REG_RGB_LV3})\\s*\\)|(?:ok)?lab\\(\\s*${REG_LAB}\\s*\\)|(?:ok)?lch\\(\\s*${REG_LCH}\\s*\\)|color\\(\\s*${REG_COLOR_FUNC}\\s*\\)`; const REG_COLOR_MIX_PART = `(?:${REG_COLOR_TYPE})(?:\\s+${REG_PCT})?`; const REG_COLOR_MIX_CAPT = `color-mix\\(\\s*in\\s+(${REG_COLOR_SPACE_COLOR_MIX})\\s*,\\s*(${REG_COLOR_MIX_PART})\\s*,\\s*(${REG_COLOR_MIX_PART})\\s*\\)`; /* named colors */ export const colorname = { aliceblue: '#f0f8ff', antiquewhite: '#faebd7', aqua: '#00ffff', aquamarine: '#7fffd4', azure: '#f0ffff', beige: '#f5f5dc', bisque: '#ffe4c4', black: '#000000', blanchedalmond: '#ffebcd', blue: '#0000ff', blueviolet: '#8a2be2', brown: '#a52a2a', burlywood: '#deb887', cadetblue: '#5f9ea0', chartreuse: '#7fff00', chocolate: '#d2691e', coral: '#ff7f50', cornflowerblue: '#6495ed', cornsilk: '#fff8dc', crimson: '#dc143c', cyan: '#00ffff', darkblue: '#00008b', darkcyan: '#008b8b', darkgoldenrod: '#b8860b', darkgray: '#a9a9a9', darkgreen: '#006400', darkgrey: '#a9a9a9', darkkhaki: '#bdb76b', darkmagenta: '#8b008b', darkolivegreen: '#556b2f', darkorange: '#ff8c00', darkorchid: '#9932cc', darkred: '#8b0000', darksalmon: '#e9967a', darkseagreen: '#8fbc8f', darkslateblue: '#483d8b', darkslategray: '#2f4f4f', darkslategrey: '#2f4f4f', darkturquoise: '#00ced1', darkviolet: '#9400d3', deeppink: '#ff1493', deepskyblue: '#00bfff', dimgray: '#696969', dimgrey: '#696969', dodgerblue: '#1e90ff', firebrick: '#b22222', floralwhite: '#fffaf0', forestgreen: '#228b22', fuchsia: '#ff00ff', gainsboro: '#dcdcdc', ghostwhite: '#f8f8ff', gold: '#ffd700', goldenrod: '#daa520', gray: '#808080', green: '#008000', greenyellow: '#adff2f', grey: '#808080', honeydew: '#f0fff0', hotpink: '#ff69b4', indianred: '#cd5c5c', indigo: '#4b0082', ivory: '#fffff0', khaki: '#f0e68c', lavender: '#e6e6fa', lavenderblush: '#fff0f5', lawngreen: '#7cfc00', lemonchiffon: '#fffacd', lightblue: '#add8e6', lightcoral: '#f08080', lightcyan: '#e0ffff', lightgoldenrodyellow: '#fafad2', lightgray: '#d3d3d3', lightgreen: '#90ee90', lightgrey: '#d3d3d3', lightpink: '#ffb6c1', lightsalmon: '#ffa07a', lightseagreen: '#20b2aa', lightskyblue: '#87cefa', lightslategray: '#778899', lightslategrey: '#778899', lightsteelblue: '#b0c4de', lightyellow: '#ffffe0', lime: '#00ff00', limegreen: '#32cd32', linen: '#faf0e6', magenta: '#ff00ff', maroon: '#800000', mediumaquamarine: '#66cdaa', mediumblue: '#0000cd', mediumorchid: '#ba55d3', mediumpurple: '#9370db', mediumseagreen: '#3cb371', mediumslateblue: '#7b68ee', mediumspringgreen: '#00fa9a', mediumturquoise: '#48d1cc', mediumvioletred: '#c71585', midnightblue: '#191970', mintcream: '#f5fffa', mistyrose: '#ffe4e1', moccasin: '#ffe4b5', navajowhite: '#ffdead', navy: '#000080', oldlace: '#fdf5e6', olive: '#808000', olivedrab: '#6b8e23', orange: '#ffa500', orangered: '#ff4500', orchid: '#da70d6', palegoldenrod: '#eee8aa', palegreen: '#98fb98', paleturquoise: '#afeeee', palevioletred: '#db7093', papayawhip: '#ffefd5', peachpuff: '#ffdab9', peru: '#cd853f', pink: '#ffc0cb', plum: '#dda0dd', powderblue: '#b0e0e6', purple: '#800080', rebeccapurple: '#663399', red: '#ff0000', rosybrown: '#bc8f8f', royalblue: '#4169e1', saddlebrown: '#8b4513', salmon: '#fa8072', sandybrown: '#f4a460', seagreen: '#2e8b57', seashell: '#fff5ee', sienna: '#a0522d', silver: '#c0c0c0', skyblue: '#87ceeb', slateblue: '#6a5acd', slategray: '#708090', slategrey: '#708090', snow: '#fffafa', springgreen: '#00ff7f', steelblue: '#4682b4', tan: '#d2b48c', teal: '#008080', thistle: '#d8bfd8', tomato: '#ff6347', turquoise: '#40e0d0', violet: '#ee82ee', wheat: '#f5deb3', white: '#ffffff', whitesmoke: '#f5f5f5', yellow: '#ffff00', yellowgreen: '#9acd32' }; /** * transform matrix * * @param {Array.<Array.<number>>} mtx - 3 * 3 matrix * @param {Array.<number>} vct - vector * @returns {Array.<number>} - [p1, p2, p3] */ export const transformMatrix = async (mtx, vct) => { if (!Array.isArray(mtx)) { throw new TypeError(`Expected Array but got ${getType(mtx)}.`); } else if (mtx.length !== TRIPLE) { throw new Error(`Expected array length of 3 but got ${mtx.length}.`); } else { for (const i of mtx) { if (!Array.isArray(i)) { throw new TypeError(`Expected Array but got ${getType(i)}.`); } else if (i.length !== TRIPLE) { throw new Error(`Expected array length of 3 but got ${i.length}.`); } else { for (const j of i) { if (typeof j !== 'number') { throw new TypeError(`Expected Number but got ${getType(j)}.`); } else if (Number.isNaN(j)) { throw new TypeError(`${j} is not a number.`); } } } } } if (!Array.isArray(vct)) { throw new TypeError(`Expected Array but got ${getType(vct)}.`); } else if (vct.length !== TRIPLE) { throw new Error(`Expected array length of 3 but got ${vct.length}.`); } else { for (const i of vct) { if (typeof i !== 'number') { throw new TypeError(`Expected Number but got ${getType(i)}.`); } else if (Number.isNaN(i)) { throw new TypeError(`${i} is not a number.`); } } } const [ [r1c1, r1c2, r1c3], [r2c1, r2c2, r2c3], [r3c1, r3c2, r3c3] ] = mtx; const [v1, v2, v3] = vct; const p1 = r1c1 * v1 + r1c2 * v2 + r1c3 * v3; const p2 = r2c1 * v1 + r2c2 * v2 + r2c3 * v3; const p3 = r3c1 * v1 + r3c2 * v2 + r3c3 * v3; return [p1, p2, p3]; }; /** * number to hex string * * @param {number} value - value * @returns {string} - hex string */ export const numberToHexString = async value => { if (typeof value !== 'number') { throw new TypeError(`Expected Number but got ${getType(value)}.`); } else if (Number.isNaN(value)) { throw new TypeError(`${value} is not a number.`); } else { value = Math.round(value); if (value < 0 || value > MAX_RGB) { throw new RangeError(`${value} is not between 0 and ${MAX_RGB}.`); } } let hex = value.toString(HEX); if (hex.length === 1) { hex = `0${hex}`; } return hex; }; /** * angle to deg * * @param {string} angle - angle * @returns {number} - deg 0..360 */ export const angleToDeg = async angle => { if (isString(angle)) { angle = angle.trim(); } else { throw new TypeError(`Expected String but got ${getType(angle)}.`); } const reg = new RegExp(`^(${REG_NUM})(${REG_ANGLE})?$`); if (!reg.test(angle)) { throw new Error(`Invalid property value: ${angle}`); } const [, val, unit] = angle.match(reg); const value = val.startsWith('.') ? `0${val}` : val; let deg; switch (unit) { case 'grad': deg = parseFloat(value) * DEG / (MAX_PCT * QUAD); break; case 'rad': deg = parseFloat(value) * DEG / (Math.PI * DOUBLE); break; case 'turn': deg = parseFloat(value) * DEG; break; default: deg = parseFloat(value); } deg %= DEG; if (deg < 0) { deg += DEG; } return deg; }; /** * rgb to linear rgb * * @param {Array.<number>} rgb - [r, g, b] r|g|b: 0..1 * @returns {Array.<number>} - [r, g, b] r|g|b: 0..1 */ export const rgbToLinearRgb = async rgb => { if (!Array.isArray(rgb)) { throw new TypeError(`Expected Array but got ${getType(rgb)}.`); } let [r, g, b] = rgb; if (typeof r !== 'number') { throw new TypeError(`Expected Number but got ${getType(r)}.`); } else if (Number.isNaN(r)) { throw new TypeError(`${r} is not a number.`); } else if (r < 0 || r > 1) { throw new RangeError(`${r} is not between 0 and 1.`); } if (typeof g !== 'number') { throw new TypeError(`Expected Number but got ${getType(g)}.`); } else if (Number.isNaN(g)) { throw new TypeError(`${g} is not a number.`); } else if (g < 0 || g > 1) { throw new RangeError(`${g} is not between 0 and 1.`); } if (typeof b !== 'number') { throw new TypeError(`Expected Number but got ${getType(b)}.`); } else if (Number.isNaN(b)) { throw new TypeError(`${b} is not a number.`); } else if (b < 0 || b > 1) { throw new RangeError(`${b} is not between 0 and 1.`); } const COND_POW = 0.04045; if (r > COND_POW) { r = Math.pow((r + LINEAR_OFFSET) / (1 + LINEAR_OFFSET), POW_LINEAR); } else { r = (r / LINEAR_COEF); } if (g > COND_POW) { g = Math.pow((g + LINEAR_OFFSET) / (1 + LINEAR_OFFSET), POW_LINEAR); } else { g = (g / LINEAR_COEF); } if (b > COND_POW) { b = Math.pow((b + LINEAR_OFFSET) / (1 + LINEAR_OFFSET), POW_LINEAR); } else { b = (b / LINEAR_COEF); } return [r, g, b]; }; /** * hex to rgb * * @param {string} value - value * @returns {Array.<number>} - [r, g, b, a] r|g|b: 0..255 a: 0..1 */ export const hexToRgb = async value => { if (isString(value)) { value = value.toLowerCase().trim(); } else { throw new TypeError(`Expected String but got ${getType(value)}.`); } if (!(/^#[\da-f]{6}$/.test(value) || /^#[\da-f]{3}$/.test(value) || /^#[\da-f]{8}$/.test(value) || /^#[\da-f]{4}$/.test(value))) { throw new Error(`Invalid property value: ${value}`); } const arr = []; if (/^#[\da-f]{6}$/.test(value)) { const [, r, g, b] = value.match(/^#([\da-f]{2})([\da-f]{2})([\da-f]{2})$/); arr.push( parseInt(r, HEX), parseInt(g, HEX), parseInt(b, HEX), 1 ); } else if (/^#[\da-f]{3}$/.test(value)) { const [, r, g, b] = value.match(/^#([\da-f])([\da-f])([\da-f])$/); arr.push( parseInt(`${r}${r}`, HEX), parseInt(`${g}${g}`, HEX), parseInt(`${b}${b}`, HEX), 1 ); } else if (/^#[\da-f]{8}$/.test(value)) { const [, r, g, b, a] = value.match(/^#([\da-f]{2})([\da-f]{2})([\da-f]{2})([\da-f]{2})$/); arr.push( parseInt(r, HEX), parseInt(g, HEX), parseInt(b, HEX), parseInt(a, HEX) / MAX_RGB ); } else if (/^#[\da-f]{4}$/.test(value)) { const [, r, g, b, a] = value.match(/^#([\da-f])([\da-f])([\da-f])([\da-f])$/); arr.push( parseInt(`${r}${r}`, HEX), parseInt(`${g}${g}`, HEX), parseInt(`${b}${b}`, HEX), parseInt(`${a}${a}`, HEX) / MAX_RGB ); } return arr; }; /** * hex to hsl * * @param {string} value - value * @returns {Array.<number>} - [h, s, l, a] h: 0..360 s|l: 0..100 a: 0..1 */ export const hexToHsl = async value => { const [rr, gg, bb, a] = await hexToRgb(value); const r = parseFloat(rr) / MAX_RGB; const g = parseFloat(gg) / MAX_RGB; const b = parseFloat(bb) / MAX_RGB; const max = Math.max(r, g, b); const min = Math.min(r, g, b); const d = max - min; const l = (max + min) * HALF; let h, s; if (l === 0 || l === 1) { h = NONE; s = NONE; } else { s = d / (1 - Math.abs(max + min - 1)) * MAX_PCT; if (s === 0) { h = NONE; } else { switch (max) { case r: h = (g - b) / d; break; case g: h = (b - r) / d + DOUBLE; break; case b: default: h = (r - g) / d + QUAD; break; } h = h * DEG_INTERVAL % DEG; if (h < 0) { h += DEG; } } } return [ h, s, l * MAX_PCT, a ]; }; /** * hex to hwb * * @param {string} value - value * @returns {Array.<number>} - [h, w, b, a] h: 0..360 w|b: 0..100 a: 0..1 */ export const hexToHwb = async value => { const [rr, gg, bb, a] = await hexToRgb(value); const r = parseFloat(rr) / MAX_RGB; const g = parseFloat(gg) / MAX_RGB; const b = parseFloat(bb) / MAX_RGB; const w = Math.min(r, g, b); const bk = 1 - Math.max(r, g, b); let h; if (w + bk === 1) { h = NONE; } else { [h] = await hexToHsl(value); } return [ h, w * MAX_PCT, bk * MAX_PCT, a ]; }; /** * hex to linear rgb * * @param {string} value - value * @returns {Array.<number>} - [r, g, b, a] r|g|b|a: 0..1 */ export const hexToLinearRgb = async value => { const [rr, gg, bb, a] = await hexToRgb(value); const [r, g, b] = await rgbToLinearRgb([ rr / MAX_RGB, gg / MAX_RGB, bb / MAX_RGB ]); return [r, g, b, a]; }; /** * hex to xyz * * @param {string} value - value * @returns {Array.<number>} - [x, y, z, a] x|y|z: around 0..1 a: 0..1 */ export const hexToXyz = async value => { const [r, g, b, a] = await hexToLinearRgb(value); const [x, y, z] = await transformMatrix(MATRIX_RGB_TO_XYZ, [r, g, b]); return [x, y, z, a]; }; /** * hex to xyz D50 * * @param {string} value - value * @returns {Array.<number>} - [x, y, z, a] x|y|z: around 0..1 a: 0..1 */ export const hexToXyzD50 = async value => { const [r, g, b, a] = await hexToLinearRgb(value); const xyz = await transformMatrix(MATRIX_RGB_TO_XYZ, [r, g, b]); const [x, y, z] = await transformMatrix(MATRIX_D65_TO_D50, xyz); return [x, y, z, a]; }; /** * hex to lab * * @param {string} value - value * @returns {Array.<number>} - [l, a, b, aa] * l: 0..100 a|b: around -160..160 aa: 0..1 */ export const hexToLab = async value => { const [x, y, z, aa] = await hexToXyzD50(value); const xyz = [x, y, z].map((val, i) => val / D50[i]); const [f0, f1, f2] = xyz.map(val => val > LAB_EPSILON ? Math.cbrt(val) : (val * LAB_KAPPA + HEX) / LAB_L ); const l = Math.min(Math.max((LAB_L * f1) - HEX, 0), 100); let a, b; if (l === 0 || l === 100) { a = NONE; b = NONE; } else { a = (f0 - f1) * LAB_A; b = (f1 - f2) * LAB_B; } return [l, a, b, aa]; }; /** * hex to lch * * @param {string} value - value * @returns {Array.<number>} - [l, c, h, a] * l: 0..100 c: around 0..230 h: 0..360 a: 0..1 */ export const hexToLch = async value => { const [l, a, b, aa] = await hexToLab(value); let c, h; if (l === 0 || l === 100) { c = NONE; h = NONE; } else { c = Math.max(Math.sqrt(Math.pow(a, POW_SQUARE) + Math.pow(b, POW_SQUARE)), 0); if (parseFloat(c.toFixed(4)) === 0) { h = NONE; } else { h = Math.atan2(b, a) * DEG * HALF / Math.PI; if (h < 0) { h += DEG; } } } return [l, c, h, aa]; }; /** * hex to oklab * * @param {string} value - value * @param {boolean} asis - leave value as is * @returns {Array.<number>} - [l, a, b, aa] l|aa: 0..1 a|b: around -0.5..0.5 */ export const hexToOklab = async (value, asis = false) => { const [xx, yy, zz, aa] = await hexToXyz(value); let x, y, z; if (asis) { x = xx; y = yy; z = zz; } else { [x, y, z] = [xx, yy, zz].map((val, i) => val * D65[i]); } const lms = await transformMatrix(MATRIX_XYZ_TO_LMS, [x, y, z]); const xyzLms = lms.map(c => Math.cbrt(c)); let [l, a, b] = await transformMatrix(MATRIX_LMS_TO_OKLAB, xyzLms); l = Math.min(Math.max(l, 0), 1); const lPct = Math.round(parseFloat(l.toFixed(4)) * MAX_PCT); if (lPct === 0 || lPct === 100) { a = NONE; b = NONE; } return [l, a, b, aa]; }; /** * hex to oklch * * @param {string} value - value * @returns {Array.<number>} - [l, a, b, aa] * l|aa: 0..1 c: around 0..0.5 h: 0..360 */ export const hexToOklch = async value => { const [l, a, b, aa] = await hexToOklab(value, true); let c, h; const lPct = Math.round(parseFloat(l.toFixed(4)) * MAX_PCT); if (lPct === 0 || lPct === 100) { c = NONE; h = NONE; } else { c = Math.max(Math.sqrt(Math.pow(a, POW_SQUARE) + Math.pow(b, POW_SQUARE)), 0); if (parseFloat(c.toFixed(4)) === 0) { h = NONE; } else { h = Math.atan2(b, a) * DEG * HALF / Math.PI; if (h < 0) { h += DEG; } } } return [l, c, h, aa]; }; /** * re-insert missing color components * * @param {string} value - value * @param {Array} color - array of color components [r, g, b, a]|[l, c, h, a] * @returns {Array} - [v1, v2, v3, v4] */ export const reInsertMissingComponents = async (value, color = []) => { if (isString(value)) { value = value.trim(); } else { throw new TypeError(`Expected String but got ${getType(value)}.`); } const [v1, v2, v3, v4] = color; let v1m, v2m, v3m, v4m; if (/none/.test(value)) { const regRgb = new RegExp(`^rgba?\\(\\s*(${REG_RGB})\\s*\\)$`); const regColor = new RegExp(`^color\\(\\s*(${REG_COLOR_FUNC})\\s*\\)$`); const regHsl = new RegExp(`^h(?:sla?|wb)\\(\\s*(${REG_HSL_HWB})\\s*\\)$`); const regLab = new RegExp(`^(?:ok)?lab\\(\\s*(${REG_LAB})\\s*\\)$`); const regLch = new RegExp(`^(?:ok)?lch\\(\\s*(${REG_LCH})\\s*\\)$`); // rgb() if (regRgb.test(value)) { [v1m, v2m, v3m, v4m] = value.match(regRgb)[1].replace('/', ' ').split(/\s+/); // color() } else if (regColor.test(value)) { [, v1m, v2m, v3m, v4m] = value.match(regColor)[1].replace('/', ' ').split(/\s+/); // hsl() } else if (value.startsWith('hsl') && regHsl.test(value)) { [v3m, v2m, v1m, v4m] = value.match(regHsl)[1].replace('/', ' ').split(/\s+/); // hwb() } else if (value.startsWith('hwb') && regHsl.test(value)) { [v3m, , , v4m] = value.match(regHsl)[1].replace('/', ' ').split(/\s+/); // lab(), oklab() } else if (regLab.test(value)) { [v1m, , , v4m] = value.match(regLab)[1].replace('/', ' ').split(/\s+/); // lch(), oklch() } else if (regLch.test(value)) { [v1m, v2m, v3m, v4m] = value.match(regLch)[1].replace('/', ' ').split(/\s+/); } } return [ v1m === NONE ? v1m : v1, v2m === NONE ? v2m : v2, v3m === NONE ? v3m : v3, v4m === NONE ? v4m : v4 ]; }; /** * normalize color components * * @param {Array} colorA - array of color components [v1, v2, v3, v4] * @param {Array} colorB - array of color components [v1, v2, v3, v4] * @returns {Array.<Array>} - [colorA, colorB] */ export const normalizeColorComponents = async (colorA, colorB) => { if (!Array.isArray(colorA)) { throw new TypeError(`Expected Array but got ${getType(colorA)}.`); } else if (colorA.length !== QUAD) { throw new Error(`Expected array length of 4 but got ${colorA.length}.`); } if (!Array.isArray(colorB)) { throw new TypeError(`Expected Array but got ${getType(colorB)}.`); } else if (colorB.length !== QUAD) { throw new Error(`Expected array length of 4 but got ${colorB.length}.`); } let i = 0; while (i < QUAD) { if (colorA[i] === NONE && colorB[i] === NONE) { colorA[i] = 0; colorB[i] = 0; } else if (colorA[i] === NONE) { colorA[i] = colorB[i]; } else if (colorB[i] === NONE) { colorB[i] = colorA[i]; } i++; } return [colorA, colorB]; }; /** * parse rgb() * * @param {string} value - value * @returns {Array.<number>} - [r, g, b, a] r|g|b: 0..255 a: 0..1 */ export const parseRgb = async value => { if (isString(value)) { value = value.trim(); } else { throw new TypeError(`Expected String but got ${getType(value)}.`); } const reg = new RegExp(`^rgba?\\(\\s*((?:${REG_RGB}|${REG_RGB_LV3}))\\s*\\)$`); if (!reg.test(value)) { throw new Error(`Invalid property value: ${value}`); } const [, val] = value.match(reg); let [r, g, b, a] = val.replace(/[,/]/g, ' ').split(/\s+/); if (r === NONE) { r = 0; } else { if (r.startsWith('.')) { r = `0${r}`; } if (r.endsWith('%')) { r = parseFloat(r) * MAX_RGB / MAX_PCT; } else { r = parseFloat(r); } } if (g === NONE) { g = 0; } else { if (g.startsWith('.')) { g = `0${g}`; } if (g.endsWith('%')) { g = parseFloat(g) * MAX_RGB / MAX_PCT; } else { g = parseFloat(g); } } if (b === NONE) { b = 0; } else { if (b.startsWith('.')) { b = `0${b}`; } if (b.endsWith('%')) { b = parseFloat(b) * MAX_RGB / MAX_PCT; } else { b = parseFloat(b); } } if (isString(a)) { if (a === NONE) { a = 0; } else { if (a.startsWith('.')) { a = `0${a}`; } if (a.endsWith('%')) { a = parseFloat(a) / MAX_PCT; } else { a = parseFloat(a); } if (a < 0) { a = 0; } else if (a > 1) { a = 1; } } } else { a = 1; } return [ Math.min(Math.max(r, 0), MAX_RGB), Math.min(Math.max(g, 0), MAX_RGB), Math.min(Math.max(b, 0), MAX_RGB), a ]; }; /** * parse hsl() * * @param {string} value - value * @returns {Array.<number>} - [r, g, b, a] r|g|b: 0..255 a: 0..1 */ export const parseHsl = async value => { if (isString(value)) { value = value.trim(); } else { throw new TypeError(`Expected String but got ${getType(value)}.`); } const reg = new RegExp(`^hsla?\\(\\s*((?:${REG_HSL_HWB}|${REG_HSL_LV3}))\\s*\\)$`); if (!reg.test(value)) { throw new Error(`Invalid property value: ${value}`); } const [, val] = value.match(reg); let [h, s, l, a] = val.replace(/[,/]/g, ' ').split(/\s+/); if (h === NONE) { h = 0; } else { h = await angleToDeg(h); } if (s === NONE) { s = 0; } else { if (s.startsWith('.')) { s = `0${s}`; } s = Math.min(Math.max(parseFloat(s), 0), MAX_PCT); } if (l === NONE) { l = 0; } else { if (l.startsWith('.')) { l = `0${l}`; } l = Math.min(Math.max(parseFloat(l), 0), MAX_PCT); } if (isString(a)) { if (a === NONE) { a = 0; } else { if (a.startsWith('.')) { a = `0${a}`; } if (a.endsWith('%')) { a = parseFloat(a) / MAX_PCT; } else { a = parseFloat(a); } if (a < 0) { a = 0; } else if (a > 1) { a = 1; } } } else { a = 1; } let max, min; if (l < MAX_PCT * HALF) { max = (l + l * (s / MAX_PCT)) * MAX_RGB / MAX_PCT; min = (l - l * (s / MAX_PCT)) * MAX_RGB / MAX_PCT; } else { max = (l + (MAX_PCT - l) * (s / MAX_PCT)) * MAX_RGB / MAX_PCT; min = (l - (MAX_PCT - l) * (s / MAX_PCT)) * MAX_RGB / MAX_PCT; } const factor = (max - min) / DEG_INTERVAL; let r, g, b; // < 60 if (h >= 0 && h < DEG_INTERVAL) { r = max; g = h * factor + min; b = min; // < 120 } else if (h < DEG_INTERVAL * DOUBLE) { r = (DEG_INTERVAL * DOUBLE - h) * factor + min; g = max; b = min; // < 180 } else if (h < DEG * HALF) { r = min; g = max; b = (h - DEG_INTERVAL * DOUBLE) * factor + min; // < 240 } else if (h < DEG_INTERVAL * QUAD) { r = min; g = (DEG_INTERVAL * QUAD - h) * factor + min; b = max; // < 300 } else if (h < DEG - DEG_INTERVAL) { r = (h - (DEG_INTERVAL * QUAD)) * factor + min; g = min; b = max; // < 360 } else if (h < DEG) { r = max; g = min; b = (DEG - h) * factor + min; } return [ Math.min(Math.max(r, 0), MAX_RGB), Math.min(Math.max(g, 0), MAX_RGB), Math.min(Math.max(b, 0), MAX_RGB), a ]; }; /** * parse hwb() * * @param {string} value - value * @returns {Array.<number>} - [r, g, b, a] r|g|b: 0..255 a: 0..1 */ export const parseHwb = async value => { if (isString(value)) { value = value.trim(); } else { throw new TypeError(`Expected String but got ${getType(value)}.`); } const reg = new RegExp(`^hwb\\(\\s*(${REG_HSL_HWB})\\s*\\)$`); if (!reg.test(value)) { throw new Error(`Invalid property value: ${value}`); } const [, val] = value.match(reg); let [h, w, b, a] = val.replace('/', ' ').split(/\s+/); if (h === NONE) { h = 0; } else { h = await angleToDeg(h); } if (w === NONE) { w = 0; } else { if (w.startsWith('.')) { w = `0${w}`; } w = Math.min(Math.max(parseFloat(w), 0), MAX_PCT) / MAX_PCT; } if (b === NONE) { b = 0; } else { if (b.startsWith('.')) { b = `0${b}`; } b = Math.min(Math.max(parseFloat(b), 0), MAX_PCT) / MAX_PCT; } if (isString(a)) { if (a === NONE) { a = 0; } else { if (a.startsWith('.')) { a = `0${a}`; } if (a.endsWith('%')) { a = parseFloat(a) / MAX_PCT; } else { a = parseFloat(a); } if (a < 0) { a = 0; } else if (a > 1) { a = 1; } } } else { a = 1; } const arr = []; if (w + b >= 1) { const v = (w / (w + b)) * MAX_RGB; arr.push(v, v, v, a); } else { const [rr, gg, bb] = await parseHsl(`hsl(${h} 100% 50%)`); const factor = (1 - w - b) / MAX_RGB; arr.push( (rr * factor + w) * MAX_RGB, (gg * factor + w) * MAX_RGB, (bb * factor + w) * MAX_RGB, a ); } return arr; }; /** + parse lab() * * @param {string} value - value * @returns {Array.<number>} - [x, y, z, a] x|y|z: around 0..1 a: 0..1 */ export const parseLab = async value => { if (isString(value)) { value = value.trim(); } else { throw new TypeError(`Expected String but got ${getType(value)}.`); } const reg = new RegExp(`^lab\\(\\s*(${REG_LAB})\\s*\\)$`); if (!reg.test(value)) { throw new Error(`Invalid property value: ${value}`); } const COEF_PCT = 1.25; const COND_POW = 8; const [, val] = value.match(reg); let [l, a, b, aa] = val.replace('/', ' ').split(/\s+/); if (l === NONE) { l = 0; } else { if (l.startsWith('.')) { l = `0${l}`; } if (l.endsWith('%')) { l = parseFloat(l); if (l > 100) { l = 100; } } else { l = parseFloat(l); } if (l < 0) { l = 0; } } if (a === NONE) { a = 0; } else { if (a.startsWith('.')) { a = `0${a}`; } if (a.endsWith('%')) { a = parseFloat(a) * COEF_PCT; } else { a = parseFloat(a); } } if (b === NONE) { b = 0; } else { if (b.endsWith('%')) { b = parseFloat(b) * COEF_PCT; } else { b = parseFloat(b); } } if (isString(aa)) { if (aa === NONE) { aa = 0; } else { if (aa.startsWith('.')) { aa = `0${aa}`; } if (aa.endsWith('%')) { aa = parseFloat(aa) / MAX_PCT; } else { aa = parseFloat(aa); } if (aa < 0) { aa = 0; } else if (aa > 1) { aa = 1; } } } else { aa = 1; } const fl = (l + HEX) / LAB_L; const fa = (a / LAB_A + fl); const fb = (fl - b / LAB_B); const powFl = Math.pow(fl, POW_CUBE); const powFa = Math.pow(fa, POW_CUBE); const powFb = Math.pow(fb, POW_CUBE); const xyz = [ powFa > LAB_EPSILON ? powFa : (fa * LAB_L - HEX) / LAB_KAPPA, l > COND_POW ? powFl : l / LAB_KAPPA, powFb > LAB_EPSILON ? powFb : (fb * LAB_L - HEX) / LAB_KAPPA ]; const [x, y, z] = xyz.map((val, i) => val * D50[i]); return [x, y, z, aa]; }; /** + parse lch() * * @param {string} value - value * @returns {Array.<number>} - [x, y, z, a] x|y|z: around 0..1 a: 0..1 */ export const parseLch = async value => { if (isString(value)) { value = value.trim(); } else { throw new TypeError(`Expected String but got ${getType(value)}.`); } const reg = new RegExp(`^lch\\(\\s*(${REG_LCH})\\s*\\)$`); if (!reg.test(value)) { throw new Error(`Invalid property value: ${value}`); } const COEF_PCT = 1.5; const [, val] = value.match(reg); let [l, c, h, aa] = val.replace('/', ' ').split(/\s+/); if (l === NONE) { l = 0; } else { if (l.startsWith('.')) { l = `0${l}`; } l = parseFloat(l); if (l < 0) { l = 0; } } if (c === NONE) { c = 0; } else { if (c.startsWith('.')) { c = `0${c}`; } if (c.endsWith('%')) { c = parseFloat(c) * COEF_PCT; } else { c = parseFloat(c); } } if (h === NONE) { h = 0; } else { h = await angleToDeg(h); } if (isString(aa)) { if (aa === NONE) { aa = 0; } else { if (aa.startsWith('.')) { aa = `0${aa}`; } if (aa.endsWith('%')) { aa = parseFloat(aa) / MAX_PCT; } else { aa = parseFloat(aa); } if (aa < 0) { aa = 0; } else if (aa > 1) { aa = 1; } } } else { aa = 1; } const a = c * Math.cos(h * Math.PI / (DEG * HALF)); const b = c * Math.sin(h * Math.PI / (DEG * HALF)); const [x, y, z] = await parseLab(`lab(${l} ${a} ${b})`); return [x, y, z, aa]; }; /** + parse oklab() * * @param {string} value - value * @returns {Array.<number>} - [x, y, z, a] x|y|z: around 0..1 a: 0..1 */ export const parseOklab = async value => { if (isString(value)) { value = value.trim(); } else { throw new TypeError(`Expected String but got ${getType(value)}.`); } const reg = new RegExp(`^oklab\\(\\s*(${REG_LAB})\\s*\\)$`); if (!reg.test(value)) { throw new Error(`Invalid property value: ${value}`); } const COEF_PCT = 0.4; const [, val] = value.match(reg); let [l, a, b, aa] = val.replace('/', ' ').split(/\s+/); if (l === NONE) { l = 0; } else { if (l.startsWith('.')) { l = `0${l}`; } if (l.endsWith('%')) { l = parseFloat(l) / MAX_PCT; } else { l = parseFloat(l); } if (l < 0) { l = 0; } } if (a === NONE) { a = 0; } else { if (a.startsWith('.')) { a = `0${a}`; } if (a.endsWith('%')) { a = parseFloat(a) * COEF_PCT / MAX_PCT; } else { a = parseFloat(a); } } if (b === NONE) { b = 0; } else { if (b.endsWith('%')) { b = parseFloat(b) * COEF_PCT / MAX_PCT; } else { b = parseFloat(b); } } if (isString(aa)) { if (aa === NONE) { aa = 0; } else { if (aa.startsWith('.')) { aa = `0${aa}`; } if (aa.endsWith('%')) { aa = parseFloat(aa) / MAX_PCT; } else { aa = parseFloat(aa); } if (aa < 0) { aa = 0; } else if (aa > 1) { aa = 1; } } } else { aa = 1; } const lms = await transformMatrix(MATRIX_OKLAB_TO_LMS, [l, a, b]); const xyzLms = lms.map(c => Math.pow(c, POW_CUBE)); const xyz = await transformMatrix(MATRIX_LMS_TO_XYZ, xyzLms); const [x, y, z] = xyz.map((val, i) => val / D65[i]); return [x, y, z, aa]; }; /** + parse oklch() * * @param {string} value - value * @returns {Array.<number>} - [x, y, z, a] x|y|z: around 0..1 a: 0..1 */ export const parseOklch = async value => { if (isString(value)) { value = value.trim(); } else { throw new TypeError(`Expected String but got ${getType(value)}.`); } const reg = new RegExp(`^oklch\\(\\s*(${REG_LAB})\\s*\\)$`); if (!reg.test(value)) { throw new Error(`Invalid property value: ${value}`); } const COEF_PCT = 0.4; const [, val] = value.match(reg); let [l, c, h, aa] = val.replace('/', ' ').split(/\s+/); if (l === NONE) { l = 0; } else { if (l.startsWith('.')) { l = `0${l}`; } if (l.endsWith('%')) { l = parseFloat(l) / MAX_PCT; } else { l = parseFloat(l); } if (l < 0) { l = 0; } } if (c === NONE) { c = 0; } else { if (c.startsWith('.')) { c = `0${c}`; } if (c.endsWith('%')) { c = parseFloat(c) * COEF_PCT / MAX_PCT; } else { c = parseFloat(c); } if (c < 0) { c = 0; } } if (h === NONE) { h = 0; } else { h = await angleToDeg(h); } if (isString(aa)) { if (aa === NONE) { aa = 0; } else { if (aa.startsWith('.')) { aa = `0${aa}`; } if (aa.endsWith('%')) { aa = parseFloat(aa) / MAX_PCT; } else { aa = parseFloat(aa); } if (aa < 0) { aa = 0; } else if (aa > 1) { aa = 1; } } } else { aa = 1; } const a = c * Math.cos(h * Math.PI / (DEG * HALF)); const b = c * Math.sin(h * Math.PI / (DEG * HALF)); const lms = await transformMatrix(MATRIX_OKLAB_TO_LMS, [l, a, b]); const xyzLms = lms.map(c => Math.pow(c, POW_CUBE)); const [x, y, z] = await transformMatrix(MATRIX_LMS_TO_XYZ, xyzLms); return [x, y, z, aa]; }; /** * convert rgb to hex color * * @param {Array.<number>} rgb - [r, g, b, a] r|g|b: 0..255 a: 0..1|undefined * @returns {string} - hex color; */ export const convertRgbToHex = async rgb => { if (!Array.isArray(rgb)) { throw new TypeError(`Expected Array but got ${getType(rgb)}.`); } let [r, g, b, a] = rgb; if (typeof r !== 'number') { throw new TypeError(`Expected Number but got ${getType(r)}.`); } else if (Number.isNaN(r)) { throw new TypeError(`${r} is not a number.`); } else if (r < 0 || r > MAX_RGB) { throw new RangeError(`${r} is not between 0 and ${MAX_RGB}.`); } if (typeof g !== 'number') { throw new TypeError(`Expected Number but got ${getType(g)}.`); } else if (Number.isNaN(g)) { throw new TypeError(`${g} is not a number.`); } else if (g < 0 || g > MAX_RGB) { throw new RangeError(`${g} is not between 0 and ${MAX_RGB}.`); } if (typeof b !== 'number') { throw new TypeError(`Expected Number but got ${getType(b)}.`); } else if (Number.isNaN(b)) { throw new TypeError(`${b} is not a number.`); } else if (b < 0 || b > MAX_RGB) { throw new RangeError(`${b} is not between 0 and ${MAX_RGB}.`); } a ??= 1; if (typeof a !== 'number') { throw new TypeError(`Expected Number but got ${getType(a)}.`); } else if (Number.isNaN(a)) { throw new TypeError(`${a} is not a number.`); } else if (a < 0 || a > 1) { throw new RangeError(`${a} is not between 0 and 1.`); } const [rr, gg, bb, aa] = await Promise.all([ numberToHexString(r), numberToHexString(g), numberToHexString(b), numberToHexString(a * MAX_RGB) ]); let hex; if (aa === 'ff') { hex = `#${rr}${gg}${bb}`; } else { hex = `#${rr}${gg}${bb}${aa}`; } return hex; }; /** * convert linear rgb to hex color * * @param {Array} rgb - [r, g, b, a] r|g|b|a: 0..1 * @returns {string} - hex color */ export const convertLinearRgbToHex = async rgb => { if (!Array.isArray(rgb)) { throw new TypeError(`Expected Array but got ${getType(rgb)}.`); } let [r, g, b, a] = rgb; if (typeof r !== 'number') { throw new TypeError(`Expected Number but got ${getType(r)}.`); } else if (Number.isNaN(r)) { throw new TypeError(`${r} is not a number.`); } else if (r < 0 || r > 1) { throw new RangeError(`${r} is not between 0 and 1.`); } if (typeof g !== 'number') { throw new TypeError(`Expected Number but got ${getType(g)}.`); } else if (Number.isNaN(g)) { throw new TypeError(`${g} is not a number.`); } else if (g < 0 || g > 1) { throw new RangeError(`${g} is not between 0 and 1.`); } if (typeof b !== 'number') { throw new TypeError(`Expected Number but got ${getType(b)}.`); } else if (Number.isNaN(b)) { throw new TypeError(`${b} is not a number.`); } else if (b < 0 || b > 1) { throw new RangeError(`${b} is not between 0 and 1.`); } if (typeof a !== 'number') { throw new TypeError(`Expected Number but got ${getType(a)}.`); } else if (Number.isNaN(a)) { throw new TypeError(`${a} is not a number.`); } else if (a < 0 || a > 1) { throw new RangeError(`${a} is not between 0 and 1.`); } const COND_POW = 809 / 258400; if (r > COND_POW) { r = Math.pow(r, 1 / POW_LINEAR) * (1 + LINEAR_OFFSET) - LINEAR_OFFSET; } else { r *= LINEAR_COEF; } if (g > COND_POW) { g = Math.pow(g, 1 / POW_LINEAR) * (1 + LINEAR_OFFSET) - LINEAR_OFFSET; } else { g *= LINEAR_COEF; } if (b > COND_POW) { b = Math.pow(b, 1 / POW_LINEAR) * (1 + LINEAR_OFFSET) - LINEAR_OFFSET; } else { b *= LINEAR_COEF; } const [rr, gg, bb, aa] = await Promise.all([ numberToHexString(r * MAX_RGB), numberToHexString(g * MAX_RGB), numberToHexString(b * MAX_RGB), numberToHexString(a * MAX_RGB) ]); let hex; if (aa === 'ff') { hex = `#${rr}${gg}${bb}`; } else { hex = `#${rr}${gg}${bb}${aa}`; } return hex; }; /** * convert xyz to hex color * * @param {Array} xyz - [x, y, z, a] x|y|z: around 0..1 a: 0..1 * @returns {string} - hex color */ export const convertXyzToHex = async xyz => { if (!Array.isArray(xyz)) { throw new TypeError(`Expected Array but got ${getType(xyz)}.`); } const [x, y, z, a] = xyz; if (typeof x !== 'number') { throw new TypeError(`Expected Number but got ${getType(x)}.`); } else if (Number.isNaN(x)) { throw new TypeError(`${x} is not a number.`); } if (typeof y !== 'number') { throw new TypeError(`Expected Number but got ${getType(y)}.`); } else if (Number.isNaN(y)) { throw new TypeError(`${y} is not a number.`); } if (typeof z !== 'number') { throw new TypeError(`Expected Number but got ${getType(z)}.`); } else if (Number.isNaN(z)) { throw new TypeError(`${z} is not a number.`); } if (typeof a !== 'number') { throw new TypeError(`Expected Number but got ${getType(a)}.`); } else if (Number.isNaN(a)) { throw new TypeError(`${a} is not a number.`); } else if (a < 0 || a > 1) { throw new RangeError(`${a} is not between 0 and 1.`); } const [r, g, b] = await transformMatrix(MATRIX_XYZ_TO_RGB, [x, y, z]); const hex = await convertLinearRgbToHex([ Math.min(Math.max(r, 0), 1), Math.min(Math.max(g, 0), 1), Math.min(Math.max(b, 0), 1), a ]); return hex; }; /** * convert xyz D50 to hex color * * @param {Array} xyz - [x, y, z, a] x|y|z: around 0..1 a: 0..1 * @returns {string} - hex color */ export const convertXyzD50ToHex = async xyz => { if (!Array.isArray(xyz)) { throw new TypeError(`Expected Array but got ${getType(xyz)}.`); } const [x, y, z, a] = xyz; if (typeof x !== 'number') { throw new TypeError(`Expected Number but got ${getType(x)}.`); } else if (Number.isNaN(x)) { throw new TypeError(`${x} is not a number.`); } if (typeof y !== 'number') { throw new TypeError(`Expected Number but got ${getType(y)}.`); } else if (Number.isNaN(y)) { throw new TypeError(`${y} is not a number.`); } if (typeof z !== 'number') { throw new TypeError(`Expected Number but got ${getType(z)}.`); } else if (Number.isNaN(z)) { throw new TypeError(`${z} is not a number.`); } if (typeof a !== 'number') { throw new TypeError(`Expected Number but got ${getType(a)}.`); } else if (Number.isNaN(a)) { throw new TypeError(`${a} is not a number.`); } else if (a < 0 || a > 1) { throw new RangeError(`${a} is not between 0 and 1.`); } const xyzD65 = await transformMatrix(MATRIX_D50_TO_D65, [x, y, z]); const [r, g, b] = await transformMatrix(MATRIX_XYZ_TO_RGB, xyzD65); const hex = await convertLinearRgbToHex([ Math.min(Math.max(r, 0), 1), Math.min(Math.max(g, 0), 1), Math.min(Math.max(b, 0), 1), a ]); return hex; }; /** * convert color to hex color * NOTE: convertColorToHex('transparent') resolves as null * convertColorToHex('transparent', true) resolves as #00000000 * convertColorToHex('currentColor') warns not supported, resolves as null * * @param {string} value - value * @param {boolean} alpha - add alpha channel value * @returns {?string} - hex color */ export const convertColorToHex = async (value, alpha = false) => { if (isString(value)) { value = value.toLowerCase().trim(); } else { throw new TypeError(`Expected String but got ${getType(value)}.`); } let hex; // named-color if (/^[a-z]+$/.test(value)) { if (Object.prototype.hasOwnProperty.call(colorname, value)) { hex = colorname[value]; } else if (value === 'transparent' && alpha) { hex = '#00000000'; } else if (/currentcolor/.test(value)) { await logWarn('currentcolor keyword is not supported.'); } // hex-color } else if (value.startsWith('#')) { if (/^#[\da-f]{6}$/.test(value)) { hex = value; } else if (/^#[\da-f]{3}$/.test(value)) { const [, r, g, b] = value.match(/^#([\da-f])([\da-f])([\da-f])$/); hex = `#${r}${r}${g}${g}${b}${b}`; } else if (/^#[\da-f]{8}$/.test(value)) { if (alpha) { hex = value; } else { const [, r, g, b] = value.match(/^#([\da-f][\da-f])([\da-f][\da-f])([\da-f][\da-f])/); hex = `#${r}${g}${b}`; } } else if (/^#[\da-f]{4}$/.test(value)) { const [, r, g, b, a] = value.match(/^#([\da-f])([\da-f])([\da-f])([\da-f])$/); hex = alpha ? `#${r}${r}${g}${g}${b}${b}${a}${a}` : `#${r}${r}${g}${g}${b}${b}`; } // lab() } else if (value.startsWith('lab')) { hex = await parseLab(value).then(convertXyzD50ToHex); // lch() } else if (value.startsWith('lch')) { hex = await parseLch(value).then(convertXyzD50ToHex); // oklab() } else if (value.startsWith('oklab')) { hex = await parseOklab(value).then(convertXyzToHex); // oklch() } else if (value.startsWith('oklch')) { hex = await parseOklch(value).then(convertXyzToHex); } else { let r, g, b, a; // rgb() if (value.startsWith('rgb')) { [r, g, b, a] = await parseRgb(value); // hsl() } else if (value.startsWith('hsl')) { [r, g, b, a] = await parseHsl(value); // hwb() } else if (value.startsWith('hwb')) { [r, g, b, a] = await parseHwb(value); } if (typeof r === 'number' && !Number.isNaN(r) && typeof g === 'number' && !Number.isNaN(g) && typeof b === 'number' && !Number.isNaN(b) && typeof a === 'number' && !Number.isNaN(a)) { if (alpha) { hex = await convertRgbToHex([r, g, b, a]); } else { hex = await convertRgbToHex([r, g, b]); } } } return hex || null; }; /** * convert color() to hex color * * @param {string} value - value * @returns {?string} - hex color */ export const convertColorFuncToHex = async value => { if (isString(value)) { value = value.trim(); } else { throw new TypeError(`Expected String but got ${getType(value)}.`); } const reg = new RegExp(`^color\\(\\s*(${REG_COLOR_FUNC})\\s*\\)$`); if (!reg.test(value)) { throw new Error(`Invalid property value: ${value}`); } const [, val] = value.match(reg); const [cs, v1, v2, v3, aa] = val.replace('/', ' ').split(/\s+/); let r, g, b, a; if (v1 === NONE) { r = 0; } else { r = v1.endsWith('%') ? parseFloat(v1) / MAX_PCT : parseFloat(v1); } if (v2 === NONE) { g = 0; } else { g = v2.endsWith('%') ? parseFloat(v2) / MAX_PCT : parseFloat(v2); } if (v3 === NONE) { b = 0; } else { b = v3.endsWith('%') ? parseFloat(v3) / MAX_PCT : parseFloat(v3); } if (isString(aa)) { if (aa === NONE) { a = 0; } else { a = aa; if (a.endsWith('%')) { a = parseFloat(a) / MAX_PCT; } else { a = parseFloat(a); } if (a < 0) { a = 0; } else if (a > 1) { a = 1; } } } else { a = 1; } let hex; // srgb if (cs === 'srgb') { hex = await convertRgbToHex([r * MAX_RGB, g * MAX_RGB, b * MAX_RGB, a]); // srgb-linear } else if (cs === 'srgb-linear') { hex = await convertLinearRgbToHex([r, g, b, a]); // display-p3 } else if (cs === 'display-p3') { const linearRgb = await rgbToLinearRgb([r, g, b]); const [x, y, z] = await transformMatrix(MATRIX_P3_TO_XYZ, linearRgb); hex = await convertXyzToHex([x, y, z, a]); // rec2020 } else if (cs === 'rec2020') { const ALPHA = 1.09929682680944; const BETA = 0.018053968510807; const REC_COEF = 0.45; const rgb = [r, g, b].map(c => { let cl; if (c < BETA * REC_COEF * DEC) { cl = c / (REC_COEF * DEC); } else { cl = Math.pow((c + ALPHA - 1) / ALPHA, 1 / REC_COEF); } return cl; }); const [x, y, z] = await transformMatrix(MATRIX_REC2020_TO_XYZ, rgb); hex = await convertXyzToHex([x, y, z, a]); // a98-rgb } else if (cs === 'a98-rgb') { const POW_A98 = 563 / 256; const rgb = [r, g, b].map(c => { const cl = Math.pow(c, POW_A98); return cl; }); const [x, y, z] = await transformMatrix(MATRIX_A98_TO_XYZ, rgb); hex = await convertXyzToHex([x, y, z, a]); // prophoto-rgb } else if (cs === 'prophoto-rgb') { const POW_PROPHOTO = 1.8; const rgb = [r, g, b].map(c => { let cl; if (c > 1 / (HEX * DOUBLE)) { cl = Math.pow(c, POW_PROPHOTO); } else { cl = c / HEX; } return cl; }); const [x, y, z] = await transformMatrix(MATRIX_PROPHOTO_TO_XYZ_D50, rgb); hex = await convertXyzD50ToHex([x, y, z, a]); // xyz, xyz-d50, xyz-d65 } else if (/^xyz(?:-d(?:50|65))?$/.test(cs)) { const [x, y, z] = [r, g, b]; if (cs === 'xyz-d50') { hex = await convertXyzD50ToHex([x, y, z, a]); } else { hex = await convertXyzToHex([x, y, z, a]); } } return hex; }; /** * convert color-mix() to hex color * * @param {string} value - value * @returns {?string} - hex color */ export const convertColorMixToHex = async value => { if (isString(value)) { value = value.trim(); } else { throw new TypeError(`Expected String but got ${getType(value)}.`); } const regColorMix = new RegExp(`^${REG_COLOR_MIX_CAPT}$`, 'i'); if (!regColorMix.test(value)) { throw new Error(`Invalid property value: ${value}`); } const [, colorSpace, colorPartA, colorPartB] = value.match(regColorMix); const regColorPart = new RegExp(`^(${REG_COLOR_TYPE})(?:\\s+(${REG_PCT}))?$`, 'i'); const regMissingLch = /^(?:h(?:sla?|wb)|(?:ok)?l(?:ab|ch))\(.*none.*\)$/; const regMissingRgb = /^(?:color|rgba?)\(.*none.*\)$/; const [, colorA, pctA] = colorPartA.match(regColorPart); const [, colorB, pctB] = colorPartB.match(regColorPart); let colorAHex, colorBHex; if (colorA.startsWith('color(')) { colorAHex = await convertColorFuncToHex(colorA); } else { colorAHex = await convertColorToHex(colorA, true); } if (colorB.startsWith('color(')) { colorBHex = await convertColorFuncToHex(colorB); } else { colorBHex = await convertColorToHex(colorB, true); } let hex; if (colorAHex && colorBHex) { // normalize percentages and set multipler let pA, pB, m; if (pctA && pctB) { const p1 = parseFloat(pctA) / MAX_PCT; const p2 = parseFloat(pctB) / MAX_PCT; if (p1 < 0 || p1 > 1) { throw new RangeError(`${pctA} is not between 0% and 100%.`); } if (p2 < 0 || p2 > 1) { throw new RangeError(`${pctB} is not between 0% and 100%.`); } const factor = p1 + p2; if (factor === 0) { throw new Error(`Invalid property value: ${value}`); } pA = p1 / factor; pB = p2 / factor; m = factor < 1 ? factor : 1; } else { if (pctA) { pA = parseFloat(pctA) / MAX_PCT; if (pA < 0 || pA > 1) { throw new RangeError(`${pctA} is not between 0% and 100%.`); } pB = 1 - pA; } else if (pctB) { pB = parseFloat(pctB) / MAX_PCT; if (pB < 0 || pB > 1) { throw new RangeError(`${pctB} is not between 0% and 100%.`); } pA = 1 - pB; } else { pA = HALF; pB = HALF; } m = 1; } // in srgb if (colorSpace === 'srgb') { let rgbA = await hexToRgb(colorAHex); let rgbB = await hexToRgb(colorBHex); if (regMissingRgb.test(colorA)) { rgbA = await reInsertMissingComponents(colorA, rgbA); } if (regMissingRgb.test(colorB)) { rgbB = await reInsertMissingComponents(colorB, rgbB); } const [ [rA, gA, bA, aA], [rB, gB, bB, aB] ] = await normalizeColorComponents(rgbA, rgbB); const factorA = aA * pA; const factorB = aB * pB; const a = (factorA + factorB); let r, g, b; if (a === 0) { r = rA * pA + rB * pB; g = gA * pA + gB * pB; b = bA * pA + bB * pB; } else { r = (rA * factorA + rB * factorB) / a; g = (gA * factorA + gB * factorB) / a; b = (bA * factorA + bB * factorB) / a; } hex = await convertRgbToHex([r, g, b, a * m]); // in srgb-linear } else if (colorSpace === 'srgb-linear') { let rgbA = await hexToLinearRgb(colorAHex); let rgbB = await hexToLinearRgb(colorBHex); if (regMissingRgb.test(colorA)) { rgbA = await reInsertMissingComponents(colorA, rgbA); } if (regMissingRgb.test(colorB)) { rgbB = await reInsertMissingComponents(colorB, rgbB); } const [ [rA, gA, bA, aA], [rB, gB, bB, aB] ] = await normalizeColorComponents(rgbA, rgbB); const factorA = aA * pA; const factorB = aB * pB; const a = (factorA + factorB); let r, g, b; if (a === 0) { r = rA * pA + rB * pB; g = gA * pA + gB * pB; b = bA * pA + bB * pB; } else { r = (rA * factorA + rB * factorB) * a; g = (gA * factorA + gB * factorB) * a; b = (bA * factorA + bB * factorB) * a; } hex = await convertLinearRgbToHex([r, g, b, a * m]); // in xyz, xyz-d65 } else if (/^xyz(?:-d65)?$/.test(colorSpace)) { let xyzA = await hexToXyz(colorAHex); let xyzB = await hexToXyz(colorBHex); if (regMissingRgb.test(colorA)) { xyzA = await reInsertMissingComponents(colorA, xyzA); } if (regMissingRgb.test(colorB)) { xyzB = await reInsertMissingComponents(colorB, xyzB); } const [ [xA, yA, zA, aA], [xB, yB, zB, aB] ] = await normalizeColorComponents(xyzA, xyzB); const factorA = aA * pA; const factorB = aB * pB; const a = (factorA + factorB); let x, y, z; if (a === 0) { x = xA * pA + xB * pB; y = yA * pA + yB * pB; z = zA * pA + zB * pB; } else { x = (xA * factorA + xB * factorB) * a; y = (yA * factorA + yB * factorB) * a; z = (zA * factorA + zB * factorB) * a; } hex = await convertXyzToHex([x, y, z, a * m]); // in xyz-d50 } else if (colorSpace === 'xyz-d50') { let xyzA = await hexToXyzD50(colorAHex); let xyzB = await hexToXyzD50(colorBHex); if (regMissingRgb.test(colorA)) { xyzA = await reInsertMissingComponents(colorA, xyzA); } if (regMissingRgb.test(colorB)) { xyzB = await reInsertMissingComponents(colorB, xyzB); } const [ [xA, yA, zA, aA], [xB, yB, zB, aB] ] = await normalizeColorComponents(xyzA, xyzB); const factorA = aA * pA; const factorB = aB * pB; const a = (factorA + factorB); let x, y, z; if (a === 0) { x = xA * pA + xB * pB; y = yA * pA + yB * pB; z = zA * pA + zB * pB; } else { x = (xA * factorA + xB * factorB) * a; y = (yA * factorA + yB * factorB) * a; z = (zA * factorA + zB * factorB) * a; } hex = await convertXyzD50ToHex([x, y, z, a * m]); // in hsl } else if (colorSpace === 'hsl') { let [hA, sA, lA, aA] = await hexToHsl(colorAHex); let [hB, sB, lB, aB] = await hexToHsl(colorBHex); if (regMissingLch.test(colorA)) { [lA, sA, hA, aA] = await reInsertMissingComponents(colorA, [lA, sA, hA, aA]); } if (regMissingLch.test(colorB)) { [lB, sB, hB, aB] = await reInsertMissingComponents(colorB, [lB, sB, hB, aB]); } [ [hA, sA, lA, aA], [hB, sB, lB, aB] ] = await normalizeColorComponents([hA, sA, lA, aA], [hB, sB, lB, aB]); const factorA = aA * pA; const factorB = aB * pB; const a = (factorA + factorB); const h = (hA * pA + hB * pB) % DEG; let s, l; if (a === 0) { s = sA * pA + sB * pB; l = lA * pA + lB * pB; } else { s = (sA * factorA + sB * factorB) / a; l = (lA * factorA + lB * factorB) / a; } hex = await convertColorToHex(`hsl(${h} ${s}% ${l}% / ${a * m})`, true); // in hwb } else if (colorSpace === 'hwb') { let [hA, wA, bA, aA] = await hexToHwb(colorAHex); let [hB, wB, bB, aB] = await hexToHwb(colorBHex); if (regMissingLch.test(colorA)) { [,, hA, aA] = await reInsertMissingComponents(colorA, [null, null, hA, aA]); } if (regMissingLch.test(colorB)) { [,, hB, aB] = await reInsertMissingComponents(colorB, [null, null, hB, aB]); } [ [hA, wA, bA, aA], [hB, wB, bB, aB] ] = await normalizeColorComponents([hA, wA, bA, aA], [hB, wB, bB, aB]); const factorA = aA * pA; const factorB = aB * pB; const a = (factorA + factorB); const h = (hA * pA + hB * pB) % DEG; let w, b; if (a === 0) { w = wA * pA + wB * pB; b = bA * pA + bB * pB; } else { w = (wA * factorA + wB * factorB) / a; b = (bA * factorA + bB * factorB) / a; } hex = await convertColorToHex(`hwb(${h} ${w}% ${b}% / ${a * m})`, true); // in lab } else if (colorSpace === 'lab') { let [lA, aA, bA, aaA] = await hexToLab(colorAHex); let [lB, aB, bB, aaB] = await hexToLab(colorBHex); if (regMissingLch.test(colorA)) { [lA,,, aaA] = await reInsertMissingComponents(colorA, [lA, null, null, aaA]); } if (regMissingLch.test(colorB)) { [lB,,, aaB] = await reInsertMissingComponents(colorB, [lB, null, null, aaB]); } [ [lA, aA, bA, aaA], [lB, aB, bB, aaB] ] = await normalizeColorComponents([lA, aA, bA, aaA], [lB, aB, bB, aaB]); const factorA = aaA * pA; const factorB = aaB * pB; const aa = (factorA + factorB); let l, a, b; if (aa === 0) { l = lA * pA + lB * pB; a = aA * pA + aB * pB; b = bA * pA + bB * pB; } else { l = (lA * factorA + lB * factorB) * aa; a = (aA * factorA + aB * factorB) * aa; b = (bA * factorA + bB * factorB) * aa; } hex = await convertColorToHex(`lab(${l} ${a} ${b} / ${aa * m})`); // in lch } else if (colorSpace === 'lch') { let lchA = await hexToLch(colorAHex); let lchB = await hexToLch(colorBHex); if (regMissingLch.test(colorA)) { lchA = await reInsertMissingComponents(colorA, lchA); } if (regMissingLch.test(colorB)) { lchB = await reInsertMissingComponents(colorB, lchB); } const [ [lA, cA, hA, aaA], [lB, cB, hB, aaB] ] = await normalizeColorComponents(lchA, lchB); const factorA = aaA * pA; const factorB = aaB * pB; const aa = (factorA + factorB); let l, c, h; if (aa === 0) { l = lA * pA + lB * pB; c = cA * pA + cB * pB; h = hA * pA + hB * pB; } else { l = (lA * factorA + lB * factorB) * aa; c = (cA * factorA + cB * factorB) * aa; h = (hA * factorA + hB * factorB) * aa; } hex = await convertColorToHex(`lch(${l} ${c} ${h} / ${aa * m})`); // in oklab } else if (colorSpace === 'oklab') { let [lA, aA, bA, aaA] = await hexToOklab(colorAHex); let [lB, aB, bB, aaB] = await hexToOklab(colorBHex); if (regMissingLch.test(colorA)) { [lA,,, aaA] = await reInsertMissingComponents(colorA, [lA, null, null, aaA]); } if (regMissingLch.test(colorB)) { [lB,,, aaB] = await reInsertMissingComponents(colorB, [lB, null, null, aaB]); } [ [lA, aA, bA, aaA], [lB, aB, bB, aaB] ] = await normalizeColorComponents([lA, aA, bA, aaA], [lB, aB, bB, aaB]); const factorA = aaA * pA; const factorB = aaB * pB; const aa = (factorA + factorB); let l, a, b; if (aa === 0) { l = lA * pA + lB * pB; a = aA * pA + aB * pB; b = bA * pA + bB * pB; } else { l = (lA * factorA + lB * factorB) * aa; a = (aA * factorA + aB * factorB) * aa; b = (bA * factorA + bB * factorB) * aa; } hex = await convertColorToHex(`oklab(${l} ${a} ${b} / ${aa * m})`); // in oklch } else if (colorSpace === 'oklch') { let lchA = await hexToOklch(colorAHex); let lchB = await hexToOklch(colorBHex); if (regMissingLch.test(colorA)) { lchA = await reInsertMissingComponents(colorA, lchA); } if (regMissingLch.test(colorB)) { lchB = await reInsertMissingComponents(colorB, lchB); } const [ [lA, cA, hA, aaA], [lB, cB, hB, aaB] ] = await normalizeColorComponents(lchA, lchB); const factorA = aaA * pA; const factorB = aaB * pB; const aa = (factorA + factorB); let l, c, h; if (aa === 0) { l = lA * pA + lB * pB; c = cA * pA + cB * pB; h = hA * pA + hB * pB; } else { l = (lA * factorA + lB * factorB) * aa; c = (cA * factorA + cB * factorB) * aa; h = (hA * factorA + hB * factorB) * aa; } hex = await convertColorToHex(`oklch(${l} ${c} ${h} / ${aa * m})`); } } return hex || null; }; /** * get color in hex color notation * * @param {string} value - value * @param {object} opt - options * @returns {?string|Array} - string of hex color or array of [prop, hex] pair */ export const getColorInHex = async (value, opt = {}) => { if (isString(value)) { value = value.trim(); } else { throw new TypeError(`Expected String but got ${getType(value)}.`); } const { alpha, prop } = opt; let hex; if (value.startsWith('color-mix')) { hex = await convertColorMixToHex(value); } else if (value.startsWith('color(')) { hex = await convertColorFuncToHex(value); } else { hex = await convertColorToHex(value, !!alpha); } return prop ? [prop, hex] : (hex || null); }; /** * composite two layered colors * * @param {string} overlay - overlay color * @param {string} base - base color * @returns {?string} - hex color */ export const compositeLayeredColors = async (overlay, base) => { const overlayHex = await getColorInHex(overlay, { alpha: true }); const baseHex = await await getColorInHex(base, { alpha: true }); let hex; if (overlayHex && baseHex) { const [rO, gO, bO, aO] = await hexToRgb(overlayHex); const [rB, gB, bB, aB] = await hexToRgb(baseHex); const alpha = 1 - (1 - aO) * (1 - aB); if (aO === 1) { hex = overlayHex; } else if (aO === 0) { hex = baseHex; } else if (alpha) { const alphaO = aO / alpha; const alphaB = aB * (1 - aO) / alpha; const [r, g, b, a] = await Promise.all([ numberToHexString(rO * alphaO + rB * alphaB), numberToHexString(gO * alphaO + gB * alphaB), numberToHexString(bO * alphaO + bB * alphaB), numberToHexString(alpha * MAX_RGB) ]); if (a === 'ff') { hex = `#${r}${g}${b}`; } else { hex = `#${r}${g}${b}${a}`; } } } return hex || null; };
src/mjs/color.js
/** * color.js * * Ref: CSS Color Module Level 4 * §17. Sample code for Color Conversions * https://w3c.github.io/csswg-drafts/css-color-4/#color-conversion-code * * NOTE: 'currentColor' keyword is not supported * TODO: 'none' keyword is not yet fully supported */ /* shared */ import { getType, isString, logWarn } from './common.js'; /* constants */ const HALF = 0.5; const DOUBLE = 2; const TRIPLE = 3; const QUAD = 4; const DEC = 10; const HEX = 16; const DEG = 360; const DEG_INTERVAL = 60; const MAX_PCT = 100; const MAX_RGB = 255; const POW_SQUARE = 2; const POW_CUBE = 3; const POW_LINEAR = 2.4; const LINEAR_COEF = 12.92; const LINEAR_OFFSET = 0.055; const LAB_L = 116; const LAB_A = 500; const LAB_B = 200; const LAB_EPSILON = 216 / 24389; const LAB_KAPPA = 24389 / 27; /* white points */ const D50 = [0.3457 / 0.3585, 1, (1 - 0.3457 - 0.3585) / 0.3585]; const D65 = [0.3127 / 0.3290, 1, (1 - 0.3127 - 0.3290) / 0.3290]; const MATRIX_D50_TO_D65 = [ [0.9554734527042182, -0.023098536874261423, 0.0632593086610217], [-0.028369706963208136, 1.0099954580058226, 0.021041398966943008], [0.012314001688319899, -0.020507696433477912, 1.3303659366080753] ]; const MATRIX_D65_TO_D50 = [ [1.0479298208405488, 0.022946793341019088, -0.05019222954313557], [0.029627815688159344, 0.990434484573249, -0.01707382502938514], [-0.009243058152591178, 0.015055144896577895, 0.7518742899580008] ]; /* color spaces */ const MATRIX_RGB_TO_XYZ = [ [506752 / 1228815, 87881 / 245763, 12673 / 70218], [87098 / 409605, 175762 / 245763, 12673 / 175545], [7918 / 409605, 87881 / 737289, 1001167 / 1053270] ]; const MATRIX_XYZ_TO_RGB = [ [12831 / 3959, -329 / 214, -1974 / 3959], [-851781 / 878810, 1648619 / 878810, 36519 / 878810], [705 / 12673, -2585 / 12673, 705 / 667] ]; const MATRIX_XYZ_TO_LMS = [ [0.8190224432164319, 0.3619062562801221, -0.12887378261216414], [0.0329836671980271, 0.9292868468965546, 0.03614466816999844], [0.048177199566046255, 0.26423952494422764, 0.6335478258136937] ]; const MATRIX_LMS_TO_XYZ = [ [1.2268798733741557, -0.5578149965554813, 0.28139105017721583], [-0.04057576262431372, 1.1122868293970594, -0.07171106666151701], [-0.07637294974672142, -0.4214933239627914, 1.5869240244272418] ]; const MATRIX_OKLAB_TO_LMS = [ [0.9999999984505196, 0.39633779217376774, 0.2158037580607588], [1.0000000088817607, -0.10556134232365633, -0.0638541747717059], [1.0000000546724108, -0.08948418209496574, -1.2914855378640917] ]; const MATRIX_LMS_TO_OKLAB = [ [0.2104542553, 0.7936177850, -0.0040720468], [1.9779984951, -2.4285922050, 0.4505937099], [0.0259040371, 0.7827717662, -0.8086757660] ]; const MATRIX_P3_TO_XYZ = [ [608311 / 1250200, 189793 / 714400, 198249 / 1000160], [35783 / 156275, 247089 / 357200, 198249 / 2500400], [0, 32229 / 714400, 5220557 / 5000800] ]; const MATRIX_REC2020_TO_XYZ = [ [63426534 / 99577255, 20160776 / 139408157, 47086771 / 278816314], [26158966 / 99577255, 472592308 / 697040785, 8267143 / 139408157], [0, 19567812 / 697040785, 295819943 / 278816314] ]; const MATRIX_A98_TO_XYZ = [ [573536 / 994567, 263643 / 1420810, 187206 / 994567], [591459 / 1989134, 6239551 / 9945670, 374412 / 4972835], [53769 / 1989134, 351524 / 4972835, 4929758 / 4972835] ]; const MATRIX_PROPHOTO_TO_XYZ_D50 = [ [0.7977604896723027, 0.13518583717574031, 0.0313493495815248], [0.2880711282292934, 0.7118432178101014, 0.00008565396060525902], [0, 0, 0.8251046025104601] ]; /* regexp */ const NONE = 'none'; const REG_ANGLE = 'deg|g?rad|turn'; const REG_COLOR_SPACE_COLOR_MIX = '(?:ok)?l(?:ab|ch)|h(?:sl|wb)|srgb(?:-linear)?|xyz(?:-d(?:50|65))?'; const REG_COLOR_SPACE_RGB = '(?:a98|prophoto)-rgb|display-p3|rec2020|srgb(?:-linear)?'; const REG_COLOR_SPACE_XYZ = 'xyz(?:-d(?:50|65))?'; const REG_NUM = '-?(?:(?:0|[1-9]\\d*)(?:\\.\\d*)?|\\.\\d+)(?:[Ee]-?(?:(?:0|[1-9]\\d*)))?'; const REG_PCT = `${REG_NUM}%`; const REG_HSL_HWB = `(?:${REG_NUM}(?:${REG_ANGLE})?|${NONE})(?:\\s+(?:${REG_PCT}|${NONE})){2}(?:\\s*\\/\\s*(?:${REG_NUM}|${REG_PCT}|${NONE}))?`; const REG_HSL_LV3 = `${REG_NUM}(?:${REG_ANGLE})?(?:\\s*,\\s*${REG_PCT}){2}(?:\\s*,\\s*(?:${REG_NUM}|${REG_PCT}))?`; const REG_RGB = `(?:(?:${REG_NUM}|${NONE})(?:\\s+(?:${REG_NUM}|${NONE})){2}|(?:${REG_PCT}|${NONE})(?:\\s+(?:${REG_PCT}|${NONE})){2})(?:\\s*\\/\\s*(?:${REG_NUM}|${REG_PCT}|${NONE}))?`; const REG_RGB_LV3 = `(?:${REG_NUM}(?:\\s*,\\s*${REG_NUM}){2}|${REG_PCT}(?:\\s*,\\s*${REG_PCT}){2})(?:\\s*,\\s*(?:${REG_NUM}|${REG_PCT}))?`; const REG_LAB = `(?:${REG_NUM}|${REG_PCT}|${NONE})(?:\\s+(?:${REG_NUM}|${REG_PCT}|${NONE})){2}(?:\\s*\\/\\s*(?:${REG_NUM}|${REG_PCT}|${NONE}))?`; const REG_LCH = `(?:(?:${REG_NUM}|${REG_PCT}|${NONE})\\s+){2}(?:${REG_NUM}(?:${REG_ANGLE})?|${NONE})(?:\\s*\\/\\s*(?:${REG_NUM}|${REG_PCT}|${NONE}))?`; const REG_COLOR_FUNC = `(?:${REG_COLOR_SPACE_RGB}|${REG_COLOR_SPACE_XYZ})(?:\\s+(?:${REG_NUM}|${REG_PCT}|${NONE})){3}(?:\\s*\\/\\s*(?:${REG_NUM}|${REG_PCT}|${NONE}))?`; const REG_COLOR_TYPE = `[a-z]+|#(?:[\\da-f]{3}|[\\da-f]{4}|[\\da-f]{6}|[\\da-f]{8})|hsla?\\(\\s*(?:${REG_HSL_HWB}|${REG_HSL_LV3})\\s*\\)|hwb\\(\\s*${REG_HSL_HWB}\\s*\\)|rgba?\\(\\s*(?:${REG_RGB}|${REG_RGB_LV3})\\s*\\)|(?:ok)?lab\\(\\s*${REG_LAB}\\s*\\)|(?:ok)?lch\\(\\s*${REG_LCH}\\s*\\)|color\\(\\s*${REG_COLOR_FUNC}\\s*\\)`; const REG_COLOR_MIX_PART = `(?:${REG_COLOR_TYPE})(?:\\s+${REG_PCT})?`; const REG_COLOR_MIX_CAPT = `color-mix\\(\\s*in\\s+(${REG_COLOR_SPACE_COLOR_MIX})\\s*,\\s*(${REG_COLOR_MIX_PART})\\s*,\\s*(${REG_COLOR_MIX_PART})\\s*\\)`; /* named colors */ export const colorname = { aliceblue: '#f0f8ff', antiquewhite: '#faebd7', aqua: '#00ffff', aquamarine: '#7fffd4', azure: '#f0ffff', beige: '#f5f5dc', bisque: '#ffe4c4', black: '#000000', blanchedalmond: '#ffebcd', blue: '#0000ff', blueviolet: '#8a2be2', brown: '#a52a2a', burlywood: '#deb887', cadetblue: '#5f9ea0', chartreuse: '#7fff00', chocolate: '#d2691e', coral: '#ff7f50', cornflowerblue: '#6495ed', cornsilk: '#fff8dc', crimson: '#dc143c', cyan: '#00ffff', darkblue: '#00008b', darkcyan: '#008b8b', darkgoldenrod: '#b8860b', darkgray: '#a9a9a9', darkgreen: '#006400', darkgrey: '#a9a9a9', darkkhaki: '#bdb76b', darkmagenta: '#8b008b', darkolivegreen: '#556b2f', darkorange: '#ff8c00', darkorchid: '#9932cc', darkred: '#8b0000', darksalmon: '#e9967a', darkseagreen: '#8fbc8f', darkslateblue: '#483d8b', darkslategray: '#2f4f4f', darkslategrey: '#2f4f4f', darkturquoise: '#00ced1', darkviolet: '#9400d3', deeppink: '#ff1493', deepskyblue: '#00bfff', dimgray: '#696969', dimgrey: '#696969', dodgerblue: '#1e90ff', firebrick: '#b22222', floralwhite: '#fffaf0', forestgreen: '#228b22', fuchsia: '#ff00ff', gainsboro: '#dcdcdc', ghostwhite: '#f8f8ff', gold: '#ffd700', goldenrod: '#daa520', gray: '#808080', green: '#008000', greenyellow: '#adff2f', grey: '#808080', honeydew: '#f0fff0', hotpink: '#ff69b4', indianred: '#cd5c5c', indigo: '#4b0082', ivory: '#fffff0', khaki: '#f0e68c', lavender: '#e6e6fa', lavenderblush: '#fff0f5', lawngreen: '#7cfc00', lemonchiffon: '#fffacd', lightblue: '#add8e6', lightcoral: '#f08080', lightcyan: '#e0ffff', lightgoldenrodyellow: '#fafad2', lightgray: '#d3d3d3', lightgreen: '#90ee90', lightgrey: '#d3d3d3', lightpink: '#ffb6c1', lightsalmon: '#ffa07a', lightseagreen: '#20b2aa', lightskyblue: '#87cefa', lightslategray: '#778899', lightslategrey: '#778899', lightsteelblue: '#b0c4de', lightyellow: '#ffffe0', lime: '#00ff00', limegreen: '#32cd32', linen: '#faf0e6', magenta: '#ff00ff', maroon: '#800000', mediumaquamarine: '#66cdaa', mediumblue: '#0000cd', mediumorchid: '#ba55d3', mediumpurple: '#9370db', mediumseagreen: '#3cb371', mediumslateblue: '#7b68ee', mediumspringgreen: '#00fa9a', mediumturquoise: '#48d1cc', mediumvioletred: '#c71585', midnightblue: '#191970', mintcream: '#f5fffa', mistyrose: '#ffe4e1', moccasin: '#ffe4b5', navajowhite: '#ffdead', navy: '#000080', oldlace: '#fdf5e6', olive: '#808000', olivedrab: '#6b8e23', orange: '#ffa500', orangered: '#ff4500', orchid: '#da70d6', palegoldenrod: '#eee8aa', palegreen: '#98fb98', paleturquoise: '#afeeee', palevioletred: '#db7093', papayawhip: '#ffefd5', peachpuff: '#ffdab9', peru: '#cd853f', pink: '#ffc0cb', plum: '#dda0dd', powderblue: '#b0e0e6', purple: '#800080', rebeccapurple: '#663399', red: '#ff0000', rosybrown: '#bc8f8f', royalblue: '#4169e1', saddlebrown: '#8b4513', salmon: '#fa8072', sandybrown: '#f4a460', seagreen: '#2e8b57', seashell: '#fff5ee', sienna: '#a0522d', silver: '#c0c0c0', skyblue: '#87ceeb', slateblue: '#6a5acd', slategray: '#708090', slategrey: '#708090', snow: '#fffafa', springgreen: '#00ff7f', steelblue: '#4682b4', tan: '#d2b48c', teal: '#008080', thistle: '#d8bfd8', tomato: '#ff6347', turquoise: '#40e0d0', violet: '#ee82ee', wheat: '#f5deb3', white: '#ffffff', whitesmoke: '#f5f5f5', yellow: '#ffff00', yellowgreen: '#9acd32' }; /** * transform matrix * * @param {Array.<Array.<number>>} mtx - 3 * 3 matrix * @param {Array.<number>} vct - vector * @returns {Array.<number>} - [p1, p2, p3] */ export const transformMatrix = async (mtx, vct) => { if (!Array.isArray(mtx)) { throw new TypeError(`Expected Array but got ${getType(mtx)}.`); } else if (mtx.length !== TRIPLE) { throw new Error(`Expected array length of 3 but got ${mtx.length}.`); } else { for (const i of mtx) { if (!Array.isArray(i)) { throw new TypeError(`Expected Array but got ${getType(i)}.`); } else if (i.length !== TRIPLE) { throw new Error(`Expected array length of 3 but got ${i.length}.`); } else { for (const j of i) { if (typeof j !== 'number') { throw new TypeError(`Expected Number but got ${getType(j)}.`); } else if (Number.isNaN(j)) { throw new TypeError(`${j} is not a number.`); } } } } } if (!Array.isArray(vct)) { throw new TypeError(`Expected Array but got ${getType(vct)}.`); } else if (vct.length !== TRIPLE) { throw new Error(`Expected array length of 3 but got ${vct.length}.`); } else { for (const i of vct) { if (typeof i !== 'number') { throw new TypeError(`Expected Number but got ${getType(i)}.`); } else if (Number.isNaN(i)) { throw new TypeError(`${i} is not a number.`); } } } const [ [r1c1, r1c2, r1c3], [r2c1, r2c2, r2c3], [r3c1, r3c2, r3c3] ] = mtx; const [v1, v2, v3] = vct; const p1 = r1c1 * v1 + r1c2 * v2 + r1c3 * v3; const p2 = r2c1 * v1 + r2c2 * v2 + r2c3 * v3; const p3 = r3c1 * v1 + r3c2 * v2 + r3c3 * v3; return [p1, p2, p3]; }; /** * number to hex string * * @param {number} value - value * @returns {string} - hex string */ export const numberToHexString = async value => { if (typeof value !== 'number') { throw new TypeError(`Expected Number but got ${getType(value)}.`); } else if (Number.isNaN(value)) { throw new TypeError(`${value} is not a number.`); } else { value = Math.round(value); if (value < 0 || value > MAX_RGB) { throw new RangeError(`${value} is not between 0 and ${MAX_RGB}.`); } } let hex = value.toString(HEX); if (hex.length === 1) { hex = `0${hex}`; } return hex; }; /** * angle to deg * * @param {string} angle - angle * @returns {number} - deg 0..360 */ export const angleToDeg = async angle => { if (isString(angle)) { angle = angle.trim(); } else { throw new TypeError(`Expected String but got ${getType(angle)}.`); } const reg = new RegExp(`^(${REG_NUM})(${REG_ANGLE})?$`); if (!reg.test(angle)) { throw new Error(`Invalid property value: ${angle}`); } const [, val, unit] = angle.match(reg); const value = val.startsWith('.') ? `0${val}` : val; let deg; switch (unit) { case 'grad': deg = parseFloat(value) * DEG / (MAX_PCT * QUAD); break; case 'rad': deg = parseFloat(value) * DEG / (Math.PI * DOUBLE); break; case 'turn': deg = parseFloat(value) * DEG; break; default: deg = parseFloat(value); } deg %= DEG; if (deg < 0) { deg += DEG; } return deg; }; /** * rgb to linear rgb * * @param {Array.<number>} rgb - [r, g, b] r|g|b: 0..1 * @returns {Array.<number>} - [r, g, b] r|g|b: 0..1 */ export const rgbToLinearRgb = async rgb => { if (!Array.isArray(rgb)) { throw new TypeError(`Expected Array but got ${getType(rgb)}.`); } let [r, g, b] = rgb; if (typeof r !== 'number') { throw new TypeError(`Expected Number but got ${getType(r)}.`); } else if (Number.isNaN(r)) { throw new TypeError(`${r} is not a number.`); } else if (r < 0 || r > 1) { throw new RangeError(`${r} is not between 0 and 1.`); } if (typeof g !== 'number') { throw new TypeError(`Expected Number but got ${getType(g)}.`); } else if (Number.isNaN(g)) { throw new TypeError(`${g} is not a number.`); } else if (g < 0 || g > 1) { throw new RangeError(`${g} is not between 0 and 1.`); } if (typeof b !== 'number') { throw new TypeError(`Expected Number but got ${getType(b)}.`); } else if (Number.isNaN(b)) { throw new TypeError(`${b} is not a number.`); } else if (b < 0 || b > 1) { throw new RangeError(`${b} is not between 0 and 1.`); } const COND_POW = 0.04045; if (r > COND_POW) { r = Math.pow((r + LINEAR_OFFSET) / (1 + LINEAR_OFFSET), POW_LINEAR); } else { r = (r / LINEAR_COEF); } if (g > COND_POW) { g = Math.pow((g + LINEAR_OFFSET) / (1 + LINEAR_OFFSET), POW_LINEAR); } else { g = (g / LINEAR_COEF); } if (b > COND_POW) { b = Math.pow((b + LINEAR_OFFSET) / (1 + LINEAR_OFFSET), POW_LINEAR); } else { b = (b / LINEAR_COEF); } return [r, g, b]; }; /** * hex to rgb * * @param {string} value - value * @returns {Array.<number>} - [r, g, b, a] r|g|b: 0..255 a: 0..1 */ export const hexToRgb = async value => { if (isString(value)) { value = value.toLowerCase().trim(); } else { throw new TypeError(`Expected String but got ${getType(value)}.`); } if (!(/^#[\da-f]{6}$/.test(value) || /^#[\da-f]{3}$/.test(value) || /^#[\da-f]{8}$/.test(value) || /^#[\da-f]{4}$/.test(value))) { throw new Error(`Invalid property value: ${value}`); } const arr = []; if (/^#[\da-f]{6}$/.test(value)) { const [, r, g, b] = value.match(/^#([\da-f]{2})([\da-f]{2})([\da-f]{2})$/); arr.push( parseInt(r, HEX), parseInt(g, HEX), parseInt(b, HEX), 1 ); } else if (/^#[\da-f]{3}$/.test(value)) { const [, r, g, b] = value.match(/^#([\da-f])([\da-f])([\da-f])$/); arr.push( parseInt(`${r}${r}`, HEX), parseInt(`${g}${g}`, HEX), parseInt(`${b}${b}`, HEX), 1 ); } else if (/^#[\da-f]{8}$/.test(value)) { const [, r, g, b, a] = value.match(/^#([\da-f]{2})([\da-f]{2})([\da-f]{2})([\da-f]{2})$/); arr.push( parseInt(r, HEX), parseInt(g, HEX), parseInt(b, HEX), parseInt(a, HEX) / MAX_RGB ); } else if (/^#[\da-f]{4}$/.test(value)) { const [, r, g, b, a] = value.match(/^#([\da-f])([\da-f])([\da-f])([\da-f])$/); arr.push( parseInt(`${r}${r}`, HEX), parseInt(`${g}${g}`, HEX), parseInt(`${b}${b}`, HEX), parseInt(`${a}${a}`, HEX) / MAX_RGB ); } return arr; }; /** * hex to hsl * * @param {string} value - value * @returns {Array.<number>} - [h, s, l, a] h: 0..360 s|l: 0..100 a: 0..1 */ export const hexToHsl = async value => { const [rr, gg, bb, a] = await hexToRgb(value); const r = parseFloat(rr) / MAX_RGB; const g = parseFloat(gg) / MAX_RGB; const b = parseFloat(bb) / MAX_RGB; const max = Math.max(r, g, b); const min = Math.min(r, g, b); const d = max - min; const l = (max + min) * HALF; let h, s; if (l === 0 || l === 1) { h = NONE; s = NONE; } else { s = d / (1 - Math.abs(max + min - 1)) * MAX_PCT; if (s === 0) { h = NONE; } else { switch (max) { case r: h = (g - b) / d; break; case g: h = (b - r) / d + DOUBLE; break; case b: default: h = (r - g) / d + QUAD; break; } h = h * DEG_INTERVAL % DEG; if (h < 0) { h += DEG; } } } return [ h, s, l * MAX_PCT, a ]; }; /** * hex to hwb * * @param {string} value - value * @returns {Array.<number>} - [h, w, b, a] h: 0..360 w|b: 0..100 a: 0..1 */ export const hexToHwb = async value => { const [rr, gg, bb, a] = await hexToRgb(value); const r = parseFloat(rr) / MAX_RGB; const g = parseFloat(gg) / MAX_RGB; const b = parseFloat(bb) / MAX_RGB; const w = Math.min(r, g, b); const bk = 1 - Math.max(r, g, b); let h; if (w + bk === 1) { h = NONE; } else { [h] = await hexToHsl(value); } return [ h, w * MAX_PCT, bk * MAX_PCT, a ]; }; /** * hex to linear rgb * * @param {string} value - value * @returns {Array.<number>} - [r, g, b, a] r|g|b|a: 0..1 */ export const hexToLinearRgb = async value => { const [rr, gg, bb, a] = await hexToRgb(value); const [r, g, b] = await rgbToLinearRgb([ rr / MAX_RGB, gg / MAX_RGB, bb / MAX_RGB ]); return [r, g, b, a]; }; /** * hex to xyz * * @param {string} value - value * @returns {Array.<number>} - [x, y, z, a] x|y|z: around 0..1 a: 0..1 */ export const hexToXyz = async value => { const [r, g, b, a] = await hexToLinearRgb(value); const [x, y, z] = await transformMatrix(MATRIX_RGB_TO_XYZ, [r, g, b]); return [x, y, z, a]; }; /** * hex to xyz D50 * * @param {string} value - value * @returns {Array.<number>} - [x, y, z, a] x|y|z: around 0..1 a: 0..1 */ export const hexToXyzD50 = async value => { const [r, g, b, a] = await hexToLinearRgb(value); const xyz = await transformMatrix(MATRIX_RGB_TO_XYZ, [r, g, b]); const [x, y, z] = await transformMatrix(MATRIX_D65_TO_D50, xyz); return [x, y, z, a]; }; /** * hex to lab * * @param {string} value - value * @returns {Array.<number>} - [l, a, b, aa] * l: 0..100 a|b: around -160..160 aa: 0..1 */ export const hexToLab = async value => { const [x, y, z, aa] = await hexToXyzD50(value); const xyz = [x, y, z].map((val, i) => val / D50[i]); const [f0, f1, f2] = xyz.map(val => val > LAB_EPSILON ? Math.cbrt(val) : (val * LAB_KAPPA + HEX) / LAB_L ); const l = Math.min(Math.max((LAB_L * f1) - HEX, 0), 100); let a, b; if (l === 0 || l === 100) { a = NONE; b = NONE; } else { a = (f0 - f1) * LAB_A; b = (f1 - f2) * LAB_B; } return [l, a, b, aa]; }; /** * hex to lch * * @param {string} value - value * @returns {Array.<number>} - [l, c, h, a] * l: 0..100 c: around 0..230 h: 0..360 a: 0..1 */ export const hexToLch = async value => { const [l, a, b, aa] = await hexToLab(value); let c, h; if (l === 0 || l === 100) { c = NONE; h = NONE; } else { c = Math.max(Math.sqrt(Math.pow(a, POW_SQUARE) + Math.pow(b, POW_SQUARE)), 0); if (parseFloat(c.toFixed(4)) === 0) { h = NONE; } else { h = Math.atan2(b, a) * DEG * HALF / Math.PI; if (h < 0) { h += DEG; } } } return [l, c, h, aa]; }; /** * hex to oklab * * @param {string} value - value * @param {boolean} asis - leave value as is * @returns {Array.<number>} - [l, a, b, aa] l|aa: 0..1 a|b: around -0.5..0.5 */ export const hexToOklab = async (value, asis = false) => { const [xx, yy, zz, aa] = await hexToXyz(value); let x, y, z; if (asis) { x = xx; y = yy; z = zz; } else { [x, y, z] = [xx, yy, zz].map((val, i) => val * D65[i]); } const lms = await transformMatrix(MATRIX_XYZ_TO_LMS, [x, y, z]); const xyzLms = lms.map(c => Math.cbrt(c)); let [l, a, b] = await transformMatrix(MATRIX_LMS_TO_OKLAB, xyzLms); l = Math.min(Math.max(l, 0), 1); const lPct = Math.round(parseFloat(l.toFixed(4)) * MAX_PCT); if (lPct === 0 || lPct === 100) { a = NONE; b = NONE; } return [l, a, b, aa]; }; /** * hex to oklch * * @param {string} value - value * @returns {Array.<number>} - [l, a, b, aa] * l|aa: 0..1 c: around 0..0.5 h: 0..360 */ export const hexToOklch = async value => { const [l, a, b, aa] = await hexToOklab(value, true); let c, h; const lPct = Math.round(parseFloat(l.toFixed(4)) * MAX_PCT); if (lPct === 0 || lPct === 100) { c = NONE; h = NONE; } else { c = Math.max(Math.sqrt(Math.pow(a, POW_SQUARE) + Math.pow(b, POW_SQUARE)), 0); if (parseFloat(c.toFixed(4)) === 0) { h = NONE; } else { h = Math.atan2(b, a) * DEG * HALF / Math.PI; if (h < 0) { h += DEG; } } } return [l, c, h, aa]; }; /** * re-insert missing color components * * @param {string} value - value * @param {Array} color - array of color components [r, g, b, a]|[l, c, h, a] * @returns {Array} - [v1, v2, v3, v4] */ export const reInsertMissingComponents = async (value, color = []) => { if (isString(value)) { value = value.trim(); } else { throw new TypeError(`Expected String but got ${getType(value)}.`); } const [v1, v2, v3, v4] = color; let v1m, v2m, v3m, v4m; if (/none/.test(value)) { const regRgb = new RegExp(`^rgba?\\(\\s*(${REG_RGB})\\s*\\)$`); const regColor = new RegExp(`^color\\(\\s*(${REG_COLOR_FUNC})\\s*\\)$`); const regHsl = new RegExp(`^h(?:sla?|wb)\\(\\s*(${REG_HSL_HWB})\\s*\\)$`); const regLab = new RegExp(`^(?:ok)?lab\\(\\s*(${REG_LAB})\\s*\\)$`); const regLch = new RegExp(`^(?:ok)?lch\\(\\s*(${REG_LCH})\\s*\\)$`); // rgb() if (regRgb.test(value)) { [v1m, v2m, v3m, v4m] = value.match(regRgb)[1].replace('/', ' ').split(/\s+/); // color() } else if (regColor.test(value)) { [, v1m, v2m, v3m, v4m] = value.match(regColor)[1].replace('/', ' ').split(/\s+/); // hsl() } else if (value.startsWith('hsl') && regHsl.test(value)) { [v3m, v2m, v1m, v4m] = value.match(regHsl)[1].replace('/', ' ').split(/\s+/); // hwb() } else if (value.startsWith('hwb') && regHsl.test(value)) { [v3m, , , v4m] = value.match(regHsl)[1].replace('/', ' ').split(/\s+/); // lab(), oklab() } else if (regLab.test(value)) { [v1m, , , v4m] = value.match(regLab)[1].replace('/', ' ').split(/\s+/); // lch(), oklch() } else if (regLch.test(value)) { [v1m, v2m, v3m, v4m] = value.match(regLch)[1].replace('/', ' ').split(/\s+/); } } return [ v1m === NONE ? v1m : v1, v2m === NONE ? v2m : v2, v3m === NONE ? v3m : v3, v4m === NONE ? v4m : v4 ]; }; /** * normalize color components * * @param {Array} colorA - array of color components [v1, v2, v3, v4] * @param {Array} colorB - array of color components [v1, v2, v3, v4] * @returns {Array.<Array>} - [colorA, colorB] */ export const normalizeColorComponents = async (colorA, colorB) => { if (!Array.isArray(colorA)) { throw new TypeError(`Expected Array but got ${getType(colorA)}.`); } else if (colorA.length !== QUAD) { throw new Error(`Expected array length of 4 but got ${colorA.length}.`); } if (!Array.isArray(colorB)) { throw new TypeError(`Expected Array but got ${getType(colorB)}.`); } else if (colorB.length !== QUAD) { throw new Error(`Expected array length of 4 but got ${colorB.length}.`); } let i = 0; while (i < QUAD) { if (colorA[i] === NONE && colorB[i] === NONE) { colorA[i] = 0; colorB[i] = 0; } else if (colorA[i] === NONE) { colorA[i] = colorB[i]; } else if (colorB[i] === NONE) { colorB[i] = colorA[i]; } i++; } return [colorA, colorB]; }; /** * parse rgb() * * @param {string} value - value * @returns {Array.<number>} - [r, g, b, a] r|g|b: 0..255 a: 0..1 */ export const parseRgb = async value => { if (isString(value)) { value = value.trim(); } else { throw new TypeError(`Expected String but got ${getType(value)}.`); } const reg = new RegExp(`^rgba?\\(\\s*((?:${REG_RGB}|${REG_RGB_LV3}))\\s*\\)$`); if (!reg.test(value)) { throw new Error(`Invalid property value: ${value}`); } const [, val] = value.match(reg); let [r, g, b, a] = val.replace(/[,/]/g, ' ').split(/\s+/); if (r === NONE) { r = 0; } else { if (r.startsWith('.')) { r = `0${r}`; } if (r.endsWith('%')) { r = parseFloat(r) * MAX_RGB / MAX_PCT; } else { r = parseFloat(r); } } if (g === NONE) { g = 0; } else { if (g.startsWith('.')) { g = `0${g}`; } if (g.endsWith('%')) { g = parseFloat(g) * MAX_RGB / MAX_PCT; } else { g = parseFloat(g); } } if (b === NONE) { b = 0; } else { if (b.startsWith('.')) { b = `0${b}`; } if (b.endsWith('%')) { b = parseFloat(b) * MAX_RGB / MAX_PCT; } else { b = parseFloat(b); } } if (isString(a)) { if (a === NONE) { a = 0; } else { if (a.startsWith('.')) { a = `0${a}`; } if (a.endsWith('%')) { a = parseFloat(a) / MAX_PCT; } else { a = parseFloat(a); } if (a < 0) { a = 0; } else if (a > 1) { a = 1; } } } else { a = 1; } return [ Math.min(Math.max(r, 0), MAX_RGB), Math.min(Math.max(g, 0), MAX_RGB), Math.min(Math.max(b, 0), MAX_RGB), a ]; }; /** * parse hsl() * * @param {string} value - value * @returns {Array.<number>} - [r, g, b, a] r|g|b: 0..255 a: 0..1 */ export const parseHsl = async value => { if (isString(value)) { value = value.trim(); } else { throw new TypeError(`Expected String but got ${getType(value)}.`); } const reg = new RegExp(`^hsla?\\(\\s*((?:${REG_HSL_HWB}|${REG_HSL_LV3}))\\s*\\)$`); if (!reg.test(value)) { throw new Error(`Invalid property value: ${value}`); } const [, val] = value.match(reg); let [h, s, l, a] = val.replace(/[,/]/g, ' ').split(/\s+/); if (h === NONE) { h = 0; } else { h = await angleToDeg(h); } if (s === NONE) { s = 0; } else { if (s.startsWith('.')) { s = `0${s}`; } s = Math.min(Math.max(parseFloat(s), 0), MAX_PCT); } if (l === NONE) { l = 0; } else { if (l.startsWith('.')) { l = `0${l}`; } l = Math.min(Math.max(parseFloat(l), 0), MAX_PCT); } if (isString(a)) { if (a === NONE) { a = 0; } else { if (a.startsWith('.')) { a = `0${a}`; } if (a.endsWith('%')) { a = parseFloat(a) / MAX_PCT; } else { a = parseFloat(a); } if (a < 0) { a = 0; } else if (a > 1) { a = 1; } } } else { a = 1; } let max, min; if (l < MAX_PCT * HALF) { max = (l + l * (s / MAX_PCT)) * MAX_RGB / MAX_PCT; min = (l - l * (s / MAX_PCT)) * MAX_RGB / MAX_PCT; } else { max = (l + (MAX_PCT - l) * (s / MAX_PCT)) * MAX_RGB / MAX_PCT; min = (l - (MAX_PCT - l) * (s / MAX_PCT)) * MAX_RGB / MAX_PCT; } const factor = (max - min) / DEG_INTERVAL; let r, g, b; // < 60 if (h >= 0 && h < DEG_INTERVAL) { r = max; g = h * factor + min; b = min; // < 120 } else if (h < DEG_INTERVAL * DOUBLE) { r = (DEG_INTERVAL * DOUBLE - h) * factor + min; g = max; b = min; // < 180 } else if (h < DEG * HALF) { r = min; g = max; b = (h - DEG_INTERVAL * DOUBLE) * factor + min; // < 240 } else if (h < DEG_INTERVAL * QUAD) { r = min; g = (DEG_INTERVAL * QUAD - h) * factor + min; b = max; // < 300 } else if (h < DEG - DEG_INTERVAL) { r = (h - (DEG_INTERVAL * QUAD)) * factor + min; g = min; b = max; // < 360 } else if (h < DEG) { r = max; g = min; b = (DEG - h) * factor + min; } return [ Math.min(Math.max(r, 0), MAX_RGB), Math.min(Math.max(g, 0), MAX_RGB), Math.min(Math.max(b, 0), MAX_RGB), a ]; }; /** * parse hwb() * * @param {string} value - value * @returns {Array.<number>} - [r, g, b, a] r|g|b: 0..255 a: 0..1 */ export const parseHwb = async value => { if (isString(value)) { value = value.trim(); } else { throw new TypeError(`Expected String but got ${getType(value)}.`); } const reg = new RegExp(`^hwb\\(\\s*(${REG_HSL_HWB})\\s*\\)$`); if (!reg.test(value)) { throw new Error(`Invalid property value: ${value}`); } const [, val] = value.match(reg); let [h, w, b, a] = val.replace('/', ' ').split(/\s+/); if (h === NONE) { h = 0; } else { h = await angleToDeg(h); } if (w === NONE) { w = 0; } else { if (w.startsWith('.')) { w = `0${w}`; } w = Math.min(Math.max(parseFloat(w), 0), MAX_PCT) / MAX_PCT; } if (b === NONE) { b = 0; } else { if (b.startsWith('.')) { b = `0${b}`; } b = Math.min(Math.max(parseFloat(b), 0), MAX_PCT) / MAX_PCT; } if (isString(a)) { if (a === NONE) { a = 0; } else { if (a.startsWith('.')) { a = `0${a}`; } if (a.endsWith('%')) { a = parseFloat(a) / MAX_PCT; } else { a = parseFloat(a); } if (a < 0) { a = 0; } else if (a > 1) { a = 1; } } } else { a = 1; } const arr = []; if (w + b >= 1) { const v = (w / (w + b)) * MAX_RGB; arr.push(v, v, v, a); } else { const [rr, gg, bb] = await parseHsl(`hsl(${h} 100% 50%)`); const factor = (1 - w - b) / MAX_RGB; arr.push( (rr * factor + w) * MAX_RGB, (gg * factor + w) * MAX_RGB, (bb * factor + w) * MAX_RGB, a ); } return arr; }; /** + parse lab() * * @param {string} value - value * @returns {Array.<number>} - [x, y, z, a] x|y|z: around 0..1 a: 0..1 */ export const parseLab = async value => { if (isString(value)) { value = value.trim(); } else { throw new TypeError(`Expected String but got ${getType(value)}.`); } const reg = new RegExp(`^lab\\(\\s*(${REG_LAB})\\s*\\)$`); if (!reg.test(value)) { throw new Error(`Invalid property value: ${value}`); } const COEF_PCT = 1.25; const COND_POW = 8; const [, val] = value.match(reg); let [l, a, b, aa] = val.replace('/', ' ').split(/\s+/); if (l === NONE) { l = 0; } else { if (l.startsWith('.')) { l = `0${l}`; } if (l.endsWith('%')) { l = parseFloat(l); if (l > 100) { l = 100; } } else { l = parseFloat(l); } if (l < 0) { l = 0; } } if (a === NONE) { a = 0; } else { if (a.startsWith('.')) { a = `0${a}`; } if (a.endsWith('%')) { a = parseFloat(a) * COEF_PCT; } else { a = parseFloat(a); } } if (b === NONE) { b = 0; } else { if (b.endsWith('%')) { b = parseFloat(b) * COEF_PCT; } else { b = parseFloat(b); } } if (isString(aa)) { if (aa === NONE) { aa = 0; } else { if (aa.startsWith('.')) { aa = `0${aa}`; } if (aa.endsWith('%')) { aa = parseFloat(aa) / MAX_PCT; } else { aa = parseFloat(aa); } if (aa < 0) { aa = 0; } else if (aa > 1) { aa = 1; } } } else { aa = 1; } const fl = (l + HEX) / LAB_L; const fa = (a / LAB_A + fl); const fb = (fl - b / LAB_B); const powFl = Math.pow(fl, POW_CUBE); const powFa = Math.pow(fa, POW_CUBE); const powFb = Math.pow(fb, POW_CUBE); const xyz = [ powFa > LAB_EPSILON ? powFa : (fa * LAB_L - HEX) / LAB_KAPPA, l > COND_POW ? powFl : l / LAB_KAPPA, powFb > LAB_EPSILON ? powFb : (fb * LAB_L - HEX) / LAB_KAPPA ]; const [x, y, z] = xyz.map((val, i) => val * D50[i]); return [x, y, z, aa]; }; /** + parse lch() * * @param {string} value - value * @returns {Array.<number>} - [x, y, z, a] x|y|z: around 0..1 a: 0..1 */ export const parseLch = async value => { if (isString(value)) { value = value.trim(); } else { throw new TypeError(`Expected String but got ${getType(value)}.`); } const reg = new RegExp(`^lch\\(\\s*(${REG_LCH})\\s*\\)$`); if (!reg.test(value)) { throw new Error(`Invalid property value: ${value}`); } const COEF_PCT = 1.5; const [, val] = value.match(reg); let [l, c, h, aa] = val.replace('/', ' ').split(/\s+/); if (l === NONE) { l = 0; } else { if (l.startsWith('.')) { l = `0${l}`; } l = parseFloat(l); if (l < 0) { l = 0; } } if (c === NONE) { c = 0; } else { if (c.startsWith('.')) { c = `0${c}`; } if (c.endsWith('%')) { c = parseFloat(c) * COEF_PCT; } else { c = parseFloat(c); } } if (h === NONE) { h = 0; } else { h = await angleToDeg(h); } if (isString(aa)) { if (aa === NONE) { aa = 0; } else { if (aa.startsWith('.')) { aa = `0${aa}`; } if (aa.endsWith('%')) { aa = parseFloat(aa) / MAX_PCT; } else { aa = parseFloat(aa); } if (aa < 0) { aa = 0; } else if (aa > 1) { aa = 1; } } } else { aa = 1; } const a = c * Math.cos(h * Math.PI / (DEG * HALF)); const b = c * Math.sin(h * Math.PI / (DEG * HALF)); const [x, y, z] = await parseLab(`lab(${l} ${a} ${b})`); return [x, y, z, aa]; }; /** + parse oklab() * * @param {string} value - value * @returns {Array.<number>} - [x, y, z, a] x|y|z: around 0..1 a: 0..1 */ export const parseOklab = async value => { if (isString(value)) { value = value.trim(); } else { throw new TypeError(`Expected String but got ${getType(value)}.`); } const reg = new RegExp(`^oklab\\(\\s*(${REG_LAB})\\s*\\)$`); if (!reg.test(value)) { throw new Error(`Invalid property value: ${value}`); } const COEF_PCT = 0.4; const [, val] = value.match(reg); let [l, a, b, aa] = val.replace('/', ' ').split(/\s+/); if (l === NONE) { l = 0; } else { if (l.startsWith('.')) { l = `0${l}`; } if (l.endsWith('%')) { l = parseFloat(l) / MAX_PCT; } else { l = parseFloat(l); } if (l < 0) { l = 0; } } if (a === NONE) { a = 0; } else { if (a.startsWith('.')) { a = `0${a}`; } if (a.endsWith('%')) { a = parseFloat(a) * COEF_PCT / MAX_PCT; } else { a = parseFloat(a); } } if (b === NONE) { b = 0; } else { if (b.endsWith('%')) { b = parseFloat(b) * COEF_PCT / MAX_PCT; } else { b = parseFloat(b); } } if (isString(aa)) { if (aa === NONE) { aa = 0; } else { if (aa.startsWith('.')) { aa = `0${aa}`; } if (aa.endsWith('%')) { aa = parseFloat(aa) / MAX_PCT; } else { aa = parseFloat(aa); } if (aa < 0) { aa = 0; } else if (aa > 1) { aa = 1; } } } else { aa = 1; } const lms = await transformMatrix(MATRIX_OKLAB_TO_LMS, [l, a, b]); const xyzLms = lms.map(c => Math.pow(c, POW_CUBE)); const xyz = await transformMatrix(MATRIX_LMS_TO_XYZ, xyzLms); const [x, y, z] = xyz.map((val, i) => val / D65[i]); return [x, y, z, aa]; }; /** + parse oklch() * * @param {string} value - value * @returns {Array.<number>} - [x, y, z, a] x|y|z: around 0..1 a: 0..1 */ export const parseOklch = async value => { if (isString(value)) { value = value.trim(); } else { throw new TypeError(`Expected String but got ${getType(value)}.`); } const reg = new RegExp(`^oklch\\(\\s*(${REG_LAB})\\s*\\)$`); if (!reg.test(value)) { throw new Error(`Invalid property value: ${value}`); } const COEF_PCT = 0.4; const [, val] = value.match(reg); let [l, c, h, aa] = val.replace('/', ' ').split(/\s+/); if (l === NONE) { l = 0; } else { if (l.startsWith('.')) { l = `0${l}`; } if (l.endsWith('%')) { l = parseFloat(l) / MAX_PCT; } else { l = parseFloat(l); } if (l < 0) { l = 0; } } if (c === NONE) { c = 0; } else { if (c.startsWith('.')) { c = `0${c}`; } if (c.endsWith('%')) { c = parseFloat(c) * COEF_PCT / MAX_PCT; } else { c = parseFloat(c); } if (c < 0) { c = 0; } } if (h === NONE) { h = 0; } else { h = await angleToDeg(h); } if (isString(aa)) { if (aa === NONE) { aa = 0; } else { if (aa.startsWith('.')) { aa = `0${aa}`; } if (aa.endsWith('%')) { aa = parseFloat(aa) / MAX_PCT; } else { aa = parseFloat(aa); } if (aa < 0) { aa = 0; } else if (aa > 1) { aa = 1; } } } else { aa = 1; } const a = c * Math.cos(h * Math.PI / (DEG * HALF)); const b = c * Math.sin(h * Math.PI / (DEG * HALF)); const lms = await transformMatrix(MATRIX_OKLAB_TO_LMS, [l, a, b]); const xyzLms = lms.map(c => Math.pow(c, POW_CUBE)); const [x, y, z] = await transformMatrix(MATRIX_LMS_TO_XYZ, xyzLms); return [x, y, z, aa]; }; /** * convert rgb to hex color * * @param {Array.<number>} rgb - [r, g, b, a] r|g|b: 0..255 a: 0..1|undefined * @returns {string} - hex color; */ export const convertRgbToHex = async rgb => { if (!Array.isArray(rgb)) { throw new TypeError(`Expected Array but got ${getType(rgb)}.`); } let [r, g, b, a] = rgb; if (typeof r !== 'number') { throw new TypeError(`Expected Number but got ${getType(r)}.`); } else if (Number.isNaN(r)) { throw new TypeError(`${r} is not a number.`); } else if (r < 0 || r > MAX_RGB) { throw new RangeError(`${r} is not between 0 and ${MAX_RGB}.`); } if (typeof g !== 'number') { throw new TypeError(`Expected Number but got ${getType(g)}.`); } else if (Number.isNaN(g)) { throw new TypeError(`${g} is not a number.`); } else if (g < 0 || g > MAX_RGB) { throw new RangeError(`${g} is not between 0 and ${MAX_RGB}.`); } if (typeof b !== 'number') { throw new TypeError(`Expected Number but got ${getType(b)}.`); } else if (Number.isNaN(b)) { throw new TypeError(`${b} is not a number.`); } else if (b < 0 || b > MAX_RGB) { throw new RangeError(`${b} is not between 0 and ${MAX_RGB}.`); } a ??= 1; if (typeof a !== 'number') { throw new TypeError(`Expected Number but got ${getType(a)}.`); } else if (Number.isNaN(a)) { throw new TypeError(`${a} is not a number.`); } else if (a < 0 || a > 1) { throw new RangeError(`${a} is not between 0 and 1.`); } const [rr, gg, bb, aa] = await Promise.all([ numberToHexString(r), numberToHexString(g), numberToHexString(b), numberToHexString(a * MAX_RGB) ]); let hex; if (aa === 'ff') { hex = `#${rr}${gg}${bb}`; } else { hex = `#${rr}${gg}${bb}${aa}`; } return hex; }; /** * convert linear rgb to hex color * * @param {Array} rgb - [r, g, b, a] r|g|b|a: 0..1 * @returns {string} - hex color */ export const convertLinearRgbToHex = async rgb => { if (!Array.isArray(rgb)) { throw new TypeError(`Expected Array but got ${getType(rgb)}.`); } let [r, g, b, a] = rgb; if (typeof r !== 'number') { throw new TypeError(`Expected Number but got ${getType(r)}.`); } else if (Number.isNaN(r)) { throw new TypeError(`${r} is not a number.`); } else if (r < 0 || r > 1) { throw new RangeError(`${r} is not between 0 and 1.`); } if (typeof g !== 'number') { throw new TypeError(`Expected Number but got ${getType(g)}.`); } else if (Number.isNaN(g)) { throw new TypeError(`${g} is not a number.`); } else if (g < 0 || g > 1) { throw new RangeError(`${g} is not between 0 and 1.`); } if (typeof b !== 'number') { throw new TypeError(`Expected Number but got ${getType(b)}.`); } else if (Number.isNaN(b)) { throw new TypeError(`${b} is not a number.`); } else if (b < 0 || b > 1) { throw new RangeError(`${b} is not between 0 and 1.`); } if (typeof a !== 'number') { throw new TypeError(`Expected Number but got ${getType(a)}.`); } else if (Number.isNaN(a)) { throw new TypeError(`${a} is not a number.`); } else if (a < 0 || a > 1) { throw new RangeError(`${a} is not between 0 and 1.`); } const COND_POW = 809 / 258400; if (r > COND_POW) { r = Math.pow(r, 1 / POW_LINEAR) * (1 + LINEAR_OFFSET) - LINEAR_OFFSET; } else { r *= LINEAR_COEF; } if (g > COND_POW) { g = Math.pow(g, 1 / POW_LINEAR) * (1 + LINEAR_OFFSET) - LINEAR_OFFSET; } else { g *= LINEAR_COEF; } if (b > COND_POW) { b = Math.pow(b, 1 / POW_LINEAR) * (1 + LINEAR_OFFSET) - LINEAR_OFFSET; } else { b *= LINEAR_COEF; } const [rr, gg, bb, aa] = await Promise.all([ numberToHexString(r * MAX_RGB), numberToHexString(g * MAX_RGB), numberToHexString(b * MAX_RGB), numberToHexString(a * MAX_RGB) ]); let hex; if (aa === 'ff') { hex = `#${rr}${gg}${bb}`; } else { hex = `#${rr}${gg}${bb}${aa}`; } return hex; }; /** * convert xyz to hex color * * @param {Array} xyz - [x, y, z, a] x|y|z: around 0..1 a: 0..1 * @returns {string} - hex color */ export const convertXyzToHex = async xyz => { if (!Array.isArray(xyz)) { throw new TypeError(`Expected Array but got ${getType(xyz)}.`); } const [x, y, z, a] = xyz; if (typeof x !== 'number') { throw new TypeError(`Expected Number but got ${getType(x)}.`); } else if (Number.isNaN(x)) { throw new TypeError(`${x} is not a number.`); } if (typeof y !== 'number') { throw new TypeError(`Expected Number but got ${getType(y)}.`); } else if (Number.isNaN(y)) { throw new TypeError(`${y} is not a number.`); } if (typeof z !== 'number') { throw new TypeError(`Expected Number but got ${getType(z)}.`); } else if (Number.isNaN(z)) { throw new TypeError(`${z} is not a number.`); } if (typeof a !== 'number') { throw new TypeError(`Expected Number but got ${getType(a)}.`); } else if (Number.isNaN(a)) { throw new TypeError(`${a} is not a number.`); } else if (a < 0 || a > 1) { throw new RangeError(`${a} is not between 0 and 1.`); } const [r, g, b] = await transformMatrix(MATRIX_XYZ_TO_RGB, [x, y, z]); const hex = await convertLinearRgbToHex([ Math.min(Math.max(r, 0), 1), Math.min(Math.max(g, 0), 1), Math.min(Math.max(b, 0), 1), a ]); return hex; }; /** * convert xyz D50 to hex color * * @param {Array} xyz - [x, y, z, a] x|y|z: around 0..1 a: 0..1 * @returns {string} - hex color */ export const convertXyzD50ToHex = async xyz => { if (!Array.isArray(xyz)) { throw new TypeError(`Expected Array but got ${getType(xyz)}.`); } const [x, y, z, a] = xyz; if (typeof x !== 'number') { throw new TypeError(`Expected Number but got ${getType(x)}.`); } else if (Number.isNaN(x)) { throw new TypeError(`${x} is not a number.`); } if (typeof y !== 'number') { throw new TypeError(`Expected Number but got ${getType(y)}.`); } else if (Number.isNaN(y)) { throw new TypeError(`${y} is not a number.`); } if (typeof z !== 'number') { throw new TypeError(`Expected Number but got ${getType(z)}.`); } else if (Number.isNaN(z)) { throw new TypeError(`${z} is not a number.`); } if (typeof a !== 'number') { throw new TypeError(`Expected Number but got ${getType(a)}.`); } else if (Number.isNaN(a)) { throw new TypeError(`${a} is not a number.`); } else if (a < 0 || a > 1) { throw new RangeError(`${a} is not between 0 and 1.`); } const xyzD65 = await transformMatrix(MATRIX_D50_TO_D65, [x, y, z]); const [r, g, b] = await transformMatrix(MATRIX_XYZ_TO_RGB, xyzD65); const hex = await convertLinearRgbToHex([ Math.min(Math.max(r, 0), 1), Math.min(Math.max(g, 0), 1), Math.min(Math.max(b, 0), 1), a ]); return hex; }; /** * convert color to hex color * NOTE: convertColorToHex('transparent') resolves as null * convertColorToHex('transparent', true) resolves as #00000000 * convertColorToHex('currentColor') warns not supported, resolves as null * * @param {string} value - value * @param {boolean} alpha - add alpha channel value * @returns {?string} - hex color */ export const convertColorToHex = async (value, alpha = false) => { if (isString(value)) { value = value.toLowerCase().trim(); } else { throw new TypeError(`Expected String but got ${getType(value)}.`); } let hex; // named-color if (/^[a-z]+$/.test(value)) { if (Object.prototype.hasOwnProperty.call(colorname, value)) { hex = colorname[value]; } else if (value === 'transparent' && alpha) { hex = '#00000000'; } else if (/currentcolor/.test(value)) { await logWarn('currentcolor keyword is not supported.'); } // hex-color } else if (value.startsWith('#')) { if (/^#[\da-f]{6}$/.test(value)) { hex = value; } else if (/^#[\da-f]{3}$/.test(value)) { const [, r, g, b] = value.match(/^#([\da-f])([\da-f])([\da-f])$/); hex = `#${r}${r}${g}${g}${b}${b}`; } else if (/^#[\da-f]{8}$/.test(value)) { if (alpha) { hex = value; } else { const [, r, g, b] = value.match(/^#([\da-f][\da-f])([\da-f][\da-f])([\da-f][\da-f])/); hex = `#${r}${g}${b}`; } } else if (/^#[\da-f]{4}$/.test(value)) { const [, r, g, b, a] = value.match(/^#([\da-f])([\da-f])([\da-f])([\da-f])$/); hex = alpha ? `#${r}${r}${g}${g}${b}${b}${a}${a}` : `#${r}${r}${g}${g}${b}${b}`; } // lab() } else if (value.startsWith('lab')) { hex = await parseLab(value).then(convertXyzD50ToHex); // lch() } else if (value.startsWith('lch')) { hex = await parseLch(value).then(convertXyzD50ToHex); // oklab() } else if (value.startsWith('oklab')) { hex = await parseOklab(value).then(convertXyzToHex); // oklch() } else if (value.startsWith('oklch')) { hex = await parseOklch(value).then(convertXyzToHex); } else { let r, g, b, a; // rgb() if (value.startsWith('rgb')) { [r, g, b, a] = await parseRgb(value); // hsl() } else if (value.startsWith('hsl')) { [r, g, b, a] = await parseHsl(value); // hwb() } else if (value.startsWith('hwb')) { [r, g, b, a] = await parseHwb(value); } if (typeof r === 'number' && !Number.isNaN(r) && typeof g === 'number' && !Number.isNaN(g) && typeof b === 'number' && !Number.isNaN(b) && typeof a === 'number' && !Number.isNaN(a)) { if (alpha) { hex = await convertRgbToHex([r, g, b, a]); } else { hex = await convertRgbToHex([r, g, b]); } } } return hex || null; }; /** * convert color() to hex color * * @param {string} value - value * @returns {?string} - hex color */ export const convertColorFuncToHex = async value => { if (isString(value)) { value = value.trim(); } else { throw new TypeError(`Expected String but got ${getType(value)}.`); } const reg = new RegExp(`^color\\(\\s*(${REG_COLOR_FUNC})\\s*\\)$`); if (!reg.test(value)) { throw new Error(`Invalid property value: ${value}`); } const [, val] = value.match(reg); const [cs, v1, v2, v3, aa] = val.replace('/', ' ').split(/\s+/); let r, g, b, a; if (v1 === NONE) { r = 0; } else { r = v1.endsWith('%') ? parseFloat(v1) / MAX_PCT : parseFloat(v1); } if (v2 === NONE) { g = 0; } else { g = v2.endsWith('%') ? parseFloat(v2) / MAX_PCT : parseFloat(v2); } if (v3 === NONE) { b = 0; } else { b = v3.endsWith('%') ? parseFloat(v3) / MAX_PCT : parseFloat(v3); } if (isString(aa)) { if (aa === NONE) { a = 0; } else { a = aa; if (a.endsWith('%')) { a = parseFloat(a) / MAX_PCT; } else { a = parseFloat(a); } if (a < 0) { a = 0; } else if (a > 1) { a = 1; } } } else { a = 1; } let hex; // srgb if (cs === 'srgb') { hex = await convertRgbToHex([r * MAX_RGB, g * MAX_RGB, b * MAX_RGB, a]); // srgb-linear } else if (cs === 'srgb-linear') { hex = await convertLinearRgbToHex([r, g, b, a]); // display-p3 } else if (cs === 'display-p3') { const linearRgb = await rgbToLinearRgb([r, g, b]); const [x, y, z] = await transformMatrix(MATRIX_P3_TO_XYZ, linearRgb); hex = await convertXyzToHex([x, y, z, a]); // rec2020 } else if (cs === 'rec2020') { const ALPHA = 1.09929682680944; const BETA = 0.018053968510807; const REC_COEF = 0.45; const rgb = [r, g, b].map(c => { let cl; if (c < BETA * REC_COEF * DEC) { cl = c / (REC_COEF * DEC); } else { cl = Math.pow((c + ALPHA - 1) / ALPHA, 1 / REC_COEF); } return cl; }); const [x, y, z] = await transformMatrix(MATRIX_REC2020_TO_XYZ, rgb); hex = await convertXyzToHex([x, y, z, a]); // a98-rgb } else if (cs === 'a98-rgb') { const POW_A98 = 563 / 256; const rgb = [r, g, b].map(c => { const cl = Math.pow(c, POW_A98); return cl; }); const [x, y, z] = await transformMatrix(MATRIX_A98_TO_XYZ, rgb); hex = await convertXyzToHex([x, y, z, a]); // prophoto-rgb } else if (cs === 'prophoto-rgb') { const POW_PROPHOTO = 1.8; const rgb = [r, g, b].map(c => { let cl; if (c > 1 / (HEX * DOUBLE)) { cl = Math.pow(c, POW_PROPHOTO); } else { cl = c / HEX; } return cl; }); const [x, y, z] = await transformMatrix(MATRIX_PROPHOTO_TO_XYZ_D50, rgb); hex = await convertXyzD50ToHex([x, y, z, a]); // xyz, xyz-d50, xyz-d65 } else if (/^xyz(?:-d(?:50|65))?$/.test(cs)) { const [x, y, z] = [r, g, b]; if (cs === 'xyz-d50') { hex = await convertXyzD50ToHex([x, y, z, a]); } else { hex = await convertXyzToHex([x, y, z, a]); } } return hex; }; /** * convert color-mix() to hex color * * @param {string} value - value * @returns {?string} - hex color */ export const convertColorMixToHex = async value => { if (isString(value)) { value = value.trim(); } else { throw new TypeError(`Expected String but got ${getType(value)}.`); } const regColorMix = new RegExp(`^${REG_COLOR_MIX_CAPT}$`, 'i'); if (!regColorMix.test(value)) { throw new Error(`Invalid property value: ${value}`); } const [, colorSpace, colorPartA, colorPartB] = value.match(regColorMix); const regColorPart = new RegExp(`^(${REG_COLOR_TYPE})(?:\\s+(${REG_PCT}))?$`, 'i'); const regMissingLch = /^(?:h(?:sla?|wb)|(?:ok)?l(?:ab|ch))\(.*none.*\)$/; const regMissingRgb = /^(?:color|rgba?)\(.*none.*\)$/; const [, colorA, pctA] = colorPartA.match(regColorPart); const [, colorB, pctB] = colorPartB.match(regColorPart); let colorAHex, colorBHex; if (colorA.startsWith('color(')) { colorAHex = await convertColorFuncToHex(colorA); } else { colorAHex = await convertColorToHex(colorA, true); } if (colorB.startsWith('color(')) { colorBHex = await convertColorFuncToHex(colorB); } else { colorBHex = await convertColorToHex(colorB, true); } let hex; if (colorAHex && colorBHex) { // normalize percentages and set multipler let pA, pB, m; if (pctA && pctB) { const p1 = parseFloat(pctA) / MAX_PCT; const p2 = parseFloat(pctB) / MAX_PCT; if (p1 < 0 || p1 > 1) { throw new RangeError(`${pctA} is not between 0% and 100%.`); } if (p2 < 0 || p2 > 1) { throw new RangeError(`${pctB} is not between 0% and 100%.`); } const factor = p1 + p2; if (factor === 0) { throw new Error(`Invalid property value: ${value}`); } pA = p1 / factor; pB = p2 / factor; m = factor < 1 ? factor : 1; } else { if (pctA) { pA = parseFloat(pctA) / MAX_PCT; if (pA < 0 || pA > 1) { throw new RangeError(`${pctA} is not between 0% and 100%.`); } pB = 1 - pA; } else if (pctB) { pB = parseFloat(pctB) / MAX_PCT; if (pB < 0 || pB > 1) { throw new RangeError(`${pctB} is not between 0% and 100%.`); } pA = 1 - pB; } else { pA = HALF; pB = HALF; } m = 1; } // in srgb if (colorSpace === 'srgb') { let rgbA = await hexToRgb(colorAHex); let rgbB = await hexToRgb(colorBHex); if (regMissingRgb.test(colorA)) { rgbA = await reInsertMissingComponents(colorA, rgbA); } if (regMissingRgb.test(colorB)) { rgbB = await reInsertMissingComponents(colorB, rgbB); } const [ [rA, gA, bA, aA], [rB, gB, bB, aB] ] = await normalizeColorComponents(rgbA, rgbB); const factorA = aA * pA; const factorB = aB * pB; const a = (factorA + factorB); let r, g, b; if (a === 0) { r = rA * pA + rB * pB; g = gA * pA + gB * pB; b = bA * pA + bB * pB; } else { r = (rA * factorA + rB * factorB) / a; g = (gA * factorA + gB * factorB) / a; b = (bA * factorA + bB * factorB) / a; } hex = await convertRgbToHex([r, g, b, a * m]); // in srgb-linear } else if (colorSpace === 'srgb-linear') { let rgbA = await hexToLinearRgb(colorAHex); let rgbB = await hexToLinearRgb(colorBHex); if (regMissingRgb.test(colorA)) { rgbA = await reInsertMissingComponents(colorA, rgbA); } if (regMissingRgb.test(colorB)) { rgbB = await reInsertMissingComponents(colorB, rgbB); } const [ [rA, gA, bA, aA], [rB, gB, bB, aB] ] = await normalizeColorComponents(rgbA, rgbB); const factorA = aA * pA; const factorB = aB * pB; const a = (factorA + factorB); let r, g, b; if (a === 0) { r = rA * pA + rB * pB; g = gA * pA + gB * pB; b = bA * pA + bB * pB; } else { r = (rA * factorA + rB * factorB) * a; g = (gA * factorA + gB * factorB) * a; b = (bA * factorA + bB * factorB) * a; } hex = await convertLinearRgbToHex([r, g, b, a * m]); // in xyz, xyz-d65 } else if (/^xyz(?:-d65)?$/.test(colorSpace)) { let xyzA = await hexToXyz(colorAHex); let xyzB = await hexToXyz(colorBHex); if (regMissingRgb.test(colorA)) { xyzA = await reInsertMissingComponents(colorA, xyzA); } if (regMissingRgb.test(colorB)) { xyzB = await reInsertMissingComponents(colorB, xyzB); } const [ [xA, yA, zA, aA], [xB, yB, zB, aB] ] = await normalizeColorComponents(xyzA, xyzB); const factorA = aA * pA; const factorB = aB * pB; const a = (factorA + factorB); let x, y, z; if (a === 0) { x = xA * pA + xB * pB; y = yA * pA + yB * pB; z = zA * pA + zB * pB; } else { x = (xA * factorA + xB * factorB) * a; y = (yA * factorA + yB * factorB) * a; z = (zA * factorA + zB * factorB) * a; } hex = await convertXyzToHex([x, y, z, a * m]); // in xyz-d50 } else if (colorSpace === 'xyz-d50') { let xyzA = await hexToXyzD50(colorAHex); let xyzB = await hexToXyzD50(colorBHex); if (regMissingRgb.test(colorA)) { xyzA = await reInsertMissingComponents(colorA, xyzA); } if (regMissingRgb.test(colorB)) { xyzB = await reInsertMissingComponents(colorB, xyzB); } const [ [xA, yA, zA, aA], [xB, yB, zB, aB] ] = await normalizeColorComponents(xyzA, xyzB); const factorA = aA * pA; const factorB = aB * pB; const a = (factorA + factorB); let x, y, z; if (a === 0) { x = xA * pA + xB * pB; y = yA * pA + yB * pB; z = zA * pA + zB * pB; } else { x = (xA * factorA + xB * factorB) * a; y = (yA * factorA + yB * factorB) * a; z = (zA * factorA + zB * factorB) * a; } hex = await convertXyzD50ToHex([x, y, z, a * m]); // in hsl } else if (colorSpace === 'hsl') { let [hA, sA, lA, aA] = await hexToHsl(colorAHex); let [hB, sB, lB, aB] = await hexToHsl(colorBHex); if (regMissingLch.test(colorA)) { [lA, sA, hA, aA] = await reInsertMissingComponents(colorA, [lA, sA, hA, aA]); } if (regMissingLch.test(colorB)) { [lB, sB, hB, aB] = await reInsertMissingComponents(colorB, [lB, sB, hB, aB]); } [ [hA, sA, lA, aA], [hB, sB, lB, aB] ] = await normalizeColorComponents([hA, sA, lA, aA], [hB, sB, lB, aB]); const factorA = aA * pA; const factorB = aB * pB; const a = (factorA + factorB); const h = (hA * pA + hB * pB) % DEG; let s, l; if (a === 0) { s = sA * pA + sB * pB; l = lA * pA + lB * pB; } else { s = (sA * factorA + sB * factorB) / a; l = (lA * factorA + lB * factorB) / a; } hex = await convertColorToHex(`hsl(${h} ${s}% ${l}% / ${a * m})`, true); // in hwb } else if (colorSpace === 'hwb') { let [hA, wA, bA, aA] = await hexToHwb(colorAHex); let [hB, wB, bB, aB] = await hexToHwb(colorBHex); if (regMissingLch.test(colorA)) { [,, hA, aA] = await reInsertMissingComponents(colorA, [null, null, hA, aA]); } if (regMissingLch.test(colorB)) { [,, hB, aB] = await reInsertMissingComponents(colorB, [null, null, hB, aB]); } [ [hA, wA, bA, aA], [hB, wB, bB, aB] ] = await normalizeColorComponents([hA, wA, bA, aA], [hB, wB, bB, aB]); const factorA = aA * pA; const factorB = aB * pB; const a = (factorA + factorB); const h = (hA * pA + hB * pB) % DEG; let w, b; if (a === 0) { w = wA * pA + wB * pB; b = bA * pA + bB * pB; } else { w = (wA * factorA + wB * factorB) / a; b = (bA * factorA + bB * factorB) / a; } hex = await convertColorToHex(`hwb(${h} ${w}% ${b}% / ${a * m})`, true); // in lab } else if (colorSpace === 'lab') { let [lA, aA, bA, aaA] = await hexToLab(colorAHex); let [lB, aB, bB, aaB] = await hexToLab(colorBHex); if (regMissingLch.test(colorA)) { [lA,,, aaA] = await reInsertMissingComponents(colorA, [lA, null, null, aaA]); } if (regMissingLch.test(colorB)) { [lB,,, aaB] = await reInsertMissingComponents(colorB, [lB, null, null, aaB]); } [ [lA, aA, bA, aaA], [lB, aB, bB, aaB] ] = await normalizeColorComponents([lA, aA, bA, aaA], [lB, aB, bB, aaB]); const factorA = aaA * pA; const factorB = aaB * pB; const aa = (factorA + factorB); let l, a, b; if (aa === 0) { l = lA * pA + lB * pB; a = aA * pA + aB * pB; b = bA * pA + bB * pB; } else { l = (lA * factorA + lB * factorB) * aa; a = (aA * factorA + aB * factorB) * aa; b = (bA * factorA + bB * factorB) * aa; } hex = await convertColorToHex(`lab(${l} ${a} ${b} / ${aa * m})`); // in lch } else if (colorSpace === 'lch') { let lchA = await hexToLch(colorAHex); let lchB = await hexToLch(colorBHex); if (regMissingLch.test(colorA)) { lchA = await reInsertMissingComponents(colorA, lchA); } if (regMissingLch.test(colorB)) { lchB = await reInsertMissingComponents(colorB, lchB); } const [ [lA, cA, hA, aaA], [lB, cB, hB, aaB] ] = await normalizeColorComponents(lchA, lchB); const factorA = aaA * pA; const factorB = aaB * pB; const aa = (factorA + factorB); let l, c, h; if (aa === 0) { l = lA * pA + lB * pB; c = cA * pA + cB * pB; h = hA * pA + hB * pB; } else { l = (lA * factorA + lB * factorB) * aa; c = (cA * factorA + cB * factorB) * aa; h = (hA * factorA + hB * factorB) * aa; } hex = await convertColorToHex(`lch(${l} ${c} ${h} / ${aa * m})`); // in oklab } else if (colorSpace === 'oklab') { let [lA, aA, bA, aaA] = await hexToOklab(colorAHex); let [lB, aB, bB, aaB] = await hexToOklab(colorBHex); if (regMissingLch.test(colorA)) { [lA,,, aaA] = await reInsertMissingComponents(colorA, [lA, null, null, aaA]); } if (regMissingLch.test(colorB)) { [lB,,, aaB] = await reInsertMissingComponents(colorB, [lB, null, null, aaB]); } [ [lA, aA, bA, aaA], [lB, aB, bB, aaB] ] = await normalizeColorComponents([lA, aA, bA, aaA], [lB, aB, bB, aaB]); const factorA = aaA * pA; const factorB = aaB * pB; const aa = (factorA + factorB); let l, a, b; if (aa === 0) { l = lA * pA + lB * pB; a = aA * pA + aB * pB; b = bA * pA + bB * pB; } else { l = (lA * factorA + lB * factorB) * aa; a = (aA * factorA + aB * factorB) * aa; b = (bA * factorA + bB * factorB) * aa; } hex = await convertColorToHex(`oklab(${l} ${a} ${b} / ${aa * m})`); // in oklch } else if (colorSpace === 'oklch') { let lchA = await hexToOklch(colorAHex); let lchB = await hexToOklch(colorBHex); if (regMissingLch.test(colorA)) { lchA = await reInsertMissingComponents(colorA, lchA); } if (regMissingLch.test(colorB)) { lchB = await reInsertMissingComponents(colorB, lchB); } const [ [lA, cA, hA, aaA], [lB, cB, hB, aaB] ] = await normalizeColorComponents(lchA, lchB); const factorA = aaA * pA; const factorB = aaB * pB; const aa = (factorA + factorB); let l, c, h; if (aa === 0) { l = lA * pA + lB * pB; c = cA * pA + cB * pB; h = hA * pA + hB * pB; } else { l = (lA * factorA + lB * factorB) * aa; c = (cA * factorA + cB * factorB) * aa; h = (hA * factorA + hB * factorB) * aa; } hex = await convertColorToHex(`oklch(${l} ${c} ${h} / ${aa * m})`); } } return hex || null; }; /** * get color in hex color notation * * @param {string} value - value * @param {object} opt - options * @returns {?string|Array} - string of hex color or array of [prop, hex] pair */ export const getColorInHex = async (value, opt = {}) => { if (isString(value)) { value = value.trim(); } else { throw new TypeError(`Expected String but got ${getType(value)}.`); } const { alpha, prop } = opt; let hex; if (value.startsWith('color-mix')) { hex = await convertColorMixToHex(value); } else if (value.startsWith('color(')) { hex = await convertColorFuncToHex(value); } else { hex = await convertColorToHex(value, !!alpha); } return prop ? [prop, hex] : (hex || null); }; /** * composite two layered colors * * @param {string} overlay - overlay color * @param {string} base - base color * @returns {?string} - hex color */ export const compositeLayeredColors = async (overlay, base) => { const overlayHex = await getColorInHex(overlay, { alpha: true }); const baseHex = await await getColorInHex(base, { alpha: true }); let hex; if (overlayHex && baseHex) { const [rO, gO, bO, aO] = await hexToRgb(overlayHex); const [rB, gB, bB, aB] = await hexToRgb(baseHex); const alpha = 1 - (1 - aO) * (1 - aB); if (aO === 1) { hex = overlayHex; } else if (aO === 0) { hex = baseHex; } else if (alpha) { const alphaO = aO / alpha; const alphaB = aB * (1 - aO) / alpha; const [r, g, b, a] = await Promise.all([ numberToHexString(rO * alphaO + rB * alphaB), numberToHexString(gO * alphaO + gB * alphaB), numberToHexString(bO * alphaO + bB * alphaB), numberToHexString(alpha * MAX_RGB) ]); if (a === 'ff') { hex = `#${r}${g}${b}`; } else { hex = `#${r}${g}${b}${a}`; } } } return hex || null; };
Update color.js
src/mjs/color.js
Update color.js
<ide><path>rc/mjs/color.js <ide> * https://w3c.github.io/csswg-drafts/css-color-4/#color-conversion-code <ide> * <ide> * NOTE: 'currentColor' keyword is not supported <del> * TODO: 'none' keyword is not yet fully supported <ide> */ <ide> <ide> /* shared */
JavaScript
mit
b907f6030738f434a2e4602d4abfa75c2c89faa1
0
drewbrokke/jack,drewbrokke/jack
var gulp = require('gulp'); var ts = require('gulp-typescript'); var tslint = require('gulp-tslint'); const tsProject = ts.createProject('tsconfig.json'); gulp.task('build', function () { return gulp.src('src/**/*.ts') .pipe(tsProject()) .pipe(gulp.dest('dist')); }); gulp.task("tslint", () => gulp.src('src/**/*.ts') .pipe(tslint()) .pipe(tslint.report()) ); gulp.task('default', ['build']);
gulpfile.js
var gulp = require('gulp'); var ts = require('gulp-typescript'); var tslint = require('gulp-tslint'); const tsProject = ts.createProject('tsconfig.json'); gulp.task('build', function () { return gulp.src('src/**/*.ts') .pipe(tsProject()) .pipe(gulp.dest('dist')); }); gulp.task("tslint", () => gulp.src('src/**/*.ts') .pipe(tslint()) .pipe(tslint.report()) ); gulp.task('default', ['build']);
gulpfile.js - sf
gulpfile.js
gulpfile.js - sf
<ide><path>ulpfile.js <ide> .pipe(gulp.dest('dist')); <ide> }); <ide> <del> <ide> gulp.task("tslint", () => <ide> gulp.src('src/**/*.ts') <ide> .pipe(tslint())
Java
agpl-3.0
0bacfc98a83a28429263473f9b37d6226c984bee
0
mnip91/programming-multiactivities,PaulKh/scale-proactive,mnip91/proactive-component-monitoring,jrochas/scale-proactive,acontes/programming,lpellegr/programming,mnip91/proactive-component-monitoring,mnip91/proactive-component-monitoring,ow2-proactive/programming,fviale/programming,mnip91/programming-multiactivities,paraita/programming,fviale/programming,ow2-proactive/programming,paraita/programming,fviale/programming,lpellegr/programming,lpellegr/programming,mnip91/proactive-component-monitoring,acontes/programming,mnip91/programming-multiactivities,fviale/programming,acontes/programming,jrochas/scale-proactive,mnip91/programming-multiactivities,paraita/programming,paraita/programming,lpellegr/programming,jrochas/scale-proactive,mnip91/proactive-component-monitoring,jrochas/scale-proactive,ow2-proactive/programming,jrochas/scale-proactive,paraita/programming,PaulKh/scale-proactive,mnip91/programming-multiactivities,acontes/programming,ow2-proactive/programming,ow2-proactive/programming,jrochas/scale-proactive,acontes/programming,jrochas/scale-proactive,PaulKh/scale-proactive,acontes/programming,ow2-proactive/programming,PaulKh/scale-proactive,fviale/programming,lpellegr/programming,fviale/programming,PaulKh/scale-proactive,mnip91/programming-multiactivities,mnip91/proactive-component-monitoring,paraita/programming,PaulKh/scale-proactive,PaulKh/scale-proactive,acontes/programming,lpellegr/programming
/* * ################################################################ * * ProActive: The Java(TM) library for Parallel, Distributed, * Concurrent computing with Security and Mobility * * Copyright (C) 1997-2008 INRIA/University of Nice-Sophia Antipolis * Contact: [email protected] * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License * as published by the Free Software Foundation; either version * 2 of the License, or 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 * 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., 59 Temple Place, Suite 330, Boston, MA 02111-1307 * USA * * Initial developer(s): The ProActive Team * http://proactive.inria.fr/team_members.htm * Contributor(s): * * ################################################################ * $$PROACTIVE_INITIAL_DEV$$ */ package org.objectweb.proactive.annotation; import java.lang.annotation.Documented; import java.lang.annotation.Retention; import java.lang.annotation.RetentionPolicy; @Documented @Retention(RetentionPolicy.RUNTIME) public @interface PublicAPI { }
src/Core/org/objectweb/proactive/annotation/PublicAPI.java
/* * ################################################################ * * ProActive: The Java(TM) library for Parallel, Distributed, * Concurrent computing with Security and Mobility * * Copyright (C) 1997-2008 INRIA/University of Nice-Sophia Antipolis * Contact: [email protected] * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License * as published by the Free Software Foundation; either version * 2 of the License, or 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 * 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., 59 Temple Place, Suite 330, Boston, MA 02111-1307 * USA * * Initial developer(s): The ProActive Team * http://proactive.inria.fr/team_members.htm * Contributor(s): * * ################################################################ * $$PROACTIVE_INITIAL_DEV$$ */ package org.objectweb.proactive.annotation; import java.lang.annotation.Documented; import java.lang.annotation.Retention; import java.lang.annotation.RetentionPolicy; @Documented @Retention(RetentionPolicy.SOURCE) public @interface PublicAPI { }
Keep @PublicAPI at runtime for JarDiff (and static analysis of public classes ) git-svn-id: 9146c88ff6d39b48099bf954d15d68f687b3fa69@11283 28e8926c-6b08-0410-baaa-805c5e19b8d6
src/Core/org/objectweb/proactive/annotation/PublicAPI.java
Keep @PublicAPI at runtime for JarDiff (and static analysis of public classes )
<ide><path>rc/Core/org/objectweb/proactive/annotation/PublicAPI.java <ide> <ide> <ide> @Documented <del>@Retention(RetentionPolicy.SOURCE) <add>@Retention(RetentionPolicy.RUNTIME) <ide> public @interface PublicAPI { <ide> }
Java
mit
error: pathspec 'turbine-condenser/src/main/java/org/jimsey/projects/turbine/condenser/domain/indicators/AroonOscillator.java' did not match any file(s) known to git
0fc27b7b8dfec8f6d6abb49d505a34f704b30a86
1
the-james-burton/the-turbine,the-james-burton/the-turbine
/** * The MIT License * Copyright (c) 2015 the-james-burton * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ package org.jimsey.projects.turbine.condenser.domain.indicators; import java.util.HashMap; import java.util.Map; import eu.verdelhan.ta4j.TimeSeries; import eu.verdelhan.ta4j.indicators.oscillators.AroonDownIndicator; import eu.verdelhan.ta4j.indicators.oscillators.AroonUpIndicator; import eu.verdelhan.ta4j.indicators.simple.ClosePriceIndicator; /** * http://stockcharts.com/school/doku.php?id=chart_school:technical_indicators:aroon_oscillator * * @author the-james-burton */ @EnableTurbineIndicator(name = "AroonOscillator", isOverlay = false) public class AroonOscillator extends BaseIndicator { private final AroonUpIndicator aroonUpIndicator; private final AroonDownIndicator aroonDownIndicator; public AroonOscillator(final TimeSeries series, final ClosePriceIndicator indicator) { super(25, series, AroonOscillator.class.getSimpleName(), indicator); // setup this indicator... aroonUpIndicator = new AroonUpIndicator(series, timeFrame); aroonDownIndicator = new AroonDownIndicator(series, timeFrame); } @Override public Map<String, Double> computeValues() { Map<String, Double> values = new HashMap<>(); double aroonUp = aroonUpIndicator.getValue(series.getEnd()).toDouble(); double aroonDown = aroonDownIndicator.getValue(series.getEnd()).toDouble(); values.put("aroonOscillator", aroonUp - aroonDown); return values; } }
turbine-condenser/src/main/java/org/jimsey/projects/turbine/condenser/domain/indicators/AroonOscillator.java
added AroonOscillator
turbine-condenser/src/main/java/org/jimsey/projects/turbine/condenser/domain/indicators/AroonOscillator.java
added AroonOscillator
<ide><path>urbine-condenser/src/main/java/org/jimsey/projects/turbine/condenser/domain/indicators/AroonOscillator.java <add>/** <add> * The MIT License <add> * Copyright (c) 2015 the-james-burton <add> * <add> * Permission is hereby granted, free of charge, to any person obtaining a copy <add> * of this software and associated documentation files (the "Software"), to deal <add> * in the Software without restriction, including without limitation the rights <add> * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell <add> * copies of the Software, and to permit persons to whom the Software is <add> * furnished to do so, subject to the following conditions: <add> * <add> * The above copyright notice and this permission notice shall be included in <add> * all copies or substantial portions of the Software. <add> * <add> * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR <add> * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, <add> * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE <add> * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER <add> * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, <add> * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN <add> * THE SOFTWARE. <add> */ <add>package org.jimsey.projects.turbine.condenser.domain.indicators; <add> <add>import java.util.HashMap; <add>import java.util.Map; <add> <add>import eu.verdelhan.ta4j.TimeSeries; <add>import eu.verdelhan.ta4j.indicators.oscillators.AroonDownIndicator; <add>import eu.verdelhan.ta4j.indicators.oscillators.AroonUpIndicator; <add>import eu.verdelhan.ta4j.indicators.simple.ClosePriceIndicator; <add> <add>/** <add> * http://stockcharts.com/school/doku.php?id=chart_school:technical_indicators:aroon_oscillator <add> * <add> * @author the-james-burton <add> */ <add>@EnableTurbineIndicator(name = "AroonOscillator", isOverlay = false) <add>public class AroonOscillator extends BaseIndicator { <add> <add> private final AroonUpIndicator aroonUpIndicator; <add> <add> private final AroonDownIndicator aroonDownIndicator; <add> <add> public AroonOscillator(final TimeSeries series, final ClosePriceIndicator indicator) { <add> super(25, series, AroonOscillator.class.getSimpleName(), indicator); <add> <add> // setup this indicator... <add> aroonUpIndicator = new AroonUpIndicator(series, timeFrame); <add> aroonDownIndicator = new AroonDownIndicator(series, timeFrame); <add> } <add> <add> @Override <add> public Map<String, Double> computeValues() { <add> Map<String, Double> values = new HashMap<>(); <add> double aroonUp = aroonUpIndicator.getValue(series.getEnd()).toDouble(); <add> double aroonDown = aroonDownIndicator.getValue(series.getEnd()).toDouble(); <add> values.put("aroonOscillator", aroonUp - aroonDown); <add> return values; <add> } <add> <add>}
Java
lgpl-2.1
70754444274392ee35e1207c11c70a882ea7eb7e
0
pbondoer/xwiki-platform,pbondoer/xwiki-platform,xwiki/xwiki-platform,xwiki/xwiki-platform,xwiki/xwiki-platform,xwiki/xwiki-platform,pbondoer/xwiki-platform,pbondoer/xwiki-platform,pbondoer/xwiki-platform,xwiki/xwiki-platform
/* * See the NOTICE file distributed with this work for additional * information regarding copyright ownership. * * This 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 software 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 software; if not, write to the Free * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA * 02110-1301 USA, or see the FSF site: http://www.fsf.org. */ package org.xwiki.webjars.internal; import java.io.IOException; import java.io.InputStream; import java.util.Arrays; import java.util.List; import javax.inject.Inject; import javax.inject.Named; import org.apache.commons.io.IOUtils; import org.xwiki.action.AbstractAction; import org.xwiki.action.ActionChain; import org.xwiki.action.ActionException; import org.xwiki.component.annotation.Component; import org.xwiki.container.Container; import org.xwiki.resource.ActionId; import org.xwiki.resource.EntityResource; import org.xwiki.resource.Resource; /** * Handles {@code webjars} action. * <p> * At the moment we're mapping calls to the "webjars" URL as an EntityResource. * In the future it would be cleaner to register some new URL factory instead of reusing the format for Entity * Resources and have some URL of the type {@code http://server/context/webjars?resource=(resourceName)}. * Since we don't have this now and we're using the Entity Resource URL format we're using the following URL format: * <code> * http://server/context/bin/webjars/resource/path?value=(resource name) * </code> * (for example: http://localhost:8080/xwiki/bin/webjars/resource/path?value=angularjs/1.1.5/angular.js) * So this means that the resource name will be parsed as a query string "value" parameter (with a fixed space of * "resource" and a fixed page name of "path"). * </p> * * @version $Id$ * @since 6.0M1 */ @Component @Named("webjars") public class WebJarsAction extends AbstractAction { /** * The WebJars Action Id. */ public static final ActionId WEBJARS = new ActionId("webjars"); /** * Prefix for locating JS resources in the classloader. */ private static final String WEBJARS_RESOURCE_PREFIX = "META-INF/resources/webjars/"; @Inject private Container container; @Override public List<ActionId> getSupportedActionIds() { return Arrays.asList(WEBJARS); } @Override public void execute(Resource resource, ActionChain chain) throws ActionException { EntityResource entityResource = (EntityResource) resource; String resourceName = entityResource.getParameterValue("value"); String resourcePath = String.format("%s%s", WEBJARS_RESOURCE_PREFIX, resourceName); InputStream resourceStream = getClassLoader().getResourceAsStream(resourcePath); if (resourceStream != null) { try { IOUtils.copy(resourceStream, this.container.getResponse().getOutputStream()); } catch (IOException e) { throw new ActionException(String.format("Failed to read resource [%s]", resourceName), e); } finally { IOUtils.closeQuietly(resourceStream); } } // Be a good citizen, continue the chain, in case some lower-priority action has something to do for this // action id. chain.executeNext(resource); } /** * @return the Class Loader from which to look for WebJars resources */ protected ClassLoader getClassLoader() { // Load the resource from the context class loader in order to support webjars located in XWiki Extensions // loaded by the Extension Manager. return Thread.currentThread().getContextClassLoader(); } }
xwiki-platform-core/xwiki-platform-webjars/src/main/java/org/xwiki/webjars/internal/WebJarsAction.java
/* * See the NOTICE file distributed with this work for additional * information regarding copyright ownership. * * This 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 software 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 software; if not, write to the Free * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA * 02110-1301 USA, or see the FSF site: http://www.fsf.org. */ package org.xwiki.webjars.internal; import java.io.IOException; import java.io.InputStream; import java.util.Arrays; import java.util.List; import javax.inject.Inject; import javax.inject.Named; import org.apache.commons.io.IOUtils; import org.xwiki.action.AbstractAction; import org.xwiki.action.ActionChain; import org.xwiki.action.ActionException; import org.xwiki.component.annotation.Component; import org.xwiki.container.Container; import org.xwiki.resource.ActionId; import org.xwiki.resource.EntityResource; import org.xwiki.resource.Resource; /** * Handles {@code webjars} action. * <p> * At the moment we're mapping calls to the "webjars" URL as an EntityResource. * In the future it would be cleaner to register some new URL factory instead of reusing the format for Entity * Resources. Since we're reusing it we're going to do the following mapping: * <code> * http://server/bin/webjars/resource/path?value=(resource name) * </code> * (for example: http://localhost:8080/bin/webjars/resource/path?value=angularjs/1.1.5/angular.js) * So this means that the resource name will be parsed as a query string "value" parameter (with a fixed space of * "resource" and a fixed page name of "path"). * </p> * * @version $Id$ * @since 6.0M1 */ @Component @Named("webjars") public class WebJarsAction extends AbstractAction { /** * The WebJars Action Id. */ public static final ActionId WEBJARS = new ActionId("webjars"); /** * Prefix for locating JS resources in the classloader. */ private static final String WEBJARS_RESOURCE_PREFIX = "META-INF/resources/webjars/"; @Inject private Container container; @Override public List<ActionId> getSupportedActionIds() { return Arrays.asList(WEBJARS); } @Override public void execute(Resource resource, ActionChain chain) throws ActionException { EntityResource entityResource = (EntityResource) resource; String resourceName = entityResource.getParameterValue("value"); String resourcePath = String.format("%s%s", WEBJARS_RESOURCE_PREFIX, resourceName); InputStream resourceStream = getClassLoader().getResourceAsStream(resourcePath); if (resourceStream != null) { try { IOUtils.copy(resourceStream, this.container.getResponse().getOutputStream()); } catch (IOException e) { throw new ActionException(String.format("Failed to read resource [%s]", resourceName), e); } finally { IOUtils.closeQuietly(resourceStream); } } // Be a good citizen, continue the chain, in case some lower-priority action has something to do for this // action id. chain.executeNext(resource); } /** * @return the Class Loader from which to look for WebJars resources */ protected ClassLoader getClassLoader() { // Load the resource from the context class loader in order to support webjars located in XWiki Extensions // loaded by the Extension Manager. return Thread.currentThread().getContextClassLoader(); } }
[Misc] A bit more explanations
xwiki-platform-core/xwiki-platform-webjars/src/main/java/org/xwiki/webjars/internal/WebJarsAction.java
[Misc] A bit more explanations
<ide><path>wiki-platform-core/xwiki-platform-webjars/src/main/java/org/xwiki/webjars/internal/WebJarsAction.java <ide> * <p> <ide> * At the moment we're mapping calls to the "webjars" URL as an EntityResource. <ide> * In the future it would be cleaner to register some new URL factory instead of reusing the format for Entity <del> * Resources. Since we're reusing it we're going to do the following mapping: <add> * Resources and have some URL of the type {@code http://server/context/webjars?resource=(resourceName)}. <add> * Since we don't have this now and we're using the Entity Resource URL format we're using the following URL format: <ide> * <code> <del> * http://server/bin/webjars/resource/path?value=(resource name) <add> * http://server/context/bin/webjars/resource/path?value=(resource name) <ide> * </code> <del> * (for example: http://localhost:8080/bin/webjars/resource/path?value=angularjs/1.1.5/angular.js) <add> * (for example: http://localhost:8080/xwiki/bin/webjars/resource/path?value=angularjs/1.1.5/angular.js) <ide> * So this means that the resource name will be parsed as a query string "value" parameter (with a fixed space of <ide> * "resource" and a fixed page name of "path"). <ide> * </p>
Java
mit
error: pathspec 'app/src/main/java/tech/akpmakes/android/taskkeeper/util/DaysOfWeek.java' did not match any file(s) known to git
a777647202a52cf986bf4141281b7c29332882db
1
WhenApp/WhenApp-Android
package tech.akpmakes.android.taskkeeper.util; import android.content.Context; import android.icu.util.Calendar; import tech.akpmakes.android.taskkeeper.R; public enum DaysOfWeek { DEFAULT(R.string._default), SUNDAY(R.string.day_1), MONDAY(R.string.day_2), TUESDAY(R.string.day_3), WEDNESDAY(R.string.day_4), THURSDAY(R.string.day_5), FRIDAY(R.string.day_6), SATURDAY(R.string.day_7); final int index; DaysOfWeek(int dayString) { index = dayString; } public String getName(Context context) { return context.getString(index); } public static DaysOfWeek get(int day) { return values()[day]; } }
app/src/main/java/tech/akpmakes/android/taskkeeper/util/DaysOfWeek.java
fix: Including all code in a commit is good to do
app/src/main/java/tech/akpmakes/android/taskkeeper/util/DaysOfWeek.java
fix: Including all code in a commit is good to do
<ide><path>pp/src/main/java/tech/akpmakes/android/taskkeeper/util/DaysOfWeek.java <add>package tech.akpmakes.android.taskkeeper.util; <add> <add>import android.content.Context; <add>import android.icu.util.Calendar; <add> <add>import tech.akpmakes.android.taskkeeper.R; <add> <add>public enum DaysOfWeek { <add> DEFAULT(R.string._default), <add> SUNDAY(R.string.day_1), <add> MONDAY(R.string.day_2), <add> TUESDAY(R.string.day_3), <add> WEDNESDAY(R.string.day_4), <add> THURSDAY(R.string.day_5), <add> FRIDAY(R.string.day_6), <add> SATURDAY(R.string.day_7); <add> <add> final int index; <add> <add> DaysOfWeek(int dayString) { <add> index = dayString; <add> } <add> <add> public String getName(Context context) { <add> return context.getString(index); <add> } <add> <add> public static DaysOfWeek get(int day) { <add> return values()[day]; <add> } <add>}
Java
apache-2.0
error: pathspec 'src/main/java/robot/tnk47/Tnk47Robot.java' did not match any file(s) known to git
79f383184f13b15471871876781dfb967c74efd6
1
wdxzs1985/ameba-robot
package robot.tnk47; import java.util.Map; import robot.AbstractRobot; import robot.LoginHandler; import robot.tnk47.battle.BattleAnimationHandler; import robot.tnk47.battle.BattleCheckHandler; import robot.tnk47.battle.BattleDetailHandler; import robot.tnk47.battle.BattleHandler; import robot.tnk47.battle.BattleResultHandler; import robot.tnk47.battle.PrefectureBattleListHandler; import robot.tnk47.battle.PrefectureBattleResultHandler; import robot.tnk47.conquest.ConquestAnimationHandler; import robot.tnk47.conquest.ConquestAreaTopHandler; import robot.tnk47.conquest.ConquestBattleCheckHandler; import robot.tnk47.conquest.ConquestBattleHandler; import robot.tnk47.conquest.ConquestBattleListHandler; import robot.tnk47.conquest.ConquestHandler; import robot.tnk47.conquest.ConquestResultHandler; import robot.tnk47.duel.DuelBattleAnimationHandler; import robot.tnk47.duel.DuelBattleCheckHandler; import robot.tnk47.duel.DuelBattleResultHandler; import robot.tnk47.duel.DuelBattleSelectHandler; import robot.tnk47.duel.DuelHandler; import robot.tnk47.gacha.BattleGachaHandler; import robot.tnk47.gacha.BoxGachaHandler; import robot.tnk47.gacha.GachaHandler; import robot.tnk47.gacha.StampGachaHandler; import robot.tnk47.gacha.TicketGachaHandler; import robot.tnk47.guildbattle.GuildBattleAnimationHandler; import robot.tnk47.guildbattle.GuildBattleChargeHandler; import robot.tnk47.guildbattle.GuildBattleCheckHandler; import robot.tnk47.guildbattle.GuildBattleHandler; import robot.tnk47.guildbattle.GuildBattleResultHandler; import robot.tnk47.guildbattle.GuildBattleSelectHandler; import robot.tnk47.guildbattle.GuildBattleSkillHandler; import robot.tnk47.marathon.MarathonHandler; import robot.tnk47.marathon.MarathonMissionAnimationHandler; import robot.tnk47.marathon.MarathonMissionHandler; import robot.tnk47.marathon.MarathonMissionResultHandler; import robot.tnk47.marathon.MarathonNotificationHandler; import robot.tnk47.marathon.MarathonStageBossHandler; import robot.tnk47.marathon.MarathonStageDetailHandler; import robot.tnk47.marathon.MarathonStageForwardHandler; import robot.tnk47.marathon.MarathonStageHandler; import robot.tnk47.quest.QuestBossHandler; import robot.tnk47.quest.QuestHandler; import robot.tnk47.quest.QuestStageDetailHandler; import robot.tnk47.quest.QuestStageForwardHandler; import robot.tnk47.quest.QuestStatusUpHandler; import robot.tnk47.raid.RaidBattleAnimationHandler; import robot.tnk47.raid.RaidBattleEncountHandler; import robot.tnk47.raid.RaidBattleHandler; import robot.tnk47.raid.RaidBattleResultHandler; import robot.tnk47.raid.RaidHandler; import robot.tnk47.raid.RaidStageForwardHandler; import robot.tnk47.raid.RaidStageHandler; import robot.tnk47.raid.model.RaidBattleDamageMap; import robot.tnk47.upgrade.UpgradeAnimationHandler; import robot.tnk47.upgrade.UpgradeAutoConfirmHandler; import robot.tnk47.upgrade.UpgradeHandler; import robot.tnk47.upgrade.UpgradeSelectBaseHandler; public class Tnk47Robot extends AbstractRobot { public static final String HOST = "http://tnk47.ameba.jp"; public static final String VERSION = "天下自动脚本 11.0"; @Override public void initHandlers() { this.registerHandler("/", new HomeHandler(this)); this.registerHandler("/login", new LoginHandler(this)); this.registerHandler("/mypage", new MypageHandler(this)); this.registerHandler("/event-infomation", new EventInfomationHandler(this)); this.registerHandler("/gacha", new GachaHandler(this)); this.registerHandler("/gacha/ticket-gacha", new TicketGachaHandler(this)); this.registerHandler("/gacha/box-gacha", new BoxGachaHandler(this)); this.registerHandler("/gacha/stamp-gacha", new StampGachaHandler(this)); this.registerHandler("/gacha/battle-gacha", new BattleGachaHandler(this)); // this.registerHandler("/gift", new GiftHandler(this)); // 控制器:合战活动 this.registerHandler("/pointrace", new BattleHandler(this)); // 控制器:合战 this.registerHandler("/battle", new BattleHandler(this)); this.registerHandler("/battle/detail", new BattleDetailHandler(this)); this.registerHandler("/battle/battle-check", new BattleCheckHandler(this)); this.registerHandler("/battle/battle-animation", new BattleAnimationHandler(this)); this.registerHandler("/battle/battle-result", new BattleResultHandler(this)); this.registerHandler("/battle/prefecture-battle-list", new PrefectureBattleListHandler(this)); this.registerHandler("/battle/prefecture-battle-result", new PrefectureBattleResultHandler(this)); // 控制器:冒险 this.registerHandler("/quest", new QuestHandler(this)); this.registerHandler("/quest/stage/detail", new QuestStageDetailHandler(this)); this.registerHandler("/quest/stage/forward", new QuestStageForwardHandler(this)); this.registerHandler("/quest/boss-animation", new QuestBossHandler(this)); this.registerHandler("/use-item", new UseItemHandler(this)); this.registerHandler("/status-up", new QuestStatusUpHandler(this)); // 控制器:爬塔活动 this.registerHandler("/marathon", new MarathonHandler(this)); this.registerHandler("/marathon/stage", new MarathonStageHandler(this)); this.registerHandler("/marathon/stage/detail", new MarathonStageDetailHandler(this)); this.registerHandler("/marathon/stage/forward", new MarathonStageForwardHandler(this)); this.registerHandler("/marathon/stage/boss", new MarathonStageBossHandler(this)); this.registerHandler("/marathon/mission", new MarathonMissionHandler(this)); this.registerHandler("/marathon/mission/animation", new MarathonMissionAnimationHandler(this)); this.registerHandler("/marathon/mission/result", new MarathonMissionResultHandler(this)); this.registerHandler("/marathon/notification", new MarathonNotificationHandler(this)); // 强化 this.registerHandler("/upgrade", new UpgradeHandler(this)); this.registerHandler("/upgrade/select-base", new UpgradeSelectBaseHandler(this)); this.registerHandler("/upgrade/auto-upgrade-confirm", new UpgradeAutoConfirmHandler(this)); this.registerHandler("/upgrade/upgrade-animation", new UpgradeAnimationHandler(this)); // 控制器:RAID final RaidBattleDamageMap damageMap = new RaidBattleDamageMap(); this.registerHandler("/raid", new RaidHandler(this, damageMap)); this.registerHandler("/raid/battle", new RaidBattleHandler(this, damageMap)); this.registerHandler("/raid/battle-animation", new RaidBattleAnimationHandler(this, damageMap)); this.registerHandler("/raid/battle-result", new RaidBattleResultHandler(this, damageMap)); this.registerHandler("/raid/battle-encount", new RaidBattleEncountHandler(this, damageMap)); this.registerHandler("/raid/stage", new RaidStageHandler(this)); this.registerHandler("/raid/stage-forward", new RaidStageForwardHandler(this)); // 控制器:戦神リーグ this.registerHandler("/duel", new DuelHandler(this)); this.registerHandler("/duel/duel-battle-select", new DuelBattleSelectHandler(this)); this.registerHandler("/duel/duel-battle-check", new DuelBattleCheckHandler(this)); this.registerHandler("/duel/duel-battle-animation", new DuelBattleAnimationHandler(this)); this.registerHandler("/duel/duel-battle-result", new DuelBattleResultHandler(this)); // 控制器:同盟戦 this.registerHandler("/guildbattle", new GuildBattleHandler(this)); this.registerHandler("/guildbattle/charge", new GuildBattleChargeHandler(this)); this.registerHandler("/guildbattle/skill", new GuildBattleSkillHandler(this)); this.registerHandler("/guildbattle/select", new GuildBattleSelectHandler(this)); this.registerHandler("/guildbattle/check", new GuildBattleCheckHandler(this)); this.registerHandler("/guildbattle/animation", new GuildBattleAnimationHandler(this)); this.registerHandler("/guildbattle/result", new GuildBattleResultHandler(this)); // 控制器:天下統一戦 this.registerHandler("/conquest", new ConquestHandler(this)); this.registerHandler("/conquest/area-top", new ConquestAreaTopHandler(this)); this.registerHandler("/conquest/battle-list", new ConquestBattleListHandler(this)); this.registerHandler("/conquest/battle-check", new ConquestBattleCheckHandler(this)); this.registerHandler("/conquest/battle-animation", new ConquestAnimationHandler(this)); this.registerHandler("/conquest/conquest-result", new ConquestResultHandler(this)); this.registerHandler("/conquest/battle", new ConquestBattleHandler(this)); } @Override public void reset() { final Map<String, Object> session = this.getSession(); session.put("isMypage", false); session.put("isStampGachaEnable", this.isStampGachaEnable()); session.put("isGachaEnable", this.isGachaEnable()); session.put("isGiftEnable", this.isGiftEnable()); session.put("isQuestEnable", this.isQuestEnable()); session.put("isBattleEnable", this.isBattleEnable()); session.put("isUpgradeEnable", this.isUpgradeEnable()); session.put("isDuelEnable", this.isDuelEnable()); session.put("isEventEnable", true); session.put("isMarathonEnable", this.isMarathonEnable()); session.put("isPointRaceEnable", this.isPointRaceEnable()); session.put("isRaidEnable", this.isRaidEnable()); session.put("isGuildBattleEnable", this.isGuildBattleEnable()); session.put("isConquestEnable", this.isConquestEnable()); session.put("isQuestCardFull", false); session.put("isQuestFindAll", false); session.put("isPointRace", false); session.put("isBattlePowerFull", false); session.put("isBattlePowerOut", false); session.put("isBattlePointEnough", false); session.put("isLimitedOpen", false); } @Override protected String getHost() { return Tnk47Robot.HOST; } public boolean isStampGachaEnable() { final String key = "Tnk47Robot.stampGachaEnable"; final String value = this.getConfig().getProperty(key, "false"); return Boolean.valueOf(value); } public boolean isMarathonEnable() { final String key = "Tnk47Robot.marathonEnable"; final String value = this.getConfig().getProperty(key, "false"); return Boolean.valueOf(value); } public boolean isRaidEnable() { final String key = "Tnk47Robot.raidEnable"; final String value = this.getConfig().getProperty(key, "false"); return Boolean.valueOf(value); } public boolean isPointRaceEnable() { final String key = "Tnk47Robot.pointRaceEnable"; final String value = this.getConfig().getProperty(key, "false"); return Boolean.valueOf(value); } public boolean isGuildBattleEnable() { final String key = "Tnk47Robot.guildBattleEnable"; final String value = this.getConfig().getProperty(key, "false"); return Boolean.valueOf(value); } public boolean isGiftEnable() { final String key = "Tnk47Robot.giftEnable"; final String value = this.getConfig().getProperty(key, "false"); return Boolean.valueOf(value); } public boolean isQuestEnable() { final String key = "Tnk47Robot.questEnable"; final String value = this.getConfig().getProperty(key, "false"); return Boolean.valueOf(value); } public boolean isBattleEnable() { final String key = "Tnk47Robot.battleEnable"; final String value = this.getConfig().getProperty(key, "false"); return Boolean.valueOf(value); } public boolean isUpgradeEnable() { final String key = "Tnk47Robot.upgradeEnable"; final String value = this.getConfig().getProperty(key, "false"); return Boolean.valueOf(value); } public boolean isUseTodayPowerRegenItem() { final String key = "Tnk47Robot.useTodayPowerRegenItem"; final String value = this.getConfig().getProperty(key, "false"); return Boolean.valueOf(value); } public boolean isUseHalfPowerRegenItem() { final String key = "Tnk47Robot.useHalfPowerRegenItem"; final String value = this.getConfig().getProperty(key, "false"); return Boolean.valueOf(value); } public boolean isUseFullPowerRegenItem() { final String key = "Tnk47Robot.useFullPowerRegenItem"; final String value = this.getConfig().getProperty(key, "false"); return Boolean.valueOf(value); } public boolean isAutoSelectStage() { final String key = "Tnk47Robot.autoSelectStage"; final String value = this.getConfig().getProperty(key, "true"); return Boolean.valueOf(value); } public String getSelectedQuestId() { final String key = "Tnk47Robot.selectedQuestId"; final String value = this.getConfig().getProperty(key, "1"); return value; } public String getSelectedAreaId() { final String key = "Tnk47Robot.selectedAreaId"; final String value = this.getConfig().getProperty(key, "1"); return value; } public String getSelectedStageId() { final String key = "Tnk47Robot.selectedStageId"; final String value = this.getConfig().getProperty(key, "1"); return value; } public boolean isUseStaminaToday() { final String key = "Tnk47Robot.useStaminaToday"; final String value = this.getConfig().getProperty(key, "false"); return Boolean.valueOf(value); } public boolean isUseStamina50() { final String key = "Tnk47Robot.useStamina50"; final String value = this.getConfig().getProperty(key, "false"); return Boolean.valueOf(value); } public boolean isUseStamina100() { final String key = "Tnk47Robot.useStamina100"; final String value = this.getConfig().getProperty(key, "false"); return Boolean.valueOf(value); } public int getStaminaUpLimit() { final String key = "Tnk47Robot.staminaUpLimit"; final String value = this.getConfig().getProperty(key, "0"); return Integer.valueOf(value); } public int getPowerUpLimit() { final String key = "Tnk47Robot.powerUpLimit"; final String value = this.getConfig().getProperty(key, "0"); return Integer.valueOf(value); } public int getMinBattlePoint() { final String key = "Tnk47Robot.minBattlePoint"; final String value = this.getConfig().getProperty(key, "0"); return Integer.valueOf(value); } public int getBattlePointFilter() { final String key = "Tnk47Robot.battlePointFilter"; final String value = this.getConfig().getProperty(key, "0"); return Integer.valueOf(value); } public String getNotificationUser() { final String key = "Tnk47Robot.notificationUser"; final String value = this.getConfig().getProperty(key); return value; } public boolean isUseGiveItemToday() { final String key = "Tnk47Robot.useGiveItemToday"; final String value = this.getConfig().getProperty(key, "false"); return Boolean.valueOf(value); } public boolean isUseGiveItem() { final String key = "Tnk47Robot.useGiveItem"; final String value = this.getConfig().getProperty(key, "false"); return Boolean.valueOf(value); } public boolean isOnlyGiveOne() { final String key = "Tnk47Robot.onlyGiveOne"; final String value = this.getConfig().getProperty(key, "false"); return Boolean.valueOf(value); } public int getUseStaminaRatio() { final String key = "Tnk47Robot.useStaminaRatio"; final String value = this.getConfig().getProperty(key, "75"); return Integer.valueOf(value); } public boolean isRaidLimitOpen() { final String key = "Tnk47Robot.raidLimitOpen"; final String value = this.getConfig().getProperty(key, "false"); return Boolean.valueOf(value); } public boolean isUseRaidRegenItem() { final String key = "Tnk47Robot.useRaidRegenItem"; final String value = this.getConfig().getProperty(key, "false"); return Boolean.valueOf(value); } public boolean isUseRaidSpecialAttack() { final String key = "Tnk47Robot.useRaidSpecialAttack"; final String value = this.getConfig().getProperty(key, "false"); return Boolean.valueOf(value); } public int getMinDamageRatio() { final String key = "Tnk47Robot.minDamageRatio"; final String value = this.getConfig().getProperty(key, "4"); return Integer.valueOf(value); } public boolean isEcoMode() { final String key = "Tnk47Robot.ecoMode"; final String value = this.getConfig().getProperty(key, "true"); return Boolean.valueOf(value); } public boolean isGachaEnable() { final String key = "Tnk47Robot.gachaEnable"; final String value = this.getConfig().getProperty(key, "false"); return Boolean.valueOf(value); } public boolean isDuelEnable() { final String key = "Tnk47Robot.duelEnable"; final String value = this.getConfig().getProperty(key, "false"); return Boolean.valueOf(value); } public boolean isConquestEnable() { final String key = "Tnk47Robot.conquestEnable"; final String value = this.getConfig().getProperty(key, "false"); return Boolean.valueOf(value); } }
src/main/java/robot/tnk47/Tnk47Robot.java
main robot
src/main/java/robot/tnk47/Tnk47Robot.java
main robot
<ide><path>rc/main/java/robot/tnk47/Tnk47Robot.java <add>package robot.tnk47; <add> <add>import java.util.Map; <add> <add>import robot.AbstractRobot; <add>import robot.LoginHandler; <add>import robot.tnk47.battle.BattleAnimationHandler; <add>import robot.tnk47.battle.BattleCheckHandler; <add>import robot.tnk47.battle.BattleDetailHandler; <add>import robot.tnk47.battle.BattleHandler; <add>import robot.tnk47.battle.BattleResultHandler; <add>import robot.tnk47.battle.PrefectureBattleListHandler; <add>import robot.tnk47.battle.PrefectureBattleResultHandler; <add>import robot.tnk47.conquest.ConquestAnimationHandler; <add>import robot.tnk47.conquest.ConquestAreaTopHandler; <add>import robot.tnk47.conquest.ConquestBattleCheckHandler; <add>import robot.tnk47.conquest.ConquestBattleHandler; <add>import robot.tnk47.conquest.ConquestBattleListHandler; <add>import robot.tnk47.conquest.ConquestHandler; <add>import robot.tnk47.conquest.ConquestResultHandler; <add>import robot.tnk47.duel.DuelBattleAnimationHandler; <add>import robot.tnk47.duel.DuelBattleCheckHandler; <add>import robot.tnk47.duel.DuelBattleResultHandler; <add>import robot.tnk47.duel.DuelBattleSelectHandler; <add>import robot.tnk47.duel.DuelHandler; <add>import robot.tnk47.gacha.BattleGachaHandler; <add>import robot.tnk47.gacha.BoxGachaHandler; <add>import robot.tnk47.gacha.GachaHandler; <add>import robot.tnk47.gacha.StampGachaHandler; <add>import robot.tnk47.gacha.TicketGachaHandler; <add>import robot.tnk47.guildbattle.GuildBattleAnimationHandler; <add>import robot.tnk47.guildbattle.GuildBattleChargeHandler; <add>import robot.tnk47.guildbattle.GuildBattleCheckHandler; <add>import robot.tnk47.guildbattle.GuildBattleHandler; <add>import robot.tnk47.guildbattle.GuildBattleResultHandler; <add>import robot.tnk47.guildbattle.GuildBattleSelectHandler; <add>import robot.tnk47.guildbattle.GuildBattleSkillHandler; <add>import robot.tnk47.marathon.MarathonHandler; <add>import robot.tnk47.marathon.MarathonMissionAnimationHandler; <add>import robot.tnk47.marathon.MarathonMissionHandler; <add>import robot.tnk47.marathon.MarathonMissionResultHandler; <add>import robot.tnk47.marathon.MarathonNotificationHandler; <add>import robot.tnk47.marathon.MarathonStageBossHandler; <add>import robot.tnk47.marathon.MarathonStageDetailHandler; <add>import robot.tnk47.marathon.MarathonStageForwardHandler; <add>import robot.tnk47.marathon.MarathonStageHandler; <add>import robot.tnk47.quest.QuestBossHandler; <add>import robot.tnk47.quest.QuestHandler; <add>import robot.tnk47.quest.QuestStageDetailHandler; <add>import robot.tnk47.quest.QuestStageForwardHandler; <add>import robot.tnk47.quest.QuestStatusUpHandler; <add>import robot.tnk47.raid.RaidBattleAnimationHandler; <add>import robot.tnk47.raid.RaidBattleEncountHandler; <add>import robot.tnk47.raid.RaidBattleHandler; <add>import robot.tnk47.raid.RaidBattleResultHandler; <add>import robot.tnk47.raid.RaidHandler; <add>import robot.tnk47.raid.RaidStageForwardHandler; <add>import robot.tnk47.raid.RaidStageHandler; <add>import robot.tnk47.raid.model.RaidBattleDamageMap; <add>import robot.tnk47.upgrade.UpgradeAnimationHandler; <add>import robot.tnk47.upgrade.UpgradeAutoConfirmHandler; <add>import robot.tnk47.upgrade.UpgradeHandler; <add>import robot.tnk47.upgrade.UpgradeSelectBaseHandler; <add> <add>public class Tnk47Robot extends AbstractRobot { <add> <add> public static final String HOST = "http://tnk47.ameba.jp"; <add> <add> public static final String VERSION = "天下自动脚本 11.0"; <add> <add> @Override <add> public void initHandlers() { <add> this.registerHandler("/", new HomeHandler(this)); <add> this.registerHandler("/login", new LoginHandler(this)); <add> this.registerHandler("/mypage", new MypageHandler(this)); <add> this.registerHandler("/event-infomation", <add> new EventInfomationHandler(this)); <add> this.registerHandler("/gacha", new GachaHandler(this)); <add> this.registerHandler("/gacha/ticket-gacha", <add> new TicketGachaHandler(this)); <add> this.registerHandler("/gacha/box-gacha", new BoxGachaHandler(this)); <add> this.registerHandler("/gacha/stamp-gacha", new StampGachaHandler(this)); <add> this.registerHandler("/gacha/battle-gacha", <add> new BattleGachaHandler(this)); <add> // <add> this.registerHandler("/gift", new GiftHandler(this)); <add> // 控制器:合战活动 <add> this.registerHandler("/pointrace", new BattleHandler(this)); <add> // 控制器:合战 <add> this.registerHandler("/battle", new BattleHandler(this)); <add> this.registerHandler("/battle/detail", new BattleDetailHandler(this)); <add> this.registerHandler("/battle/battle-check", <add> new BattleCheckHandler(this)); <add> this.registerHandler("/battle/battle-animation", <add> new BattleAnimationHandler(this)); <add> this.registerHandler("/battle/battle-result", <add> new BattleResultHandler(this)); <add> this.registerHandler("/battle/prefecture-battle-list", <add> new PrefectureBattleListHandler(this)); <add> this.registerHandler("/battle/prefecture-battle-result", <add> new PrefectureBattleResultHandler(this)); <add> // 控制器:冒险 <add> this.registerHandler("/quest", new QuestHandler(this)); <add> this.registerHandler("/quest/stage/detail", <add> new QuestStageDetailHandler(this)); <add> this.registerHandler("/quest/stage/forward", <add> new QuestStageForwardHandler(this)); <add> this.registerHandler("/quest/boss-animation", <add> new QuestBossHandler(this)); <add> this.registerHandler("/use-item", new UseItemHandler(this)); <add> this.registerHandler("/status-up", new QuestStatusUpHandler(this)); <add> // 控制器:爬塔活动 <add> this.registerHandler("/marathon", new MarathonHandler(this)); <add> this.registerHandler("/marathon/stage", new MarathonStageHandler(this)); <add> this.registerHandler("/marathon/stage/detail", <add> new MarathonStageDetailHandler(this)); <add> this.registerHandler("/marathon/stage/forward", <add> new MarathonStageForwardHandler(this)); <add> this.registerHandler("/marathon/stage/boss", <add> new MarathonStageBossHandler(this)); <add> this.registerHandler("/marathon/mission", <add> new MarathonMissionHandler(this)); <add> this.registerHandler("/marathon/mission/animation", <add> new MarathonMissionAnimationHandler(this)); <add> this.registerHandler("/marathon/mission/result", <add> new MarathonMissionResultHandler(this)); <add> this.registerHandler("/marathon/notification", <add> new MarathonNotificationHandler(this)); <add> // 强化 <add> this.registerHandler("/upgrade", new UpgradeHandler(this)); <add> this.registerHandler("/upgrade/select-base", <add> new UpgradeSelectBaseHandler(this)); <add> this.registerHandler("/upgrade/auto-upgrade-confirm", <add> new UpgradeAutoConfirmHandler(this)); <add> this.registerHandler("/upgrade/upgrade-animation", <add> new UpgradeAnimationHandler(this)); <add> <add> // 控制器:RAID <add> final RaidBattleDamageMap damageMap = new RaidBattleDamageMap(); <add> this.registerHandler("/raid", new RaidHandler(this, damageMap)); <add> this.registerHandler("/raid/battle", new RaidBattleHandler(this, <add> damageMap)); <add> this.registerHandler("/raid/battle-animation", <add> new RaidBattleAnimationHandler(this, damageMap)); <add> this.registerHandler("/raid/battle-result", <add> new RaidBattleResultHandler(this, damageMap)); <add> this.registerHandler("/raid/battle-encount", <add> new RaidBattleEncountHandler(this, damageMap)); <add> this.registerHandler("/raid/stage", new RaidStageHandler(this)); <add> this.registerHandler("/raid/stage-forward", <add> new RaidStageForwardHandler(this)); <add> <add> // 控制器:戦神リーグ <add> this.registerHandler("/duel", new DuelHandler(this)); <add> this.registerHandler("/duel/duel-battle-select", <add> new DuelBattleSelectHandler(this)); <add> this.registerHandler("/duel/duel-battle-check", <add> new DuelBattleCheckHandler(this)); <add> this.registerHandler("/duel/duel-battle-animation", <add> new DuelBattleAnimationHandler(this)); <add> this.registerHandler("/duel/duel-battle-result", <add> new DuelBattleResultHandler(this)); <add> <add> // 控制器:同盟戦 <add> this.registerHandler("/guildbattle", new GuildBattleHandler(this)); <add> this.registerHandler("/guildbattle/charge", <add> new GuildBattleChargeHandler(this)); <add> this.registerHandler("/guildbattle/skill", <add> new GuildBattleSkillHandler(this)); <add> this.registerHandler("/guildbattle/select", <add> new GuildBattleSelectHandler(this)); <add> this.registerHandler("/guildbattle/check", <add> new GuildBattleCheckHandler(this)); <add> this.registerHandler("/guildbattle/animation", <add> new GuildBattleAnimationHandler(this)); <add> this.registerHandler("/guildbattle/result", <add> new GuildBattleResultHandler(this)); <add> <add> // 控制器:天下統一戦 <add> this.registerHandler("/conquest", new ConquestHandler(this)); <add> this.registerHandler("/conquest/area-top", <add> new ConquestAreaTopHandler(this)); <add> this.registerHandler("/conquest/battle-list", <add> new ConquestBattleListHandler(this)); <add> this.registerHandler("/conquest/battle-check", <add> new ConquestBattleCheckHandler(this)); <add> this.registerHandler("/conquest/battle-animation", <add> new ConquestAnimationHandler(this)); <add> this.registerHandler("/conquest/conquest-result", <add> new ConquestResultHandler(this)); <add> this.registerHandler("/conquest/battle", <add> new ConquestBattleHandler(this)); <add> } <add> <add> @Override <add> public void reset() { <add> final Map<String, Object> session = this.getSession(); <add> session.put("isMypage", false); <add> session.put("isStampGachaEnable", this.isStampGachaEnable()); <add> session.put("isGachaEnable", this.isGachaEnable()); <add> session.put("isGiftEnable", this.isGiftEnable()); <add> session.put("isQuestEnable", this.isQuestEnable()); <add> session.put("isBattleEnable", this.isBattleEnable()); <add> session.put("isUpgradeEnable", this.isUpgradeEnable()); <add> session.put("isDuelEnable", this.isDuelEnable()); <add> <add> session.put("isEventEnable", true); <add> session.put("isMarathonEnable", this.isMarathonEnable()); <add> session.put("isPointRaceEnable", this.isPointRaceEnable()); <add> session.put("isRaidEnable", this.isRaidEnable()); <add> session.put("isGuildBattleEnable", this.isGuildBattleEnable()); <add> session.put("isConquestEnable", this.isConquestEnable()); <add> <add> session.put("isQuestCardFull", false); <add> session.put("isQuestFindAll", false); <add> session.put("isPointRace", false); <add> session.put("isBattlePowerFull", false); <add> session.put("isBattlePowerOut", false); <add> session.put("isBattlePointEnough", false); <add> session.put("isLimitedOpen", false); <add> } <add> <add> @Override <add> protected String getHost() { <add> return Tnk47Robot.HOST; <add> } <add> <add> public boolean isStampGachaEnable() { <add> final String key = "Tnk47Robot.stampGachaEnable"; <add> final String value = this.getConfig().getProperty(key, "false"); <add> return Boolean.valueOf(value); <add> } <add> <add> public boolean isMarathonEnable() { <add> final String key = "Tnk47Robot.marathonEnable"; <add> final String value = this.getConfig().getProperty(key, "false"); <add> return Boolean.valueOf(value); <add> } <add> <add> public boolean isRaidEnable() { <add> final String key = "Tnk47Robot.raidEnable"; <add> final String value = this.getConfig().getProperty(key, "false"); <add> return Boolean.valueOf(value); <add> } <add> <add> public boolean isPointRaceEnable() { <add> final String key = "Tnk47Robot.pointRaceEnable"; <add> final String value = this.getConfig().getProperty(key, "false"); <add> return Boolean.valueOf(value); <add> } <add> <add> public boolean isGuildBattleEnable() { <add> final String key = "Tnk47Robot.guildBattleEnable"; <add> final String value = this.getConfig().getProperty(key, "false"); <add> return Boolean.valueOf(value); <add> } <add> <add> public boolean isGiftEnable() { <add> final String key = "Tnk47Robot.giftEnable"; <add> final String value = this.getConfig().getProperty(key, "false"); <add> return Boolean.valueOf(value); <add> } <add> <add> public boolean isQuestEnable() { <add> final String key = "Tnk47Robot.questEnable"; <add> final String value = this.getConfig().getProperty(key, "false"); <add> return Boolean.valueOf(value); <add> } <add> <add> public boolean isBattleEnable() { <add> final String key = "Tnk47Robot.battleEnable"; <add> final String value = this.getConfig().getProperty(key, "false"); <add> return Boolean.valueOf(value); <add> } <add> <add> public boolean isUpgradeEnable() { <add> final String key = "Tnk47Robot.upgradeEnable"; <add> final String value = this.getConfig().getProperty(key, "false"); <add> return Boolean.valueOf(value); <add> } <add> <add> public boolean isUseTodayPowerRegenItem() { <add> final String key = "Tnk47Robot.useTodayPowerRegenItem"; <add> final String value = this.getConfig().getProperty(key, "false"); <add> return Boolean.valueOf(value); <add> } <add> <add> public boolean isUseHalfPowerRegenItem() { <add> final String key = "Tnk47Robot.useHalfPowerRegenItem"; <add> final String value = this.getConfig().getProperty(key, "false"); <add> return Boolean.valueOf(value); <add> } <add> <add> public boolean isUseFullPowerRegenItem() { <add> final String key = "Tnk47Robot.useFullPowerRegenItem"; <add> final String value = this.getConfig().getProperty(key, "false"); <add> return Boolean.valueOf(value); <add> } <add> <add> public boolean isAutoSelectStage() { <add> final String key = "Tnk47Robot.autoSelectStage"; <add> final String value = this.getConfig().getProperty(key, "true"); <add> return Boolean.valueOf(value); <add> } <add> <add> public String getSelectedQuestId() { <add> final String key = "Tnk47Robot.selectedQuestId"; <add> final String value = this.getConfig().getProperty(key, "1"); <add> return value; <add> } <add> <add> public String getSelectedAreaId() { <add> final String key = "Tnk47Robot.selectedAreaId"; <add> final String value = this.getConfig().getProperty(key, "1"); <add> return value; <add> } <add> <add> public String getSelectedStageId() { <add> final String key = "Tnk47Robot.selectedStageId"; <add> final String value = this.getConfig().getProperty(key, "1"); <add> return value; <add> } <add> <add> public boolean isUseStaminaToday() { <add> final String key = "Tnk47Robot.useStaminaToday"; <add> final String value = this.getConfig().getProperty(key, "false"); <add> return Boolean.valueOf(value); <add> } <add> <add> public boolean isUseStamina50() { <add> final String key = "Tnk47Robot.useStamina50"; <add> final String value = this.getConfig().getProperty(key, "false"); <add> return Boolean.valueOf(value); <add> } <add> <add> public boolean isUseStamina100() { <add> final String key = "Tnk47Robot.useStamina100"; <add> final String value = this.getConfig().getProperty(key, "false"); <add> return Boolean.valueOf(value); <add> } <add> <add> public int getStaminaUpLimit() { <add> final String key = "Tnk47Robot.staminaUpLimit"; <add> final String value = this.getConfig().getProperty(key, "0"); <add> return Integer.valueOf(value); <add> } <add> <add> public int getPowerUpLimit() { <add> final String key = "Tnk47Robot.powerUpLimit"; <add> final String value = this.getConfig().getProperty(key, "0"); <add> return Integer.valueOf(value); <add> } <add> <add> public int getMinBattlePoint() { <add> final String key = "Tnk47Robot.minBattlePoint"; <add> final String value = this.getConfig().getProperty(key, "0"); <add> return Integer.valueOf(value); <add> } <add> <add> public int getBattlePointFilter() { <add> final String key = "Tnk47Robot.battlePointFilter"; <add> final String value = this.getConfig().getProperty(key, "0"); <add> return Integer.valueOf(value); <add> } <add> <add> public String getNotificationUser() { <add> final String key = "Tnk47Robot.notificationUser"; <add> final String value = this.getConfig().getProperty(key); <add> return value; <add> } <add> <add> public boolean isUseGiveItemToday() { <add> final String key = "Tnk47Robot.useGiveItemToday"; <add> final String value = this.getConfig().getProperty(key, "false"); <add> return Boolean.valueOf(value); <add> } <add> <add> public boolean isUseGiveItem() { <add> final String key = "Tnk47Robot.useGiveItem"; <add> final String value = this.getConfig().getProperty(key, "false"); <add> return Boolean.valueOf(value); <add> } <add> <add> public boolean isOnlyGiveOne() { <add> final String key = "Tnk47Robot.onlyGiveOne"; <add> final String value = this.getConfig().getProperty(key, "false"); <add> return Boolean.valueOf(value); <add> } <add> <add> public int getUseStaminaRatio() { <add> final String key = "Tnk47Robot.useStaminaRatio"; <add> final String value = this.getConfig().getProperty(key, "75"); <add> return Integer.valueOf(value); <add> } <add> <add> public boolean isRaidLimitOpen() { <add> final String key = "Tnk47Robot.raidLimitOpen"; <add> final String value = this.getConfig().getProperty(key, "false"); <add> return Boolean.valueOf(value); <add> } <add> <add> public boolean isUseRaidRegenItem() { <add> final String key = "Tnk47Robot.useRaidRegenItem"; <add> final String value = this.getConfig().getProperty(key, "false"); <add> return Boolean.valueOf(value); <add> } <add> <add> public boolean isUseRaidSpecialAttack() { <add> final String key = "Tnk47Robot.useRaidSpecialAttack"; <add> final String value = this.getConfig().getProperty(key, "false"); <add> return Boolean.valueOf(value); <add> } <add> <add> public int getMinDamageRatio() { <add> final String key = "Tnk47Robot.minDamageRatio"; <add> final String value = this.getConfig().getProperty(key, "4"); <add> return Integer.valueOf(value); <add> } <add> <add> public boolean isEcoMode() { <add> final String key = "Tnk47Robot.ecoMode"; <add> final String value = this.getConfig().getProperty(key, "true"); <add> return Boolean.valueOf(value); <add> } <add> <add> public boolean isGachaEnable() { <add> final String key = "Tnk47Robot.gachaEnable"; <add> final String value = this.getConfig().getProperty(key, "false"); <add> return Boolean.valueOf(value); <add> } <add> <add> public boolean isDuelEnable() { <add> final String key = "Tnk47Robot.duelEnable"; <add> final String value = this.getConfig().getProperty(key, "false"); <add> return Boolean.valueOf(value); <add> } <add> <add> public boolean isConquestEnable() { <add> final String key = "Tnk47Robot.conquestEnable"; <add> final String value = this.getConfig().getProperty(key, "false"); <add> return Boolean.valueOf(value); <add> } <add>}
JavaScript
apache-2.0
ec81ea4e9ac1e26e29c9162b04afe64f8bfcecba
0
alinarezrangel/cnatural,alinarezrangel/cnatural,alinarezrangel/cnatural,alinarezrangel/cnatural
/************************************************ ********************** *** CNatural: Remote embed systems control. *** * Native Desktop Environment (natural window system). ********************** Copyright 2016 Alejandro Linarez Rangel 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. ********************** ************************************************/ (function() { var natsec = function(window, document) { if(typeof window.NaturalObject === "undefined") { throw new Error("Error at CNatural.JS.Desktop.Native.Window.System: NaturalObject is undefined"); } if(typeof window.NaturalShell.Base.WindowSystem === "undefined") { throw new Error("Error at CNatural.JS.Desktop.Native.Window.System: NaturalShell.WindowSystem is undefined"); } window.NaturalShell = window.NaturalShell || {}; window.NaturalShell.Native = window.NaturalShell.Native || {}; window.NaturalShell.Native.NaturalWindowSystem = function(context, manager) { window.NaturalShell.Base.WindowSystem.call(this, context, manager); }; window.NaturalShell.Native.NaturalWindowSystem.prototype = Object.create(window.NaturalShell.Base.WindowSystem.prototype); window.NaturalShell.Native.NaturalWindowSystem.prototype.createDefaultWindow = function(title, appdata) { var normal = function(winel, appdata) { var titlebar = document.createElement("div"); var titlebarCloseOrBackButton = document.createElement("span"); var titlebarTitle = document.createElement("h2"); var titlebarMenuButton = document.createElement("span"); var body = document.createElement("div"); var parentWindow = null; var makeIcon = function(iconName) { var sp = document.createElement("span"); sp.className = "gui-font-iconset-v2"; sp.appendChild(document.createTextNode(iconName)); return sp; }; titlebar.className = "gui-widget-window-header gui-flexcore-row no-margin od-1"; titlebar.dataset["widget"] = "window-header"; titlebarCloseOrBackButton.className = "gui-font-iconset-v2 color-gui-window-close-button flat-button od-1 text-jumbo gui-clickeable padding-2 margin-8 color-transparent gui-shape-circle gui-circular-button-50"; titlebarCloseOrBackButton.dataset["widget"] = "button"; titlebarTitle.className = "text-jumbo font-bold od-2 fx-1 margin-8 color-transparent"; titlebarTitle.dataset["widget"] = "text"; titlebarMenuButton.className = "gui-font-iconset-v2 color-gui-window-menu-button flat-button od-3 text-jumbo gui-clickeable padding-2 margin-8 color-transparent gui-shape-circle gui-circular-button-50"; titlebarMenuButton.dataset["widget"] = "button"; body.className = "gui-widget-window-body container overflow-hide border no-padding no-margin od-2 fx-1 force-relative"; body.dataset["widget"] = "window-body"; if(appdata.mainWindowCreated) { titlebarCloseOrBackButton.appendChild(document.createTextNode("back")); } else { titlebarCloseOrBackButton.appendChild(document.createTextNode("close")); } titlebarMenuButton.appendChild(document.createTextNode("menu")); titlebarTitle.appendChild(document.createTextNode(title)); titlebar.appendChild(titlebarCloseOrBackButton); titlebar.appendChild(titlebarTitle); titlebar.appendChild(titlebarMenuButton); winel.appendChild(titlebar); winel.appendChild(body); return { "titlebar": titlebar, "titlebarCloseOrBackButton": titlebarCloseOrBackButton, "titlebarMenuButton": titlebarMenuButton, "titlebarTitle": titlebarTitle, "body": body }; }; return this.createCustomWindow(normal, appdata); }; window.NaturalShell.Native.NaturalWindowSystem.prototype.createCustomWindow = function(callback, appdata) { var winel = document.createElement("div"); var menu = document.createElement("div"); var menuSideNav = document.createElement("div"); var menuSideNavCloseMenu = document.createElement("span"); var menuSideNavCloseWindow = document.createElement("span"); var menuSideNavMinimizeWindow = document.createElement("span"); var resmap = { titlebar: null, titlebarCloseOrBackButton: null, titlebarMenuButton: null, titlebarTitle: null, body: null, result: null }; var parentWindow = null; var makeIcon = function(iconName) { var sp = document.createElement("span"); sp.className = "gui-font-iconset-v2"; sp.appendChild(document.createTextNode(iconName)); return sp; }; winel.className = "gui-widget-window no-padding no-margin force-relative"; winel.dataset["widget"] = "window"; winel.dataset["name"] = appdata.applicationName; winel.dataset["ns"] = appdata.namespace; winel.dataset["appid"] = appdata.applicationID; winel.dataset["instanceId"] = appdata.instanceID.toString(); winel.dataset["windowId"] = appdata.windowID.toString(); appdata.windowID++; menu.className = "gui-widget-window-menu container padding-8 no-margin card gui-hidden"; menu.dataset["widget"] = "window-menu"; // menuSideNav.className = "side-navigation border-bottom bs-2 border-color-natural-black"; menuSideNav.className = "row wrap padding-4 border-bottom bs-2 border-color-natural-black color-transparent"; menuSideNav.dataset["widget"] = "window-menu-native"; menuSideNavCloseMenu.className = menuSideNavCloseWindow.className = menuSideNavMinimizeWindow.className = "col flat-button text-jumbo padding-16 fx-1"; menuSideNavCloseMenu.dataset["widget"] = menuSideNavCloseWindow.dataset["widget"] = menuSideNavMinimizeWindow.dataset["widget"] = "button"; menuSideNavCloseMenu.classList.add("od-1"); menuSideNavCloseWindow.classList.add("od-2"); menuSideNavMinimizeWindow.classList.add("od-3"); menuSideNavCloseMenu.appendChild(makeIcon("back")); // menuSideNavCloseMenu.appendChild(document.createTextNode("Close menu")); menuSideNavCloseWindow.appendChild(makeIcon("close")); // menuSideNavCloseWindow.appendChild(document.createTextNode("Close Window")); menuSideNavMinimizeWindow.appendChild(makeIcon("minimize")); // menuSideNavMinimizeWindow.appendChild(document.createTextNode("Minimize window")); menuSideNav.appendChild(menuSideNavCloseMenu); menuSideNav.appendChild(menuSideNavCloseWindow); menuSideNav.appendChild(menuSideNavMinimizeWindow); menu.appendChild(menuSideNav); resmap = callback(winel, appdata); winel.appendChild(menu); if(appdata.mainWindowCreated) { parentWindow = appdata.mainWindow; } else { appdata.mainWindowCreated = true; } var win = new window.NaturalShell.Native.NaturalWindow(parentWindow, appdata, window.$natural.wrap(winel)); this.initWindowEvents( win, winel, resmap.titlebar, resmap.titlebarCloseOrBackButton, resmap.titlebarMenuButton, resmap.body, menu, menuSideNavCloseMenu, menuSideNavCloseWindow, menuSideNavMinimizeWindow ); if(parentWindow === null) { appdata.mainWindow = win; } this.getWindowManager().packWindowAsToplevel(win.getWMElement()); return win; }; window.NaturalShell.Native.NaturalWindowSystem.prototype.destroyWindow = function(windowObject) { return this.destroyCustomWindow(windowObject); }; window.NaturalShell.Native.NaturalWindowSystem.prototype.destroyCustomWindow = function(windowObject) { var params = {}; var canBeRemoved = true; windowObject.apply((windowObject) => { canBeRemoved = canBeRemoved && windowObject.original.dispatchEvent(new CustomEvent("close", params)); }).forEach(); if(canBeRemoved) { this.getWindowManager().unpackWindow(this.getEqualsCallback(windowObject)); return true; } return false; }; window.NaturalShell.Native.NaturalWindowSystem.prototype.getEqualsCallback = function(windowObject) { return (windowElement) => { return ((windowElement.data("instanceId") == windowObject.data("instanceId")) && (windowElement.data("windowId") == windowObject.data("windowId")) && (windowElement.data("appid") == windowObject.data("appid")) && (windowElement.data("ns") == windowObject.data("ns"))); }; }; window.NaturalShell.Native.NaturalWindowSystem.prototype.initWindowEvents = function( windowObject, windowElement, titlebar, titlebarCloseOrBackButton, titlebarMenuButton, body, menu, menuSideNavCloseMenu, menuSideNavCloseWindow, menuSideNavMinimizeWindow ) { windowElement = window.$natural.wrap(windowElement); menu = window.$natural.wrap(menu); menuSideNavCloseMenu = window.$natural.wrap(menuSideNavCloseMenu); menuSideNavCloseWindow = window.$natural.wrap(menuSideNavCloseWindow); menuSideNavMinimizeWindow = window.$natural.wrap(menuSideNavMinimizeWindow); if(titlebar !== null) { titlebar = window.$natural.wrap(titlebar); titlebarCloseOrBackButton = window.$natural.wrap(titlebarCloseOrBackButton); titlebarMenuButton = window.$natural.wrap(titlebarMenuButton); titlebarCloseOrBackButton.attach(() => { this.destroyWindow(windowElement); }).on("click"); titlebarMenuButton.attach(() => { menu.showMoveFromTopToCenter(); }).on("click"); } menuSideNavCloseMenu.attach(() => { menu.hideMoveFromCenterToTop(); }).on("click"); menuSideNavCloseWindow.attach(() => { menu.hideMoveFromCenterToTop(); this.destroyWindow(windowElement); }).on("click"); menuSideNavMinimizeWindow.attach(() => { menu.hideMoveFromCenterToTop(); windowElement.addClass("gui-hidden"); }).on("click"); windowElement.attach((ev) => { menu.showMoveFromTopToCenter(); ev.preventDefault(); }).on("contextmenu"); }; }; if(typeof module !== "undefined") { module.exports = natsec; // NodeJS, AngularJS, NativeScript, RequireJS, etc } else { natsec(window, document); // Browser JS } }());
private_http/jscore/shells/native/natural_window_system.js
/************************************************ ********************** *** CNatural: Remote embed systems control. *** * Native Desktop Environment (natural window system). ********************** Copyright 2016 Alejandro Linarez Rangel 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. ********************** ************************************************/ (function() { var natsec = function(window, document) { if(typeof window.NaturalObject === "undefined") { throw new Error("Error at CNatural.JS.Desktop.Native.Window.System: NaturalObject is undefined"); } if(typeof window.NaturalShell.Base.WindowSystem === "undefined") { throw new Error("Error at CNatural.JS.Desktop.Native.Window.System: NaturalShell.WindowSystem is undefined"); } window.NaturalShell = window.NaturalShell || {}; window.NaturalShell.Native = window.NaturalShell.Native || {}; window.NaturalShell.Native.NaturalWindowSystem = function(context, manager) { window.NaturalShell.Base.WindowSystem.call(this, context, manager); }; window.NaturalShell.Native.NaturalWindowSystem.prototype = Object.create(window.NaturalShell.Base.WindowSystem.prototype); window.NaturalShell.Native.NaturalWindowSystem.prototype.createDefaultWindow = function(title, appdata) { var normal = function(winel, appdata) { var titlebar = document.createElement("div"); var titlebarCloseOrBackButton = document.createElement("span"); var titlebarTitle = document.createElement("h2"); var titlebarMenuButton = document.createElement("span"); var body = document.createElement("div"); var parentWindow = null; var makeIcon = function(iconName) { var sp = document.createElement("span"); sp.className = "gui-font-iconset-v2"; sp.appendChild(document.createTextNode(iconName)); return sp; }; titlebar.className = "gui-widget-window-header gui-flexcore-row no-margin od-1"; titlebar.dataset["widget"] = "window-header"; titlebarCloseOrBackButton.className = "gui-font-iconset-v2 color-gui-window-close-button flat-button od-1 text-jumbo gui-clickeable padding-2 margin-8 color-transparent gui-shape-circle gui-circular-button-50"; titlebarCloseOrBackButton.dataset["widget"] = "button"; titlebarTitle.className = "text-jumbo font-bold od-2 fx-1 margin-8 color-transparent"; titlebarTitle.dataset["widget"] = "text"; titlebarMenuButton.className = "gui-font-iconset-v2 color-gui-window-menu-button flat-button od-3 text-jumbo gui-clickeable padding-2 margin-8 color-transparent gui-shape-circle gui-circular-button-50"; titlebarMenuButton.dataset["widget"] = "button"; body.className = "gui-widget-window-body container overflow-auto border no-padding no-margin od-2 fx-1 force-relative"; body.dataset["widget"] = "window-body"; if(appdata.mainWindowCreated) { titlebarCloseOrBackButton.appendChild(document.createTextNode("back")); } else { titlebarCloseOrBackButton.appendChild(document.createTextNode("close")); } titlebarMenuButton.appendChild(document.createTextNode("menu")); titlebarTitle.appendChild(document.createTextNode(title)); titlebar.appendChild(titlebarCloseOrBackButton); titlebar.appendChild(titlebarTitle); titlebar.appendChild(titlebarMenuButton); winel.appendChild(titlebar); winel.appendChild(body); return { "titlebar": titlebar, "titlebarCloseOrBackButton": titlebarCloseOrBackButton, "titlebarMenuButton": titlebarMenuButton, "titlebarTitle": titlebarTitle, "body": body }; }; return this.createCustomWindow(normal, appdata); }; window.NaturalShell.Native.NaturalWindowSystem.prototype.createCustomWindow = function(callback, appdata) { var winel = document.createElement("div"); var menu = document.createElement("div"); var menuSideNav = document.createElement("div"); var menuSideNavCloseMenu = document.createElement("span"); var menuSideNavCloseWindow = document.createElement("span"); var menuSideNavMinimizeWindow = document.createElement("span"); var resmap = { titlebar: null, titlebarCloseOrBackButton: null, titlebarMenuButton: null, titlebarTitle: null, body: null, result: null }; var parentWindow = null; var makeIcon = function(iconName) { var sp = document.createElement("span"); sp.className = "gui-font-iconset-v2"; sp.appendChild(document.createTextNode(iconName)); return sp; }; winel.className = "gui-widget-window no-padding no-margin force-relative"; winel.dataset["widget"] = "window"; winel.dataset["name"] = appdata.applicationName; winel.dataset["ns"] = appdata.namespace; winel.dataset["appid"] = appdata.applicationID; winel.dataset["instanceId"] = appdata.instanceID.toString(); winel.dataset["windowId"] = appdata.windowID.toString(); appdata.windowID++; menu.className = "gui-widget-window-menu container padding-8 no-margin card gui-hidden"; menu.dataset["widget"] = "window-menu"; // menuSideNav.className = "side-navigation border-bottom bs-2 border-color-natural-black"; menuSideNav.className = "row wrap padding-4 border-bottom bs-2 border-color-natural-black color-transparent"; menuSideNav.dataset["widget"] = "window-menu-native"; menuSideNavCloseMenu.className = menuSideNavCloseWindow.className = menuSideNavMinimizeWindow.className = "col flat-button text-jumbo padding-16 fx-1"; menuSideNavCloseMenu.dataset["widget"] = menuSideNavCloseWindow.dataset["widget"] = menuSideNavMinimizeWindow.dataset["widget"] = "button"; menuSideNavCloseMenu.classList.add("od-1"); menuSideNavCloseWindow.classList.add("od-2"); menuSideNavMinimizeWindow.classList.add("od-3"); menuSideNavCloseMenu.appendChild(makeIcon("back")); // menuSideNavCloseMenu.appendChild(document.createTextNode("Close menu")); menuSideNavCloseWindow.appendChild(makeIcon("close")); // menuSideNavCloseWindow.appendChild(document.createTextNode("Close Window")); menuSideNavMinimizeWindow.appendChild(makeIcon("minimize")); // menuSideNavMinimizeWindow.appendChild(document.createTextNode("Minimize window")); menuSideNav.appendChild(menuSideNavCloseMenu); menuSideNav.appendChild(menuSideNavCloseWindow); menuSideNav.appendChild(menuSideNavMinimizeWindow); menu.appendChild(menuSideNav); resmap = callback(winel, appdata); winel.appendChild(menu); if(appdata.mainWindowCreated) { parentWindow = appdata.mainWindow; } else { appdata.mainWindowCreated = true; } var win = new window.NaturalShell.Native.NaturalWindow(parentWindow, appdata, window.$natural.wrap(winel)); this.initWindowEvents( win, winel, resmap.titlebar, resmap.titlebarCloseOrBackButton, resmap.titlebarMenuButton, resmap.body, menu, menuSideNavCloseMenu, menuSideNavCloseWindow, menuSideNavMinimizeWindow ); if(parentWindow === null) { appdata.mainWindow = win; } this.getWindowManager().packWindowAsToplevel(win.getWMElement()); return win; }; window.NaturalShell.Native.NaturalWindowSystem.prototype.destroyWindow = function(windowObject) { return this.destroyCustomWindow(windowObject); }; window.NaturalShell.Native.NaturalWindowSystem.prototype.destroyCustomWindow = function(windowObject) { var params = {}; var canBeRemoved = true; windowObject.apply((windowObject) => { canBeRemoved = canBeRemoved && windowObject.original.dispatchEvent(new CustomEvent("close", params)); }).forEach(); if(canBeRemoved) { this.getWindowManager().unpackWindow(this.getEqualsCallback(windowObject)); return true; } return false; }; window.NaturalShell.Native.NaturalWindowSystem.prototype.getEqualsCallback = function(windowObject) { return (windowElement) => { return ((windowElement.data("instanceId") == windowObject.data("instanceId")) && (windowElement.data("windowId") == windowObject.data("windowId")) && (windowElement.data("appid") == windowObject.data("appid")) && (windowElement.data("ns") == windowObject.data("ns"))); }; }; window.NaturalShell.Native.NaturalWindowSystem.prototype.initWindowEvents = function( windowObject, windowElement, titlebar, titlebarCloseOrBackButton, titlebarMenuButton, body, menu, menuSideNavCloseMenu, menuSideNavCloseWindow, menuSideNavMinimizeWindow ) { windowElement = window.$natural.wrap(windowElement); menu = window.$natural.wrap(menu); menuSideNavCloseMenu = window.$natural.wrap(menuSideNavCloseMenu); menuSideNavCloseWindow = window.$natural.wrap(menuSideNavCloseWindow); menuSideNavMinimizeWindow = window.$natural.wrap(menuSideNavMinimizeWindow); if(titlebar !== null) { titlebar = window.$natural.wrap(titlebar); titlebarCloseOrBackButton = window.$natural.wrap(titlebarCloseOrBackButton); titlebarMenuButton = window.$natural.wrap(titlebarMenuButton); titlebarCloseOrBackButton.attach(() => { this.destroyWindow(windowElement); }).on("click"); titlebarMenuButton.attach(() => { menu.showMoveFromTopToCenter(); }).on("click"); } menuSideNavCloseMenu.attach(() => { menu.hideMoveFromCenterToTop(); }).on("click"); menuSideNavCloseWindow.attach(() => { menu.hideMoveFromCenterToTop(); this.destroyWindow(windowElement); }).on("click"); menuSideNavMinimizeWindow.attach(() => { menu.hideMoveFromCenterToTop(); windowElement.addClass("gui-hidden"); }).on("click"); windowElement.attach((ev) => { menu.showMoveFromTopToCenter(); ev.preventDefault(); }).on("contextmenu"); }; }; if(typeof module !== "undefined") { module.exports = natsec; // NodeJS, AngularJS, NativeScript, RequireJS, etc } else { natsec(window, document); // Browser JS } }());
fixed overflow scroll bug in windows
private_http/jscore/shells/native/natural_window_system.js
fixed overflow scroll bug in windows
<ide><path>rivate_http/jscore/shells/native/natural_window_system.js <ide> titlebarMenuButton.className = "gui-font-iconset-v2 color-gui-window-menu-button flat-button od-3 text-jumbo gui-clickeable padding-2 margin-8 color-transparent gui-shape-circle gui-circular-button-50"; <ide> titlebarMenuButton.dataset["widget"] = "button"; <ide> <del> body.className = "gui-widget-window-body container overflow-auto border no-padding no-margin od-2 fx-1 force-relative"; <add> body.className = "gui-widget-window-body container overflow-hide border no-padding no-margin od-2 fx-1 force-relative"; <ide> body.dataset["widget"] = "window-body"; <ide> <ide> if(appdata.mainWindowCreated)
Java
mit
9d48ee784ee50597276e06046c0099f645107818
0
FIRST-Team-1699/autonomous-code
public interface AutoCommand{ }
src/org/usfirst/frc/team1699/utils/autonomous/AutoCommand.java
public interface AutoCommand{ }
Update AutoCommand.java
src/org/usfirst/frc/team1699/utils/autonomous/AutoCommand.java
Update AutoCommand.java
<ide><path>rc/org/usfirst/frc/team1699/utils/autonomous/AutoCommand.java <ide> public interface AutoCommand{ <del> <add> <ide> }
Java
apache-2.0
9c5141090655399fc70abaa89c647eb46062942b
0
mdvd4/java_pft
package lavr.stqa.pft.addressbook.tests; import lavr.stqa.pft.addressbook.model.ContactData; import org.testng.annotations.Test; /** * Created by Lavr on 04.09.2016. */ public class ContactModificationTests extends TestBase { @Test public void testContactModification() { app.getNavigationHelper().gotoHomePage(); if (!app.getContactHelper().isThereAContact()) { app.getContactHelper().createContact(new ContactData("John", "Smith2", "[none]", "www.leningrad.spb.ru", "123-34-45-01", null, null, "123-34-45-03", "[email protected]", null, null)); } app.getContactHelper().editContact(); app.getContactHelper().fillContactForm(new ContactData("John", "Smith_mod1", null, null, "123-34-45-99", "123-34-45-02", null, null, null, "[email protected]", null), false); app.getContactHelper().submitContactModification(); app.getContactHelper().returnToHomePage(); } }
addressbook-web-tests/src/test/java/lavr/stqa/pft/addressbook/tests/ContactModificationTests.java
package lavr.stqa.pft.addressbook.tests; import lavr.stqa.pft.addressbook.model.ContactData; import org.testng.annotations.Test; /** * Created by Lavr on 04.09.2016. */ public class ContactModificationTests extends TestBase { @Test public void testContactModification() { app.getNavigationHelper().gotoHomePage(); if (!app.getContactHelper().isThereAContact()) { app.getContactHelper().createContact(new ContactData("John", "Smith", "[none]", "www.leningrad.spb.ru", "123-34-45-01", null, null, "123-34-45-03", "[email protected]", null, null), true); } app.getContactHelper().editContact(); app.getContactHelper().fillContactForm(new ContactData("John", "Smith_mod1", null, null, "123-34-45-99", "123-34-45-02", null, null, null, "[email protected]", null), false); app.getContactHelper().submitContactModification(); app.getContactHelper().returnToHomePage(); } }
Исправление замечаний
addressbook-web-tests/src/test/java/lavr/stqa/pft/addressbook/tests/ContactModificationTests.java
Исправление замечаний
<ide><path>ddressbook-web-tests/src/test/java/lavr/stqa/pft/addressbook/tests/ContactModificationTests.java <ide> public void testContactModification() { <ide> app.getNavigationHelper().gotoHomePage(); <ide> if (!app.getContactHelper().isThereAContact()) { <del> app.getContactHelper().createContact(new ContactData("John", "Smith", "[none]", "www.leningrad.spb.ru", "123-34-45-01", null, null, "123-34-45-03", "[email protected]", null, null), true); <add> app.getContactHelper().createContact(new ContactData("John", "Smith2", "[none]", "www.leningrad.spb.ru", "123-34-45-01", null, null, "123-34-45-03", "[email protected]", null, null)); <ide> } <ide> app.getContactHelper().editContact(); <ide> app.getContactHelper().fillContactForm(new ContactData("John", "Smith_mod1", null, null, "123-34-45-99", "123-34-45-02", null, null, null, "[email protected]", null), false);
JavaScript
mit
3c947af740bc6e032123eece083682581d511b38
0
nerdgrass/immutable-js-diff,intelie/immutable-js-diff,tgriesser/immutable-diff
'use strict'; var diff = require('../src/diff'); var Immutable = require('Immutable'); var JSC = require('jscheck'); var assert = require('assert'); describe('Map diff', function(){ var failure = null; before(function(){ JSC.on_report(function(report){ console.log(report); }); JSC.on_fail(function(jsc_failure){ failure = jsc_failure; }); }); it('check properties', function(){ JSC.test( 'returns [] when equal', function(veredict, obj){ var map1 = Immutable.fromJS(obj); var map2 = Immutable.fromJS(obj); var result = diff.diff(map1, map2); return veredict(result.length === 0); }, [ JSC.object(5) ] ); JSC.test( 'returns add op when missing attribute', function(veredict, obj, obj2){ var map1 = Immutable.fromJS(obj); var map2 = Immutable.fromJS(obj).set('key2', obj2.key2); var result = diff.diff(map1, map2); var expected = {op: 'add', path: '/key2', value: obj2.key2}; return veredict( result.length !== 0 && result.every(function(op){ return opsAreEqual(op, expected); }) ); }, [ JSC.object({ key: JSC.integer(1, 100) }), JSC.object({ key2: JSC.integer(101, 200) }) ] ); JSC.test( 'returns replace op when same attribute with different values', function(veredict, obj, newValue){ var map1 = Immutable.fromJS(obj); var map2 = Immutable.fromJS(obj).set('key', newValue); var result = diff.diff(map1, map2); var expected = {op: 'replace', path: '/key', value: newValue}; return veredict( result.length !== 0 && result.every(function(op){ return opsAreEqual(op, expected); }) ); }, [ JSC.object({ key: JSC.integer(1, 50) }), JSC.integer(51, 100) ] ); JSC.test( 'returns remove op when attribute is missing', function(veredict, obj){ var map1 = Immutable.fromJS(obj); var map2 = Immutable.Map(); var result = diff.diff(map1, map2); var expected = {op: 'remove', path: '/key'}; return veredict( result.length !== 0 && result.every(function(op){ return opsAreEqual(op, expected); }) ); }, [ JSC.object({ key: JSC.integer(1, 50) }), ] ); if(failure){ console.error(failure); throw failure; } }); it('check nested structures', function(){ var map1 = Immutable.fromJS({a: 1, b: {c: 2}}); var map2 = Immutable.fromJS({a: 1, b: {c: 2, d: 3}}); var result = diff.diff(map1, map2); var expected = {op: 'add', path: '/b/d', value: 3}; assert.ok(result.every(function(op){ return opsAreEqual(op, expected); })); }); }); var opsAreEqual = function(value, expected){ return value.op === expected.op && value.path === expected.path && value.value === expected.value; };
tests/MapDiff.test.js
'use strict'; var diff = require('../src/diff'); var Immutable = require('Immutable'); var JSC = require('jscheck'); var assert = require('assert'); describe('Map diff', function(){ var failure = null; before(function(){ JSC.on_report(function(report){ console.log(report); }); JSC.on_fail(function(jsc_failure){ failure = jsc_failure; }); }); it('check properties', function(){ JSC.test( 'returns [] when equal', function(veredict, key, value){ var map1 = Immutable.Map().set(key, value); var map2 = Immutable.Map().set(key, value); var result = diff.diff(map1, map2); return veredict(result.length === 0); }, [ JSC.character('a', 'z'), JSC.integer(1, 100) ] ); JSC.test( 'returns add op when missing attribute', function(veredict, aKey, bKey, aValue, bValue){ var map1 = Immutable.Map().set(aKey, aValue); var map2 = Immutable.Map() .set(aKey, aValue) .set(bKey, bValue); var result = diff.diff(map1, map2); var expected = {op: 'add', path: '/'+bKey, value: bValue}; return veredict( result.length !== 0 && result.every(function(op){ return opsAreEqual(op, expected); }) ); }, [ JSC.character('a', 'j'), JSC.character('k', 'z'), JSC.integer(1, 100), JSC.integer(101, 200) ] ); JSC.test( 'returns replace op when same attribute with different values', function(veredict, aKey, aValue, bValue){ var map1 = Immutable.Map().set(aKey, aValue); var map2 = Immutable.Map().set(aKey, bValue); var result = diff.diff(map1, map2); var expected = {op: 'replace', path: '/'+aKey, value: bValue}; return veredict( result.length !== 0 && result.every(function(op){ return opsAreEqual(op, expected); }) ); }, [ JSC.character('a', 'z'), JSC.integer(1, 50), JSC.integer(51, 100) ] ); JSC.test( 'returns remove op when attribute is missing', function(veredict, aKey, aValue, bValue){ var map1 = Immutable.Map().set(aKey, aValue); var map2 = Immutable.Map(); var result = diff.diff(map1, map2); var expected = {op: 'remove', path: '/'+aKey}; return veredict( result.length !== 0 && result.every(function(op){ return opsAreEqual(op, expected); }) ); }, [ JSC.character('a', 'z'), JSC.integer(1, 50), JSC.integer(51, 100) ] ); if(failure){ console.error(failure); throw failure; } }); it('check nested structures', function(){ var map1 = Immutable.fromJS({a: 1, b: {c: 2}}); var map2 = Immutable.fromJS({a: 1, b: {c: 2, d: 3}}); var result = diff.diff(map1, map2); var expected = {op: 'add', path: '/b/d', value: 3}; assert.ok(result.every(function(op){ return opsAreEqual(op, expected); })); }); }); var opsAreEqual = function(value, expected){ return value.op === expected.op && value.path === expected.path && value.value === expected.value; };
generating better JSCheck test data
tests/MapDiff.test.js
generating better JSCheck test data
<ide><path>ests/MapDiff.test.js <ide> it('check properties', function(){ <ide> JSC.test( <ide> 'returns [] when equal', <del> function(veredict, key, value){ <del> var map1 = Immutable.Map().set(key, value); <del> var map2 = Immutable.Map().set(key, value); <add> function(veredict, obj){ <add> var map1 = Immutable.fromJS(obj); <add> var map2 = Immutable.fromJS(obj); <ide> <ide> var result = diff.diff(map1, map2); <ide> <ide> return veredict(result.length === 0); <ide> }, <ide> [ <del> JSC.character('a', 'z'), <del> JSC.integer(1, 100) <add> JSC.object(5) <ide> ] <ide> ); <ide> <ide> <ide> JSC.test( <ide> 'returns add op when missing attribute', <del> function(veredict, aKey, bKey, aValue, bValue){ <del> var map1 = Immutable.Map().set(aKey, aValue); <del> var map2 = Immutable.Map() <del> .set(aKey, aValue) <del> .set(bKey, bValue); <del> <add> function(veredict, obj, obj2){ <add> var map1 = Immutable.fromJS(obj); <add> var map2 = Immutable.fromJS(obj).set('key2', obj2.key2); <ide> <ide> var result = diff.diff(map1, map2); <del> var expected = {op: 'add', path: '/'+bKey, value: bValue}; <add> var expected = {op: 'add', path: '/key2', value: obj2.key2}; <ide> <ide> return veredict( <ide> result.length !== 0 && <ide> ); <ide> }, <ide> [ <del> JSC.character('a', 'j'), <del> JSC.character('k', 'z'), <del> JSC.integer(1, 100), <del> JSC.integer(101, 200) <add> JSC.object({ <add> key: JSC.integer(1, 100) <add> }), <add> JSC.object({ <add> key2: JSC.integer(101, 200) <add> }) <ide> ] <ide> ); <ide> <ide> JSC.test( <ide> 'returns replace op when same attribute with different values', <del> function(veredict, aKey, aValue, bValue){ <del> var map1 = Immutable.Map().set(aKey, aValue); <del> var map2 = Immutable.Map().set(aKey, bValue); <add> function(veredict, obj, newValue){ <add> var map1 = Immutable.fromJS(obj); <add> var map2 = Immutable.fromJS(obj).set('key', newValue); <ide> <ide> var result = diff.diff(map1, map2); <del> var expected = {op: 'replace', path: '/'+aKey, value: bValue}; <add> var expected = {op: 'replace', path: '/key', value: newValue}; <ide> <ide> return veredict( <ide> result.length !== 0 && <ide> ); <ide> }, <ide> [ <del> JSC.character('a', 'z'), <del> JSC.integer(1, 50), <add> JSC.object({ <add> key: JSC.integer(1, 50) <add> }), <ide> JSC.integer(51, 100) <ide> ] <ide> ); <ide> <ide> JSC.test( <ide> 'returns remove op when attribute is missing', <del> function(veredict, aKey, aValue, bValue){ <del> var map1 = Immutable.Map().set(aKey, aValue); <add> function(veredict, obj){ <add> var map1 = Immutable.fromJS(obj); <ide> var map2 = Immutable.Map(); <ide> <ide> var result = diff.diff(map1, map2); <del> var expected = {op: 'remove', path: '/'+aKey}; <add> var expected = {op: 'remove', path: '/key'}; <ide> <ide> return veredict( <ide> result.length !== 0 && <ide> ); <ide> }, <ide> [ <del> JSC.character('a', 'z'), <del> JSC.integer(1, 50), <del> JSC.integer(51, 100) <add> JSC.object({ <add> key: JSC.integer(1, 50) <add> }), <ide> ] <ide> ); <ide>
Java
mit
94c0d206a2596e034ec7d46146e850cee89cc585
0
iSach/Samaritan
package be.isach.samaritan; import be.isach.samaritan.birthday.BirthdayTask; import be.isach.samaritan.brainfuck.BrainfuckInterpreter; import be.isach.samaritan.chat.PrivateMessageChatThread; import be.isach.samaritan.command.console.ConsoleListenerThread; import be.isach.samaritan.history.MessageHistoryPrinter; import be.isach.samaritan.level.AccessLevelManager; import be.isach.samaritan.listener.CommandListener; import be.isach.samaritan.listener.PrivateMessageListener; import be.isach.samaritan.log.SmartLogger; import be.isach.samaritan.music.SongPlayer; import be.isach.samaritan.runtime.ShutdownThread; import be.isach.samaritan.util.GifFactory; import be.isach.samaritan.util.SamaritanStatus; import be.isach.samaritan.websocket.SamaritanWebsocketServer; import net.dv8tion.jda.JDA; import net.dv8tion.jda.JDABuilder; import net.dv8tion.jda.entities.Guild; import net.dv8tion.jda.entities.PrivateChannel; import org.joda.time.Instant; import javax.security.auth.login.LoginException; import java.io.File; import java.net.InetSocketAddress; import java.net.UnknownHostException; import java.util.*; /** * Project: samaritan * Package: be.isach.samaritan * Created by: Sacha * Created on: 15th May, 2016 * <p> * Description: Represents a Samaritan Instance. */ public class Samaritan { /** * Song Players map with their corresponding guilds. */ private Map<Guild, SongPlayer> songPlayers; /** * Samaritan Status. */ private SamaritanStatus status; /** * The Jda of this Samaritan Instance. */ private JDA jda; /** * Message History Printer Util. */ private MessageHistoryPrinter messageHistoryPrinter; /** * The Smart Logger of this Samaritan Instance. */ private SmartLogger logger; /** * Absolute File! */ private File workingDirectory; /** * Brainfuck Code Interpreter */ private BrainfuckInterpreter brainfuckInterpreter; /** * UI WebSocket Server. */ private SamaritanWebsocketServer samaritanWebsocketServer; /** * Private Message Listener. */ private PrivateMessageListener pmListener; /** * Bot Token. */ private String botToken; /** * Main Admin. Owner. As Discord User ID. */ private String ownerId; /** * WEB Interface using WebSockets? */ private boolean webUi; /** * Web Interface WebSocket Server Port. */ private int uiWebSocketPort; /** * Gif Factory. */ private GifFactory gifFactory; /** * Birthday task */ private BirthdayTask birthdayTask; /** * Timer. */ private Timer timer; /** * Users Acess Level Manager. */ private AccessLevelManager accessLevelManager; /** * Samaritan Constructor. * * @param args Program Arguments. * Given when program is started * @param botToken Bot Token. * From samaritan.properties * @param webUi Use Web UI or not. * From samaritan.properties. * @param uiWebSocketPort Web UI Port. * From <samaritan.properties. */ public Samaritan(String[] args, String botToken, boolean webUi, int uiWebSocketPort, long ownerId, File workingDirectory) { this.botToken = botToken; this.logger = new SmartLogger(); this.status = new SamaritanStatus(); this.songPlayers = new HashMap<>(); this.gifFactory = new GifFactory(); this.ownerId = String.valueOf(ownerId); this.workingDirectory = workingDirectory; this.brainfuckInterpreter = new BrainfuckInterpreter(); this.messageHistoryPrinter = new MessageHistoryPrinter(); this.accessLevelManager = new AccessLevelManager(this); this.webUi = webUi; status.setBootInstant(new Instant()); logger.write("--------------------------------------------------------"); logger.write(); logger.write("Hello."); logger.write(); logger.write("I am Samaritan."); logger.write(); logger.write("Starting..."); logger.write(); logger.write("Boot Instant: " + new Instant().toString()); logger.write(); if (!initJda()) { logger.write("Invalid token! Please change it in samaritan.properties"); System.exit(1); return; } this.birthdayTask = new BirthdayTask(this); this.timer = new Timer(); timer.schedule(birthdayTask, 0L, 1000L * 30L); this.accessLevelManager.loadUsers(); Runtime.getRuntime().addShutdownHook(new ShutdownThread(this)); startSongPlayers(); setUpListeners(); if (webUi) startWebSocketServer(); new ConsoleListenerThread(this).start(); } /** * Starts JDA. * * @return {@code true} if everything went well, {@code false} otherwise. */ private boolean initJda() { try { jda = new JDABuilder().setBotToken(botToken).buildBlocking(); jda.getAccountManager().setGame("Beta 2.0.1"); jda.getAccountManager().update(); } catch (LoginException | InterruptedException e) { logger.write("Couldn't connect!"); return false; } return true; } /** * Shuts Samaritan down. * * @param exitSystem If true, will execute a 'System.exit(0);' */ public final void shutdown(boolean exitSystem) { for (PrivateMessageChatThread chatThread : getPrivateMessageListener().getChatThreads().values()) { PrivateChannel privateChannel = (PrivateChannel) chatThread.getMessageChannel(); privateChannel.sendMessage("I must go, a reboot is in the queue!\nYou can try speaking to me again in a few moments.\nGood bye, my dear " + privateChannel.getUser().getUsername() + "."); } try { jda.getAccountManager().setUsername("Samaritan"); jda.getAccountManager().update(); } catch (Exception exc) { } jda.shutdown(); if (exitSystem) System.exit(0); } /** * Starts WebSocket Server (for UI). */ private void startWebSocketServer() { try { samaritanWebsocketServer = new SamaritanWebsocketServer(new InetSocketAddress(11350)); samaritanWebsocketServer.start(); System.out.println("WS Server started."); } catch (UnknownHostException e) { System.out.println("WS Server couldn't start."); e.printStackTrace(); } } /** * Set up Listeners. */ private void setUpListeners() { this.pmListener = new PrivateMessageListener(); jda.addEventListener(new CommandListener(this)); jda.addEventListener(pmListener); } /** * Start Song Players. */ private void startSongPlayers() { for (Guild guild : jda.getGuilds()) { SongPlayer songPlayer = new SongPlayer(guild, this); songPlayers.put(guild, songPlayer); } } /** * @param guild The Guild. * @return A song Player by Guild. */ public SongPlayer getSongPlayer(Guild guild) { return songPlayers.get(guild); } /** * @return The SongPlayers map. */ public Map<Guild, SongPlayer> getSongPlayers() { return songPlayers; } /** * @return The UI WebSocket Server. */ public SamaritanWebsocketServer getWebSocketServer() { return samaritanWebsocketServer; } /** * @return The JDA of this Samaritan Instance. */ public JDA getJda() { return jda; } /** * @return The Smart Logger. */ public SmartLogger getLogger() { return logger; } /** * @return The Private Message Listener */ public PrivateMessageListener getPrivateMessageListener() { return pmListener; } /** * @return Samaritan's status. */ public SamaritanStatus getStatus() { return status; } /** * @return The Gif Factory. */ public GifFactory getGifFactory() { return gifFactory; } /** * @return webUi value. */ public boolean useWebUi() { return webUi; } /** * @return Access Level Manager. */ public AccessLevelManager getAccessLevelManager() { return accessLevelManager; } /** * @return Brainfuck code Interpreter. */ public BrainfuckInterpreter getBrainfuckInterpreter() { return brainfuckInterpreter; } /** * @return Message History Printer Util. */ public MessageHistoryPrinter getMessageHistoryPrinter() { return messageHistoryPrinter; } /** * @return Directory where Samaritan is currently running. */ public File getWorkingDirectory() { return workingDirectory; } /** * @return Main Admin ID. */ public String getOwnerId() { return ownerId; } }
src/main/java/be/isach/samaritan/Samaritan.java
package be.isach.samaritan; import be.isach.samaritan.birthday.BirthdayTask; import be.isach.samaritan.brainfuck.BrainfuckInterpreter; import be.isach.samaritan.chat.PrivateMessageChatThread; import be.isach.samaritan.command.console.ConsoleListenerThread; import be.isach.samaritan.history.MessageHistoryPrinter; import be.isach.samaritan.level.AccessLevelManager; import be.isach.samaritan.listener.CommandListener; import be.isach.samaritan.listener.PrivateMessageListener; import be.isach.samaritan.log.SmartLogger; import be.isach.samaritan.music.SongPlayer; import be.isach.samaritan.runtime.ShutdownThread; import be.isach.samaritan.util.GifFactory; import be.isach.samaritan.util.SamaritanStatus; import be.isach.samaritan.websocket.SamaritanWebsocketServer; import net.dv8tion.jda.JDA; import net.dv8tion.jda.JDABuilder; import net.dv8tion.jda.entities.Guild; import net.dv8tion.jda.entities.PrivateChannel; import org.joda.time.Instant; import javax.security.auth.login.LoginException; import java.io.File; import java.net.InetSocketAddress; import java.net.UnknownHostException; import java.util.*; /** * Project: samaritan * Package: be.isach.samaritan * Created by: Sacha * Created on: 15th May, 2016 * <p> * Description: Represents a Samaritan Instance. */ public class Samaritan { /** * Song Players map with their corresponding guilds. */ private Map<Guild, SongPlayer> songPlayers; /** * Samaritan Status. */ private SamaritanStatus status; /** * The Jda of this Samaritan Instance. */ private JDA jda; /** * Message History Printer Util. */ private MessageHistoryPrinter messageHistoryPrinter; /** * The Smart Logger of this Samaritan Instance. */ private SmartLogger logger; /** * Absolute File! */ private File workingDirectory; /** * Brainfuck Code Interpreter */ private BrainfuckInterpreter brainfuckInterpreter; /** * UI WebSocket Server. */ private SamaritanWebsocketServer samaritanWebsocketServer; /** * Private Message Listener. */ private PrivateMessageListener pmListener; /** * Bot Token. */ private String botToken; /** * Main Admin. Owner. As Discord User ID. */ private String ownerId; /** * WEB Interface using WebSockets? */ private boolean webUi; /** * Web Interface WebSocket Server Port. */ private int uiWebSocketPort; /** * Gif Factory. */ private GifFactory gifFactory; /** * Birthday task */ private BirthdayTask birthdayTask; /** * Timer. */ private Timer timer; /** * Users Acess Level Manager. */ private AccessLevelManager accessLevelManager; /** * Samaritan Constructor. * * @param args Program Arguments. * Given when program is started * @param botToken Bot Token. * From samaritan.properties * @param webUi Use Web UI or not. * From samaritan.properties. * @param uiWebSocketPort Web UI Port. * From <samaritan.properties. */ public Samaritan(String[] args, String botToken, boolean webUi, int uiWebSocketPort, long ownerId, File workingDirectory) { this.botToken = botToken; this.logger = new SmartLogger(); this.status = new SamaritanStatus(); this.songPlayers = new HashMap<>(); this.gifFactory = new GifFactory(); this.ownerId = String.valueOf(ownerId); this.workingDirectory = workingDirectory; this.brainfuckInterpreter = new BrainfuckInterpreter(); this.messageHistoryPrinter = new MessageHistoryPrinter(); this.accessLevelManager = new AccessLevelManager(this); this.webUi = webUi; status.setBootInstant(new Instant()); logger.write("--------------------------------------------------------"); logger.write(); logger.write("Hello."); logger.write(); logger.write("I am Samaritan."); logger.write(); logger.write("Starting..."); logger.write(); logger.write("Boot Instant: " + new Instant().toString()); logger.write(); if (!initJda()) { logger.write("Invalid token! Please change it in samaritan.properties"); System.exit(1); return; } birthdayTask = new BirthdayTask(this); timer.schedule(birthdayTask, 0L, 1000L * 30L); this.accessLevelManager.loadUsers(); Runtime.getRuntime().addShutdownHook(new ShutdownThread(this)); startSongPlayers(); setUpListeners(); if (webUi) startWebSocketServer(); new ConsoleListenerThread(this).start(); } /** * Starts JDA. * * @return {@code true} if everything went well, {@code false} otherwise. */ private boolean initJda() { try { jda = new JDABuilder().setBotToken(botToken).buildBlocking(); jda.getAccountManager().setGame("Beta 2.0.1"); jda.getAccountManager().update(); } catch (LoginException | InterruptedException e) { logger.write("Couldn't connect!"); return false; } return true; } /** * Shuts Samaritan down. * * @param exitSystem If true, will execute a 'System.exit(0);' */ public final void shutdown(boolean exitSystem) { for (PrivateMessageChatThread chatThread : getPrivateMessageListener().getChatThreads().values()) { PrivateChannel privateChannel = (PrivateChannel) chatThread.getMessageChannel(); privateChannel.sendMessage("I must go, a reboot is in the queue!\nYou can try speaking to me again in a few moments.\nGood bye, my dear " + privateChannel.getUser().getUsername() + "."); } try { jda.getAccountManager().setUsername("Samaritan"); jda.getAccountManager().update(); } catch (Exception exc) { } jda.shutdown(); if (exitSystem) System.exit(0); } /** * Starts WebSocket Server (for UI). */ private void startWebSocketServer() { try { samaritanWebsocketServer = new SamaritanWebsocketServer(new InetSocketAddress(11350)); samaritanWebsocketServer.start(); System.out.println("WS Server started."); } catch (UnknownHostException e) { System.out.println("WS Server couldn't start."); e.printStackTrace(); } } /** * Set up Listeners. */ private void setUpListeners() { this.pmListener = new PrivateMessageListener(); jda.addEventListener(new CommandListener(this)); jda.addEventListener(pmListener); } /** * Start Song Players. */ private void startSongPlayers() { for (Guild guild : jda.getGuilds()) { SongPlayer songPlayer = new SongPlayer(guild, this); songPlayers.put(guild, songPlayer); } } /** * @param guild The Guild. * @return A song Player by Guild. */ public SongPlayer getSongPlayer(Guild guild) { return songPlayers.get(guild); } /** * @return The SongPlayers map. */ public Map<Guild, SongPlayer> getSongPlayers() { return songPlayers; } /** * @return The UI WebSocket Server. */ public SamaritanWebsocketServer getWebSocketServer() { return samaritanWebsocketServer; } /** * @return The JDA of this Samaritan Instance. */ public JDA getJda() { return jda; } /** * @return The Smart Logger. */ public SmartLogger getLogger() { return logger; } /** * @return The Private Message Listener */ public PrivateMessageListener getPrivateMessageListener() { return pmListener; } /** * @return Samaritan's status. */ public SamaritanStatus getStatus() { return status; } /** * @return The Gif Factory. */ public GifFactory getGifFactory() { return gifFactory; } /** * @return webUi value. */ public boolean useWebUi() { return webUi; } /** * @return Access Level Manager. */ public AccessLevelManager getAccessLevelManager() { return accessLevelManager; } /** * @return Brainfuck code Interpreter. */ public BrainfuckInterpreter getBrainfuckInterpreter() { return brainfuckInterpreter; } /** * @return Message History Printer Util. */ public MessageHistoryPrinter getMessageHistoryPrinter() { return messageHistoryPrinter; } /** * @return Directory where Samaritan is currently running. */ public File getWorkingDirectory() { return workingDirectory; } /** * @return Main Admin ID. */ public String getOwnerId() { return ownerId; } }
Birthday
src/main/java/be/isach/samaritan/Samaritan.java
Birthday
<ide><path>rc/main/java/be/isach/samaritan/Samaritan.java <ide> return; <ide> } <ide> <del> birthdayTask = new BirthdayTask(this); <add> this.birthdayTask = new BirthdayTask(this); <add> this.timer = new Timer(); <ide> <ide> timer.schedule(birthdayTask, 0L, 1000L * 30L); <ide>
Java
lgpl-2.1
31211b56d1c4046113aeffde5c1dee857f3e4aec
0
retoo/pystructure,retoo/pystructure,retoo/pystructure,retoo/pystructure
/* * Copyright (C) 2007-2008 Reto Schuettel, Robin Stocker * * IFS Institute for Software, HSR Rapperswil, Switzerland * * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 2.1 of the License, or (at your option) any later version. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA * */ package ch.hsr.ifs.pystructure.typeinference.visitors; import java.util.List; import java.util.Map; import java.util.Stack; import java.util.Map.Entry; import org.python.pydev.parser.jython.ast.Assign; import org.python.pydev.parser.jython.ast.Attribute; import org.python.pydev.parser.jython.ast.Call; import org.python.pydev.parser.jython.ast.ClassDef; import org.python.pydev.parser.jython.ast.Comprehension; import org.python.pydev.parser.jython.ast.For; import org.python.pydev.parser.jython.ast.FunctionDef; import org.python.pydev.parser.jython.ast.Global; import org.python.pydev.parser.jython.ast.If; import org.python.pydev.parser.jython.ast.Import; import org.python.pydev.parser.jython.ast.ImportFrom; import org.python.pydev.parser.jython.ast.Index; import org.python.pydev.parser.jython.ast.Lambda; import org.python.pydev.parser.jython.ast.ListComp; import org.python.pydev.parser.jython.ast.Name; import org.python.pydev.parser.jython.ast.NameTokType; import org.python.pydev.parser.jython.ast.Subscript; import org.python.pydev.parser.jython.ast.TryExcept; import org.python.pydev.parser.jython.ast.TryFinally; import org.python.pydev.parser.jython.ast.While; import org.python.pydev.parser.jython.ast.aliasType; import org.python.pydev.parser.jython.ast.argumentsType; import org.python.pydev.parser.jython.ast.comprehensionType; import org.python.pydev.parser.jython.ast.excepthandlerType; import org.python.pydev.parser.jython.ast.exprType; import org.python.pydev.parser.jython.ast.sliceType; import org.python.pydev.parser.jython.ast.stmtType; import org.python.pydev.parser.jython.ast.suiteType; import ch.hsr.ifs.pystructure.typeinference.model.base.NamePath; import ch.hsr.ifs.pystructure.typeinference.model.base.NodeUtils; import ch.hsr.ifs.pystructure.typeinference.model.definitions.AliasedImportDefinition; import ch.hsr.ifs.pystructure.typeinference.model.definitions.Argument; import ch.hsr.ifs.pystructure.typeinference.model.definitions.AssignDefinition; import ch.hsr.ifs.pystructure.typeinference.model.definitions.AttributeUse; import ch.hsr.ifs.pystructure.typeinference.model.definitions.Class; import ch.hsr.ifs.pystructure.typeinference.model.definitions.Definition; import ch.hsr.ifs.pystructure.typeinference.model.definitions.ExceptDefinition; import ch.hsr.ifs.pystructure.typeinference.model.definitions.Function; import ch.hsr.ifs.pystructure.typeinference.model.definitions.ImportDefinition; import ch.hsr.ifs.pystructure.typeinference.model.definitions.ImportPath; import ch.hsr.ifs.pystructure.typeinference.model.definitions.LoopVariableDefinition; import ch.hsr.ifs.pystructure.typeinference.model.definitions.Module; import ch.hsr.ifs.pystructure.typeinference.model.definitions.NameUse; import ch.hsr.ifs.pystructure.typeinference.model.definitions.Use; import ch.hsr.ifs.pystructure.typeinference.model.scopes.Block; import ch.hsr.ifs.pystructure.typeinference.model.scopes.ExternalScope; import ch.hsr.ifs.pystructure.typeinference.model.scopes.ModuleScope; import ch.hsr.ifs.pystructure.typeinference.model.scopes.Scope; public class DefinitionVisitor extends StructuralVisitor { private final Module module; private final ExternalScope externalScope; private final ModuleScope moduleScope; private final Stack<Block> blocks; private final List<Use> uses; public DefinitionVisitor(Module module) { this.module = module; this.externalScope = new ExternalScope(module); this.moduleScope = new ModuleScope(externalScope); module.setModuleScope(moduleScope); this.blocks = new Stack<Block>(); this.uses = module.getContainedUses(); } public void run() { try { super.run(module); } catch (Exception e) { throw new RuntimeException(e); } } @Override public Object visitModule(org.python.pydev.parser.jython.ast.Module node) throws Exception { blocks.push(moduleScope); super.visitModule(node); visitChildren(module); blocks.pop(); moduleScope.connectGlobals(); return null; } @Override public Object visitClassDef(ClassDef node) throws Exception { Class klass = getDefinitionFor(node); if (isFirstVisit(klass)) { addDefinition(klass); } else { blocks.push(new Scope(getBlock())); super.visitClassDef(node); visitChildren(klass); blocks.pop(); } return null; } @Override public Object visitFunctionDef(FunctionDef node) throws Exception { Function function = getDefinitionFor(node); if (isFirstVisit(function)) { /* * TODO: What about this? * * global func * def func(): * print "I'm global" */ addDefinition(function); } else { Scope functionScope = new Scope(getBlock()); blocks.push(functionScope); addArgumentDefinitions(node.args, function); super.visitFunctionDef(node); visitChildren(function); blocks.pop(); } return null; } @Override public Object visitLambda(Lambda node) throws Exception { // TODO: Implement lambda properly return null; } private void addArgumentDefinitions(argumentsType args, Function function) { int firstDefault = args.args.length - args.defaults.length; for (int position = 0; position < args.args.length; ++position) { exprType argument = args.args[position]; if (argument instanceof Name) { String name = ((Name) argument).id; exprType defaultValue = null; if (position >= firstDefault) { defaultValue = args.defaults[position - firstDefault]; } addDefinition(new Argument(module, name, argument, position, defaultValue, function)); } } } /* * Assign statements like these: * * a = 1 * b, c = 2, 3 * d, e = function_returning_tuple() */ @Override public Object visitAssign(Assign node) throws Exception { node.value.accept(this); node.value.parent = node; for (exprType target : node.targets) { Map<exprType, exprType> values = NodeUtils.createTupleElementAssignments(target, node.value); for (Entry<exprType, exprType> entry : values.entrySet()) { exprType targetPart = entry.getKey(); exprType value = entry.getValue(); if (targetPart instanceof Name) { String name = ((Name) targetPart).id; Definition d = new AssignDefinition(module, name, node, value); addDefinition(d); } else if (targetPart instanceof Subscript) { processSubscriptAssignment(targetPart, value); } else { targetPart.accept(this); } } target.parent = node; } return null; } /** * d["key"] = 42 → d.__setitem__("key", 42) */ private void processSubscriptAssignment(exprType target, exprType value) throws Exception { Subscript subscript = (Subscript) target; exprType receiver = subscript.value; sliceType slice = subscript.slice; if (slice instanceof Index) { exprType key = ((Index) slice).value; exprType[] arguments = new exprType[] {key, value}; Call setitemCall = NodeUtils.createMethodCall(receiver, "__setitem__", arguments); setitemCall.accept(this); } } /* * Node for bare names (variables), for example the "instance" of * "instance.method" but not the "method" (which is an attribute). */ @Override public Object visitName(Name node) throws Exception { addNameUse(node); super.visitName(node); return null; } /* * Examples: * * module.function * instance.method */ @Override public Object visitAttribute(Attribute node) throws Exception { uses.add(new AttributeUse(node, module)); node.parent = stack.peek(); stack.push(node); // Don't visit node.attr, we don't want a NameUse for it. node.attr.parent = node; node.value.accept(this); stack.pop(); return null; } @Override public Object visitGlobal(Global node) throws Exception { for (NameTokType nameTok : node.names) { String name = NodeUtils.getId(nameTok); getScope().setGlobal(name); nameTok.accept(this); } return null; } @Override public Object visitIf(If node) throws Exception { Block parent = getBlock(); node.test.accept(this); Block bodyBlock = new Block(parent); Block orelseBlock = new Block(parent); visitBlock(bodyBlock, node.body); visitBlock(orelseBlock, node.orelse); parent.addCurrentDefinitions(bodyBlock); parent.addCurrentDefinitions(orelseBlock); return null; } @Override public Object visitFor(For node) throws Exception { Block parent = getBlock(); Block bodyBlock = new Block(parent); Call iterCall = NodeUtils.createMethodCall(node.iter, "__iter__"); Call nextCall = NodeUtils.createMethodCall(iterCall, "next"); nextCall.accept(this); Map<exprType, exprType> assignments = NodeUtils.createTupleElementAssignments(node.target, nextCall); for (Map.Entry<exprType, exprType> entry : assignments.entrySet()) { exprType target = entry.getKey(); exprType value = entry.getValue(); if (target instanceof Name) { String name = ((Name) target).id; Definition loopVariable = new LoopVariableDefinition(module, name, (Name) target, value); bodyBlock.setDefinition(loopVariable); parent.addDefinition(loopVariable); } else if (target instanceof Subscript) { processSubscriptAssignment(target, value); } else if (target instanceof Attribute) { /* * TODO: What to do about this?: * * x = Class() * for x.attribute in [1, 2, 3]: * print x.attribute */ } } visitBlock(bodyBlock, node.body); Block orelseBlock = new Block(parent); // Definitions may flow from the body to the else block. orelseBlock.addCurrentDefinitions(bodyBlock); visitBlock(orelseBlock, node.orelse); parent.addCurrentDefinitions(bodyBlock); parent.addCurrentDefinitions(orelseBlock); return null; } @Override public Object visitListComp(ListComp node) throws Exception { Block block = new Block(getBlock()); for (comprehensionType generator : node.generators) { /* Comprehension is the only subclass of comprehensionType */ Comprehension comp = (Comprehension) generator; Call iterCall = NodeUtils.createMethodCall(comp.iter, "__iter__"); Call nextCall = NodeUtils.createMethodCall(iterCall, "next"); nextCall.accept(this); Map<exprType, exprType> assignments = NodeUtils.createTupleElementAssignments(comp.target, nextCall); for (Map.Entry<exprType, exprType> entry : assignments.entrySet()) { exprType target = entry.getKey(); exprType value = entry.getValue(); if (target instanceof Name) { String name = ((Name) target).id; Definition loopVariable = new LoopVariableDefinition(module, name, (Name) target, value); block.setDefinition(loopVariable); } else if (target instanceof Subscript) { processSubscriptAssignment(target, value); } else if (target instanceof Attribute) { // Ignore for now } } } blocks.push(block); node.elt.accept(this); blocks.pop(); return null; } @Override public Object visitWhile(While node) throws Exception { Block parent = getBlock(); node.test.accept(this); Block bodyBlock = new Block(parent); Block orelseBlock = new Block(parent); visitBlock(bodyBlock, node.body); orelseBlock.addCurrentDefinitions(bodyBlock); visitBlock(orelseBlock, node.orelse); parent.addCurrentDefinitions(bodyBlock); parent.addCurrentDefinitions(orelseBlock); return null; } @Override public Object visitTryExcept(TryExcept node) throws Exception { Block parent = getBlock(); Block bodyBlock = new Block(parent); Block orelseBlock = new Block(parent); visitBlock(bodyBlock, node.body); for (excepthandlerType handler : node.handlers) { Block handlerBlock = new Block(parent); handlerBlock.addBlockDefinitions(bodyBlock); // TODO: What about tuples? if (handler.name instanceof Name) { String name = ((Name) handler.name).id; ExceptDefinition definition = new ExceptDefinition(module, name, handler); handlerBlock.setDefinition(definition); } visitBlock(handlerBlock, handler.body); parent.addCurrentDefinitions(handlerBlock); } orelseBlock.addBlockDefinitions(bodyBlock); visitBlock(orelseBlock, node.orelse); // We need to add all definitions of the block, because we don't know // where the exception was thrown, it could be between two definitions // of the same name. parent.addBlockDefinitions(bodyBlock); parent.addCurrentDefinitions(orelseBlock); return null; } @Override public Object visitTryFinally(TryFinally node) throws Exception { Block parent = getBlock(); Block bodyBlock = new Block(parent); Block finallyBlock = new Block(parent); visitBlock(bodyBlock, node.body); finallyBlock.addBlockDefinitions(bodyBlock); visitBlock(finallyBlock, node.finalbody); parent.addBlockDefinitions(bodyBlock); // Overwrite the current definitions, because we don't know whether an // exception occurred or not. for (Definition definition : finallyBlock.getCurrentDefinitions()) { parent.setDefinition(definition); } return null; } private void visitBlock(Block block, stmtType[] body) throws Exception { if (body == null) { return; } blocks.push(block); for (stmtType statement : body) { statement.accept(this); } blocks.pop(); } private void visitBlock(Block block, suiteType suite) throws Exception { if (suite != null) { visitBlock(block, suite.body); } } private void addDefinition(Definition definition) { if (getScope().isGlobal(definition.getName())) { moduleScope.addGlobalDefinition(definition); } else { getBlock().setDefinition(definition); } } private void addNameUse(Name node) { NameUse nameUse = new NameUse(node.id, node, module); String name = nameUse.getName(); List<Definition> definitions = getBlock().getCurrentDefinitions(name); /* Check if this nameuse is alised by the import definieren (from module import Class as Alias). If * this is the case we register another NameUse using the 'Alias' as name. This enables the * PotentialReferences Evaluator to find the name, even when it is aliased. */ for (Definition def : definitions) { if (def instanceof AliasedImportDefinition) { AliasedImportDefinition id = (AliasedImportDefinition) def; NameUse aliasedNameUse = new NameUse(id.getElement(), node, module); aliasedNameUse.addDefinition(id); uses.add(aliasedNameUse); } } nameUse.addDefinitions(definitions); if (getScope() == moduleScope || getScope().isGlobal(name)) { moduleScope.addGlobalNameUse(nameUse); } uses.add(nameUse); } private Block getBlock() { return blocks.peek(); } private Scope getScope() { Block scope = getBlock(); while (!(scope instanceof Scope)) { scope = scope.getParent(); } return (Scope) scope; } /* import stuff */ /* * Examples: * * import pkg.module * import pkg.module as module * import pkg.module, pkg2.module2 * import pkg * * Doesn't work: * * import pkg.module.Class */ @Override public Object visitImport(Import node) throws Exception { for (aliasType entry : node.names) { ImportDefinition definition; if (entry.asname == null) { /* import package.module # package -> package */ NamePath fullPath = new NamePath(NodeUtils.getId(entry.name)); NamePath name = new NamePath(fullPath.getFirstPart()); ImportPath importPath = new ImportPath(module, name, 0); definition = new ImportDefinition(module, node, importPath, null, name.toString()); } else { /* import package.module as alias # alias -> package.module */ String alias = NodeUtils.getId(entry.asname); NamePath path = new NamePath(NodeUtils.getId(entry.name)); ImportPath importPath = new ImportPath(module, path, 0); definition = new ImportDefinition(module, node, importPath, null, alias); } addDefinition(definition); } return null; } /* * Examples: * * from pkg.module import Class * from pkg.module import Class as C1, ClassTwo as C2 * from pkg.module import * # grrr * from pkg import module * from pkg import subpkg * from pkg import * # doesn't import all modules, but everything in __init__.py * from .module import Class * from . import module */ @Override public Object visitImportFrom(ImportFrom node) throws Exception { NamePath path = new NamePath(NodeUtils.getId(node.module)); ImportPath importPath = new ImportPath(module, path, node.level); if (node.names.length == 0) { /* This is a "star" import (from module import *) */ externalScope.addImportStarPath(importPath); } else { for (aliasType entry : node.names) { String element = NodeUtils.getId(entry.name); ImportDefinition definition; if (entry.asname != null) { definition = new AliasedImportDefinition(module, node, importPath, element, NodeUtils.getId(entry.asname)); } else { definition = new ImportDefinition(module, node, importPath, element, element); } addDefinition(definition); } } return null; } }
src/ch/hsr/ifs/pystructure/typeinference/visitors/DefinitionVisitor.java
/* * Copyright (C) 2007-2008 Reto Schuettel, Robin Stocker * * IFS Institute for Software, HSR Rapperswil, Switzerland * * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 2.1 of the License, or (at your option) any later version. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA * */ package ch.hsr.ifs.pystructure.typeinference.visitors; import java.util.List; import java.util.Map; import java.util.Stack; import java.util.Map.Entry; import org.python.pydev.parser.jython.ast.Assign; import org.python.pydev.parser.jython.ast.Attribute; import org.python.pydev.parser.jython.ast.Call; import org.python.pydev.parser.jython.ast.ClassDef; import org.python.pydev.parser.jython.ast.Comprehension; import org.python.pydev.parser.jython.ast.For; import org.python.pydev.parser.jython.ast.FunctionDef; import org.python.pydev.parser.jython.ast.Global; import org.python.pydev.parser.jython.ast.If; import org.python.pydev.parser.jython.ast.Import; import org.python.pydev.parser.jython.ast.ImportFrom; import org.python.pydev.parser.jython.ast.Index; import org.python.pydev.parser.jython.ast.Lambda; import org.python.pydev.parser.jython.ast.ListComp; import org.python.pydev.parser.jython.ast.Name; import org.python.pydev.parser.jython.ast.NameTokType; import org.python.pydev.parser.jython.ast.Subscript; import org.python.pydev.parser.jython.ast.TryExcept; import org.python.pydev.parser.jython.ast.TryFinally; import org.python.pydev.parser.jython.ast.While; import org.python.pydev.parser.jython.ast.aliasType; import org.python.pydev.parser.jython.ast.argumentsType; import org.python.pydev.parser.jython.ast.comprehensionType; import org.python.pydev.parser.jython.ast.excepthandlerType; import org.python.pydev.parser.jython.ast.exprType; import org.python.pydev.parser.jython.ast.sliceType; import org.python.pydev.parser.jython.ast.stmtType; import org.python.pydev.parser.jython.ast.suiteType; import ch.hsr.ifs.pystructure.typeinference.model.base.NamePath; import ch.hsr.ifs.pystructure.typeinference.model.base.NodeUtils; import ch.hsr.ifs.pystructure.typeinference.model.definitions.AliasedImportDefinition; import ch.hsr.ifs.pystructure.typeinference.model.definitions.Argument; import ch.hsr.ifs.pystructure.typeinference.model.definitions.AssignDefinition; import ch.hsr.ifs.pystructure.typeinference.model.definitions.AttributeUse; import ch.hsr.ifs.pystructure.typeinference.model.definitions.Class; import ch.hsr.ifs.pystructure.typeinference.model.definitions.Definition; import ch.hsr.ifs.pystructure.typeinference.model.definitions.ExceptDefinition; import ch.hsr.ifs.pystructure.typeinference.model.definitions.Function; import ch.hsr.ifs.pystructure.typeinference.model.definitions.ImportDefinition; import ch.hsr.ifs.pystructure.typeinference.model.definitions.ImportPath; import ch.hsr.ifs.pystructure.typeinference.model.definitions.LoopVariableDefinition; import ch.hsr.ifs.pystructure.typeinference.model.definitions.Module; import ch.hsr.ifs.pystructure.typeinference.model.definitions.NameUse; import ch.hsr.ifs.pystructure.typeinference.model.definitions.Use; import ch.hsr.ifs.pystructure.typeinference.model.scopes.Block; import ch.hsr.ifs.pystructure.typeinference.model.scopes.ExternalScope; import ch.hsr.ifs.pystructure.typeinference.model.scopes.ModuleScope; import ch.hsr.ifs.pystructure.typeinference.model.scopes.Scope; public class DefinitionVisitor extends StructuralVisitor { private final Module module; private final ExternalScope externalScope; private final ModuleScope moduleScope; private final Stack<Block> blocks; private final List<Use> uses; public DefinitionVisitor(Module module) { this.module = module; this.externalScope = new ExternalScope(module); this.moduleScope = new ModuleScope(externalScope); module.setModuleScope(moduleScope); this.blocks = new Stack<Block>(); this.uses = module.getContainedUses(); } public void run() { try { super.run(module); } catch (Exception e) { throw new RuntimeException(e); } } @Override public Object visitModule(org.python.pydev.parser.jython.ast.Module node) throws Exception { blocks.push(moduleScope); super.visitModule(node); visitChildren(module); blocks.pop(); moduleScope.connectGlobals(); return null; } @Override public Object visitClassDef(ClassDef node) throws Exception { Class klass = getDefinitionFor(node); if (isFirstVisit(klass)) { addDefinition(klass); } else { blocks.push(new Scope(getBlock())); super.visitClassDef(node); visitChildren(klass); blocks.pop(); } return null; } @Override public Object visitFunctionDef(FunctionDef node) throws Exception { Function function = getDefinitionFor(node); if (isFirstVisit(function)) { /* * TODO: What about this? * * global func * def func(): * print "I'm global" */ addDefinition(function); } else { Scope functionScope = new Scope(getBlock()); blocks.push(functionScope); addArgumentDefinitions(node.args, function); super.visitFunctionDef(node); visitChildren(function); blocks.pop(); } return null; } @Override public Object visitLambda(Lambda node) throws Exception { // TODO: Implement lambda properly return null; } private void addArgumentDefinitions(argumentsType args, Function function) { int firstDefault = args.args.length - args.defaults.length; for (int position = 0; position < args.args.length; ++position) { exprType argument = args.args[position]; if (argument instanceof Name) { String name = ((Name) argument).id; exprType defaultValue = null; if (position >= firstDefault) { defaultValue = args.defaults[position - firstDefault]; } addDefinition(new Argument(module, name, argument, position, defaultValue, function)); } } } /* * Assign statements like these: * * a = 1 * b, c = 2, 3 * d, e = function_returning_tuple() */ @Override public Object visitAssign(Assign node) throws Exception { node.value.accept(this); node.value.parent = node; for (exprType target : node.targets) { Map<exprType, exprType> values = NodeUtils.createTupleElementAssignments(target, node.value); for (Entry<exprType, exprType> entry : values.entrySet()) { exprType targetPart = entry.getKey(); exprType value = entry.getValue(); if (targetPart instanceof Name) { String name = ((Name) targetPart).id; Definition d = new AssignDefinition(module, name, node, value); addDefinition(d); targetPart.accept(this); } else if (targetPart instanceof Subscript) { processSubscriptAssignment(targetPart, value); } else { targetPart.accept(this); } } target.parent = node; } return null; } /** * d["key"] = 42 → d.__setitem__("key", 42) */ private void processSubscriptAssignment(exprType target, exprType value) throws Exception { Subscript subscript = (Subscript) target; exprType receiver = subscript.value; sliceType slice = subscript.slice; if (slice instanceof Index) { exprType key = ((Index) slice).value; exprType[] arguments = new exprType[] {key, value}; Call setitemCall = NodeUtils.createMethodCall(receiver, "__setitem__", arguments); setitemCall.accept(this); } } /* * Node for bare names (variables), for example the "instance" of * "instance.method" but not the "method" (which is an attribute). */ @Override public Object visitName(Name node) throws Exception { addNameUse(node); super.visitName(node); return null; } /* * Examples: * * module.function * instance.method */ @Override public Object visitAttribute(Attribute node) throws Exception { uses.add(new AttributeUse(node, module)); node.parent = stack.peek(); stack.push(node); // Don't visit node.attr, we don't want a NameUse for it. node.attr.parent = node; node.value.accept(this); stack.pop(); return null; } @Override public Object visitGlobal(Global node) throws Exception { for (NameTokType nameTok : node.names) { String name = NodeUtils.getId(nameTok); getScope().setGlobal(name); nameTok.accept(this); } return null; } @Override public Object visitIf(If node) throws Exception { Block parent = getBlock(); node.test.accept(this); Block bodyBlock = new Block(parent); Block orelseBlock = new Block(parent); visitBlock(bodyBlock, node.body); visitBlock(orelseBlock, node.orelse); parent.addCurrentDefinitions(bodyBlock); parent.addCurrentDefinitions(orelseBlock); return null; } @Override public Object visitFor(For node) throws Exception { Block parent = getBlock(); Block bodyBlock = new Block(parent); Call iterCall = NodeUtils.createMethodCall(node.iter, "__iter__"); Call nextCall = NodeUtils.createMethodCall(iterCall, "next"); nextCall.accept(this); Map<exprType, exprType> assignments = NodeUtils.createTupleElementAssignments(node.target, nextCall); for (Map.Entry<exprType, exprType> entry : assignments.entrySet()) { exprType target = entry.getKey(); exprType value = entry.getValue(); if (target instanceof Name) { String name = ((Name) target).id; Definition loopVariable = new LoopVariableDefinition(module, name, (Name) target, value); bodyBlock.setDefinition(loopVariable); parent.addDefinition(loopVariable); } else if (target instanceof Subscript) { processSubscriptAssignment(target, value); } else if (target instanceof Attribute) { /* * TODO: What to do about this?: * * x = Class() * for x.attribute in [1, 2, 3]: * print x.attribute */ } } visitBlock(bodyBlock, node.body); Block orelseBlock = new Block(parent); // Definitions may flow from the body to the else block. orelseBlock.addCurrentDefinitions(bodyBlock); visitBlock(orelseBlock, node.orelse); parent.addCurrentDefinitions(bodyBlock); parent.addCurrentDefinitions(orelseBlock); return null; } @Override public Object visitListComp(ListComp node) throws Exception { Block block = new Block(getBlock()); for (comprehensionType generator : node.generators) { /* Comprehension is the only subclass of comprehensionType */ Comprehension comp = (Comprehension) generator; Call iterCall = NodeUtils.createMethodCall(comp.iter, "__iter__"); Call nextCall = NodeUtils.createMethodCall(iterCall, "next"); nextCall.accept(this); Map<exprType, exprType> assignments = NodeUtils.createTupleElementAssignments(comp.target, nextCall); for (Map.Entry<exprType, exprType> entry : assignments.entrySet()) { exprType target = entry.getKey(); exprType value = entry.getValue(); if (target instanceof Name) { String name = ((Name) target).id; Definition loopVariable = new LoopVariableDefinition(module, name, (Name) target, value); block.setDefinition(loopVariable); } else if (target instanceof Subscript) { processSubscriptAssignment(target, value); } else if (target instanceof Attribute) { // Ignore for now } } } blocks.push(block); node.elt.accept(this); blocks.pop(); return null; } @Override public Object visitWhile(While node) throws Exception { Block parent = getBlock(); node.test.accept(this); Block bodyBlock = new Block(parent); Block orelseBlock = new Block(parent); visitBlock(bodyBlock, node.body); orelseBlock.addCurrentDefinitions(bodyBlock); visitBlock(orelseBlock, node.orelse); parent.addCurrentDefinitions(bodyBlock); parent.addCurrentDefinitions(orelseBlock); return null; } @Override public Object visitTryExcept(TryExcept node) throws Exception { Block parent = getBlock(); Block bodyBlock = new Block(parent); Block orelseBlock = new Block(parent); visitBlock(bodyBlock, node.body); for (excepthandlerType handler : node.handlers) { Block handlerBlock = new Block(parent); handlerBlock.addBlockDefinitions(bodyBlock); // TODO: What about tuples? if (handler.name instanceof Name) { String name = ((Name) handler.name).id; ExceptDefinition definition = new ExceptDefinition(module, name, handler); handlerBlock.setDefinition(definition); } visitBlock(handlerBlock, handler.body); parent.addCurrentDefinitions(handlerBlock); } orelseBlock.addBlockDefinitions(bodyBlock); visitBlock(orelseBlock, node.orelse); // We need to add all definitions of the block, because we don't know // where the exception was thrown, it could be between two definitions // of the same name. parent.addBlockDefinitions(bodyBlock); parent.addCurrentDefinitions(orelseBlock); return null; } @Override public Object visitTryFinally(TryFinally node) throws Exception { Block parent = getBlock(); Block bodyBlock = new Block(parent); Block finallyBlock = new Block(parent); visitBlock(bodyBlock, node.body); finallyBlock.addBlockDefinitions(bodyBlock); visitBlock(finallyBlock, node.finalbody); parent.addBlockDefinitions(bodyBlock); // Overwrite the current definitions, because we don't know whether an // exception occurred or not. for (Definition definition : finallyBlock.getCurrentDefinitions()) { parent.setDefinition(definition); } return null; } private void visitBlock(Block block, stmtType[] body) throws Exception { if (body == null) { return; } blocks.push(block); for (stmtType statement : body) { statement.accept(this); } blocks.pop(); } private void visitBlock(Block block, suiteType suite) throws Exception { if (suite != null) { visitBlock(block, suite.body); } } private void addDefinition(Definition definition) { if (getScope().isGlobal(definition.getName())) { moduleScope.addGlobalDefinition(definition); } else { getBlock().setDefinition(definition); } } private void addNameUse(Name node) { NameUse nameUse = new NameUse(node.id, node, module); String name = nameUse.getName(); List<Definition> definitions = getBlock().getCurrentDefinitions(name); /* Check if this nameuse is alised by the import definieren (from module import Class as Alias). If * this is the case we register another NameUse using the 'Alias' as name. This enables the * PotentialReferences Evaluator to find the name, even when it is aliased. */ for (Definition def : definitions) { if (def instanceof AliasedImportDefinition) { AliasedImportDefinition id = (AliasedImportDefinition) def; NameUse aliasedNameUse = new NameUse(id.getElement(), node, module); aliasedNameUse.addDefinition(id); uses.add(aliasedNameUse); } } nameUse.addDefinitions(definitions); if (getScope() == moduleScope || getScope().isGlobal(name)) { moduleScope.addGlobalNameUse(nameUse); } uses.add(nameUse); } private Block getBlock() { return blocks.peek(); } private Scope getScope() { Block scope = getBlock(); while (!(scope instanceof Scope)) { scope = scope.getParent(); } return (Scope) scope; } /* import stuff */ /* * Examples: * * import pkg.module * import pkg.module as module * import pkg.module, pkg2.module2 * import pkg * * Doesn't work: * * import pkg.module.Class */ @Override public Object visitImport(Import node) throws Exception { for (aliasType entry : node.names) { ImportDefinition definition; if (entry.asname == null) { /* import package.module # package -> package */ NamePath fullPath = new NamePath(NodeUtils.getId(entry.name)); NamePath name = new NamePath(fullPath.getFirstPart()); ImportPath importPath = new ImportPath(module, name, 0); definition = new ImportDefinition(module, node, importPath, null, name.toString()); } else { /* import package.module as alias # alias -> package.module */ String alias = NodeUtils.getId(entry.asname); NamePath path = new NamePath(NodeUtils.getId(entry.name)); ImportPath importPath = new ImportPath(module, path, 0); definition = new ImportDefinition(module, node, importPath, null, alias); } addDefinition(definition); } return null; } /* * Examples: * * from pkg.module import Class * from pkg.module import Class as C1, ClassTwo as C2 * from pkg.module import * # grrr * from pkg import module * from pkg import subpkg * from pkg import * # doesn't import all modules, but everything in __init__.py * from .module import Class * from . import module */ @Override public Object visitImportFrom(ImportFrom node) throws Exception { NamePath path = new NamePath(NodeUtils.getId(node.module)); ImportPath importPath = new ImportPath(module, path, node.level); if (node.names.length == 0) { /* This is a "star" import (from module import *) */ externalScope.addImportStarPath(importPath); } else { for (aliasType entry : node.names) { String element = NodeUtils.getId(entry.name); ImportDefinition definition; if (entry.asname != null) { definition = new AliasedImportDefinition(module, node, importPath, element, NodeUtils.getId(entry.asname)); } else { definition = new ImportDefinition(module, node, importPath, element, element); } addDefinition(definition); } } return null; } }
Don't visit name targets of assignments.
src/ch/hsr/ifs/pystructure/typeinference/visitors/DefinitionVisitor.java
Don't visit name targets of assignments.
<ide><path>rc/ch/hsr/ifs/pystructure/typeinference/visitors/DefinitionVisitor.java <ide> String name = ((Name) targetPart).id; <ide> Definition d = new AssignDefinition(module, name, node, value); <ide> addDefinition(d); <del> targetPart.accept(this); <ide> } else if (targetPart instanceof Subscript) { <ide> processSubscriptAssignment(targetPart, value); <ide> } else {
Java
mit
7625f09401bf78daa3367e29658eb3808ed0a474
0
MHaubenstock/File-Encrypter
// // OutsideChainingMode.java // import java.io.*; import java.nio.file.*; import java.util.*; public class OutsideChainingMode { private List _listeners = new ArrayList(); public OutsideChainingMode() { } public void encode(String filePath, String k1, String k2, String initVector) throws IOException { beganProcessing(); //Convert keys and initialization vector to byte arrays long d1 = Long.decode("0x" + k1.substring(0,8)).longValue(); long d2 = Long.decode("0x" + k1.substring(8,16)).longValue(); byte[] key1 = DES.twoLongsTo8ByteArray(d2, d1); d1 = Long.decode("0x" + k2.substring(0,8)).longValue(); d2 = Long.decode("0x" + k2.substring(8,16)).longValue(); byte[] key2 = DES.twoLongsTo8ByteArray(d2, d1); d1 = Long.decode("0x" + initVector.substring(0,8)).longValue(); d2 = Long.decode("0x" + initVector.substring(8,16)).longValue(); byte[] initializationVector = DES.twoLongsTo8ByteArray(d2, d1); InputStreamReader in = new InputStreamReader(new FileInputStream(filePath), "iso-8859-1"); long c, fileSize = new File(filePath).length(), bytesRead = 0; //Decode DESRound round = new DESRound(); byte[] messageSegment = new byte[8]; String messageSegString; //Open print writer FileOutputStream out = new FileOutputStream("testoutputEncoded.txt"); while ((c = in.read()) != -1) { ++bytesRead; //Reset message segment string messageSegString = ""; messageSegString += String.format("%02x", c); //Already read first byte of block, now read the next seven for(int x = 1; x <= 7; ++x) { if((c = in.read()) != -1) { messageSegString += String.format("%02x", c); ++bytesRead; } else { messageSegString += String.format("%02x", 32); } } d1 = Long.decode("0x" + messageSegString.substring(0,8)).longValue(); d2 = Long.decode("0x" + messageSegString.substring(8,16)).longValue(); messageSegment = DES.twoLongsTo8ByteArray(d2, d1); //XOR with the initialization vector messageSegment = DES.XORByteArrays(messageSegment, initializationVector); //Triple des messageSegment = DES.encode(messageSegment, key1, round); messageSegment = DES.decode(messageSegment, key2, round); messageSegment = DES.encode(messageSegment, key1, round); //Set IV to the decrypted block for chaining initializationVector = messageSegment; //Write 64 bits to the out file out.write(messageSegment); //Trigger event processedData(bytesRead, fileSize); } //Close the out file out.close(); //Trigger finished event finishedProcessing(); } public void decode(String filePath, String k1, String k2, String initVector) throws IOException { beganProcessing(); //Convert keys and initialization vector to byte arrays long d1 = Long.decode("0x" + k1.substring(0,8)).longValue(); long d2 = Long.decode("0x" + k1.substring(8,16)).longValue(); byte[] key1 = DES.twoLongsTo8ByteArray(d2, d1); d1 = Long.decode("0x" + k2.substring(0,8)).longValue(); d2 = Long.decode("0x" + k2.substring(8,16)).longValue(); byte[] key2 = DES.twoLongsTo8ByteArray(d2, d1); d1 = Long.decode("0x" + initVector.substring(0,8)).longValue(); d2 = Long.decode("0x" + initVector.substring(8,16)).longValue(); byte[] initializationVector = DES.twoLongsTo8ByteArray(d2, d1); InputStreamReader in = new InputStreamReader(new FileInputStream(filePath), "iso-8859-1"); long c, fileSize = new File(filePath).length(), bytesRead = 0; //Decode DESRound round = new DESRound(); byte[] messageSegment = new byte[8]; byte[] tempInitVector; String messageSegString; //Open print writer FileOutputStream out = new FileOutputStream("testoutputDecoded.txt"); while ((c = in.read()) != -1) { ++bytesRead; //Reset message segment string messageSegString = ""; messageSegString += String.format("%02x", c); //Already read first byte of block, now read the next seven for(int x = 1; x <= 7; ++x) { if((c = in.read()) != -1) { messageSegString += String.format("%02x", c); ++bytesRead; } else { messageSegString += String.format("%02x", 32); } } d1 = Long.decode("0x" + messageSegString.substring(0,8)).longValue(); d2 = Long.decode("0x" + messageSegString.substring(8,16)).longValue(); messageSegment = DES.twoLongsTo8ByteArray(d2, d1); tempInitVector = messageSegment; //Triple des messageSegment = DES.decode(messageSegment, key1, round); messageSegment = DES.encode(messageSegment, key2, round); messageSegment = DES.decode(messageSegment, key1, round); //XOR with the initialization vector messageSegment = DES.XORByteArrays(messageSegment, initializationVector); //Set IV to the decrypted block for chaining initializationVector = tempInitVector; //Write 64 bits to the out file out.write(messageSegment); //Trigger event processedData(bytesRead, fileSize); } //Close the out file out.close(); //Trigger finished event finishedProcessing(); } public synchronized void addEventListener(EncryptEventListener listener) { _listeners.add(listener); } public synchronized void removeEventListener(EncryptEventListener listener) { _listeners.remove(listener); } private synchronized void beganProcessing() { Iterator i = _listeners.iterator(); while(i.hasNext()) { ((EncryptEventListener) i.next()).beganProcessing(); } } private synchronized void processedData(long bytesProcessed, long totalBytes) { Iterator i = _listeners.iterator(); while(i.hasNext()) { ((EncryptEventListener) i.next()).processedData(bytesProcessed, totalBytes); } } private synchronized void finishedProcessing() { Iterator i = _listeners.iterator(); while(i.hasNext()) { ((EncryptEventListener) i.next()).finishedProcessing(); } } }
OutsideChainingMode.java
// // OutsideChainingMode.java // import java.io.*; import java.nio.file.*; import java.util.*; public class OutsideChainingMode { private List _listeners = new ArrayList(); public OutsideChainingMode() { } public void encode(String filePath, String k1, String k2, String initVector) throws IOException { beganProcessing(); //Convert keys and initialization vector to byte arrays long d1 = Long.decode("0x" + k1.substring(0,8)).longValue(); long d2 = Long.decode("0x" + k1.substring(8,16)).longValue(); byte[] key1 = DES.twoLongsTo8ByteArray(d2, d1); d1 = Long.decode("0x" + k2.substring(0,8)).longValue(); d2 = Long.decode("0x" + k2.substring(8,16)).longValue(); byte[] key2 = DES.twoLongsTo8ByteArray(d2, d1); d1 = Long.decode("0x" + initVector.substring(0,8)).longValue(); d2 = Long.decode("0x" + initVector.substring(8,16)).longValue(); byte[] initializationVector = DES.twoLongsTo8ByteArray(d2, d1); InputStreamReader in = new InputStreamReader(new FileInputStream(filePath), "iso-8859-1"); long c, filesize = new File(filePath).length(), bytesRead = 0; //Decode DESRound round = new DESRound(); byte[] messageSegment = new byte[8]; String messageSegString; //Open print writer PrintWriter out = new PrintWriter("testoutputEncoded.txt"); while ((c = in.read()) != -1) { ++bytesRead; //Reset message segment string messageSegString = ""; messageSegString += String.format("%02x", c); //Already read first byte of block, now read the next seven for(int x = 1; x <= 7; ++x) { if((c = in.read()) != -1) { messageSegString += String.format("%02x", c); ++bytesRead; } else { messageSegString += String.format("%02x", 32); } } d1 = Long.decode("0x" + messageSegString.substring(0,8)).longValue(); d2 = Long.decode("0x" + messageSegString.substring(8,16)).longValue(); messageSegment = DES.twoLongsTo8ByteArray(d2, d1); //XOR with the initialization vector messageSegment = DES.XORByteArrays(messageSegment, initializationVector); //Triple des messageSegment = DES.encode(messageSegment, key1, round); messageSegment = DES.decode(messageSegment, key2, round); messageSegment = DES.encode(messageSegment, key1, round); //Set IV to the decrypted block for chaining initializationVector = messageSegment; //Write 64 bits to the out file out.print(DES.byteArrayToString(messageSegment)); //Trigger event processedData(bytesRead, filesize); } //Close the out file out.close(); //Trigger finished event finishedProcessing(); } public void decode(String filePath, String k1, String k2, String initVector) throws IOException { beganProcessing(); //Convert keys and initialization vector to byte arrays long d1 = Long.decode("0x" + k1.substring(0,8)).longValue(); long d2 = Long.decode("0x" + k1.substring(8,16)).longValue(); byte[] key1 = DES.twoLongsTo8ByteArray(d2, d1); d1 = Long.decode("0x" + k2.substring(0,8)).longValue(); d2 = Long.decode("0x" + k2.substring(8,16)).longValue(); byte[] key2 = DES.twoLongsTo8ByteArray(d2, d1); d1 = Long.decode("0x" + initVector.substring(0,8)).longValue(); d2 = Long.decode("0x" + initVector.substring(8,16)).longValue(); byte[] initializationVector = DES.twoLongsTo8ByteArray(d2, d1); InputStreamReader in = new InputStreamReader(new FileInputStream(filePath), "iso-8859-1"); long c, filesize = new File(filePath).length(), bytesRead = 0; //Decode DESRound round = new DESRound(); byte[] messageSegment = new byte[8]; byte[] tempInitVector; String messageSegString; //Open print writer FileOutputStream out = new FileOutputStream("testoutputDecoded.txt"); while ((c = in.read()) != -1) { ++bytesRead; //Reset message segment string messageSegString = ""; messageSegString += (char)c; //Already read first byte of block, now read the next seven for(int x = 1; x <= 15; ++x) { if((c = in.read()) != -1) //If its a valid hex digit, keep processing if(Character.digit((char)c, 16) != -1) { messageSegString += (char)c; ++bytesRead; } //Else throw an IOException //This is because you are reading in a decrypted file that should be all hex digits else { //Close the out file to prevent memory leaks out.close(); throw new IOException("The encrypted file is corrupted!"); } else messageSegString += "0"; } d1 = Long.decode("0x" + messageSegString.substring(0,8)).longValue(); d2 = Long.decode("0x" + messageSegString.substring(8,16)).longValue(); messageSegment = DES.twoLongsTo8ByteArray(d2, d1); tempInitVector = messageSegment; //Triple des messageSegment = DES.decode(messageSegment, key1, round); messageSegment = DES.encode(messageSegment, key2, round); messageSegment = DES.decode(messageSegment, key1, round); //XOR with the initialization vector messageSegment = DES.XORByteArrays(messageSegment, initializationVector); //Set IV to the decrypted block for chaining initializationVector = tempInitVector; //Write 64 bits to the out file out.write(messageSegment); //Trigger event processedData(bytesRead, filesize); } //Close the out file out.close(); //Trigger finished event finishedProcessing(); } public synchronized void addEventListener(EncryptEventListener listener) { _listeners.add(listener); } public synchronized void removeEventListener(EncryptEventListener listener) { _listeners.remove(listener); } private synchronized void beganProcessing() { Iterator i = _listeners.iterator(); while(i.hasNext()) { ((EncryptEventListener) i.next()).beganProcessing(); } } private synchronized void processedData(long bytesProcessed, long totalBytes) { Iterator i = _listeners.iterator(); while(i.hasNext()) { ((EncryptEventListener) i.next()).processedData(bytesProcessed, totalBytes); } } private synchronized void finishedProcessing() { Iterator i = _listeners.iterator(); while(i.hasNext()) { ((EncryptEventListener) i.next()).finishedProcessing(); } } }
Now uses bytes all the way through. No longer stores encrypted data as text file of hex digits.
OutsideChainingMode.java
Now uses bytes all the way through. No longer stores encrypted data as text file of hex digits.
<ide><path>utsideChainingMode.java <ide> byte[] initializationVector = DES.twoLongsTo8ByteArray(d2, d1); <ide> <ide> InputStreamReader in = new InputStreamReader(new FileInputStream(filePath), "iso-8859-1"); <del> long c, filesize = new File(filePath).length(), bytesRead = 0; <add> long c, fileSize = new File(filePath).length(), bytesRead = 0; <ide> <ide> //Decode <ide> DESRound round = new DESRound(); <ide> String messageSegString; <ide> <ide> //Open print writer <del> PrintWriter out = new PrintWriter("testoutputEncoded.txt"); <add> FileOutputStream out = new FileOutputStream("testoutputEncoded.txt"); <ide> <ide> while ((c = in.read()) != -1) <ide> { <ide> initializationVector = messageSegment; <ide> <ide> //Write 64 bits to the out file <del> out.print(DES.byteArrayToString(messageSegment)); <add> out.write(messageSegment); <ide> <ide> //Trigger event <del> processedData(bytesRead, filesize); <add> processedData(bytesRead, fileSize); <ide> } <ide> <ide> //Close the out file <ide> byte[] initializationVector = DES.twoLongsTo8ByteArray(d2, d1); <ide> <ide> InputStreamReader in = new InputStreamReader(new FileInputStream(filePath), "iso-8859-1"); <del> long c, filesize = new File(filePath).length(), bytesRead = 0; <add> long c, fileSize = new File(filePath).length(), bytesRead = 0; <ide> <ide> //Decode <ide> DESRound round = new DESRound(); <ide> //Reset message segment string <ide> messageSegString = ""; <ide> <del> messageSegString += (char)c; <add> messageSegString += String.format("%02x", c); <ide> <ide> //Already read first byte of block, now read the next seven <del> for(int x = 1; x <= 15; ++x) <add> for(int x = 1; x <= 7; ++x) <ide> { <ide> if((c = in.read()) != -1) <del> //If its a valid hex digit, keep processing <del> if(Character.digit((char)c, 16) != -1) <del> { <del> messageSegString += (char)c; <del> ++bytesRead; <del> } <del> //Else throw an IOException <del> //This is because you are reading in a decrypted file that should be all hex digits <del> else <del> { <del> //Close the out file to prevent memory leaks <del> out.close(); <del> <del> throw new IOException("The encrypted file is corrupted!"); <del> } <add> { <add> messageSegString += String.format("%02x", c); <add> ++bytesRead; <add> } <ide> else <del> messageSegString += "0"; <add> { <add> messageSegString += String.format("%02x", 32); <add> } <ide> } <ide> <ide> d1 = Long.decode("0x" + messageSegString.substring(0,8)).longValue(); <ide> out.write(messageSegment); <ide> <ide> //Trigger event <del> processedData(bytesRead, filesize); <add> processedData(bytesRead, fileSize); <ide> } <ide> <ide> //Close the out file
Java
apache-2.0
d8a3c7c1b1959420d872c160884459cc4c0b64a0
0
ol-loginov/intellij-community,ryano144/intellij-community,supersven/intellij-community,salguarnieri/intellij-community,TangHao1987/intellij-community,jagguli/intellij-community,diorcety/intellij-community,vvv1559/intellij-community,suncycheng/intellij-community,FHannes/intellij-community,fitermay/intellij-community,muntasirsyed/intellij-community,wreckJ/intellij-community,caot/intellij-community,adedayo/intellij-community,petteyg/intellij-community,vvv1559/intellij-community,ibinti/intellij-community,allotria/intellij-community,kool79/intellij-community,adedayo/intellij-community,supersven/intellij-community,mglukhikh/intellij-community,diorcety/intellij-community,apixandru/intellij-community,amith01994/intellij-community,idea4bsd/idea4bsd,salguarnieri/intellij-community,ryano144/intellij-community,ol-loginov/intellij-community,MichaelNedzelsky/intellij-community,kdwink/intellij-community,MichaelNedzelsky/intellij-community,youdonghai/intellij-community,ThiagoGarciaAlves/intellij-community,kdwink/intellij-community,semonte/intellij-community,clumsy/intellij-community,ahb0327/intellij-community,MichaelNedzelsky/intellij-community,fengbaicanhe/intellij-community,fitermay/intellij-community,lucafavatella/intellij-community,ivan-fedorov/intellij-community,mglukhikh/intellij-community,da1z/intellij-community,allotria/intellij-community,orekyuu/intellij-community,fitermay/intellij-community,idea4bsd/idea4bsd,caot/intellij-community,ftomassetti/intellij-community,vladmm/intellij-community,MER-GROUP/intellij-community,Lekanich/intellij-community,salguarnieri/intellij-community,signed/intellij-community,lucafavatella/intellij-community,clumsy/intellij-community,signed/intellij-community,vladmm/intellij-community,SerCeMan/intellij-community,diorcety/intellij-community,orekyuu/intellij-community,ibinti/intellij-community,fengbaicanhe/intellij-community,SerCeMan/intellij-community,tmpgit/intellij-community,robovm/robovm-studio,da1z/intellij-community,holmes/intellij-community,ivan-fedorov/intellij-community,adedayo/intellij-community,FHannes/intellij-community,pwoodworth/intellij-community,ryano144/intellij-community,blademainer/intellij-community,fitermay/intellij-community,amith01994/intellij-community,MichaelNedzelsky/intellij-community,petteyg/intellij-community,izonder/intellij-community,samthor/intellij-community,ernestp/consulo,salguarnieri/intellij-community,izonder/intellij-community,akosyakov/intellij-community,fitermay/intellij-community,fitermay/intellij-community,caot/intellij-community,fengbaicanhe/intellij-community,xfournet/intellij-community,slisson/intellij-community,orekyuu/intellij-community,salguarnieri/intellij-community,MichaelNedzelsky/intellij-community,slisson/intellij-community,michaelgallacher/intellij-community,mglukhikh/intellij-community,jagguli/intellij-community,amith01994/intellij-community,dslomov/intellij-community,ernestp/consulo,mglukhikh/intellij-community,semonte/intellij-community,SerCeMan/intellij-community,orekyuu/intellij-community,hurricup/intellij-community,vvv1559/intellij-community,youdonghai/intellij-community,ryano144/intellij-community,youdonghai/intellij-community,michaelgallacher/intellij-community,Lekanich/intellij-community,ThiagoGarciaAlves/intellij-community,Lekanich/intellij-community,gnuhub/intellij-community,kdwink/intellij-community,blademainer/intellij-community,kdwink/intellij-community,lucafavatella/intellij-community,fnouama/intellij-community,suncycheng/intellij-community,fnouama/intellij-community,jagguli/intellij-community,jagguli/intellij-community,ivan-fedorov/intellij-community,asedunov/intellij-community,robovm/robovm-studio,dslomov/intellij-community,nicolargo/intellij-community,TangHao1987/intellij-community,FHannes/intellij-community,pwoodworth/intellij-community,michaelgallacher/intellij-community,allotria/intellij-community,gnuhub/intellij-community,izonder/intellij-community,xfournet/intellij-community,nicolargo/intellij-community,holmes/intellij-community,robovm/robovm-studio,vvv1559/intellij-community,alphafoobar/intellij-community,kool79/intellij-community,suncycheng/intellij-community,signed/intellij-community,retomerz/intellij-community,ivan-fedorov/intellij-community,apixandru/intellij-community,kdwink/intellij-community,retomerz/intellij-community,SerCeMan/intellij-community,Lekanich/intellij-community,slisson/intellij-community,TangHao1987/intellij-community,allotria/intellij-community,semonte/intellij-community,fengbaicanhe/intellij-community,michaelgallacher/intellij-community,caot/intellij-community,supersven/intellij-community,apixandru/intellij-community,caot/intellij-community,robovm/robovm-studio,supersven/intellij-community,clumsy/intellij-community,MER-GROUP/intellij-community,ThiagoGarciaAlves/intellij-community,kdwink/intellij-community,nicolargo/intellij-community,fitermay/intellij-community,xfournet/intellij-community,retomerz/intellij-community,akosyakov/intellij-community,MER-GROUP/intellij-community,TangHao1987/intellij-community,da1z/intellij-community,lucafavatella/intellij-community,ThiagoGarciaAlves/intellij-community,youdonghai/intellij-community,da1z/intellij-community,mglukhikh/intellij-community,hurricup/intellij-community,robovm/robovm-studio,ivan-fedorov/intellij-community,consulo/consulo,amith01994/intellij-community,FHannes/intellij-community,vladmm/intellij-community,robovm/robovm-studio,supersven/intellij-community,ibinti/intellij-community,signed/intellij-community,muntasirsyed/intellij-community,Lekanich/intellij-community,semonte/intellij-community,fnouama/intellij-community,idea4bsd/idea4bsd,TangHao1987/intellij-community,wreckJ/intellij-community,jagguli/intellij-community,clumsy/intellij-community,amith01994/intellij-community,xfournet/intellij-community,gnuhub/intellij-community,ibinti/intellij-community,lucafavatella/intellij-community,amith01994/intellij-community,akosyakov/intellij-community,michaelgallacher/intellij-community,alphafoobar/intellij-community,MER-GROUP/intellij-community,xfournet/intellij-community,supersven/intellij-community,retomerz/intellij-community,salguarnieri/intellij-community,holmes/intellij-community,fitermay/intellij-community,slisson/intellij-community,fnouama/intellij-community,muntasirsyed/intellij-community,gnuhub/intellij-community,slisson/intellij-community,mglukhikh/intellij-community,semonte/intellij-community,asedunov/intellij-community,fitermay/intellij-community,fnouama/intellij-community,vvv1559/intellij-community,samthor/intellij-community,pwoodworth/intellij-community,blademainer/intellij-community,blademainer/intellij-community,muntasirsyed/intellij-community,ftomassetti/intellij-community,apixandru/intellij-community,asedunov/intellij-community,vladmm/intellij-community,gnuhub/intellij-community,mglukhikh/intellij-community,ThiagoGarciaAlves/intellij-community,samthor/intellij-community,MichaelNedzelsky/intellij-community,fnouama/intellij-community,holmes/intellij-community,lucafavatella/intellij-community,signed/intellij-community,samthor/intellij-community,ernestp/consulo,fitermay/intellij-community,orekyuu/intellij-community,caot/intellij-community,wreckJ/intellij-community,TangHao1987/intellij-community,asedunov/intellij-community,petteyg/intellij-community,samthor/intellij-community,caot/intellij-community,youdonghai/intellij-community,tmpgit/intellij-community,holmes/intellij-community,kdwink/intellij-community,signed/intellij-community,slisson/intellij-community,ivan-fedorov/intellij-community,orekyuu/intellij-community,hurricup/intellij-community,diorcety/intellij-community,vladmm/intellij-community,fnouama/intellij-community,ahb0327/intellij-community,jagguli/intellij-community,semonte/intellij-community,petteyg/intellij-community,MER-GROUP/intellij-community,TangHao1987/intellij-community,dslomov/intellij-community,ThiagoGarciaAlves/intellij-community,ibinti/intellij-community,michaelgallacher/intellij-community,holmes/intellij-community,hurricup/intellij-community,ibinti/intellij-community,supersven/intellij-community,petteyg/intellij-community,semonte/intellij-community,retomerz/intellij-community,slisson/intellij-community,tmpgit/intellij-community,jagguli/intellij-community,vvv1559/intellij-community,allotria/intellij-community,adedayo/intellij-community,suncycheng/intellij-community,samthor/intellij-community,ThiagoGarciaAlves/intellij-community,SerCeMan/intellij-community,kool79/intellij-community,orekyuu/intellij-community,mglukhikh/intellij-community,samthor/intellij-community,MichaelNedzelsky/intellij-community,ol-loginov/intellij-community,kdwink/intellij-community,lucafavatella/intellij-community,xfournet/intellij-community,clumsy/intellij-community,apixandru/intellij-community,apixandru/intellij-community,alphafoobar/intellij-community,ibinti/intellij-community,ahb0327/intellij-community,apixandru/intellij-community,vladmm/intellij-community,pwoodworth/intellij-community,pwoodworth/intellij-community,allotria/intellij-community,akosyakov/intellij-community,ftomassetti/intellij-community,ol-loginov/intellij-community,mglukhikh/intellij-community,ryano144/intellij-community,ivan-fedorov/intellij-community,clumsy/intellij-community,youdonghai/intellij-community,allotria/intellij-community,diorcety/intellij-community,lucafavatella/intellij-community,nicolargo/intellij-community,consulo/consulo,asedunov/intellij-community,idea4bsd/idea4bsd,ol-loginov/intellij-community,kdwink/intellij-community,tmpgit/intellij-community,samthor/intellij-community,fengbaicanhe/intellij-community,hurricup/intellij-community,suncycheng/intellij-community,adedayo/intellij-community,ahb0327/intellij-community,jagguli/intellij-community,signed/intellij-community,hurricup/intellij-community,wreckJ/intellij-community,alphafoobar/intellij-community,wreckJ/intellij-community,muntasirsyed/intellij-community,MER-GROUP/intellij-community,holmes/intellij-community,ol-loginov/intellij-community,FHannes/intellij-community,lucafavatella/intellij-community,Distrotech/intellij-community,signed/intellij-community,diorcety/intellij-community,gnuhub/intellij-community,MER-GROUP/intellij-community,jagguli/intellij-community,pwoodworth/intellij-community,jagguli/intellij-community,xfournet/intellij-community,supersven/intellij-community,salguarnieri/intellij-community,retomerz/intellij-community,hurricup/intellij-community,FHannes/intellij-community,orekyuu/intellij-community,fitermay/intellij-community,ftomassetti/intellij-community,slisson/intellij-community,apixandru/intellij-community,retomerz/intellij-community,hurricup/intellij-community,robovm/robovm-studio,suncycheng/intellij-community,semonte/intellij-community,wreckJ/intellij-community,fnouama/intellij-community,holmes/intellij-community,blademainer/intellij-community,tmpgit/intellij-community,youdonghai/intellij-community,gnuhub/intellij-community,dslomov/intellij-community,idea4bsd/idea4bsd,xfournet/intellij-community,allotria/intellij-community,holmes/intellij-community,kool79/intellij-community,alphafoobar/intellij-community,michaelgallacher/intellij-community,amith01994/intellij-community,izonder/intellij-community,michaelgallacher/intellij-community,ol-loginov/intellij-community,Distrotech/intellij-community,ftomassetti/intellij-community,FHannes/intellij-community,ibinti/intellij-community,diorcety/intellij-community,SerCeMan/intellij-community,ahb0327/intellij-community,retomerz/intellij-community,caot/intellij-community,muntasirsyed/intellij-community,vvv1559/intellij-community,MichaelNedzelsky/intellij-community,semonte/intellij-community,ryano144/intellij-community,adedayo/intellij-community,TangHao1987/intellij-community,asedunov/intellij-community,Lekanich/intellij-community,amith01994/intellij-community,fitermay/intellij-community,vladmm/intellij-community,akosyakov/intellij-community,dslomov/intellij-community,holmes/intellij-community,FHannes/intellij-community,hurricup/intellij-community,ftomassetti/intellij-community,retomerz/intellij-community,dslomov/intellij-community,wreckJ/intellij-community,jagguli/intellij-community,alphafoobar/intellij-community,lucafavatella/intellij-community,idea4bsd/idea4bsd,ftomassetti/intellij-community,da1z/intellij-community,SerCeMan/intellij-community,kool79/intellij-community,dslomov/intellij-community,ahb0327/intellij-community,supersven/intellij-community,MER-GROUP/intellij-community,kool79/intellij-community,semonte/intellij-community,Lekanich/intellij-community,izonder/intellij-community,youdonghai/intellij-community,pwoodworth/intellij-community,vvv1559/intellij-community,ivan-fedorov/intellij-community,ol-loginov/intellij-community,supersven/intellij-community,fengbaicanhe/intellij-community,caot/intellij-community,suncycheng/intellij-community,petteyg/intellij-community,gnuhub/intellij-community,nicolargo/intellij-community,mglukhikh/intellij-community,samthor/intellij-community,Lekanich/intellij-community,allotria/intellij-community,ol-loginov/intellij-community,hurricup/intellij-community,muntasirsyed/intellij-community,blademainer/intellij-community,signed/intellij-community,MichaelNedzelsky/intellij-community,lucafavatella/intellij-community,vvv1559/intellij-community,Distrotech/intellij-community,blademainer/intellij-community,da1z/intellij-community,blademainer/intellij-community,slisson/intellij-community,adedayo/intellij-community,alphafoobar/intellij-community,robovm/robovm-studio,tmpgit/intellij-community,vladmm/intellij-community,xfournet/intellij-community,ibinti/intellij-community,clumsy/intellij-community,petteyg/intellij-community,hurricup/intellij-community,suncycheng/intellij-community,alphafoobar/intellij-community,dslomov/intellij-community,fengbaicanhe/intellij-community,kool79/intellij-community,robovm/robovm-studio,wreckJ/intellij-community,muntasirsyed/intellij-community,gnuhub/intellij-community,diorcety/intellij-community,ivan-fedorov/intellij-community,fitermay/intellij-community,akosyakov/intellij-community,asedunov/intellij-community,apixandru/intellij-community,consulo/consulo,kool79/intellij-community,Distrotech/intellij-community,fengbaicanhe/intellij-community,signed/intellij-community,clumsy/intellij-community,tmpgit/intellij-community,dslomov/intellij-community,ahb0327/intellij-community,blademainer/intellij-community,ernestp/consulo,tmpgit/intellij-community,nicolargo/intellij-community,youdonghai/intellij-community,consulo/consulo,ahb0327/intellij-community,Distrotech/intellij-community,asedunov/intellij-community,ol-loginov/intellij-community,muntasirsyed/intellij-community,izonder/intellij-community,dslomov/intellij-community,youdonghai/intellij-community,lucafavatella/intellij-community,supersven/intellij-community,holmes/intellij-community,ahb0327/intellij-community,signed/intellij-community,semonte/intellij-community,Distrotech/intellij-community,ryano144/intellij-community,retomerz/intellij-community,fengbaicanhe/intellij-community,fnouama/intellij-community,ernestp/consulo,retomerz/intellij-community,Distrotech/intellij-community,wreckJ/intellij-community,tmpgit/intellij-community,Distrotech/intellij-community,Lekanich/intellij-community,orekyuu/intellij-community,semonte/intellij-community,akosyakov/intellij-community,da1z/intellij-community,pwoodworth/intellij-community,tmpgit/intellij-community,lucafavatella/intellij-community,Distrotech/intellij-community,vladmm/intellij-community,Lekanich/intellij-community,ThiagoGarciaAlves/intellij-community,suncycheng/intellij-community,da1z/intellij-community,asedunov/intellij-community,mglukhikh/intellij-community,nicolargo/intellij-community,samthor/intellij-community,TangHao1987/intellij-community,michaelgallacher/intellij-community,allotria/intellij-community,akosyakov/intellij-community,muntasirsyed/intellij-community,retomerz/intellij-community,MichaelNedzelsky/intellij-community,michaelgallacher/intellij-community,amith01994/intellij-community,kdwink/intellij-community,alphafoobar/intellij-community,TangHao1987/intellij-community,orekyuu/intellij-community,adedayo/intellij-community,tmpgit/intellij-community,retomerz/intellij-community,TangHao1987/intellij-community,kool79/intellij-community,ahb0327/intellij-community,asedunov/intellij-community,nicolargo/intellij-community,nicolargo/intellij-community,orekyuu/intellij-community,idea4bsd/idea4bsd,nicolargo/intellij-community,clumsy/intellij-community,FHannes/intellij-community,kool79/intellij-community,slisson/intellij-community,asedunov/intellij-community,youdonghai/intellij-community,caot/intellij-community,tmpgit/intellij-community,ThiagoGarciaAlves/intellij-community,xfournet/intellij-community,supersven/intellij-community,michaelgallacher/intellij-community,izonder/intellij-community,gnuhub/intellij-community,ftomassetti/intellij-community,diorcety/intellij-community,samthor/intellij-community,alphafoobar/intellij-community,petteyg/intellij-community,izonder/intellij-community,da1z/intellij-community,clumsy/intellij-community,MER-GROUP/intellij-community,SerCeMan/intellij-community,robovm/robovm-studio,allotria/intellij-community,salguarnieri/intellij-community,wreckJ/intellij-community,clumsy/intellij-community,slisson/intellij-community,petteyg/intellij-community,ivan-fedorov/intellij-community,TangHao1987/intellij-community,pwoodworth/intellij-community,alphafoobar/intellij-community,blademainer/intellij-community,vladmm/intellij-community,ahb0327/intellij-community,salguarnieri/intellij-community,idea4bsd/idea4bsd,hurricup/intellij-community,blademainer/intellij-community,diorcety/intellij-community,FHannes/intellij-community,salguarnieri/intellij-community,amith01994/intellij-community,idea4bsd/idea4bsd,ftomassetti/intellij-community,FHannes/intellij-community,amith01994/intellij-community,vladmm/intellij-community,holmes/intellij-community,youdonghai/intellij-community,petteyg/intellij-community,apixandru/intellij-community,consulo/consulo,apixandru/intellij-community,fengbaicanhe/intellij-community,ahb0327/intellij-community,gnuhub/intellij-community,muntasirsyed/intellij-community,SerCeMan/intellij-community,ibinti/intellij-community,da1z/intellij-community,ftomassetti/intellij-community,adedayo/intellij-community,Distrotech/intellij-community,fengbaicanhe/intellij-community,slisson/intellij-community,ryano144/intellij-community,MichaelNedzelsky/intellij-community,pwoodworth/intellij-community,izonder/intellij-community,akosyakov/intellij-community,izonder/intellij-community,alphafoobar/intellij-community,samthor/intellij-community,kool79/intellij-community,adedayo/intellij-community,kool79/intellij-community,kdwink/intellij-community,idea4bsd/idea4bsd,petteyg/intellij-community,da1z/intellij-community,Lekanich/intellij-community,muntasirsyed/intellij-community,vvv1559/intellij-community,ryano144/intellij-community,mglukhikh/intellij-community,fnouama/intellij-community,jagguli/intellij-community,ryano144/intellij-community,da1z/intellij-community,allotria/intellij-community,blademainer/intellij-community,SerCeMan/intellij-community,ibinti/intellij-community,allotria/intellij-community,xfournet/intellij-community,Lekanich/intellij-community,ryano144/intellij-community,da1z/intellij-community,idea4bsd/idea4bsd,ThiagoGarciaAlves/intellij-community,Distrotech/intellij-community,dslomov/intellij-community,idea4bsd/idea4bsd,suncycheng/intellij-community,SerCeMan/intellij-community,izonder/intellij-community,asedunov/intellij-community,salguarnieri/intellij-community,caot/intellij-community,ThiagoGarciaAlves/intellij-community,MER-GROUP/intellij-community,ernestp/consulo,ol-loginov/intellij-community,FHannes/intellij-community,ftomassetti/intellij-community,ibinti/intellij-community,akosyakov/intellij-community,vladmm/intellij-community,michaelgallacher/intellij-community,orekyuu/intellij-community,nicolargo/intellij-community,gnuhub/intellij-community,consulo/consulo,suncycheng/intellij-community,signed/intellij-community,xfournet/intellij-community,ryano144/intellij-community,kdwink/intellij-community,SerCeMan/intellij-community,akosyakov/intellij-community,ThiagoGarciaAlves/intellij-community,vvv1559/intellij-community,apixandru/intellij-community,apixandru/intellij-community,ibinti/intellij-community,nicolargo/intellij-community,wreckJ/intellij-community,diorcety/intellij-community,fengbaicanhe/intellij-community,ivan-fedorov/intellij-community,suncycheng/intellij-community,caot/intellij-community,MER-GROUP/intellij-community,pwoodworth/intellij-community,signed/intellij-community,salguarnieri/intellij-community,apixandru/intellij-community,wreckJ/intellij-community,ftomassetti/intellij-community,petteyg/intellij-community,fnouama/intellij-community,xfournet/intellij-community,diorcety/intellij-community,robovm/robovm-studio,MER-GROUP/intellij-community,asedunov/intellij-community,dslomov/intellij-community,pwoodworth/intellij-community,semonte/intellij-community,adedayo/intellij-community,Distrotech/intellij-community,amith01994/intellij-community,youdonghai/intellij-community,robovm/robovm-studio,vvv1559/intellij-community,ivan-fedorov/intellij-community,adedayo/intellij-community,izonder/intellij-community,akosyakov/intellij-community,FHannes/intellij-community,idea4bsd/idea4bsd,MichaelNedzelsky/intellij-community,hurricup/intellij-community,clumsy/intellij-community,fnouama/intellij-community,mglukhikh/intellij-community,vvv1559/intellij-community,ol-loginov/intellij-community
package org.jetbrains.plugins.groovy.extensions; import com.intellij.openapi.extensions.ExtensionPointName; import com.intellij.openapi.util.text.StringUtil; import com.intellij.util.xmlb.annotations.*; import org.jetbrains.annotations.Nullable; import java.util.HashMap; import java.util.Map; import java.util.StringTokenizer; /** * @author Sergey Evdokimov */ public class SimpleGroovyNamedArgumentProvider { public static final ExtensionPointName<SimpleGroovyNamedArgumentProvider> EP_NAME = new ExtensionPointName<SimpleGroovyNamedArgumentProvider>("org.intellij.groovy.namedArguments"); private static final String ATTR_NAMES_DELIMITER = " \t\n\r,;"; @Attribute("class") public String className; @Property(surroundWithTag = false) @AbstractCollection(surroundWithTag = false) public MethodDescriptor[] methods; private static Map<String, Map<String, Map<String, GroovyNamedArgumentProvider.ArgumentDescriptor>>> MAP; public static Map<String, GroovyNamedArgumentProvider.ArgumentDescriptor> getMethodMap(@Nullable String className, @Nullable String methodName) { if (MAP == null) { Map<String, Map<String, Map<String, GroovyNamedArgumentProvider.ArgumentDescriptor>>> map = new HashMap<String, Map<String, Map<String, GroovyNamedArgumentProvider.ArgumentDescriptor>>>(); for (SimpleGroovyNamedArgumentProvider provider : EP_NAME.getExtensions()) { assert !StringUtil.isEmptyOrSpaces(provider.className); Map<String, Map<String, GroovyNamedArgumentProvider.ArgumentDescriptor>> methodMap = map.get(provider.className); if (methodMap == null) { methodMap = new HashMap<String, Map<String, GroovyNamedArgumentProvider.ArgumentDescriptor>>(); map.put(provider.className, methodMap); } for (MethodDescriptor methodDescriptor : provider.methods) { assert !StringUtil.isEmptyOrSpaces(methodDescriptor.name); Object oldValue = methodMap.put(methodDescriptor.name, methodDescriptor.getArgumentsMap()); assert oldValue == null; } } MAP = map; } Map<String, Map<String, GroovyNamedArgumentProvider.ArgumentDescriptor>> methodMap = MAP.get(className); if (methodMap == null) return null; return methodMap.get(methodName); } @Tag("method") public static class MethodDescriptor { @Attribute("name") public String name; @Attribute("attrNames") public String attrNames; @Attribute("showFirst") public Boolean isFirst; @Property(surroundWithTag = false) @AbstractCollection(surroundWithTag = false) //public Arguments[] arguments; public Arguments[] myArguments; public Map<String, GroovyNamedArgumentProvider.ArgumentDescriptor> getArgumentsMap() { Map<String, GroovyNamedArgumentProvider.ArgumentDescriptor> res = new HashMap<String, GroovyNamedArgumentProvider.ArgumentDescriptor>(); if (myArguments != null) { for (Arguments arguments : myArguments) { GroovyNamedArgumentProvider.ArgumentDescriptor descriptor = getDescriptor(isFirst, arguments.isFirst, arguments.type); assert StringUtil.isEmptyOrSpaces(arguments.names) != StringUtil.isEmptyOrSpaces(arguments.text); String names = arguments.names; if (StringUtil.isEmptyOrSpaces(names)) { names = arguments.text; } for (StringTokenizer st = new StringTokenizer(names, ATTR_NAMES_DELIMITER); st.hasMoreTokens(); ) { String name = st.nextToken(); Object oldValue = res.put(name, descriptor); assert oldValue == null; } } } if (!StringUtil.isEmptyOrSpaces(attrNames)) { GroovyNamedArgumentProvider.ArgumentDescriptor descriptor = getDescriptor(isFirst, null, null); for (StringTokenizer st = new StringTokenizer(attrNames, ATTR_NAMES_DELIMITER); st.hasMoreTokens(); ) { String name = st.nextToken(); Object oldValue = res.put(name, descriptor); assert oldValue == null; } } return res; } private static GroovyNamedArgumentProvider.ArgumentDescriptor getDescriptor(@Nullable Boolean methodFirstFlag, @Nullable Boolean attrFirstFlag, @Nullable String type) { Boolean objShowFirst = attrFirstFlag; if (objShowFirst == null) { objShowFirst = methodFirstFlag; } boolean showFirst = objShowFirst == null || objShowFirst; if (StringUtil.isEmptyOrSpaces(type)) { return showFirst ? GroovyNamedArgumentProvider.TYPE_ANY : GroovyNamedArgumentProvider.TYPE_ANY_NOT_FIRST; } GroovyNamedArgumentProvider.ArgumentDescriptor descriptor = new GroovyNamedArgumentProvider.StringTypeCondition(type.trim()); if (!showFirst) { descriptor.setShowFirst(false); } return descriptor; } } @Tag("attrs") public static class Arguments { @Attribute("type") public String type; @Attribute("showFirst") public Boolean isFirst; @Attribute("names") public String names; @Text public String text; } }
plugins/groovy/src/org/jetbrains/plugins/groovy/extensions/SimpleGroovyNamedArgumentProvider.java
package org.jetbrains.plugins.groovy.extensions; import com.intellij.openapi.extensions.ExtensionPointName; import com.intellij.openapi.util.text.StringUtil; import com.intellij.util.xmlb.annotations.*; import org.jetbrains.annotations.Nullable; import java.util.HashMap; import java.util.Map; import java.util.StringTokenizer; /** * @author Sergey Evdokimov */ public class SimpleGroovyNamedArgumentProvider { public static final ExtensionPointName<SimpleGroovyNamedArgumentProvider> EP_NAME = new ExtensionPointName<SimpleGroovyNamedArgumentProvider>("org.intellij.groovy.namedArguments"); @Attribute("class") public String className; @Property(surroundWithTag = false) @AbstractCollection(surroundWithTag = false) public MethodDescriptor[] methods; private static Map<String, Map<String, Map<String, GroovyNamedArgumentProvider.ArgumentDescriptor>>> MAP; public static Map<String, GroovyNamedArgumentProvider.ArgumentDescriptor> getMethodMap(@Nullable String className, @Nullable String methodName) { if (MAP == null) { Map<String, Map<String, Map<String, GroovyNamedArgumentProvider.ArgumentDescriptor>>> map = new HashMap<String, Map<String, Map<String, GroovyNamedArgumentProvider.ArgumentDescriptor>>>(); for (SimpleGroovyNamedArgumentProvider provider : EP_NAME.getExtensions()) { assert !StringUtil.isEmptyOrSpaces(provider.className); Map<String, Map<String, GroovyNamedArgumentProvider.ArgumentDescriptor>> methodMap = map.get(provider.className); if (methodMap == null) { methodMap = new HashMap<String, Map<String, GroovyNamedArgumentProvider.ArgumentDescriptor>>(); map.put(provider.className, methodMap); } for (MethodDescriptor methodDescriptor : provider.methods) { assert !StringUtil.isEmptyOrSpaces(methodDescriptor.name); Object oldValue = methodMap.put(methodDescriptor.name, methodDescriptor.getArgumentsMap()); assert oldValue == null; } } MAP = map; } Map<String, Map<String, GroovyNamedArgumentProvider.ArgumentDescriptor>> methodMap = MAP.get(className); if (methodMap == null) return null; return methodMap.get(methodName); } @Tag("method") public static class MethodDescriptor { @Attribute("name") public String name; @Attribute("showFirst") public Boolean isFirst; @Property(surroundWithTag = false) @AbstractCollection(surroundWithTag = false) public Argument[] arguments; @Property(surroundWithTag = false) @AbstractCollection(surroundWithTag = false) public Arguments[] argumentLists; public Map<String, GroovyNamedArgumentProvider.ArgumentDescriptor> getArgumentsMap() { Map<String, GroovyNamedArgumentProvider.ArgumentDescriptor> res = new HashMap<String, GroovyNamedArgumentProvider.ArgumentDescriptor>(); if (arguments != null) { for (Argument argument : arguments) { String name = argument.name.trim(); assert name.length() > 0; Object oldValue = res.put(name, getDescriptor(argument.isFirst, isFirst, argument.type)); assert oldValue == null; } } if (argumentLists != null) { for (Arguments arguments : argumentLists) { GroovyNamedArgumentProvider.ArgumentDescriptor descriptor = getDescriptor(arguments.isFirst, isFirst, arguments.type); assert !StringUtil.isEmptyOrSpaces(arguments.text); for (StringTokenizer st = new StringTokenizer(arguments.text, " \t\n\r,;"); st.hasMoreTokens(); ) { String name = st.nextToken(); Object oldValue = res.put(name, descriptor); assert oldValue == null; } } } return res; } private static GroovyNamedArgumentProvider.ArgumentDescriptor getDescriptor(Boolean methodFirstFlag, Boolean attrFirstFlag, String type) { Boolean objShowFirst = attrFirstFlag; if (objShowFirst == null) { objShowFirst = methodFirstFlag; } boolean showFirst = objShowFirst == null || objShowFirst; if (StringUtil.isEmptyOrSpaces(type)) { return showFirst ? GroovyNamedArgumentProvider.TYPE_ANY : GroovyNamedArgumentProvider.TYPE_ANY_NOT_FIRST; } GroovyNamedArgumentProvider.ArgumentDescriptor descriptor = new GroovyNamedArgumentProvider.StringTypeCondition(type.trim()); if (!showFirst) { descriptor.setShowFirst(false); } return descriptor; } } @Tag("attrs") public static class Arguments { @Attribute("type") public String type; @Attribute("showFirst") public Boolean isFirst; @Text public String text; } @Tag("attr") public static class Argument { @Attribute("type") public String type; @Attribute("showFirst") public Boolean isFirst; @Attribute("name") public String name; } }
Change API of extensionPoint 'namedArguments' to simplify declaration of attribute names.
plugins/groovy/src/org/jetbrains/plugins/groovy/extensions/SimpleGroovyNamedArgumentProvider.java
Change API of extensionPoint 'namedArguments' to simplify declaration of attribute names.
<ide><path>lugins/groovy/src/org/jetbrains/plugins/groovy/extensions/SimpleGroovyNamedArgumentProvider.java <ide> <ide> public static final ExtensionPointName<SimpleGroovyNamedArgumentProvider> EP_NAME = <ide> new ExtensionPointName<SimpleGroovyNamedArgumentProvider>("org.intellij.groovy.namedArguments"); <add> <add> private static final String ATTR_NAMES_DELIMITER = " \t\n\r,;"; <ide> <ide> @Attribute("class") <ide> public String className; <ide> @Attribute("name") <ide> public String name; <ide> <add> @Attribute("attrNames") <add> public String attrNames; <add> <ide> @Attribute("showFirst") <ide> public Boolean isFirst; <ide> <ide> @Property(surroundWithTag = false) <ide> @AbstractCollection(surroundWithTag = false) <del> public Argument[] arguments; <del> <del> @Property(surroundWithTag = false) <del> @AbstractCollection(surroundWithTag = false) <del> public Arguments[] argumentLists; <add> //public Arguments[] arguments; <add> public Arguments[] myArguments; <ide> <ide> public Map<String, GroovyNamedArgumentProvider.ArgumentDescriptor> getArgumentsMap() { <ide> Map<String, GroovyNamedArgumentProvider.ArgumentDescriptor> res = <ide> new HashMap<String, GroovyNamedArgumentProvider.ArgumentDescriptor>(); <ide> <del> if (arguments != null) { <del> for (Argument argument : arguments) { <del> String name = argument.name.trim(); <del> assert name.length() > 0; <add> if (myArguments != null) { <add> for (Arguments arguments : myArguments) { <add> GroovyNamedArgumentProvider.ArgumentDescriptor descriptor = getDescriptor(isFirst, arguments.isFirst, arguments.type); <ide> <del> Object oldValue = res.put(name, getDescriptor(argument.isFirst, isFirst, argument.type)); <del> assert oldValue == null; <del> } <del> } <add> assert StringUtil.isEmptyOrSpaces(arguments.names) != StringUtil.isEmptyOrSpaces(arguments.text); <ide> <del> if (argumentLists != null) { <del> for (Arguments arguments : argumentLists) { <del> GroovyNamedArgumentProvider.ArgumentDescriptor descriptor = getDescriptor(arguments.isFirst, isFirst, arguments.type); <add> String names = arguments.names; <add> if (StringUtil.isEmptyOrSpaces(names)) { <add> names = arguments.text; <add> } <ide> <del> assert !StringUtil.isEmptyOrSpaces(arguments.text); <del> for (StringTokenizer st = new StringTokenizer(arguments.text, " \t\n\r,;"); st.hasMoreTokens(); ) { <add> for (StringTokenizer st = new StringTokenizer(names, ATTR_NAMES_DELIMITER); st.hasMoreTokens(); ) { <ide> String name = st.nextToken(); <ide> <ide> Object oldValue = res.put(name, descriptor); <ide> } <ide> } <ide> <add> if (!StringUtil.isEmptyOrSpaces(attrNames)) { <add> GroovyNamedArgumentProvider.ArgumentDescriptor descriptor = getDescriptor(isFirst, null, null); <add> <add> for (StringTokenizer st = new StringTokenizer(attrNames, ATTR_NAMES_DELIMITER); st.hasMoreTokens(); ) { <add> String name = st.nextToken(); <add> <add> Object oldValue = res.put(name, descriptor); <add> assert oldValue == null; <add> } <add> } <add> <ide> return res; <ide> } <ide> <del> private static GroovyNamedArgumentProvider.ArgumentDescriptor getDescriptor(Boolean methodFirstFlag, <del> Boolean attrFirstFlag, <del> String type) { <add> private static GroovyNamedArgumentProvider.ArgumentDescriptor getDescriptor(@Nullable Boolean methodFirstFlag, <add> @Nullable Boolean attrFirstFlag, <add> @Nullable String type) { <ide> Boolean objShowFirst = attrFirstFlag; <ide> if (objShowFirst == null) { <ide> objShowFirst = methodFirstFlag; <ide> @Attribute("showFirst") <ide> public Boolean isFirst; <ide> <add> @Attribute("names") <add> public String names; <add> <ide> @Text <ide> public String text; <ide> } <del> <del> @Tag("attr") <del> public static class Argument { <del> @Attribute("type") <del> public String type; <del> <del> @Attribute("showFirst") <del> public Boolean isFirst; <del> <del> @Attribute("name") <del> public String name; <del> } <ide> }
Java
agpl-3.0
6027612a6d9724d370125b0b1999ec4156eebe0f
0
ngaut/sql-layer,ngaut/sql-layer,wfxiang08/sql-layer-1,relateiq/sql-layer,relateiq/sql-layer,jaytaylor/sql-layer,qiuyesuifeng/sql-layer,wfxiang08/sql-layer-1,relateiq/sql-layer,ngaut/sql-layer,shunwang/sql-layer-1,shunwang/sql-layer-1,wfxiang08/sql-layer-1,jaytaylor/sql-layer,shunwang/sql-layer-1,qiuyesuifeng/sql-layer,qiuyesuifeng/sql-layer,jaytaylor/sql-layer,shunwang/sql-layer-1,jaytaylor/sql-layer,relateiq/sql-layer,wfxiang08/sql-layer-1,ngaut/sql-layer,qiuyesuifeng/sql-layer
/** * END USER LICENSE AGREEMENT (“EULA”) * * READ THIS AGREEMENT CAREFULLY (date: 9/13/2011): * http://www.akiban.com/licensing/20110913 * * BY INSTALLING OR USING ALL OR ANY PORTION OF THE SOFTWARE, YOU ARE ACCEPTING * ALL OF THE TERMS AND CONDITIONS OF THIS AGREEMENT. YOU AGREE THAT THIS * AGREEMENT IS ENFORCEABLE LIKE ANY WRITTEN AGREEMENT SIGNED BY YOU. * * IF YOU HAVE PAID A LICENSE FEE FOR USE OF THE SOFTWARE AND DO NOT AGREE TO * THESE TERMS, YOU MAY RETURN THE SOFTWARE FOR A FULL REFUND PROVIDED YOU (A) DO * NOT USE THE SOFTWARE AND (B) RETURN THE SOFTWARE WITHIN THIRTY (30) DAYS OF * YOUR INITIAL PURCHASE. * * IF YOU WISH TO USE THE SOFTWARE AS AN EMPLOYEE, CONTRACTOR, OR AGENT OF A * CORPORATION, PARTNERSHIP OR SIMILAR ENTITY, THEN YOU MUST BE AUTHORIZED TO SIGN * FOR AND BIND THE ENTITY IN ORDER TO ACCEPT THE TERMS OF THIS AGREEMENT. THE * LICENSES GRANTED UNDER THIS AGREEMENT ARE EXPRESSLY CONDITIONED UPON ACCEPTANCE * BY SUCH AUTHORIZED PERSONNEL. * * IF YOU HAVE ENTERED INTO A SEPARATE WRITTEN LICENSE AGREEMENT WITH AKIBAN FOR * USE OF THE SOFTWARE, THE TERMS AND CONDITIONS OF SUCH OTHER AGREEMENT SHALL * PREVAIL OVER ANY CONFLICTING TERMS OR CONDITIONS IN THIS AGREEMENT. */ package com.akiban.server.types3.mcompat.mcasts; import com.akiban.server.types3.TStrongCasts; import com.akiban.server.types3.mcompat.MBundle; import com.akiban.server.types3.mcompat.mtypes.MApproximateNumber; import com.akiban.server.types3.mcompat.mtypes.MDatetimes; import com.akiban.server.types3.mcompat.mtypes.MNumeric; import com.akiban.server.types3.mcompat.mtypes.MString; public final class Strongs { public static final TStrongCasts fromVarchar = TStrongCasts.from(MString.VARCHAR).toAll(MBundle.INSTANCE.id()); public static final TStrongCasts fromTinyint = TStrongCasts.from(MNumeric.TINYINT).to( MNumeric.SMALLINT, MNumeric.MEDIUMINT, MNumeric.INT, MNumeric.BIGINT, MNumeric.TINYINT_UNSIGNED, MNumeric.SMALLINT_UNSIGNED, MNumeric.MEDIUMINT_UNSIGNED, MNumeric.INT_UNSIGNED, MNumeric.BIGINT_UNSIGNED, MNumeric.DECIMAL, MApproximateNumber.DOUBLE ); public static final TStrongCasts fromSmallint = TStrongCasts.from(MNumeric.SMALLINT).to( MNumeric.MEDIUMINT, MNumeric.INT, MNumeric.BIGINT, MNumeric.SMALLINT_UNSIGNED, MNumeric.MEDIUMINT_UNSIGNED, MNumeric.INT_UNSIGNED, MNumeric.BIGINT_UNSIGNED, MNumeric.DECIMAL, MApproximateNumber.DOUBLE ); public static final TStrongCasts fromMediumint = TStrongCasts.from(MNumeric.MEDIUMINT).to( MNumeric.INT, MNumeric.BIGINT, MNumeric.MEDIUMINT_UNSIGNED, MNumeric.INT_UNSIGNED, MNumeric.BIGINT_UNSIGNED, MNumeric.DECIMAL, MApproximateNumber.DOUBLE ); public static final TStrongCasts fromInt = TStrongCasts.from(MNumeric.INT).to( MNumeric.BIGINT, MNumeric.INT_UNSIGNED, MNumeric.BIGINT_UNSIGNED, MNumeric.DECIMAL, MApproximateNumber.DOUBLE ); public static final TStrongCasts fromBigint = TStrongCasts.from(MNumeric.BIGINT).to( MNumeric.BIGINT_UNSIGNED, MNumeric.DECIMAL, MApproximateNumber.DOUBLE ); public static final TStrongCasts fromTinyintUnsigned = TStrongCasts.from(MNumeric.TINYINT_UNSIGNED).to( MNumeric.SMALLINT_UNSIGNED, MNumeric.MEDIUMINT_UNSIGNED, MNumeric.INT_UNSIGNED, MNumeric.BIGINT_UNSIGNED, MNumeric.DECIMAL, MNumeric.DECIMAL_UNSIGNED, MApproximateNumber.DOUBLE ); public static final TStrongCasts fromSmallintUnsigned = TStrongCasts.from(MNumeric.SMALLINT_UNSIGNED).to( MNumeric.MEDIUMINT_UNSIGNED, MNumeric.INT_UNSIGNED, MNumeric.BIGINT_UNSIGNED, MNumeric.DECIMAL, MNumeric.DECIMAL_UNSIGNED, MApproximateNumber.DOUBLE ); public static final TStrongCasts fromMediumintUnsigned = TStrongCasts.from(MNumeric.MEDIUMINT_UNSIGNED).to( MNumeric.INT_UNSIGNED, MNumeric.BIGINT_UNSIGNED, MNumeric.DECIMAL, MNumeric.DECIMAL_UNSIGNED, MApproximateNumber.DOUBLE ); public static final TStrongCasts fromIntUnsigned = TStrongCasts.from(MNumeric.INT_UNSIGNED).to( MNumeric.BIGINT_UNSIGNED, MNumeric.DECIMAL, MNumeric.DECIMAL_UNSIGNED, MApproximateNumber.DOUBLE ); public static final TStrongCasts fromBigintUnsigned = TStrongCasts.from(MNumeric.BIGINT_UNSIGNED).to( MNumeric.DECIMAL, MNumeric.DECIMAL_UNSIGNED, MApproximateNumber.DOUBLE ); public static final TStrongCasts fromDatetime = TStrongCasts.from(MDatetimes.DATETIME).to( MApproximateNumber.DOUBLE ); public static final TStrongCasts fromDate = TStrongCasts.from(MDatetimes.DATE).to( MApproximateNumber.DOUBLE ); public static final TStrongCasts fromTime = TStrongCasts.from(MDatetimes.TIME).to( MApproximateNumber.DOUBLE ); public static final TStrongCasts fromYear = TStrongCasts.from(MDatetimes.YEAR).to( MApproximateNumber.DOUBLE ); public static final TStrongCasts fromTimestamp = TStrongCasts.from(MDatetimes.TIMESTAMP).to( MApproximateNumber.DOUBLE ); public static final TStrongCasts fromDecimal = TStrongCasts.from(MNumeric.DECIMAL).to( MNumeric.DECIMAL_UNSIGNED, MApproximateNumber.DOUBLE ); public static final TStrongCasts fromDecimalUnsigned = TStrongCasts.from(MNumeric.DECIMAL_UNSIGNED).to( MApproximateNumber.DOUBLE ); public static final TStrongCasts fromFloat = TStrongCasts.from(MApproximateNumber.FLOAT).to( MApproximateNumber.DOUBLE ); public static final TStrongCasts fromFloatUnsigned = TStrongCasts.from(MApproximateNumber.FLOAT_UNSIGNED).to( MApproximateNumber.DOUBLE ); public static final TStrongCasts fromDoubleUnsigned = TStrongCasts.from(MApproximateNumber.DOUBLE_UNSIGNED).to( MApproximateNumber.DOUBLE ); }
src/main/java/com/akiban/server/types3/mcompat/mcasts/Strongs.java
/** * END USER LICENSE AGREEMENT (“EULA”) * * READ THIS AGREEMENT CAREFULLY (date: 9/13/2011): * http://www.akiban.com/licensing/20110913 * * BY INSTALLING OR USING ALL OR ANY PORTION OF THE SOFTWARE, YOU ARE ACCEPTING * ALL OF THE TERMS AND CONDITIONS OF THIS AGREEMENT. YOU AGREE THAT THIS * AGREEMENT IS ENFORCEABLE LIKE ANY WRITTEN AGREEMENT SIGNED BY YOU. * * IF YOU HAVE PAID A LICENSE FEE FOR USE OF THE SOFTWARE AND DO NOT AGREE TO * THESE TERMS, YOU MAY RETURN THE SOFTWARE FOR A FULL REFUND PROVIDED YOU (A) DO * NOT USE THE SOFTWARE AND (B) RETURN THE SOFTWARE WITHIN THIRTY (30) DAYS OF * YOUR INITIAL PURCHASE. * * IF YOU WISH TO USE THE SOFTWARE AS AN EMPLOYEE, CONTRACTOR, OR AGENT OF A * CORPORATION, PARTNERSHIP OR SIMILAR ENTITY, THEN YOU MUST BE AUTHORIZED TO SIGN * FOR AND BIND THE ENTITY IN ORDER TO ACCEPT THE TERMS OF THIS AGREEMENT. THE * LICENSES GRANTED UNDER THIS AGREEMENT ARE EXPRESSLY CONDITIONED UPON ACCEPTANCE * BY SUCH AUTHORIZED PERSONNEL. * * IF YOU HAVE ENTERED INTO A SEPARATE WRITTEN LICENSE AGREEMENT WITH AKIBAN FOR * USE OF THE SOFTWARE, THE TERMS AND CONDITIONS OF SUCH OTHER AGREEMENT SHALL * PREVAIL OVER ANY CONFLICTING TERMS OR CONDITIONS IN THIS AGREEMENT. */ package com.akiban.server.types3.mcompat.mcasts; import com.akiban.server.types3.TStrongCasts; import com.akiban.server.types3.mcompat.MBundle; import com.akiban.server.types3.mcompat.mtypes.MApproximateNumber; import com.akiban.server.types3.mcompat.mtypes.MDatetimes; import com.akiban.server.types3.mcompat.mtypes.MNumeric; import com.akiban.server.types3.mcompat.mtypes.MString; public final class Strongs { public static final TStrongCasts fromVarchar = TStrongCasts.from(MString.VARCHAR).toAll(MBundle.INSTANCE.id()); public static final TStrongCasts fromTinyint = TStrongCasts.from(MNumeric.TINYINT).to( MNumeric.SMALLINT, MNumeric.MEDIUMINT, MNumeric.INT, MNumeric.BIGINT, MNumeric.TINYINT_UNSIGNED, MNumeric.SMALLINT_UNSIGNED, MNumeric.MEDIUMINT_UNSIGNED, MNumeric.INT_UNSIGNED, MNumeric.BIGINT_UNSIGNED, MNumeric.DECIMAL, MNumeric.DECIMAL_UNSIGNED, MApproximateNumber.DOUBLE ); public static final TStrongCasts fromSmallint = TStrongCasts.from(MNumeric.SMALLINT).to( MNumeric.MEDIUMINT, MNumeric.INT, MNumeric.BIGINT, MNumeric.SMALLINT_UNSIGNED, MNumeric.MEDIUMINT_UNSIGNED, MNumeric.INT_UNSIGNED, MNumeric.BIGINT_UNSIGNED, MNumeric.DECIMAL, MNumeric.DECIMAL_UNSIGNED, MApproximateNumber.DOUBLE ); public static final TStrongCasts fromMediumint = TStrongCasts.from(MNumeric.MEDIUMINT).to( MNumeric.INT, MNumeric.BIGINT, MNumeric.SMALLINT_UNSIGNED, MNumeric.MEDIUMINT_UNSIGNED, MNumeric.INT_UNSIGNED, MNumeric.BIGINT_UNSIGNED, MNumeric.DECIMAL, MNumeric.DECIMAL_UNSIGNED, MApproximateNumber.DOUBLE ); public static final TStrongCasts fromInt = TStrongCasts.from(MNumeric.INT).to( MNumeric.BIGINT, MNumeric.SMALLINT_UNSIGNED, MNumeric.MEDIUMINT_UNSIGNED, MNumeric.INT_UNSIGNED, MNumeric.BIGINT_UNSIGNED, MNumeric.DECIMAL, MNumeric.DECIMAL_UNSIGNED, MApproximateNumber.DOUBLE ); public static final TStrongCasts fromBigint = TStrongCasts.from(MNumeric.BIGINT).to( MNumeric.SMALLINT_UNSIGNED, MNumeric.MEDIUMINT_UNSIGNED, MNumeric.INT_UNSIGNED, MNumeric.BIGINT_UNSIGNED, MNumeric.DECIMAL, MNumeric.DECIMAL_UNSIGNED, MApproximateNumber.DOUBLE ); public static final TStrongCasts fromTinyintUnsigned = TStrongCasts.from(MNumeric.TINYINT_UNSIGNED).to( MNumeric.SMALLINT_UNSIGNED, MNumeric.MEDIUMINT_UNSIGNED, MNumeric.INT_UNSIGNED, MNumeric.BIGINT_UNSIGNED, MNumeric.DECIMAL_UNSIGNED, MApproximateNumber.DOUBLE ); public static final TStrongCasts fromSmallintUnsigned = TStrongCasts.from(MNumeric.SMALLINT_UNSIGNED).to( MNumeric.MEDIUMINT_UNSIGNED, MNumeric.INT_UNSIGNED, MNumeric.BIGINT_UNSIGNED, MNumeric.DECIMAL_UNSIGNED, MApproximateNumber.DOUBLE ); public static final TStrongCasts fromMediumintUnsigned = TStrongCasts.from(MNumeric.MEDIUMINT_UNSIGNED).to( MNumeric.INT_UNSIGNED, MNumeric.BIGINT_UNSIGNED, MNumeric.DECIMAL_UNSIGNED, MApproximateNumber.DOUBLE ); public static final TStrongCasts fromIntUnsigned = TStrongCasts.from(MNumeric.INT_UNSIGNED).to( MNumeric.BIGINT_UNSIGNED, MNumeric.DECIMAL_UNSIGNED, MApproximateNumber.DOUBLE ); public static final TStrongCasts fromBigintUnsigned = TStrongCasts.from(MNumeric.BIGINT_UNSIGNED).to( MNumeric.DECIMAL, MNumeric.DECIMAL_UNSIGNED, MApproximateNumber.DOUBLE ); public static final TStrongCasts fromDatetime = TStrongCasts.from(MDatetimes.DATETIME).to( MApproximateNumber.DOUBLE ); public static final TStrongCasts fromTimestamp = TStrongCasts.from(MDatetimes.TIMESTAMP).to( MApproximateNumber.DOUBLE ); public static final TStrongCasts fromDecimal = TStrongCasts.from(MNumeric.DECIMAL).to( MNumeric.DECIMAL_UNSIGNED, MApproximateNumber.DOUBLE ); public static final TStrongCasts fromDecimalUnsigned = TStrongCasts.from(MNumeric.DECIMAL_UNSIGNED).to( MApproximateNumber.DOUBLE ); public static final TStrongCasts fromFloat = TStrongCasts.from(MApproximateNumber.FLOAT).to( MApproximateNumber.DOUBLE ); }
adjusting strong casts
src/main/java/com/akiban/server/types3/mcompat/mcasts/Strongs.java
adjusting strong casts
<ide><path>rc/main/java/com/akiban/server/types3/mcompat/mcasts/Strongs.java <ide> MNumeric.INT_UNSIGNED, <ide> MNumeric.BIGINT_UNSIGNED, <ide> MNumeric.DECIMAL, <del> MNumeric.DECIMAL_UNSIGNED, <ide> MApproximateNumber.DOUBLE <ide> ); <ide> public static final TStrongCasts fromSmallint = TStrongCasts.from(MNumeric.SMALLINT).to( <ide> MNumeric.INT_UNSIGNED, <ide> MNumeric.BIGINT_UNSIGNED, <ide> MNumeric.DECIMAL, <del> MNumeric.DECIMAL_UNSIGNED, <ide> MApproximateNumber.DOUBLE <ide> ); <ide> public static final TStrongCasts fromMediumint = TStrongCasts.from(MNumeric.MEDIUMINT).to( <ide> MNumeric.INT, <ide> MNumeric.BIGINT, <del> MNumeric.SMALLINT_UNSIGNED, <ide> MNumeric.MEDIUMINT_UNSIGNED, <ide> MNumeric.INT_UNSIGNED, <ide> MNumeric.BIGINT_UNSIGNED, <ide> MNumeric.DECIMAL, <del> MNumeric.DECIMAL_UNSIGNED, <ide> MApproximateNumber.DOUBLE <ide> ); <ide> public static final TStrongCasts fromInt = TStrongCasts.from(MNumeric.INT).to( <ide> MNumeric.BIGINT, <del> MNumeric.SMALLINT_UNSIGNED, <del> MNumeric.MEDIUMINT_UNSIGNED, <ide> MNumeric.INT_UNSIGNED, <ide> MNumeric.BIGINT_UNSIGNED, <ide> MNumeric.DECIMAL, <del> MNumeric.DECIMAL_UNSIGNED, <ide> MApproximateNumber.DOUBLE <ide> ); <ide> public static final TStrongCasts fromBigint = TStrongCasts.from(MNumeric.BIGINT).to( <del> MNumeric.SMALLINT_UNSIGNED, <del> MNumeric.MEDIUMINT_UNSIGNED, <del> MNumeric.INT_UNSIGNED, <ide> MNumeric.BIGINT_UNSIGNED, <ide> MNumeric.DECIMAL, <del> MNumeric.DECIMAL_UNSIGNED, <ide> MApproximateNumber.DOUBLE <ide> ); <ide> <ide> MNumeric.MEDIUMINT_UNSIGNED, <ide> MNumeric.INT_UNSIGNED, <ide> MNumeric.BIGINT_UNSIGNED, <add> MNumeric.DECIMAL, <ide> MNumeric.DECIMAL_UNSIGNED, <ide> MApproximateNumber.DOUBLE <ide> ); <ide> MNumeric.MEDIUMINT_UNSIGNED, <ide> MNumeric.INT_UNSIGNED, <ide> MNumeric.BIGINT_UNSIGNED, <add> MNumeric.DECIMAL, <ide> MNumeric.DECIMAL_UNSIGNED, <ide> MApproximateNumber.DOUBLE <ide> ); <ide> public static final TStrongCasts fromMediumintUnsigned = TStrongCasts.from(MNumeric.MEDIUMINT_UNSIGNED).to( <ide> MNumeric.INT_UNSIGNED, <ide> MNumeric.BIGINT_UNSIGNED, <add> MNumeric.DECIMAL, <ide> MNumeric.DECIMAL_UNSIGNED, <ide> MApproximateNumber.DOUBLE <ide> ); <ide> public static final TStrongCasts fromIntUnsigned = TStrongCasts.from(MNumeric.INT_UNSIGNED).to( <ide> MNumeric.BIGINT_UNSIGNED, <add> MNumeric.DECIMAL, <ide> MNumeric.DECIMAL_UNSIGNED, <ide> MApproximateNumber.DOUBLE <ide> ); <ide> ); <ide> <ide> public static final TStrongCasts fromDatetime = TStrongCasts.from(MDatetimes.DATETIME).to( <add> MApproximateNumber.DOUBLE <add> ); <add> <add> public static final TStrongCasts fromDate = TStrongCasts.from(MDatetimes.DATE).to( <add> MApproximateNumber.DOUBLE <add> ); <add> <add> public static final TStrongCasts fromTime = TStrongCasts.from(MDatetimes.TIME).to( <add> MApproximateNumber.DOUBLE <add> ); <add> <add> public static final TStrongCasts fromYear = TStrongCasts.from(MDatetimes.YEAR).to( <ide> MApproximateNumber.DOUBLE <ide> ); <ide> <ide> public static final TStrongCasts fromFloat = TStrongCasts.from(MApproximateNumber.FLOAT).to( <ide> MApproximateNumber.DOUBLE <ide> ); <add> <add> public static final TStrongCasts fromFloatUnsigned = TStrongCasts.from(MApproximateNumber.FLOAT_UNSIGNED).to( <add> MApproximateNumber.DOUBLE <add> ); <add> <add> public static final TStrongCasts fromDoubleUnsigned = TStrongCasts.from(MApproximateNumber.DOUBLE_UNSIGNED).to( <add> MApproximateNumber.DOUBLE <add> ); <ide> }
Java
bsd-3-clause
fd237c3cc89f8800508975de3500d8d3f418d204
0
asamgir/openspecimen,krishagni/openspecimen,krishagni/openspecimen,krishagni/openspecimen,asamgir/openspecimen,asamgir/openspecimen
/** * */ package edu.wustl.catissuecore.action.querysuite; import java.util.ArrayList; import java.util.Collection; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import javax.servlet.http.HttpSession; import org.hibernate.HibernateException; import org.apache.struts.action.ActionForm; import org.apache.struts.action.ActionForward; import org.apache.struts.action.ActionMapping; import org.apache.struts.action.ActionMessage; import org.apache.struts.action.ActionMessages; import edu.wustl.catissuecore.actionForm.querysuite.SaveQueryForm; import edu.wustl.catissuecore.flex.dag.DAGConstant; import edu.wustl.catissuecore.util.global.Constants; import edu.wustl.common.action.BaseAction; import edu.wustl.common.querysuite.queryobject.IParameterizedQuery; import edu.wustl.common.util.dbManager.HibernateUtility; import edu.wustl.common.util.global.ApplicationProperties; /** * @author chetan_patil * @created September 12, 2007, 10:24:05 PM */ public class RetrieveQueryAction extends BaseAction { protected ActionForward executeAction(ActionMapping actionMapping, ActionForm actionForm, HttpServletRequest request, HttpServletResponse response) throws Exception { ActionForward actionForward = null; try { HttpSession session = request.getSession(); session.removeAttribute(Constants.SELECTED_COLUMN_META_DATA); session.removeAttribute(Constants.SAVE_GENERATED_SQL); session.removeAttribute(Constants.SAVE_TREE_NODE_LIST); session.removeAttribute(Constants.ID_NODES_MAP); session.removeAttribute(Constants.MAIN_ENTITY_MAP); session.removeAttribute(Constants.EXPORT_DATA_LIST); session.removeAttribute(Constants.ENTITY_IDS_MAP); session.removeAttribute(DAGConstant.TQUIMap); SaveQueryForm saveQueryForm = (SaveQueryForm) actionForm; Collection<IParameterizedQuery> parameterizedQueryCollection = (Collection<IParameterizedQuery>) HibernateUtility .executeHQL(HibernateUtility.GET_PARAMETERIZED_QUERIES_DETAILS); String message = null; if (parameterizedQueryCollection != null) { saveQueryForm.setParameterizedQueryCollection(parameterizedQueryCollection); message = parameterizedQueryCollection.size() + ""; } else { saveQueryForm.setParameterizedQueryCollection(new ArrayList<IParameterizedQuery>()); message = "No"; } ActionMessages actionMessages = new ActionMessages(); ActionMessage actionMessage = new ActionMessage("query.resultFound.message", message); actionMessages.add(ActionMessages.GLOBAL_MESSAGE, actionMessage); saveMessages(request, actionMessages); actionForward = actionMapping.findForward(Constants.SUCCESS); } catch (HibernateException hibernateException) { actionForward = actionMapping.findForward(Constants.FAILURE); } request.setAttribute(Constants.POPUP_MESSAGE, ApplicationProperties.getValue("query.confirmBox.message")); return actionForward; } }
WEB-INF/src/edu/wustl/catissuecore/action/querysuite/RetrieveQueryAction.java
/** * */ package edu.wustl.catissuecore.action.querysuite; import java.util.ArrayList; import java.util.Collection; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import javax.servlet.http.HttpSession; import org.hibernate.HibernateException; import org.apache.struts.action.ActionForm; import org.apache.struts.action.ActionForward; import org.apache.struts.action.ActionMapping; import org.apache.struts.action.ActionMessage; import org.apache.struts.action.ActionMessages; import edu.wustl.catissuecore.actionForm.querysuite.SaveQueryForm; import edu.wustl.catissuecore.util.global.Constants; import edu.wustl.common.action.BaseAction; import edu.wustl.common.querysuite.queryobject.IParameterizedQuery; import edu.wustl.common.util.dbManager.HibernateUtility; import edu.wustl.common.util.global.ApplicationProperties; /** * @author chetan_patil * @created September 12, 2007, 10:24:05 PM */ public class RetrieveQueryAction extends BaseAction { protected ActionForward executeAction(ActionMapping actionMapping, ActionForm actionForm, HttpServletRequest request, HttpServletResponse response) throws Exception { ActionForward actionForward = null; try { HttpSession session = request.getSession(); session.removeAttribute(Constants.SELECTED_COLUMN_META_DATA); session.removeAttribute(Constants.SAVE_GENERATED_SQL); session.removeAttribute(Constants.SAVE_TREE_NODE_LIST); session.removeAttribute(Constants.ID_NODES_MAP); session.removeAttribute(Constants.MAIN_ENTITY_MAP); session.removeAttribute(Constants.EXPORT_DATA_LIST); session.removeAttribute(Constants.ENTITY_IDS_MAP); SaveQueryForm saveQueryForm = (SaveQueryForm) actionForm; Collection<IParameterizedQuery> parameterizedQueryCollection = (Collection<IParameterizedQuery>) HibernateUtility .executeHQL(HibernateUtility.GET_PARAMETERIZED_QUERIES_DETAILS); String message = null; if (parameterizedQueryCollection != null) { saveQueryForm.setParameterizedQueryCollection(parameterizedQueryCollection); message = parameterizedQueryCollection.size() + ""; } else { saveQueryForm.setParameterizedQueryCollection(new ArrayList<IParameterizedQuery>()); message = "No"; } ActionMessages actionMessages = new ActionMessages(); ActionMessage actionMessage = new ActionMessage("query.resultFound.message", message); actionMessages.add(ActionMessages.GLOBAL_MESSAGE, actionMessage); saveMessages(request, actionMessages); actionForward = actionMapping.findForward(Constants.SUCCESS); } catch (HibernateException hibernateException) { actionForward = actionMapping.findForward(Constants.FAILURE); } request.setAttribute(Constants.POPUP_MESSAGE, ApplicationProperties.getValue("query.confirmBox.message")); return actionForward; } }
Added line to remove session attribute TQUIMap SVN-Revision: 15088
WEB-INF/src/edu/wustl/catissuecore/action/querysuite/RetrieveQueryAction.java
Added line to remove session attribute TQUIMap
<ide><path>EB-INF/src/edu/wustl/catissuecore/action/querysuite/RetrieveQueryAction.java <ide> import org.apache.struts.action.ActionMessages; <ide> <ide> import edu.wustl.catissuecore.actionForm.querysuite.SaveQueryForm; <add>import edu.wustl.catissuecore.flex.dag.DAGConstant; <ide> import edu.wustl.catissuecore.util.global.Constants; <ide> import edu.wustl.common.action.BaseAction; <ide> import edu.wustl.common.querysuite.queryobject.IParameterizedQuery; <ide> session.removeAttribute(Constants.MAIN_ENTITY_MAP); <ide> session.removeAttribute(Constants.EXPORT_DATA_LIST); <ide> session.removeAttribute(Constants.ENTITY_IDS_MAP); <add> session.removeAttribute(DAGConstant.TQUIMap); <ide> SaveQueryForm saveQueryForm = (SaveQueryForm) actionForm; <ide> Collection<IParameterizedQuery> parameterizedQueryCollection = (Collection<IParameterizedQuery>) HibernateUtility <ide> .executeHQL(HibernateUtility.GET_PARAMETERIZED_QUERIES_DETAILS);
Java
apache-2.0
0105ba0ed1811c46ce2801558af62af993f6b865
0
mosaic-cloud/mosaic-java-platform,mosaic-cloud/mosaic-java-platform
/* * #%L * mosaic-connectors * %% * Copyright (C) 2010 - 2012 Institute e-Austria Timisoara (Romania) * %% * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * #L% */ package eu.mosaic_cloud.connectors.queue.amqp; import java.util.UUID; import eu.mosaic_cloud.connectors.core.ConfigProperties; import eu.mosaic_cloud.connectors.tools.ConnectorEnvironment; import eu.mosaic_cloud.platform.core.configuration.ConfigUtils; import eu.mosaic_cloud.platform.core.configuration.ConfigurationIdentifier; import eu.mosaic_cloud.platform.core.configuration.IConfiguration; import eu.mosaic_cloud.platform.core.utils.DataEncoder; import eu.mosaic_cloud.platform.core.utils.EncodingException; import eu.mosaic_cloud.platform.interop.common.amqp.AmqpExchangeType; import eu.mosaic_cloud.platform.interop.common.amqp.AmqpOutboundMessage; import eu.mosaic_cloud.tools.callbacks.core.CallbackCompletion; import eu.mosaic_cloud.tools.exceptions.core.FallbackExceptionTracer; public final class AmqpQueuePublisherConnectorProxy<TMessage> extends AmqpQueueConnectorProxy<TMessage> implements IAmqpQueuePublisherConnector<TMessage> { private final boolean definePassive; private final String exchange; private final boolean exchangeAutoDelete; private final boolean exchangeDurable; private final AmqpExchangeType exchangeType; private final String identity; private final String publishRoutingKey; public static <Message> AmqpQueuePublisherConnectorProxy<Message> create( final IConfiguration configuration, final ConnectorEnvironment environment, final Class<Message> messageClass, final DataEncoder<Message> messageEncoder) { final AmqpQueueRawConnectorProxy rawProxy = AmqpQueueRawConnectorProxy .create(configuration, environment); final IConfiguration subConfiguration = configuration .spliceConfiguration(ConfigurationIdentifier .resolveRelative("publisher")); final AmqpQueuePublisherConnectorProxy<Message> proxy = new AmqpQueuePublisherConnectorProxy<Message>( rawProxy, subConfiguration, messageClass, messageEncoder); return proxy; } private AmqpQueuePublisherConnectorProxy( final AmqpQueueRawConnectorProxy rawProxy, final IConfiguration configuration, final Class<TMessage> messageClass, final DataEncoder<TMessage> messageEncoder) { super(rawProxy, configuration, messageClass, messageEncoder); this.identity = UUID.randomUUID().toString(); this.exchange = ConfigUtils .resolveParameter( configuration, ConfigProperties.getString("AmqpQueueConnector.0"), String.class, this.identity); //$NON-NLS-1$ this.exchangeType = ConfigUtils .resolveParameter( configuration, ConfigProperties.getString("AmqpQueueConnector.5"), AmqpExchangeType.class, AmqpExchangeType.DIRECT);//$NON-NLS-1$ this.exchangeDurable = ConfigUtils .resolveParameter( configuration, ConfigProperties.getString("AmqpQueueConnector.9"), Boolean.class, Boolean.FALSE).booleanValue(); //$NON-NLS-1$ this.exchangeAutoDelete = ConfigUtils .resolveParameter( configuration, ConfigProperties.getString("AmqpQueueConnector.7"), Boolean.class, Boolean.TRUE).booleanValue(); //$NON-NLS-1$ this.publishRoutingKey = ConfigUtils .resolveParameter( configuration, ConfigProperties.getString("AmqpQueueConnector.1"), String.class, this.identity); //$NON-NLS-1$ this.definePassive = ConfigUtils .resolveParameter( configuration, ConfigProperties.getString("AmqpQueueConnector.8"), Boolean.class, Boolean.FALSE).booleanValue(); //$NON-NLS-1$ } @Override public CallbackCompletion<Void> destroy() { return this.raw.destroy(); } @Override public CallbackCompletion<Void> initialize() { this.raw.initialize(); return this.raw.declareExchange(this.exchange, this.exchangeType, this.exchangeDurable, this.exchangeAutoDelete, this.definePassive); } @Override public CallbackCompletion<Void> publish(final TMessage message) { byte[] data = null; CallbackCompletion<Void> result = null; try { data = this.messageEncoder.encode(message); } catch (final EncodingException exception) { FallbackExceptionTracer.defaultInstance .traceDeferredException(exception); result = CallbackCompletion.createFailure(exception); } if (result == null) { final AmqpOutboundMessage outbound = new AmqpOutboundMessage( this.exchange, this.publishRoutingKey, data, false, false, false, null); result = this.raw.publish(outbound); } return result; } }
connectors/src/main/java/eu/mosaic_cloud/connectors/queue/amqp/AmqpQueuePublisherConnectorProxy.java
/* * #%L * mosaic-connectors * %% * Copyright (C) 2010 - 2012 Institute e-Austria Timisoara (Romania) * %% * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * #L% */ package eu.mosaic_cloud.connectors.queue.amqp; import java.util.UUID; import eu.mosaic_cloud.connectors.core.ConfigProperties; import eu.mosaic_cloud.connectors.tools.ConnectorEnvironment; import eu.mosaic_cloud.platform.core.configuration.ConfigUtils; import eu.mosaic_cloud.platform.core.configuration.ConfigurationIdentifier; import eu.mosaic_cloud.platform.core.configuration.IConfiguration; import eu.mosaic_cloud.platform.core.utils.DataEncoder; import eu.mosaic_cloud.platform.core.utils.EncodingException; import eu.mosaic_cloud.platform.interop.common.amqp.AmqpExchangeType; import eu.mosaic_cloud.platform.interop.common.amqp.AmqpOutboundMessage; import eu.mosaic_cloud.tools.callbacks.core.CallbackCompletion; import eu.mosaic_cloud.tools.exceptions.core.FallbackExceptionTracer; public final class AmqpQueuePublisherConnectorProxy<TMessage> extends AmqpQueueConnectorProxy<TMessage> implements IAmqpQueuePublisherConnector<TMessage> { private final boolean definePassive; private final String exchange; private final boolean exchangeAutoDelete; private final boolean exchangeDurable; private final AmqpExchangeType exchangeType; private final String identity; private final String publishRoutingKey; public static <Message> AmqpQueuePublisherConnectorProxy<Message> create( final IConfiguration configuration, final ConnectorEnvironment environment, final Class<Message> messageClass, final DataEncoder<Message> messageEncoder) { final AmqpQueueRawConnectorProxy rawProxy = AmqpQueueRawConnectorProxy .create(configuration, environment); final IConfiguration subConfiguration = configuration .spliceConfiguration(ConfigurationIdentifier .resolveRelative("publisher")); final AmqpQueuePublisherConnectorProxy<Message> proxy = new AmqpQueuePublisherConnectorProxy<Message>( rawProxy, subConfiguration, messageClass, messageEncoder); return proxy; } private AmqpQueuePublisherConnectorProxy( final AmqpQueueRawConnectorProxy rawProxy, final IConfiguration configuration, final Class<TMessage> messageClass, final DataEncoder<TMessage> messageEncoder) { super(rawProxy, configuration, messageClass, messageEncoder); this.identity = UUID.randomUUID().toString(); this.exchange = ConfigUtils .resolveParameter( configuration, ConfigProperties.getString("AmqpQueueConnector.0"), String.class, this.identity); //$NON-NLS-1$ this.exchangeType = ConfigUtils .resolveParameter( configuration, ConfigProperties.getString("AmqpQueueConnector.5"), AmqpExchangeType.class, AmqpExchangeType.DIRECT);//$NON-NLS-1$ this.exchangeDurable = ConfigUtils .resolveParameter( configuration, ConfigProperties.getString("AmqpQueueConnector.9"), Boolean.class, Boolean.FALSE).booleanValue(); //$NON-NLS-1$ this.exchangeAutoDelete = ConfigUtils .resolveParameter( configuration, ConfigProperties.getString("AmqpQueueConnector.7"), Boolean.class, Boolean.TRUE).booleanValue(); //$NON-NLS-1$ this.publishRoutingKey = ConfigUtils .resolveParameter( configuration, ConfigProperties.getString("AmqpQueueConnector.1"), String.class, this.identity); //$NON-NLS-1$ this.definePassive = ConfigUtils .resolveParameter( configuration, ConfigProperties.getString("AmqpQueueConnector.8"), Boolean.class, Boolean.FALSE).booleanValue(); //$NON-NLS-1$ } @Override public CallbackCompletion<Void> destroy() { return this.raw.destroy(); } @Override public CallbackCompletion<Void> initialize() { this.raw.initialize(); return this.raw.declareExchange(this.exchange, this.exchangeType, this.exchangeDurable, this.exchangeAutoDelete, this.definePassive); } @Override public CallbackCompletion<Void> publish(final TMessage message) { final byte[] data; CallbackCompletion<Void> result; try { data = this.messageEncoder.encode(message); final AmqpOutboundMessage outbound = new AmqpOutboundMessage( this.exchange, this.publishRoutingKey, data, false, false, false, null); result = this.raw.publish(outbound); } catch (final EncodingException exception) { FallbackExceptionTracer.defaultInstance .traceDeferredException(exception); result = CallbackCompletion.createFailure(exception); } return result; } }
Fix `AmqpQueuePublisherConnectorProxy` `publish` flow to not delegate the publish inside the decoding `try / catch` That `try / catch` should only cover the encoding part.
connectors/src/main/java/eu/mosaic_cloud/connectors/queue/amqp/AmqpQueuePublisherConnectorProxy.java
Fix `AmqpQueuePublisherConnectorProxy` `publish` flow to not delegate the publish inside the decoding `try / catch`
<ide><path>onnectors/src/main/java/eu/mosaic_cloud/connectors/queue/amqp/AmqpQueuePublisherConnectorProxy.java <ide> <ide> @Override <ide> public CallbackCompletion<Void> publish(final TMessage message) { <del> final byte[] data; <del> CallbackCompletion<Void> result; <add> byte[] data = null; <add> CallbackCompletion<Void> result = null; <ide> try { <ide> data = this.messageEncoder.encode(message); <del> final AmqpOutboundMessage outbound = new AmqpOutboundMessage( <del> this.exchange, this.publishRoutingKey, data, false, false, <del> false, null); <del> result = this.raw.publish(outbound); <ide> } catch (final EncodingException exception) { <ide> FallbackExceptionTracer.defaultInstance <ide> .traceDeferredException(exception); <ide> result = CallbackCompletion.createFailure(exception); <ide> } <del> <add> if (result == null) { <add> final AmqpOutboundMessage outbound = new AmqpOutboundMessage( <add> this.exchange, this.publishRoutingKey, data, false, false, <add> false, null); <add> result = this.raw.publish(outbound); <add> } <ide> return result; <ide> } <ide> }
Java
apache-2.0
384ef51d9cfb41ceb77a328d270bda7c7f74c279
0
JAVACAFE-STUDY/logjdbc
package net.chandol.logjdbc.util; import java.lang.Character.UnicodeScript; import java.util.ArrayList; import java.util.List; import static java.lang.Character.UnicodeScript.HANGUL; /** * Create asciiTable for java * * <pre> * AsciiTable4j table = new AsciiTable4j(); * * table.addRow(Arrays.asList("id", "name", "hobby")); * table.addRow(Arrays.asList("1", "박세종", "Programming")); * table.addRow(Arrays.asList("2", "Gordon Park", "Swimming ")); * table.addRow(Arrays.asList("3", "Sejong Park", "Playing Piano")); * * System.out.println(table.renderTable()); * * // result * +----+-------------+---------------+ * | id | name | hobby | * |----+-------------+---------------| * | 1 | 박세종 | Programming | * | 2 | Gordon Park | Swimming | * | 3 | Sejong Park | Playing Piano | * +----+-------------+---------------+ * </pre> */ public class AsciiTable4j { private List<List<String>> rows; public AsciiTable4j() { rows = new ArrayList<>(); } public void addRow(List<String> row) { for (int idx = 0, rowSize = row.size(); idx < rowSize; idx++) { if (row.get(idx) == null) row.set(idx, ""); } rows.add(row); } public String renderTable() { List<Integer> lengthOfColumns = calculateLengthOfColumns(); StringBuilder builder = new StringBuilder(); builder.append(rowSplitter('+', lengthOfColumns)).append("\n"); int rowSize = rows.size(); for (int idx = 0; idx < rowSize; idx++) { StringBuilder row = getRowString(rows.get(idx), lengthOfColumns); builder.append(row).append("\n"); if (idx == 0) builder.append(rowSplitter('|', lengthOfColumns)).append("\n"); } builder.append(rowSplitter('+', lengthOfColumns)); return builder.toString(); } private String rowSplitter(Character padCharacter, List<Integer> lengthOfColumns) { StringBuilder builder = new StringBuilder(); builder.append(padCharacter); for (int i = 0, lengthOfColumnsSize = lengthOfColumns.size(); i < lengthOfColumnsSize; i++) { int lengthOfColumn = lengthOfColumns.get(i); builder.append(repeatCharacter('-', lengthOfColumn + 2)); if (i < lengthOfColumnsSize - 1) builder.append("+"); else builder.append(padCharacter); } return builder.toString(); } private List<Integer> calculateLengthOfColumns() { List<Integer> lengthOfColumns = new ArrayList<>(); int columnSize = rows.get(0).size(); for (int idx = 0; idx < columnSize; idx++) { int longColumnLength = -1; for (List<String> row : rows) { int itemLength = getConsoleLength(row.get(idx)); if (longColumnLength < itemLength) longColumnLength = itemLength; } lengthOfColumns.add(longColumnLength); } return lengthOfColumns; } public StringBuilder getRowString(List<String> row, List<Integer> lengthOfColumns) { StringBuilder builder = new StringBuilder("|"); int rowSize = row.size(); for (int idx = 0; idx < rowSize; idx++) { int length = lengthOfColumns.get(idx); String item = row.get(idx); String paddedItem = " " + padRight(item, length) + " "; builder.append(paddedItem).append("|"); } return builder; } static String padRight(String target, int length) { int lengthCorrection = target.length() - getConsoleLength(target); int adjustedLength = length + lengthCorrection; return String.format("%1$-" + adjustedLength + "s", target); } static String repeatCharacter(Character c, int length) { return new String(new char[length]).replace('\0', c); } static int getConsoleLength(String str) { int koreanChracterSize = 0; for (int i = 0; i < str.length(); i++) { int codepoint = str.codePointAt(i); if (HANGUL == UnicodeScript.of(codepoint)) koreanChracterSize += 1; } return str.length() + koreanChracterSize; } }
src/main/java/net/chandol/logjdbc/util/AsciiTable4j.java
package net.chandol.logjdbc.util; import java.lang.Character.UnicodeScript; import java.util.ArrayList; import java.util.List; import static java.lang.Character.UnicodeScript.HANGUL; public class AsciiTable4j { private List<List<String>> rows; public AsciiTable4j() { rows = new ArrayList<>(); } public void addRow(List<String> row) { for (int idx = 0, rowSize = row.size(); idx < rowSize; idx++) { if (row.get(idx) == null) row.set(idx, ""); } rows.add(row); } public String renderTable() { List<Integer> lengthOfColumns = calculateLengthOfColumns(); StringBuilder builder = new StringBuilder(); builder.append(rowSplitter('+', lengthOfColumns)).append("\n"); int rowSize = rows.size(); for (int idx = 0; idx < rowSize; idx++) { StringBuilder row = getRowString(rows.get(idx), lengthOfColumns); builder.append(row).append("\n"); if (idx == 0) builder.append(rowSplitter('|', lengthOfColumns)).append("\n"); } builder.append(rowSplitter('+', lengthOfColumns)); return builder.toString(); } private String rowSplitter(Character padCharacter, List<Integer> lengthOfColumns) { StringBuilder builder = new StringBuilder(); builder.append(padCharacter); for (int i = 0, lengthOfColumnsSize = lengthOfColumns.size(); i < lengthOfColumnsSize; i++) { int lengthOfColumn = lengthOfColumns.get(i); builder.append(repeatCharacter('-', lengthOfColumn + 2)); if (i < lengthOfColumnsSize - 1) builder.append("+"); else builder.append(padCharacter); } return builder.toString(); } private List<Integer> calculateLengthOfColumns() { List<Integer> lengthOfColumns = new ArrayList<>(); int columnSize = rows.get(0).size(); for (int idx = 0; idx < columnSize; idx++) { int longColumnLength = -1; for (List<String> row : rows) { int itemLength = getConsoleLength(row.get(idx)); if (longColumnLength < itemLength) longColumnLength = itemLength; } lengthOfColumns.add(longColumnLength); } return lengthOfColumns; } public StringBuilder getRowString(List<String> row, List<Integer> lengthOfColumns) { StringBuilder builder = new StringBuilder("|"); int rowSize = row.size(); for (int idx = 0; idx < rowSize; idx++) { int length = lengthOfColumns.get(idx); String item = row.get(idx); String paddedItem = " " + padRight(item, length) + " "; builder.append(paddedItem).append("|"); } return builder; } static String padRight(String target, int length) { int lengthCorrection = target.length() - getConsoleLength(target); int adjustedLength = length + lengthCorrection; return String.format("%1$-" + adjustedLength + "s", target); } static String repeatCharacter(Character c, int length) { return new String(new char[length]).replace('\0', c); } static int getConsoleLength(String str) { int koreanChracterSize = 0; for (int i = 0; i < str.length(); i++) { int codepoint = str.codePointAt(i); if (HANGUL == UnicodeScript.of(codepoint)) koreanChracterSize += 1; } return str.length() + koreanChracterSize; } }
docs : add doc @ AsciiTable4j
src/main/java/net/chandol/logjdbc/util/AsciiTable4j.java
docs : add doc @ AsciiTable4j
<ide><path>rc/main/java/net/chandol/logjdbc/util/AsciiTable4j.java <ide> <ide> import static java.lang.Character.UnicodeScript.HANGUL; <ide> <add>/** <add> * Create asciiTable for java <add> * <add> * <pre> <add> * AsciiTable4j table = new AsciiTable4j(); <add> * <add> * table.addRow(Arrays.asList("id", "name", "hobby")); <add> * table.addRow(Arrays.asList("1", "박세종", "Programming")); <add> * table.addRow(Arrays.asList("2", "Gordon Park", "Swimming ")); <add> * table.addRow(Arrays.asList("3", "Sejong Park", "Playing Piano")); <add> * <add> * System.out.println(table.renderTable()); <add> * <add> * // result <add> * +----+-------------+---------------+ <add> * | id | name | hobby | <add> * |----+-------------+---------------| <add> * | 1 | 박세종 | Programming | <add> * | 2 | Gordon Park | Swimming | <add> * | 3 | Sejong Park | Playing Piano | <add> * +----+-------------+---------------+ <add> * </pre> <add> */ <ide> public class AsciiTable4j { <ide> private List<List<String>> rows; <ide>
Java
apache-2.0
78413e37c4ea50778a5448f5e50071e1039457c4
0
apache/archiva,sadlil/archiva,sadlil/archiva,apache/archiva,apache/archiva,sadlil/archiva,apache/archiva,apache/archiva,sadlil/archiva,sadlil/archiva
package org.apache.archiva.rest.v2.svc.maven; /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ import org.apache.archiva.admin.model.AuditInformation; import org.apache.archiva.admin.model.RepositoryAdminException; import org.apache.archiva.admin.model.managed.ManagedRepositoryAdmin; import org.apache.archiva.components.rest.model.PagedResult; import org.apache.archiva.components.rest.util.QueryHelper; import org.apache.archiva.redback.authentication.AuthenticationResult; import org.apache.archiva.redback.authorization.AuthorizationException; import org.apache.archiva.redback.rest.services.RedbackAuthenticationThreadLocal; import org.apache.archiva.redback.rest.services.RedbackRequestInformation; import org.apache.archiva.redback.system.DefaultSecuritySession; import org.apache.archiva.redback.system.SecuritySession; import org.apache.archiva.redback.system.SecuritySystem; import org.apache.archiva.redback.users.User; import org.apache.archiva.redback.users.UserManagerException; import org.apache.archiva.redback.users.UserNotFoundException; import org.apache.archiva.repository.ManagedRepository; import org.apache.archiva.repository.ReleaseScheme; import org.apache.archiva.repository.Repository; import org.apache.archiva.repository.RepositoryRegistry; import org.apache.archiva.repository.RepositoryType; import org.apache.archiva.repository.content.ContentItem; import org.apache.archiva.repository.content.LayoutException; import org.apache.archiva.repository.storage.fs.FsStorageUtil; import org.apache.archiva.rest.api.v2.model.FileInfo; import org.apache.archiva.rest.api.v2.model.MavenManagedRepository; import org.apache.archiva.rest.api.v2.model.MavenManagedRepositoryUpdate; import org.apache.archiva.rest.api.v2.svc.ArchivaRestServiceException; import org.apache.archiva.rest.api.v2.svc.ErrorKeys; import org.apache.archiva.rest.api.v2.svc.ErrorMessage; import org.apache.archiva.rest.api.v2.svc.maven.MavenManagedRepositoryService; import org.apache.archiva.security.common.ArchivaRoleConstants; import org.apache.commons.lang3.StringUtils; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.stereotype.Service; import javax.servlet.http.HttpServletResponse; import javax.ws.rs.core.Context; import javax.ws.rs.core.Response; import javax.ws.rs.core.UriInfo; import java.io.IOException; import java.util.Collection; import java.util.Comparator; import java.util.List; import java.util.function.Predicate; import java.util.stream.Collectors; import static org.apache.archiva.security.common.ArchivaRoleConstants.OPERATION_READ_REPOSITORY; import static org.apache.archiva.security.common.ArchivaRoleConstants.OPERATION_ADD_ARTIFACT; /** * @author Martin Stockhammer <[email protected]> */ @Service("v2.managedMavenRepositoryService#rest") public class DefaultMavenManagedRepositoryService implements MavenManagedRepositoryService { @Context HttpServletResponse httpServletResponse; @Context UriInfo uriInfo; private static final Logger log = LoggerFactory.getLogger( DefaultMavenManagedRepositoryService.class ); private static final QueryHelper<ManagedRepository> QUERY_HELPER = new QueryHelper<>( new String[]{"id", "name"} ); static { QUERY_HELPER.addStringFilter( "id", ManagedRepository::getId ); QUERY_HELPER.addStringFilter( "name", ManagedRepository::getName ); QUERY_HELPER.addStringFilter( "location", (r) -> r.getLocation().toString() ); QUERY_HELPER.addBooleanFilter( "snapshot", (r) -> r.getActiveReleaseSchemes( ).contains( ReleaseScheme.SNAPSHOT ) ); QUERY_HELPER.addBooleanFilter( "release", (r) -> r.getActiveReleaseSchemes().contains( ReleaseScheme.RELEASE )); QUERY_HELPER.addNullsafeFieldComparator( "id", ManagedRepository::getId ); QUERY_HELPER.addNullsafeFieldComparator( "name", ManagedRepository::getName ); } private final ManagedRepositoryAdmin managedRepositoryAdmin; private final RepositoryRegistry repositoryRegistry; private final SecuritySystem securitySystem; public DefaultMavenManagedRepositoryService( SecuritySystem securitySystem, RepositoryRegistry repositoryRegistry, ManagedRepositoryAdmin managedRepositoryAdmin ) { this.securitySystem = securitySystem; this.repositoryRegistry = repositoryRegistry; this.managedRepositoryAdmin = managedRepositoryAdmin; } protected AuditInformation getAuditInformation( ) { RedbackRequestInformation redbackRequestInformation = RedbackAuthenticationThreadLocal.get( ); User user; String remoteAddr; if (redbackRequestInformation==null) { user = null; remoteAddr = null; } else { user = redbackRequestInformation.getUser( ); remoteAddr = redbackRequestInformation.getRemoteAddr( ); } return new AuditInformation( user, remoteAddr ); } @Override public PagedResult<MavenManagedRepository> getManagedRepositories( final String searchTerm, final Integer offset, final Integer limit, final List<String> orderBy, final String order ) throws ArchivaRestServiceException { try { Collection<ManagedRepository> repos = repositoryRegistry.getManagedRepositories( ); final Predicate<ManagedRepository> queryFilter = QUERY_HELPER.getQueryFilter( searchTerm ).and( r -> r.getType() == RepositoryType.MAVEN ); final Comparator<ManagedRepository> comparator = QUERY_HELPER.getComparator( orderBy, order ); int totalCount = Math.toIntExact( repos.stream( ).filter( queryFilter ).count( ) ); return PagedResult.of( totalCount, offset, limit, repos.stream( ).filter( queryFilter ).sorted( comparator ) .map( MavenManagedRepository::of ).skip( offset ).limit( limit ).collect( Collectors.toList( ) ) ); } catch (ArithmeticException e) { log.error( "Invalid number of repositories detected." ); throw new ArchivaRestServiceException( ErrorMessage.of( ErrorKeys.INVALID_RESULT_SET_ERROR ) ); } } @Override public MavenManagedRepository getManagedRepository( String repositoryId ) throws ArchivaRestServiceException { ManagedRepository repo = repositoryRegistry.getManagedRepository( repositoryId ); if (repo==null) { throw new ArchivaRestServiceException( ErrorMessage.of( ErrorKeys.REPOSITORY_NOT_FOUND, repositoryId ), 404 ); } if (repo.getType()!=RepositoryType.MAVEN) { throw new ArchivaRestServiceException( ErrorMessage.of( ErrorKeys.REPOSITORY_WRONG_TYPE, repositoryId, repo.getType().name() ), 404 ); } return MavenManagedRepository.of( repo ); } @Override public Response deleteManagedRepository( String repositoryId, Boolean deleteContent ) throws ArchivaRestServiceException { MavenManagedRepository repo = getManagedRepository( repositoryId ); if (repo != null) { try { managedRepositoryAdmin.deleteManagedRepository( repositoryId, getAuditInformation( ), deleteContent ); return Response.ok( ).build( ); } catch ( RepositoryAdminException e ) { throw new ArchivaRestServiceException( ErrorMessage.of( ErrorKeys.REPOSITORY_DELETE_FAILED, e.getMessage( ) ) ); } } else { throw new ArchivaRestServiceException( ErrorMessage.of( ErrorKeys.REPOSITORY_NOT_FOUND, repositoryId ), 404 ); } } private org.apache.archiva.admin.model.beans.ManagedRepository convert(MavenManagedRepository repository) { org.apache.archiva.admin.model.beans.ManagedRepository repoBean = new org.apache.archiva.admin.model.beans.ManagedRepository( ); repoBean.setId( repository.getId( ) ); repoBean.setName( repository.getName() ); repoBean.setDescription( repository.getDescription() ); repoBean.setBlockRedeployments( repository.isBlocksRedeployments() ); repoBean.setCronExpression( repository.getSchedulingDefinition() ); repoBean.setLocation( repository.getLocation() ); repoBean.setReleases( repository.getReleaseSchemes().contains( ReleaseScheme.RELEASE.name() ) ); repoBean.setSnapshots( repository.getReleaseSchemes().contains( ReleaseScheme.SNAPSHOT.name() ) ); repoBean.setScanned( repository.isScanned() ); repoBean.setDeleteReleasedSnapshots( repository.isDeleteSnapshotsOfRelease() ); repoBean.setSkipPackedIndexCreation( repository.isSkipPackedIndexCreation() ); repoBean.setRetentionCount( repository.getRetentionCount() ); repoBean.setRetentionPeriod( repository.getRetentionPeriod().getDays() ); repoBean.setIndexDirectory( repository.getIndexPath() ); repoBean.setPackedIndexDirectory( repository.getPackedIndexPath() ); repoBean.setLayout( repository.getLayout() ); repoBean.setType( RepositoryType.MAVEN.name( ) ); return repoBean; } @Override public MavenManagedRepository addManagedRepository( MavenManagedRepository managedRepository ) throws ArchivaRestServiceException { final String repoId = managedRepository.getId( ); if ( StringUtils.isEmpty( repoId ) ) { throw new ArchivaRestServiceException( ErrorMessage.of( ErrorKeys.REPOSITORY_INVALID_ID, repoId ), 422 ); } Repository repo = repositoryRegistry.getRepository( repoId ); if (repo!=null) { httpServletResponse.setHeader( "Location", uriInfo.getAbsolutePathBuilder( ).path( repoId ).build( ).toString( ) ); throw new ArchivaRestServiceException( ErrorMessage.of( ErrorKeys.REPOSITORY_ID_EXISTS, repoId ), 303 ); } try { managedRepositoryAdmin.addManagedRepository( convert( managedRepository ), managedRepository.isHasStagingRepository(), getAuditInformation() ); httpServletResponse.setStatus( 201 ); return MavenManagedRepository.of( repositoryRegistry.getManagedRepository( repoId ) ); } catch ( RepositoryAdminException e ) { throw new ArchivaRestServiceException( ErrorMessage.of( ErrorKeys.REPOSITORY_ADMIN_ERROR, e.getMessage( ) ) ); } } @Override public MavenManagedRepository updateManagedRepository( final String repositoryId, final MavenManagedRepositoryUpdate managedRepository ) throws ArchivaRestServiceException { org.apache.archiva.admin.model.beans.ManagedRepository repo = convert( managedRepository ); try { managedRepositoryAdmin.updateManagedRepository( repo, managedRepository.isHasStagingRepository( ), getAuditInformation( ), managedRepository.isResetStats( ) ); ManagedRepository newRepo = repositoryRegistry.getManagedRepository( managedRepository.getId( ) ); if (newRepo==null) { throw new ArchivaRestServiceException( ErrorMessage.of( ErrorKeys.REPOSITORY_UPDATE_FAILED, repositoryId ) ); } return MavenManagedRepository.of( newRepo ); } catch ( RepositoryAdminException e ) { throw new ArchivaRestServiceException( ErrorMessage.of( ErrorKeys.REPOSITORY_ADMIN_ERROR, e.getMessage( ) ) ); } } @Override public FileInfo getFileStatus( String repositoryId, String fileLocation ) throws ArchivaRestServiceException { ManagedRepository repo = repositoryRegistry.getManagedRepository( repositoryId ); if (repo==null) { throw new ArchivaRestServiceException( ErrorMessage.of( ErrorKeys.REPOSITORY_NOT_FOUND, repositoryId ), 404 ); } try { ContentItem contentItem = repo.getContent( ).toItem( fileLocation ); if (contentItem.getAsset( ).exists( )) { return FileInfo.of( contentItem.getAsset( ) ); } else { throw new ArchivaRestServiceException( ErrorMessage.of( ErrorKeys.ARTIFACT_NOT_FOUND, repositoryId, fileLocation ), 404 ); } } catch ( LayoutException e ) { throw new ArchivaRestServiceException( ErrorMessage.of( ErrorKeys.REPOSITORY_LAYOUT_ERROR, e.getMessage( ) ) ); } } @Override public Response copyArtifact( String srcRepositoryId, String dstRepositoryId, String path ) throws ArchivaRestServiceException { final AuditInformation auditInformation = getAuditInformation( ); final String userName = auditInformation.getUser( ).getUsername( ); if ( StringUtils.isEmpty( userName ) ) { httpServletResponse.setHeader( "WWW-Authenticate", "Bearer realm=\"archiva\"" ); throw new ArchivaRestServiceException( ErrorMessage.of( ErrorKeys.NOT_AUTHENTICATED ), 401 ); } ManagedRepository srcRepo = repositoryRegistry.getManagedRepository( srcRepositoryId ); if (srcRepo==null) { throw new ArchivaRestServiceException( ErrorMessage.of( ErrorKeys.REPOSITORY_NOT_FOUND, srcRepositoryId ), 404 ); } ManagedRepository dstRepo = repositoryRegistry.getManagedRepository( dstRepositoryId ); if (dstRepo==null) { throw new ArchivaRestServiceException( ErrorMessage.of( ErrorKeys.REPOSITORY_NOT_FOUND, dstRepositoryId ), 404 ); } checkAuthority( auditInformation.getUser().getUsername(), srcRepositoryId, dstRepositoryId ); try { ContentItem srcItem = srcRepo.getContent( ).toItem( path ); ContentItem dstItem = dstRepo.getContent( ).toItem( path ); if (!srcItem.getAsset().exists()){ throw new ArchivaRestServiceException( ErrorMessage.of( ErrorKeys.ARTIFACT_NOT_FOUND, srcRepositoryId, path ), 404 ); } if (dstItem.getAsset().exists()) { throw new ArchivaRestServiceException( ErrorMessage.of( ErrorKeys.ARTIFACT_EXISTS_AT_DEST, srcRepositoryId, path ), 400 ); } FsStorageUtil.copyAsset( srcItem.getAsset( ), dstItem.getAsset( ), true ); } catch ( LayoutException e ) { throw new ArchivaRestServiceException( ErrorMessage.of( ErrorKeys.REPOSITORY_LAYOUT_ERROR, e.getMessage() ) ); } catch ( IOException e ) { throw new ArchivaRestServiceException( ErrorMessage.of( ErrorKeys.ARTIFACT_COPY_ERROR, e.getMessage() ) ); } return Response.ok( ).build(); } private void checkAuthority(final String userName, final String srcRepositoryId, final String dstRepositoryId ) throws ArchivaRestServiceException { User user; try { user = securitySystem.getUserManager().findUser( userName ); } catch ( UserNotFoundException e ) { httpServletResponse.setHeader( "WWW-Authenticate", "Bearer realm=\"archiva\"" ); throw new ArchivaRestServiceException( ErrorMessage.of( ErrorKeys.USER_NOT_FOUND, userName ), 401 ); } catch ( UserManagerException e ) { throw new ArchivaRestServiceException( ErrorMessage.of( ErrorKeys.USER_MANAGER_ERROR, e.getMessage( ) ) ); } // check karma on source : read AuthenticationResult authn = new AuthenticationResult( true, userName, null ); SecuritySession securitySession = new DefaultSecuritySession( authn, user ); try { boolean authz = securitySystem.isAuthorized( securitySession, OPERATION_READ_REPOSITORY, srcRepositoryId ); if ( !authz ) { throw new ArchivaRestServiceException(ErrorMessage.of( ErrorKeys.PERMISSION_REPOSITORY_DENIED, srcRepositoryId, OPERATION_READ_REPOSITORY ), 403); } } catch ( AuthorizationException e ) { log.error( "Error reading permission: {}", e.getMessage(), e ); throw new ArchivaRestServiceException( ErrorMessage.of( ErrorKeys.AUTHORIZATION_ERROR, e.getMessage() ), 403); } // check karma on target: write try { boolean authz = securitySystem.isAuthorized( securitySession, ArchivaRoleConstants.OPERATION_ADD_ARTIFACT, dstRepositoryId ); if ( !authz ) { throw new ArchivaRestServiceException( ErrorMessage.of( ErrorKeys.PERMISSION_REPOSITORY_DENIED, dstRepositoryId, OPERATION_ADD_ARTIFACT ) ); } } catch ( AuthorizationException e ) { log.error( "Error reading permission: {}", e.getMessage(), e ); throw new ArchivaRestServiceException( ErrorMessage.of( ErrorKeys.AUTHORIZATION_ERROR, e.getMessage() ), 403); } } @Override public Response deleteArtifact( String repositoryId, String path ) throws ArchivaRestServiceException { return null; } @Override public Response removeProjectVersion( String repositoryId, String namespace, String projectId, String version ) throws org.apache.archiva.rest.api.services.ArchivaRestServiceException { return null; } @Override public Response deleteProject( String repositoryId, String namespace, String projectId ) throws org.apache.archiva.rest.api.services.ArchivaRestServiceException { return null; } @Override public Response deleteNamespace( String repositoryId, String namespace ) throws org.apache.archiva.rest.api.services.ArchivaRestServiceException { return null; } }
archiva-modules/archiva-web/archiva-rest/archiva-rest-services/src/main/java/org/apache/archiva/rest/v2/svc/maven/DefaultMavenManagedRepositoryService.java
package org.apache.archiva.rest.v2.svc.maven; /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ import org.apache.archiva.admin.model.AuditInformation; import org.apache.archiva.admin.model.RepositoryAdminException; import org.apache.archiva.admin.model.managed.ManagedRepositoryAdmin; import org.apache.archiva.components.rest.model.PagedResult; import org.apache.archiva.components.rest.util.QueryHelper; import org.apache.archiva.redback.authentication.AuthenticationResult; import org.apache.archiva.redback.authorization.AuthorizationException; import org.apache.archiva.redback.rest.services.RedbackAuthenticationThreadLocal; import org.apache.archiva.redback.rest.services.RedbackRequestInformation; import org.apache.archiva.redback.system.DefaultSecuritySession; import org.apache.archiva.redback.system.SecuritySession; import org.apache.archiva.redback.system.SecuritySystem; import org.apache.archiva.redback.users.User; import org.apache.archiva.redback.users.UserManagerException; import org.apache.archiva.redback.users.UserNotFoundException; import org.apache.archiva.repository.ManagedRepository; import org.apache.archiva.repository.ReleaseScheme; import org.apache.archiva.repository.Repository; import org.apache.archiva.repository.RepositoryRegistry; import org.apache.archiva.repository.RepositoryType; import org.apache.archiva.repository.content.ContentItem; import org.apache.archiva.repository.content.LayoutException; import org.apache.archiva.repository.storage.fs.FsStorageUtil; import org.apache.archiva.rest.api.v2.model.FileInfo; import org.apache.archiva.rest.api.v2.model.MavenManagedRepository; import org.apache.archiva.rest.api.v2.model.MavenManagedRepositoryUpdate; import org.apache.archiva.rest.api.v2.svc.ArchivaRestServiceException; import org.apache.archiva.rest.api.v2.svc.ErrorKeys; import org.apache.archiva.rest.api.v2.svc.ErrorMessage; import org.apache.archiva.rest.api.v2.svc.maven.MavenManagedRepositoryService; import org.apache.archiva.security.common.ArchivaRoleConstants; import org.apache.commons.lang3.StringUtils; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.stereotype.Service; import javax.servlet.http.HttpServletResponse; import javax.ws.rs.core.Context; import javax.ws.rs.core.Response; import javax.ws.rs.core.UriInfo; import java.io.IOException; import java.util.Collection; import java.util.Comparator; import java.util.List; import java.util.function.Predicate; import java.util.stream.Collectors; import static org.apache.archiva.security.common.ArchivaRoleConstants.OPERATION_READ_REPOSITORY; import static org.apache.archiva.security.common.ArchivaRoleConstants.OPERATION_ADD_ARTIFACT; /** * @author Martin Stockhammer <[email protected]> */ @Service("v2.managedMavenRepositoryService#rest") public class DefaultMavenManagedRepositoryService implements MavenManagedRepositoryService { @Context HttpServletResponse httpServletResponse; @Context UriInfo uriInfo; private static final Logger log = LoggerFactory.getLogger( DefaultMavenManagedRepositoryService.class ); private static final QueryHelper<ManagedRepository> QUERY_HELPER = new QueryHelper<>( new String[]{"id", "name"} ); static { QUERY_HELPER.addStringFilter( "id", ManagedRepository::getId ); QUERY_HELPER.addStringFilter( "name", ManagedRepository::getName ); QUERY_HELPER.addStringFilter( "location", (r) -> r.getLocation().toString() ); QUERY_HELPER.addBooleanFilter( "snapshot", (r) -> r.getActiveReleaseSchemes( ).contains( ReleaseScheme.SNAPSHOT ) ); QUERY_HELPER.addBooleanFilter( "release", (r) -> r.getActiveReleaseSchemes().contains( ReleaseScheme.RELEASE )); QUERY_HELPER.addNullsafeFieldComparator( "id", ManagedRepository::getId ); QUERY_HELPER.addNullsafeFieldComparator( "name", ManagedRepository::getName ); } private ManagedRepositoryAdmin managedRepositoryAdmin; private RepositoryRegistry repositoryRegistry; private SecuritySystem securitySystem; public DefaultMavenManagedRepositoryService( SecuritySystem securitySystem, RepositoryRegistry repositoryRegistry, ManagedRepositoryAdmin managedRepositoryAdmin ) { this.securitySystem = securitySystem; this.repositoryRegistry = repositoryRegistry; this.managedRepositoryAdmin = managedRepositoryAdmin; } protected AuditInformation getAuditInformation( ) { RedbackRequestInformation redbackRequestInformation = RedbackAuthenticationThreadLocal.get( ); User user; String remoteAddr; if (redbackRequestInformation==null) { user = null; remoteAddr = null; } else { user = redbackRequestInformation.getUser( ); remoteAddr = redbackRequestInformation.getRemoteAddr( ); } return new AuditInformation( user, remoteAddr ); } @Override public PagedResult<MavenManagedRepository> getManagedRepositories( final String searchTerm, final Integer offset, final Integer limit, final List<String> orderBy, final String order ) throws ArchivaRestServiceException { try { Collection<ManagedRepository> repos = repositoryRegistry.getManagedRepositories( ); final Predicate<ManagedRepository> queryFilter = QUERY_HELPER.getQueryFilter( searchTerm ).and( r -> r.getType() == RepositoryType.MAVEN ); final Comparator<ManagedRepository> comparator = QUERY_HELPER.getComparator( orderBy, order ); int totalCount = Math.toIntExact( repos.stream( ).filter( queryFilter ).count( ) ); return PagedResult.of( totalCount, offset, limit, repos.stream( ).filter( queryFilter ).sorted( comparator ) .map(mr -> MavenManagedRepository.of(mr)).skip( offset ).limit( limit ).collect( Collectors.toList( ) ) ); } catch (ArithmeticException e) { log.error( "Invalid number of repositories detected." ); throw new ArchivaRestServiceException( ErrorMessage.of( ErrorKeys.INVALID_RESULT_SET_ERROR ) ); } } @Override public MavenManagedRepository getManagedRepository( String repositoryId ) throws ArchivaRestServiceException { ManagedRepository repo = repositoryRegistry.getManagedRepository( repositoryId ); if (repo==null) { throw new ArchivaRestServiceException( ErrorMessage.of( ErrorKeys.REPOSITORY_NOT_FOUND, repositoryId ), 404 ); } if (repo.getType()!=RepositoryType.MAVEN) { throw new ArchivaRestServiceException( ErrorMessage.of( ErrorKeys.REPOSITORY_WRONG_TYPE, repositoryId, repo.getType().name() ), 404 ); } return MavenManagedRepository.of( repo ); } @Override public Response deleteManagedRepository( String repositoryId, Boolean deleteContent ) throws ArchivaRestServiceException { ManagedRepository repo = repositoryRegistry.getManagedRepository( repositoryId ); if (repo==null) { throw new ArchivaRestServiceException( ErrorMessage.of( ErrorKeys.REPOSITORY_NOT_FOUND, repositoryId ), 404 ); } if (repo.getType()!=RepositoryType.MAVEN) { throw new ArchivaRestServiceException( ErrorMessage.of( ErrorKeys.REPOSITORY_WRONG_TYPE, repositoryId, repo.getType().name() ), 404 ); } try { managedRepositoryAdmin.deleteManagedRepository( repositoryId, getAuditInformation( ), deleteContent ); return Response.ok( ).build( ); } catch ( RepositoryAdminException e ) { throw new ArchivaRestServiceException( ErrorMessage.of( ErrorKeys.REPOSITORY_DELETE_FAILED, e.getMessage( ) ) ); } } private org.apache.archiva.admin.model.beans.ManagedRepository convert(MavenManagedRepository repository) { org.apache.archiva.admin.model.beans.ManagedRepository repoBean = new org.apache.archiva.admin.model.beans.ManagedRepository( ); repoBean.setId( repository.getId( ) ); repoBean.setName( repository.getName() ); repoBean.setDescription( repository.getDescription() ); repoBean.setBlockRedeployments( repository.isBlocksRedeployments() ); repoBean.setCronExpression( repository.getSchedulingDefinition() ); repoBean.setLocation( repository.getLocation() ); repoBean.setReleases( repository.getReleaseSchemes().contains( ReleaseScheme.RELEASE.name() ) ); repoBean.setSnapshots( repository.getReleaseSchemes().contains( ReleaseScheme.SNAPSHOT.name() ) ); repoBean.setScanned( repository.isScanned() ); repoBean.setDeleteReleasedSnapshots( repository.isDeleteSnapshotsOfRelease() ); repoBean.setSkipPackedIndexCreation( repository.isSkipPackedIndexCreation() ); repoBean.setRetentionCount( repository.getRetentionCount() ); repoBean.setRetentionPeriod( repository.getRetentionPeriod().getDays() ); repoBean.setIndexDirectory( repository.getIndexPath() ); repoBean.setPackedIndexDirectory( repository.getPackedIndexPath() ); repoBean.setLayout( repository.getLayout() ); repoBean.setType( RepositoryType.MAVEN.name( ) ); return repoBean; } @Override public MavenManagedRepository addManagedRepository( MavenManagedRepository managedRepository ) throws ArchivaRestServiceException { final String repoId = managedRepository.getId( ); if ( StringUtils.isEmpty( repoId ) ) { throw new ArchivaRestServiceException( ErrorMessage.of( ErrorKeys.REPOSITORY_INVALID_ID, repoId ), 422 ); } Repository repo = repositoryRegistry.getRepository( repoId ); if (repo!=null) { httpServletResponse.setHeader( "Location", uriInfo.getAbsolutePathBuilder( ).path( repoId ).build( ).toString( ) ); throw new ArchivaRestServiceException( ErrorMessage.of( ErrorKeys.REPOSITORY_ID_EXISTS, repoId ), 303 ); } try { managedRepositoryAdmin.addManagedRepository( convert( managedRepository ), managedRepository.isHasStagingRepository(), getAuditInformation() ); httpServletResponse.setStatus( 201 ); return MavenManagedRepository.of( repositoryRegistry.getManagedRepository( repoId ) ); } catch ( RepositoryAdminException e ) { throw new ArchivaRestServiceException( ErrorMessage.of( ErrorKeys.REPOSITORY_ADMIN_ERROR, e.getMessage( ) ) ); } } @Override public MavenManagedRepository updateManagedRepository( final String repositoryId, final MavenManagedRepositoryUpdate managedRepository ) throws ArchivaRestServiceException { org.apache.archiva.admin.model.beans.ManagedRepository repo = convert( managedRepository ); try { managedRepositoryAdmin.updateManagedRepository( repo, managedRepository.isHasStagingRepository( ), getAuditInformation( ), managedRepository.isResetStats( ) ); ManagedRepository newRepo = repositoryRegistry.getManagedRepository( managedRepository.getId( ) ); if (newRepo==null) { throw new ArchivaRestServiceException( ErrorMessage.of( ErrorKeys.REPOSITORY_UPDATE_FAILED, repositoryId ) ); } return MavenManagedRepository.of( newRepo ); } catch ( RepositoryAdminException e ) { throw new ArchivaRestServiceException( ErrorMessage.of( ErrorKeys.REPOSITORY_ADMIN_ERROR, e.getMessage( ) ) ); } } @Override public FileInfo getFileStatus( String repositoryId, String fileLocation ) throws ArchivaRestServiceException { ManagedRepository repo = repositoryRegistry.getManagedRepository( repositoryId ); if (repo==null) { throw new ArchivaRestServiceException( ErrorMessage.of( ErrorKeys.REPOSITORY_NOT_FOUND, repositoryId ), 404 ); } try { ContentItem contentItem = repo.getContent( ).toItem( fileLocation ); if (contentItem.getAsset( ).exists( )) { return FileInfo.of( contentItem.getAsset( ) ); } else { throw new ArchivaRestServiceException( ErrorMessage.of( ErrorKeys.ARTIFACT_NOT_FOUND, repositoryId, fileLocation ), 404 ); } } catch ( LayoutException e ) { throw new ArchivaRestServiceException( ErrorMessage.of( ErrorKeys.REPOSITORY_LAYOUT_ERROR, e.getMessage( ) ) ); } } @Override public Response copyArtifact( String srcRepositoryId, String dstRepositoryId, String path ) throws ArchivaRestServiceException { final AuditInformation auditInformation = getAuditInformation( ); final String userName = auditInformation.getUser( ).getUsername( ); if ( StringUtils.isEmpty( userName ) ) { httpServletResponse.setHeader( "WWW-Authenticate", "Bearer realm=\"archiva\"" ); throw new ArchivaRestServiceException( ErrorMessage.of( ErrorKeys.NOT_AUTHENTICATED ), 401 ); } ManagedRepository srcRepo = repositoryRegistry.getManagedRepository( srcRepositoryId ); if (srcRepo==null) { throw new ArchivaRestServiceException( ErrorMessage.of( ErrorKeys.REPOSITORY_NOT_FOUND, srcRepositoryId ), 404 ); } ManagedRepository dstRepo = repositoryRegistry.getManagedRepository( dstRepositoryId ); if (dstRepo==null) { throw new ArchivaRestServiceException( ErrorMessage.of( ErrorKeys.REPOSITORY_NOT_FOUND, dstRepositoryId ), 404 ); } checkAuthority( auditInformation.getUser().getUsername(), srcRepositoryId, dstRepositoryId ); try { ContentItem srcItem = srcRepo.getContent( ).toItem( path ); ContentItem dstItem = dstRepo.getContent( ).toItem( path ); if (!srcItem.getAsset().exists()){ throw new ArchivaRestServiceException( ErrorMessage.of( ErrorKeys.ARTIFACT_NOT_FOUND, srcRepositoryId, path ), 404 ); } if (dstItem.getAsset().exists()) { throw new ArchivaRestServiceException( ErrorMessage.of( ErrorKeys.ARTIFACT_EXISTS_AT_DEST, srcRepositoryId, path ), 400 ); } FsStorageUtil.copyAsset( srcItem.getAsset( ), dstItem.getAsset( ), true ); } catch ( LayoutException e ) { throw new ArchivaRestServiceException( ErrorMessage.of( ErrorKeys.REPOSITORY_LAYOUT_ERROR, e.getMessage() ) ); } catch ( IOException e ) { throw new ArchivaRestServiceException( ErrorMessage.of( ErrorKeys.ARTIFACT_COPY_ERROR, e.getMessage() ) ); } return Response.ok( ).build(); } private void checkAuthority(final String userName, final String srcRepositoryId, final String dstRepositoryId ) throws ArchivaRestServiceException { User user = null; try { user = securitySystem.getUserManager().findUser( userName ); } catch ( UserNotFoundException e ) { httpServletResponse.setHeader( "WWW-Authenticate", "Bearer realm=\"archiva\"" ); throw new ArchivaRestServiceException( ErrorMessage.of( ErrorKeys.USER_NOT_FOUND, userName ), 401 ); } catch ( UserManagerException e ) { throw new ArchivaRestServiceException( ErrorMessage.of( ErrorKeys.USER_MANAGER_ERROR, e.getMessage( ) ) ); } // check karma on source : read AuthenticationResult authn = new AuthenticationResult( true, userName, null ); SecuritySession securitySession = new DefaultSecuritySession( authn, user ); try { boolean authz = securitySystem.isAuthorized( securitySession, OPERATION_READ_REPOSITORY, srcRepositoryId ); if ( !authz ) { throw new ArchivaRestServiceException(ErrorMessage.of( ErrorKeys.PERMISSION_REPOSITORY_DENIED, srcRepositoryId, OPERATION_READ_REPOSITORY ), 403); } } catch ( AuthorizationException e ) { log.error( "Error reading permission: {}", e.getMessage(), e ); throw new ArchivaRestServiceException( ErrorMessage.of( ErrorKeys.AUTHORIZATION_ERROR, e.getMessage() ), 403); } // check karma on target: write try { boolean authz = securitySystem.isAuthorized( securitySession, ArchivaRoleConstants.OPERATION_ADD_ARTIFACT, dstRepositoryId ); if ( !authz ) { throw new ArchivaRestServiceException( ErrorMessage.of( ErrorKeys.PERMISSION_REPOSITORY_DENIED, dstRepositoryId, OPERATION_ADD_ARTIFACT ) ); } } catch ( AuthorizationException e ) { log.error( "Error reading permission: {}", e.getMessage(), e ); throw new ArchivaRestServiceException( ErrorMessage.of( ErrorKeys.AUTHORIZATION_ERROR, e.getMessage() ), 403); } } @Override public Response deleteArtifact( String repositoryId, String path ) throws ArchivaRestServiceException { return null; } @Override public Response removeProjectVersion( String repositoryId, String namespace, String projectId, String version ) throws org.apache.archiva.rest.api.services.ArchivaRestServiceException { return null; } @Override public Response deleteProject( String repositoryId, String namespace, String projectId ) throws org.apache.archiva.rest.api.services.ArchivaRestServiceException { return null; } @Override public Response deleteNamespace( String repositoryId, String namespace ) throws org.apache.archiva.rest.api.services.ArchivaRestServiceException { return null; } }
code cleanup
archiva-modules/archiva-web/archiva-rest/archiva-rest-services/src/main/java/org/apache/archiva/rest/v2/svc/maven/DefaultMavenManagedRepositoryService.java
code cleanup
<ide><path>rchiva-modules/archiva-web/archiva-rest/archiva-rest-services/src/main/java/org/apache/archiva/rest/v2/svc/maven/DefaultMavenManagedRepositoryService.java <ide> QUERY_HELPER.addNullsafeFieldComparator( "name", ManagedRepository::getName ); <ide> } <ide> <del> private ManagedRepositoryAdmin managedRepositoryAdmin; <del> private RepositoryRegistry repositoryRegistry; <del> private SecuritySystem securitySystem; <add> private final ManagedRepositoryAdmin managedRepositoryAdmin; <add> private final RepositoryRegistry repositoryRegistry; <add> private final SecuritySystem securitySystem; <ide> <ide> public DefaultMavenManagedRepositoryService( SecuritySystem securitySystem, <ide> RepositoryRegistry repositoryRegistry, <ide> final Comparator<ManagedRepository> comparator = QUERY_HELPER.getComparator( orderBy, order ); <ide> int totalCount = Math.toIntExact( repos.stream( ).filter( queryFilter ).count( ) ); <ide> return PagedResult.of( totalCount, offset, limit, repos.stream( ).filter( queryFilter ).sorted( comparator ) <del> .map(mr -> MavenManagedRepository.of(mr)).skip( offset ).limit( limit ).collect( Collectors.toList( ) ) ); <add> .map( MavenManagedRepository::of ).skip( offset ).limit( limit ).collect( Collectors.toList( ) ) ); <ide> } <ide> catch (ArithmeticException e) { <ide> log.error( "Invalid number of repositories detected." ); <ide> @Override <ide> public Response deleteManagedRepository( String repositoryId, Boolean deleteContent ) throws ArchivaRestServiceException <ide> { <del> ManagedRepository repo = repositoryRegistry.getManagedRepository( repositoryId ); <del> if (repo==null) { <add> MavenManagedRepository repo = getManagedRepository( repositoryId ); <add> if (repo != null) <add> { <add> try <add> { <add> managedRepositoryAdmin.deleteManagedRepository( repositoryId, getAuditInformation( ), deleteContent ); <add> return Response.ok( ).build( ); <add> } <add> catch ( RepositoryAdminException e ) <add> { <add> throw new ArchivaRestServiceException( ErrorMessage.of( ErrorKeys.REPOSITORY_DELETE_FAILED, e.getMessage( ) ) ); <add> } <add> } else { <ide> throw new ArchivaRestServiceException( ErrorMessage.of( ErrorKeys.REPOSITORY_NOT_FOUND, repositoryId ), 404 ); <del> } <del> if (repo.getType()!=RepositoryType.MAVEN) { <del> throw new ArchivaRestServiceException( ErrorMessage.of( ErrorKeys.REPOSITORY_WRONG_TYPE, repositoryId, repo.getType().name() ), 404 ); <del> } <del> try <del> { <del> managedRepositoryAdmin.deleteManagedRepository( repositoryId, getAuditInformation( ), deleteContent ); <del> return Response.ok( ).build( ); <del> } <del> catch ( RepositoryAdminException e ) <del> { <del> throw new ArchivaRestServiceException( ErrorMessage.of( ErrorKeys.REPOSITORY_DELETE_FAILED, e.getMessage( ) ) ); <ide> } <ide> } <ide> <ide> } <ide> <ide> private void checkAuthority(final String userName, final String srcRepositoryId, final String dstRepositoryId ) throws ArchivaRestServiceException { <del> User user = null; <add> User user; <ide> try <ide> { <ide> user = securitySystem.getUserManager().findUser( userName );
Java
mit
error: pathspec 'src/test/java/studentcapture/datalayer/filesystem/FilesystemInterfaceTest.java' did not match any file(s) known to git
fbbe46effbcc6c2004d8d2fe7e37f607202f0d6e
1
student-capture/student-capture
package studentcapture.datalayer.filesystem; import static org.junit.Assert.*; import org.junit.Test; public class FilesystemInterfaceTest { @Test public void testGeneratePathWithoutStudent() { String path = FilesystemInterface.generatePath("5DV151", 1, 123); assertEquals(path, FilesystemConstants.FILESYSTEM_PATH + "/5DV151/1/123/"); } @Test public void testGeneratePathWithStudent() { String path = FilesystemInterface.generatePath("5DV151", 1, 123, 654); assertEquals(path, FilesystemConstants.FILESYSTEM_PATH + "/5DV151/1/123/654/"); } }
src/test/java/studentcapture/datalayer/filesystem/FilesystemInterfaceTest.java
saved filesysteminterface tests from merge
src/test/java/studentcapture/datalayer/filesystem/FilesystemInterfaceTest.java
saved filesysteminterface tests from merge
<ide><path>rc/test/java/studentcapture/datalayer/filesystem/FilesystemInterfaceTest.java <add>package studentcapture.datalayer.filesystem; <add> <add>import static org.junit.Assert.*; <add> <add>import org.junit.Test; <add> <add>public class FilesystemInterfaceTest { <add> <add> @Test <add> public void testGeneratePathWithoutStudent() { <add> String path = FilesystemInterface.generatePath("5DV151", 1, 123); <add> <add> assertEquals(path, FilesystemConstants.FILESYSTEM_PATH <add> + "/5DV151/1/123/"); <add> } <add> <add> @Test <add> public void testGeneratePathWithStudent() { <add> String path = FilesystemInterface.generatePath("5DV151", 1, 123, 654); <add> <add> assertEquals(path, FilesystemConstants.FILESYSTEM_PATH <add> + "/5DV151/1/123/654/"); <add> } <add> <add>}
Java
agpl-3.0
eb9064e76e003c74507edbd9a3c66c9946186de6
0
c0deh4xor/jPOS,barspi/jPOS,barspi/jPOS,yinheli/jPOS,bharavi/jPOS,bharavi/jPOS,yinheli/jPOS,c0deh4xor/jPOS,poynt/jPOS,alcarraz/jPOS,bharavi/jPOS,atancasis/jPOS,jpos/jPOS,fayezasar/jPOS,imam-san/jPOS-1,jpos/jPOS,atancasis/jPOS,alcarraz/jPOS,imam-san/jPOS-1,sebastianpacheco/jPOS,juanibdn/jPOS,sebastianpacheco/jPOS,fayezasar/jPOS,alcarraz/jPOS,sebastianpacheco/jPOS,poynt/jPOS,poynt/jPOS,c0deh4xor/jPOS,barspi/jPOS,jpos/jPOS,juanibdn/jPOS,yinheli/jPOS,atancasis/jPOS,juanibdn/jPOS,imam-san/jPOS-1
/* * jPOS Project [http://jpos.org] * Copyright (C) 2000-2013 Alejandro P. Revilla * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU Affero General Public License as * published by the Free Software Foundation, either version 3 of the * License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Affero General Public License for more details. * * You should have received a copy of the GNU Affero General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ package org.jpos.util; import static org.hamcrest.Matchers.is; import static org.hamcrest.Matchers.nullValue; import static org.junit.Assert.assertThat; import static org.junit.Assert.assertTrue; import static org.junit.Assert.fail; import java.util.ArrayList; import java.util.Collections; import java.util.List; import java.util.concurrent.CountDownLatch; import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors; import java.util.concurrent.TimeUnit; import org.jpos.util.NameRegistrar.NotFoundException; import org.junit.Test; public class NameRegistrarConcurrencyTest { static final int TOTAL_THREADS_TO_RUN = 100; @Test public void testConcurrency() throws Exception { List<Runnable> parrallelTasksList = new ArrayList<Runnable>(TOTAL_THREADS_TO_RUN); for (int i = 0; i < TOTAL_THREADS_TO_RUN; i++) { final int counter = i; parrallelTasksList.add(new Runnable() { public void run() { String key = "testKey" + counter; String value = "testValue" + counter; assertThat(NameRegistrar.getIfExists(key), is(nullValue())); NameRegistrar.register(key, value); try { String actualValue = (String) NameRegistrar.get(key); assertThat(actualValue, is(value)); } catch (NotFoundException e) { fail("key not found: " + key); } NameRegistrar.unregister(key); // Uncomment the sysout below to show that test were not // completed in order, the numbers should be interleaved // (not an ordered list) to hopefully show // the threads had the opportunity to step on each other; // i.e. thread safety of operations (and not just of Sysout!). // If it were to run too fast, can insert a Thread.sleep // part way through - say, after the register step above for // 200 milliseconds. // // System.out.println("done: "+ key); } }); } int maxTimeoutSeconds = 5; assertConcurrent("Remove/Get/Add of NameRegistrar items must be ThreadSafe", parrallelTasksList, maxTimeoutSeconds); } public static void assertConcurrent(final String message, final List<? extends Runnable> runnables, final int maxTimeoutSeconds) throws InterruptedException { final int numThreads = runnables.size(); final List<Throwable> exceptions = Collections.synchronizedList(new ArrayList<Throwable>()); final ExecutorService threadPool = Executors.newFixedThreadPool(numThreads); try { final CountDownLatch allExecutorThreadsReady = new CountDownLatch(numThreads); final CountDownLatch afterInitBlocker = new CountDownLatch(1); final CountDownLatch allDone = new CountDownLatch(numThreads); for (final Runnable submittedTestRunnable : runnables) { threadPool.submit(new Runnable() { public void run() { allExecutorThreadsReady.countDown(); try { afterInitBlocker.await(); submittedTestRunnable.run(); } catch (final Throwable e) { exceptions.add(e); } finally { allDone.countDown(); } } }); } // wait until all threads are ready assertTrue( "Timeout initializing threads! Perform long lasting initializations before passing runnables to assertConcurrent", allExecutorThreadsReady.await(runnables.size() * 10, TimeUnit.MILLISECONDS)); // start all test runners afterInitBlocker.countDown(); assertTrue(message + " timeout! More than" + maxTimeoutSeconds + "seconds", allDone.await(maxTimeoutSeconds, TimeUnit.SECONDS)); } finally { threadPool.shutdownNow(); } assertTrue(message + "failed with exception(s)" + exceptions, exceptions.isEmpty()); } }
jpos/src/test/java/org/jpos/util/NameRegistrarConcurrencyTest.java
/* * jPOS Project [http://jpos.org] * Copyright (C) 2000-2013 Alejandro P. Revilla * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU Affero General Public License as * published by the Free Software Foundation, either version 3 of the * License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Affero General Public License for more details. * * You should have received a copy of the GNU Affero General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ package org.jpos.util; import static org.hamcrest.Matchers.is; import static org.hamcrest.Matchers.nullValue; import static org.junit.Assert.assertThat; import static org.junit.Assert.assertTrue; import static org.junit.Assert.fail; import java.util.ArrayList; import java.util.Collections; import java.util.List; import java.util.concurrent.CountDownLatch; import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors; import java.util.concurrent.TimeUnit; import org.jpos.util.NameRegistrar.NotFoundException; import org.junit.Test; public class NameRegistrarConcurrencyTest { static final int TOTAL_THREADS_TO_RUN = 1000; @Test public void testConcurrency() throws Exception { List<Runnable> parrallelTasksList = new ArrayList<Runnable>(TOTAL_THREADS_TO_RUN); for (int i = 0; i < TOTAL_THREADS_TO_RUN; i++) { final int counter = i; parrallelTasksList.add(new Runnable() { public void run() { String key = "testKey" + counter; String value = "testValue" + counter; assertThat(NameRegistrar.getIfExists(key), is(nullValue())); NameRegistrar.register(key, value); try { String actualValue = (String) NameRegistrar.get(key); assertThat(actualValue, is(value)); } catch (NotFoundException e) { fail("key not found: " + key); } NameRegistrar.unregister(key); // Uncomment the sysout below to show that test were not // completed in order, the numbers should be interleaved // (not an ordered list) to hopefully show // the threads had the opportunity to step on each other; // i.e. thread safety of operations (and not just of Sysout!). // If it were to run too fast, can insert a Thread.sleep // part way through - say, after the register step above for // 200 milliseconds. // // System.out.println("done: "+ key); } }); } int maxTimeoutSeconds = 5; assertConcurrent("Remove/Get/Add of NameRegistrar items must be ThreadSafe", parrallelTasksList, maxTimeoutSeconds); } public static void assertConcurrent(final String message, final List<? extends Runnable> runnables, final int maxTimeoutSeconds) throws InterruptedException { final int numThreads = runnables.size(); final List<Throwable> exceptions = Collections.synchronizedList(new ArrayList<Throwable>()); final ExecutorService threadPool = Executors.newFixedThreadPool(numThreads); try { final CountDownLatch allExecutorThreadsReady = new CountDownLatch(numThreads); final CountDownLatch afterInitBlocker = new CountDownLatch(1); final CountDownLatch allDone = new CountDownLatch(numThreads); for (final Runnable submittedTestRunnable : runnables) { threadPool.submit(new Runnable() { public void run() { allExecutorThreadsReady.countDown(); try { afterInitBlocker.await(); submittedTestRunnable.run(); } catch (final Throwable e) { exceptions.add(e); } finally { allDone.countDown(); } } }); } // wait until all threads are ready assertTrue( "Timeout initializing threads! Perform long lasting initializations before passing runnables to assertConcurrent", allExecutorThreadsReady.await(runnables.size() * 10, TimeUnit.MILLISECONDS)); // start all test runners afterInitBlocker.countDown(); assertTrue(message + " timeout! More than" + maxTimeoutSeconds + "seconds", allDone.await(maxTimeoutSeconds, TimeUnit.SECONDS)); } finally { threadPool.shutdownNow(); } assertTrue(message + "failed with exception(s)" + exceptions, exceptions.isEmpty()); } }
we don't need 1000 threads in this test which causes OutOfMemoryException on some boxes
jpos/src/test/java/org/jpos/util/NameRegistrarConcurrencyTest.java
we don't need 1000 threads in this test
<ide><path>pos/src/test/java/org/jpos/util/NameRegistrarConcurrencyTest.java <ide> import org.junit.Test; <ide> <ide> public class NameRegistrarConcurrencyTest { <del> static final int TOTAL_THREADS_TO_RUN = 1000; <add> static final int TOTAL_THREADS_TO_RUN = 100; <ide> <ide> @Test <ide> public void testConcurrency() throws Exception {
Java
lgpl-2.1
24347bcb61bf2dfa63471cb51e1a8d1965b9ba2f
0
zanata/zanata-platform,zanata/zanata-platform,zanata/zanata-platform,zanata/zanata-platform,zanata/zanata-platform,zanata/zanata-platform,zanata/zanata-platform
package org.zanata.adapter.xliff; import java.io.File; import java.io.FileOutputStream; import java.io.IOException; import java.util.ArrayList; import java.util.Collections; import java.util.HashMap; import java.util.List; import java.util.Map; import javax.xml.stream.XMLOutputFactory; import javax.xml.stream.XMLStreamException; import javax.xml.stream.XMLStreamWriter; import org.zanata.rest.dto.extensions.comment.SimpleComment; import org.zanata.rest.dto.extensions.gettext.TextFlowExtension; import org.zanata.rest.dto.resource.Resource; import org.zanata.rest.dto.resource.TextFlow; import org.zanata.rest.dto.resource.TextFlowTarget; import org.zanata.rest.dto.resource.TranslationsResource; import org.zanata.util.PathUtil; import net.sf.saxon.Configuration; import net.sf.saxon.event.StreamWriterToReceiver; import net.sf.saxon.s9api.Processor; import net.sf.saxon.s9api.SaxonApiException; import net.sf.saxon.s9api.Serializer; public class XliffWriter extends XliffCommon { /** * Write document header with XML, xliff, file and body tag * * @param writer * @param doc * @param targetLocale * (use hyphen, not underscore) * @throws XMLStreamException */ private static void writeHeader(StreamWriterToReceiver writer, Resource doc, String targetLocale) throws XMLStreamException { // XML tag writer.writeStartDocument("utf-8", "1.0"); writer.writeComment("XLIFF document generated by Zanata. Visit http://zanata.org for more infomation."); writer.writeCharacters("\n"); // XLiff tag writer.writeStartElement("xliff"); writer.writeNamespace("", "urn:oasis:names:tc:xliff:document:1.1"); writer.writeNamespace("xyz", "urn:appInfo:Items"); writer.writeNamespace("xsi", "http://www.w3.org/2001/XMLSchema-instance"); writer.writeAttribute( "xsi:schemaLocation", "urn:oasis:names:tc:xliff:document:1.1 http://www.oasis-open.org/committees/xliff/documents/xliff-core-1.1.xsd"); writer.writeAttribute("version", "1.1"); // file tag writer.writeStartElement(ELE_FILE); writer.writeAttribute(ATTRI_SOURCE_LANGUAGE, doc.getLang().getId()); writer.writeAttribute(ATTRI_DATATYPE, "plaintext"); writer.writeAttribute(ATTRI_ORIGINAL, ""); if (targetLocale != null) { writer.writeAttribute(ATTRI_TARGET_LANGUAGE, targetLocale); } // body tag writer.writeStartElement(ELE_BODY); } private static void writeTransUnits(StreamWriterToReceiver writer, Resource doc, TranslationsResource targetDoc, boolean createSkeletons) throws XMLStreamException { Map<String, TextFlowTarget> targets = Collections.emptyMap(); if (targetDoc != null) { targets = new HashMap<String, TextFlowTarget>(); for (TextFlowTarget target : targetDoc.getTextFlowTargets()) { targets.put(target.getResId(), target); } } for (TextFlow textFlow : doc.getTextFlows()) { TextFlowTarget target = targets.get(textFlow.getId()); if (target == null && !createSkeletons) { continue; } writer.writeStartElement(ELE_TRANS_UNIT); writer.writeAttribute(ATTRI_ID, textFlow.getId()); writeTransUnitSource(writer, textFlow); if (target != null && target.getState().isTranslated()) { writeTransUnitTarget(writer, target); } writeTransUnitContext(writer, textFlow); // end trans-unit tag writer.writeEndElement(); } } private static void writeTransUnitSource(StreamWriterToReceiver writer, TextFlow textFlow) throws XMLStreamException { writer.writeStartElement(ELE_SOURCE); List<String> contents = textFlow.getContents(); if (contents.size() != 1) { throw new RuntimeException( "file format does not support plural forms: resId=" + textFlow.getId()); } writer.writeCharacters(contents.get(0)); // end source tag writer.writeEndElement(); } private static void writeTransUnitTarget(StreamWriterToReceiver writer, TextFlowTarget target) throws XMLStreamException { writer.writeStartElement(ELE_TARGET); List<String> contents = target.getContents(); if (contents.size() != 1) { throw new RuntimeException( "file format does not support plural forms: resId=" + target.getResId()); } writer.writeCharacters(contents.get(0)); // end target tag writer.writeEndElement(); } private static void writeTransUnitContext(StreamWriterToReceiver writer, TextFlow textFlow) throws XMLStreamException { if (!textFlow.getExtensions(true).isEmpty()) { Map<String, ArrayList<String[]>> contextGroupMap = new HashMap<String, ArrayList<String[]>>(); for (TextFlowExtension textFlowExtension : textFlow.getExtensions()) { SimpleComment comment = (SimpleComment) textFlowExtension; String[] contextValues = comment.getValue().split(DELIMITER, 3); if (!contextGroupMap.containsKey(contextValues[0])) { ArrayList<String[]> list = new ArrayList<String[]>(); list.add(new String[] { contextValues[1], contextValues[2] }); contextGroupMap.put(contextValues[0], list); } else { ArrayList<String[]> list = contextGroupMap.get(contextValues[0]); list.add(new String[] { contextValues[1], contextValues[2] }); } } for (Map.Entry<String, ArrayList<String[]>> entry : contextGroupMap .entrySet()) { String key = entry.getKey(); ArrayList<String[]> values = entry.getValue(); writer.writeStartElement(ELE_CONTEXT_GROUP); writer.writeAttribute(ATTRI_NAME, key); for (String[] val : values) { writer.writeStartElement(ELE_CONTEXT); writer.writeAttribute(ATTRI_CONTEXT_TYPE, val[0]); writer.writeCharacters(val[1]); // end context writer.writeEndElement(); } // end context-group writer.writeEndElement(); } } } /** * Used for writing target file * * @param baseDir * @param doc * @param locale * (use hyphen, not underscore) * @param targetDoc * may be null */ public static void write(File baseDir, Resource doc, String locale, TranslationsResource targetDoc, boolean createSkeletons) { File outFile = new File(baseDir, doc.getName() + "_" + locale.replace('-', '_') + ".xml"); writeFile(outFile, doc, locale, targetDoc, createSkeletons); } /** * Used for writing translation file with given translations map * * @param doc * @param targetDoc * @param file * @param locale (use hyphen, not underscore) */ public static void writeFile(File file, Resource doc, String locale, TranslationsResource targetDoc, boolean createSkeletons) { try { PathUtil.makeParents(file); } catch (IOException e) { throw new RuntimeException("Error writing XLIFF file ", e); } Configuration config = new Configuration(); Processor processor = new Processor(config); Serializer serializer = processor.newSerializer(); serializer.setOutputProperty(Serializer.Property.METHOD, "xml"); serializer.setOutputProperty(Serializer.Property.INDENT, "yes"); serializer.setOutputProperty(Serializer.Property.ENCODING, "utf-8"); StreamWriterToReceiver writer = null; try (FileOutputStream fileStream = new FileOutputStream(file)) { serializer.setOutputStream(fileStream); try { writer = serializer.getXMLStreamWriter(); writeHeader(writer, doc, locale); writeTransUnits(writer, doc, targetDoc, createSkeletons); // end body tag writer.writeEndElement(); // end file tag writer.writeEndElement(); // end xliff tag writer.writeEndDocument(); writer.flush(); } finally { if (writer != null) { writer.close(); } } } catch (XMLStreamException e) { throw new RuntimeException("Error generating XLIFF file format ", e); } catch (IOException | SaxonApiException e) { throw new RuntimeException("Error writing XLIFF file ", e); } } /** * Used for writing source file * * @param baseDir * @param doc * @param locale * (use hyphen, not underscore) */ public static void write(File baseDir, Resource doc, String locale) { write(baseDir, doc, locale, null, true); } }
zanata-adapter-xliff/src/main/java/org/zanata/adapter/xliff/XliffWriter.java
package org.zanata.adapter.xliff; import java.io.File; import java.io.FileOutputStream; import java.io.IOException; import java.util.ArrayList; import java.util.Collections; import java.util.HashMap; import java.util.List; import java.util.Map; import javax.xml.stream.XMLOutputFactory; import javax.xml.stream.XMLStreamException; import javax.xml.stream.XMLStreamWriter; import org.zanata.rest.dto.extensions.comment.SimpleComment; import org.zanata.rest.dto.extensions.gettext.TextFlowExtension; import org.zanata.rest.dto.resource.Resource; import org.zanata.rest.dto.resource.TextFlow; import org.zanata.rest.dto.resource.TextFlowTarget; import org.zanata.rest.dto.resource.TranslationsResource; import org.zanata.util.PathUtil; import net.sf.saxon.Configuration; import net.sf.saxon.event.StreamWriterToReceiver; import net.sf.saxon.s9api.Processor; import net.sf.saxon.s9api.SaxonApiException; import net.sf.saxon.s9api.Serializer; public class XliffWriter extends XliffCommon { /** * Write document header with XML, xliff, file and body tag * * @param writer * @param doc * @param targetLocale * (use hyphen, not underscore) * @throws XMLStreamException */ private static void writeHeader(StreamWriterToReceiver writer, Resource doc, String targetLocale) throws XMLStreamException { // XML tag writer.writeStartDocument("utf-8", "1.0"); writer.writeComment("XLIFF document generated by Zanata. Visit http://zanata.org for more infomation."); writer.writeCharacters("\n"); // XLiff tag writer.writeStartElement("xliff"); writer.writeNamespace("", "urn:oasis:names:tc:xliff:document:1.1"); writer.writeNamespace("xyz", "urn:appInfo:Items"); writer.writeNamespace("xsi", "http://www.w3.org/2001/XMLSchema-instance"); writer.writeAttribute( "xsi:schemaLocation", "urn:oasis:names:tc:xliff:document:1.1 http://www.oasis-open.org/committees/xliff/documents/xliff-core-1.1.xsd"); writer.writeAttribute("version", "1.1"); // file tag writer.writeStartElement(ELE_FILE); writer.writeAttribute(ATTRI_SOURCE_LANGUAGE, doc.getLang().getId()); writer.writeAttribute(ATTRI_DATATYPE, "plaintext"); writer.writeAttribute(ATTRI_ORIGINAL, ""); if (targetLocale != null) { writer.writeAttribute(ATTRI_TARGET_LANGUAGE, targetLocale); } // body tag writer.writeStartElement(ELE_BODY); } private static void writeTransUnits(StreamWriterToReceiver writer, Resource doc, TranslationsResource targetDoc, boolean createSkeletons) throws XMLStreamException { Map<String, TextFlowTarget> targets = Collections.emptyMap(); if (targetDoc != null) { targets = new HashMap<String, TextFlowTarget>(); for (TextFlowTarget target : targetDoc.getTextFlowTargets()) { targets.put(target.getResId(), target); } } for (TextFlow textFlow : doc.getTextFlows()) { TextFlowTarget target = targets.get(textFlow.getId()); if (target == null && !createSkeletons) { continue; } writer.writeStartElement(ELE_TRANS_UNIT); writer.writeAttribute(ATTRI_ID, textFlow.getId()); writeTransUnitSource(writer, textFlow); if (target != null && target.getState().isTranslated()) { writeTransUnitTarget(writer, target); } writeTransUnitContext(writer, textFlow); // end trans-unit tag writer.writeEndElement(); } } private static void writeTransUnitSource(StreamWriterToReceiver writer, TextFlow textFlow) throws XMLStreamException { writer.writeStartElement(ELE_SOURCE); List<String> contents = textFlow.getContents(); if (contents.size() != 1) { throw new RuntimeException( "file format does not support plural forms: resId=" + textFlow.getId()); } writer.writeCharacters(contents.get(0)); // end source tag writer.writeEndElement(); } private static void writeTransUnitTarget(StreamWriterToReceiver writer, TextFlowTarget target) throws XMLStreamException { writer.writeStartElement(ELE_TARGET); List<String> contents = target.getContents(); if (contents.size() != 1) { throw new RuntimeException( "file format does not support plural forms: resId=" + target.getResId()); } writer.writeCharacters(contents.get(0)); // end target tag writer.writeEndElement(); } private static void writeTransUnitContext(StreamWriterToReceiver writer, TextFlow textFlow) throws XMLStreamException { if (!textFlow.getExtensions(true).isEmpty()) { Map<String, ArrayList<String[]>> contextGroupMap = new HashMap<String, ArrayList<String[]>>(); for (TextFlowExtension textFlowExtension : textFlow.getExtensions()) { SimpleComment comment = (SimpleComment) textFlowExtension; String[] contextValues = comment.getValue().split(DELIMITER, 3); if (!contextGroupMap.containsKey(contextValues[0])) { ArrayList<String[]> list = new ArrayList<String[]>(); list.add(new String[] { contextValues[1], contextValues[2] }); contextGroupMap.put(contextValues[0], list); } else { ArrayList<String[]> list = contextGroupMap.get(contextValues[0]); list.add(new String[] { contextValues[1], contextValues[2] }); } } for (Map.Entry<String, ArrayList<String[]>> entry : contextGroupMap .entrySet()) { String key = entry.getKey(); ArrayList<String[]> values = entry.getValue(); writer.writeStartElement(ELE_CONTEXT_GROUP); writer.writeAttribute(ATTRI_NAME, key); for (String[] val : values) { writer.writeStartElement(ELE_CONTEXT); writer.writeAttribute(ATTRI_CONTEXT_TYPE, val[0]); writer.writeCharacters(val[1]); // end context writer.writeEndElement(); } // end context-group writer.writeEndElement(); } } } /** * Used for writing target file * * @param baseDir * @param doc * @param locale * (use hyphen, not underscore) * @param targetDoc * may be null */ public static void write(File baseDir, Resource doc, String locale, TranslationsResource targetDoc, boolean createSkeletons) { File outFile = new File(baseDir, doc.getName() + "_" + locale.replace('-', '_') + ".xml"); writeFile(outFile, doc, locale, targetDoc, createSkeletons); } /** * Used for writing translation file with given translations map * * @param doc * @param targetDoc * @param file * @param locale (use hyphen, not underscore) */ public static void writeFile(File file, Resource doc, String locale, TranslationsResource targetDoc, boolean createSkeletons) { try { PathUtil.makeParents(file); } catch (IOException e) { throw new RuntimeException("Error writing XLIFF file ", e); } Configuration config = new Configuration(); Processor processor = new Processor(config); Serializer serializer = processor.newSerializer(); serializer.setOutputProperty(Serializer.Property.METHOD, "xml"); serializer.setOutputProperty(Serializer.Property.INDENT, "yes"); serializer.setOutputProperty(Serializer.Property.ENCODING, "utf-8"); StreamWriterToReceiver writer = null; try (FileOutputStream fileStream = new FileOutputStream(file)) { serializer.setOutputStream(fileStream); writer = serializer.getXMLStreamWriter(); writeHeader(writer, doc, locale); writeTransUnits(writer, doc, targetDoc, createSkeletons); // end body tag writer.writeEndElement(); // end file tag writer.writeEndElement(); // end xliff tag writer.writeEndDocument(); writer.flush(); writer.close(); } catch (XMLStreamException e) { throw new RuntimeException("Error generating XLIFF file format ", e); } catch (IOException | SaxonApiException e) { throw new RuntimeException("Error writing XLIFF file ", e); } } /** * Used for writing source file * * @param baseDir * @param doc * @param locale * (use hyphen, not underscore) */ public static void write(File baseDir, Resource doc, String locale) { write(baseDir, doc, locale, null, true); } }
ZNTA-901 - close writer in finally block
zanata-adapter-xliff/src/main/java/org/zanata/adapter/xliff/XliffWriter.java
ZNTA-901 - close writer in finally block
<ide><path>anata-adapter-xliff/src/main/java/org/zanata/adapter/xliff/XliffWriter.java <ide> <ide> try (FileOutputStream fileStream = new FileOutputStream(file)) { <ide> serializer.setOutputStream(fileStream); <del> writer = serializer.getXMLStreamWriter(); <del> <del> writeHeader(writer, doc, locale); <del> <del> writeTransUnits(writer, doc, targetDoc, createSkeletons); <del> <del> // end body tag <del> writer.writeEndElement(); <del> // end file tag <del> writer.writeEndElement(); <del> // end xliff tag <del> writer.writeEndDocument(); <del> writer.flush(); <del> writer.close(); <add> try { <add> writer = serializer.getXMLStreamWriter(); <add> <add> writeHeader(writer, doc, locale); <add> <add> writeTransUnits(writer, doc, targetDoc, createSkeletons); <add> <add> // end body tag <add> writer.writeEndElement(); <add> // end file tag <add> writer.writeEndElement(); <add> // end xliff tag <add> writer.writeEndDocument(); <add> writer.flush(); <add> } finally { <add> if (writer != null) { <add> writer.close(); <add> } <add> } <add> <ide> } catch (XMLStreamException e) { <ide> throw new RuntimeException("Error generating XLIFF file format ", <ide> e);
Java
apache-2.0
d46c9df20e14112b0bd420f60b9822da3a61970f
0
OresteVisari/alien4cloud,alien4cloud/alien4cloud,san-tak/alien4cloud,alien4cloud/alien4cloud,OresteVisari/alien4cloud,OresteVisari/alien4cloud,broly-git/alien4cloud,alien4cloud/alien4cloud,alien4cloud/alien4cloud,broly-git/alien4cloud,san-tak/alien4cloud,san-tak/alien4cloud,san-tak/alien4cloud,OresteVisari/alien4cloud,broly-git/alien4cloud,broly-git/alien4cloud
package alien4cloud.deployment; import java.util.*; import javax.annotation.Resource; import javax.inject.Inject; import lombok.extern.slf4j.Slf4j; import org.elasticsearch.index.query.QueryBuilder; import org.elasticsearch.index.query.QueryBuilders; import org.springframework.stereotype.Service; import alien4cloud.dao.IGenericSearchDAO; import alien4cloud.dao.model.GetMultipleDataResult; import alien4cloud.exception.NotFoundException; import alien4cloud.model.deployment.Deployment; import alien4cloud.model.deployment.DeploymentTopology; import alien4cloud.paas.model.PaaSTopologyDeploymentContext; import alien4cloud.utils.MapUtil; import com.google.common.collect.Maps; /** * Manage deployment operations on a cloud. */ @Service @Slf4j public class DeploymentService { @Resource(name = "alien-es-dao") private IGenericSearchDAO alienDao; @Inject private DeploymentRuntimeStateService deploymentRuntimeStateService; @Inject private DeploymentContextService deploymentContextService; @Inject private DeploymentTopologyService deploymentTopologyService; /** * Get all deployments for a given orchestrator an application * * @param orchestratorId Id of the cloud for which to get deployments (can be null to get deployments for all clouds). * @param sourceId Id of the application for which to get deployments (can be null to get deployments for all applications). * @return A {@link GetMultipleDataResult} that contains deployments. */ public List<Deployment> getDeployments(String orchestratorId, String sourceId) { QueryBuilder query = QueryBuilders.boolQuery(); if (orchestratorId != null) { query = QueryBuilders.boolQuery().must(QueryBuilders.termsQuery("orchestratorId", orchestratorId)); } if (sourceId != null) { query = QueryBuilders.boolQuery().must(query).must(QueryBuilders.termsQuery("sourceId", sourceId)); } if (orchestratorId == null && sourceId == null) { query = QueryBuilders.matchAllQuery(); } return alienDao.customFindAll(Deployment.class, query); } /** * Get a deployment given its id * * @param id id of the deployment * @return deployment with given id */ public Deployment get(String id) { return alienDao.findById(Deployment.class, id); } /** * Get a deployment given its id * * @param id id of the deployment * @return deployment with given id */ public Deployment getOrfail(String id) { Deployment deployment = alienDao.findById(Deployment.class, id); if (deployment == null) { throw new NotFoundException("Deployment <" + id + "> doesn't exist."); } return deployment; } /** * Get an active Deployment for a given environment or throw a NotFoundException if no active deployment can be found for this environment. * * @param environmentId Id of the application environment. * @return The active deployment for this environment */ public Deployment getActiveDeploymentOrFail(String environmentId) { Deployment deployment = getActiveDeployment(environmentId); if (deployment == null) { throw new NotFoundException("Deployment for environment <" + environmentId + "> doesn't exist."); } return deployment; } /** * Get a deployment for a given environment * * @param applicationEnvironmentId id of the environment * @return active deployment or null if not exist */ public Deployment getDeployment(String applicationEnvironmentId) { Map<String, String[]> activeDeploymentFilters = MapUtil.newHashMap(new String[] { "environmentId" }, new String[][] { new String[] { applicationEnvironmentId } }); GetMultipleDataResult<Deployment> dataResult = alienDao.search(Deployment.class, null, activeDeploymentFilters, 1); if (dataResult.getData() != null && dataResult.getData().length > 0) { return dataResult.getData()[0]; } return null; } /** * Get an active deployment for a given environment * * @param applicationEnvironmentId id of the environment * @return active deployment or null if not exist */ public Deployment getActiveDeployment(String applicationEnvironmentId) { Map<String, String[]> activeDeploymentFilters = MapUtil.newHashMap(new String[] { "environmentId", "endDate" }, new String[][] { new String[] { applicationEnvironmentId }, new String[] { null } }); GetMultipleDataResult<Deployment> dataResult = alienDao.search(Deployment.class, null, activeDeploymentFilters, 1); if (dataResult.getData() != null && dataResult.getData().length > 0) { return dataResult.getData()[0]; } return null; } /** * Get an active Deployment for a given cloud and topology or throw a NotFoundException if no active deployment can be found. * * @param topologyId id of the topology that has been deployed * @param orchestratorId id of the target orchestrator. * @return a deployment * @throws alien4cloud.exception.NotFoundException if not any deployment exists */ public Deployment getActiveDeploymentOrFail(String topologyId, String orchestratorId) { Deployment deployment = getActiveDeployment(orchestratorId, topologyId); if (deployment == null) { throw new NotFoundException("Deployment for cloud <" + orchestratorId + "> and topology <" + topologyId + "> doesn't exist."); } return deployment; } /** * Get a topology for a given cloud / topology * * @param orchestratorId targeted orchestrator id * @param topologyId id of the topology to deploy * @return a deployment */ public Deployment getActiveDeployment(String orchestratorId, String topologyId) { Deployment deployment = null; Map<String, String[]> activeDeploymentFilters = MapUtil.newHashMap(new String[] { "orchestratorId", "topologyId", "endDate" }, new String[][] { new String[] { orchestratorId }, new String[] { topologyId }, new String[] { null } }); GetMultipleDataResult<Deployment> dataResult = alienDao.search(Deployment.class, null, activeDeploymentFilters, 1); if (dataResult.getData() != null && dataResult.getData().length > 0) { deployment = dataResult.getData()[0]; } return deployment; } /** * Check if there is an active deployment on a given orchestrator with the given orchestrator deployment id. * * @param orchestratorId The if of the orchestrator for which to check if there is a deployment with the given orchestratorDeploymentId. * @param orchestratorDeploymentId Unique if of the deployment for a given orchestrator * @return True if there is an active deployment for theses ids, false if not. */ public boolean isActiveDeployment(String orchestratorId, String orchestratorDeploymentId) { Map<String, String[]> activeDeploymentFilters = MapUtil.newHashMap(new String[] { "orchestratorId", "orchestratorDeploymentId", "endDate" }, new String[][] { new String[] { orchestratorId }, new String[] { orchestratorDeploymentId }, new String[] { null } }); GetMultipleDataResult<Deployment> dataResult = alienDao.find(Deployment.class, activeDeploymentFilters, Integer.MAX_VALUE); if (dataResult.getData() != null && dataResult.getData().length > 0) { return true; } return false; } public Map<String, PaaSTopologyDeploymentContext> getCloudActiveDeploymentContexts(String orchestratorId) { Deployment[] deployments = getOrchestratorActiveDeployments(orchestratorId); Map<String, PaaSTopologyDeploymentContext> activeDeploymentContexts = Maps.newHashMap(); for (Deployment deployment : deployments) { DeploymentTopology topology = deploymentRuntimeStateService.getRuntimeTopology(deployment.getId()); activeDeploymentContexts.put(deployment.getOrchestratorDeploymentId(), deploymentContextService.buildTopologyDeploymentContext(deployment, deploymentTopologyService.getLocations(topology), topology)); } return activeDeploymentContexts; } private Deployment[] getOrchestratorActiveDeployments(String orchestratorId) { Map<String, String[]> activeDeploymentFilters = MapUtil.newHashMap(new String[]{"orchestratorId", "endDate"}, new String[][]{new String[]{orchestratorId}, new String[]{null}}); GetMultipleDataResult<Deployment> dataResult = alienDao.search(Deployment.class, null, activeDeploymentFilters, 1); return dataResult.getData(); } public Map<String, Set<String>> getAllOrchestratorIdsAndOrchestratorDeploymentId(String applicationEnvironmentId) { Map<String, Set<String>> result = new HashMap<>(); Map<String, String[]> activeDeploymentFilters = MapUtil.newHashMap(new String[] { "environmentId" }, new String[][] { new String[] { applicationEnvironmentId }}); GetMultipleDataResult<Deployment> dataResult = alienDao.search(Deployment.class, null, activeDeploymentFilters, Integer.MAX_VALUE); if (dataResult.getData() != null && dataResult.getData().length > 0) { for (Deployment deployment : dataResult.getData()) { if (!result.containsKey(deployment.getOrchestratorId())) { result.put(deployment.getOrchestratorId(), new HashSet<String>()); } result.get(deployment.getOrchestratorId()).add(deployment.getOrchestratorDeploymentId()); } } return result; } }
alien4cloud-core/src/main/java/alien4cloud/deployment/DeploymentService.java
package alien4cloud.deployment; import java.util.*; import javax.annotation.Resource; import javax.inject.Inject; import lombok.extern.slf4j.Slf4j; import org.elasticsearch.index.query.QueryBuilder; import org.elasticsearch.index.query.QueryBuilders; import org.springframework.stereotype.Service; import alien4cloud.dao.IGenericSearchDAO; import alien4cloud.dao.model.GetMultipleDataResult; import alien4cloud.exception.NotFoundException; import alien4cloud.model.deployment.Deployment; import alien4cloud.model.deployment.DeploymentTopology; import alien4cloud.paas.model.PaaSTopologyDeploymentContext; import alien4cloud.utils.MapUtil; import com.google.common.collect.Maps; /** * Manage deployment operations on a cloud. */ @Service @Slf4j public class DeploymentService { @Resource(name = "alien-es-dao") private IGenericSearchDAO alienDao; @Inject private DeploymentRuntimeStateService deploymentRuntimeStateService; @Inject private DeploymentContextService deploymentContextService; @Inject private DeploymentTopologyService deploymentTopologyService; /** * Get all deployments for a given orchestrator an application * * @param orchestratorId Id of the cloud for which to get deployments (can be null to get deployments for all clouds). * @param sourceId Id of the application for which to get deployments (can be null to get deployments for all applications). * @return A {@link GetMultipleDataResult} that contains deployments. */ public List<Deployment> getDeployments(String orchestratorId, String sourceId) { QueryBuilder query = QueryBuilders.boolQuery(); if (orchestratorId != null) { query = QueryBuilders.boolQuery().must(QueryBuilders.termsQuery("orchestratorId", orchestratorId)); } if (sourceId != null) { query = QueryBuilders.boolQuery().must(query).must(QueryBuilders.termsQuery("sourceId", sourceId)); } if (orchestratorId == null && sourceId == null) { query = QueryBuilders.matchAllQuery(); } return alienDao.customFindAll(Deployment.class, query); } /** * Get a deployment given its id * * @param id id of the deployment * @return deployment with given id */ public Deployment get(String id) { return alienDao.findById(Deployment.class, id); } /** * Get a deployment given its id * * @param id id of the deployment * @return deployment with given id */ public Deployment getOrfail(String id) { Deployment deployment = alienDao.findById(Deployment.class, id); if (deployment == null) { throw new NotFoundException("Deployment <" + id + "> doesn't exist."); } return deployment; } /** * Get an active Deployment for a given environment or throw a NotFoundException if no active deployment can be found for this environment. * * @param environmentId Id of the application environment. * @return The active deployment for this environment */ public Deployment getActiveDeploymentOrFail(String environmentId) { Deployment deployment = getActiveDeployment(environmentId); if (deployment == null) { throw new NotFoundException("Deployment for environment <" + environmentId + "> doesn't exist."); } return deployment; } /** * Get an active deployment for a given environment * * @param applicationEnvironmentId id of the environment * @return active deployment or null if not exist */ public Deployment getActiveDeployment(String applicationEnvironmentId) { Map<String, String[]> activeDeploymentFilters = MapUtil.newHashMap(new String[] { "environmentId", "endDate" }, new String[][] { new String[] { applicationEnvironmentId }, new String[] { null } }); GetMultipleDataResult<Deployment> dataResult = alienDao.search(Deployment.class, null, activeDeploymentFilters, 1); if (dataResult.getData() != null && dataResult.getData().length > 0) { return dataResult.getData()[0]; } return null; } /** * Get an active Deployment for a given cloud and topology or throw a NotFoundException if no active deployment can be found. * * @param topologyId id of the topology that has been deployed * @param orchestratorId id of the target orchestrator. * @return a deployment * @throws alien4cloud.exception.NotFoundException if not any deployment exists */ public Deployment getActiveDeploymentOrFail(String topologyId, String orchestratorId) { Deployment deployment = getActiveDeployment(orchestratorId, topologyId); if (deployment == null) { throw new NotFoundException("Deployment for cloud <" + orchestratorId + "> and topology <" + topologyId + "> doesn't exist."); } return deployment; } /** * Get a topology for a given cloud / topology * * @param orchestratorId targeted orchestrator id * @param topologyId id of the topology to deploy * @return a deployment */ public Deployment getActiveDeployment(String orchestratorId, String topologyId) { Deployment deployment = null; Map<String, String[]> activeDeploymentFilters = MapUtil.newHashMap(new String[] { "orchestratorId", "topologyId", "endDate" }, new String[][] { new String[] { orchestratorId }, new String[] { topologyId }, new String[] { null } }); GetMultipleDataResult<Deployment> dataResult = alienDao.search(Deployment.class, null, activeDeploymentFilters, 1); if (dataResult.getData() != null && dataResult.getData().length > 0) { deployment = dataResult.getData()[0]; } return deployment; } /** * Check if there is an active deployment on a given orchestrator with the given orchestrator deployment id. * * @param orchestratorId The if of the orchestrator for which to check if there is a deployment with the given orchestratorDeploymentId. * @param orchestratorDeploymentId Unique if of the deployment for a given orchestrator * @return True if there is an active deployment for theses ids, false if not. */ public boolean isActiveDeployment(String orchestratorId, String orchestratorDeploymentId) { Map<String, String[]> activeDeploymentFilters = MapUtil.newHashMap(new String[] { "orchestratorId", "orchestratorDeploymentId", "endDate" }, new String[][] { new String[] { orchestratorId }, new String[] { orchestratorDeploymentId }, new String[] { null } }); GetMultipleDataResult<Deployment> dataResult = alienDao.find(Deployment.class, activeDeploymentFilters, Integer.MAX_VALUE); if (dataResult.getData() != null && dataResult.getData().length > 0) { return true; } return false; } public Map<String, PaaSTopologyDeploymentContext> getCloudActiveDeploymentContexts(String orchestratorId) { Deployment[] deployments = getOrchestratorActiveDeployments(orchestratorId); Map<String, PaaSTopologyDeploymentContext> activeDeploymentContexts = Maps.newHashMap(); for (Deployment deployment : deployments) { DeploymentTopology topology = deploymentRuntimeStateService.getRuntimeTopology(deployment.getId()); activeDeploymentContexts.put(deployment.getOrchestratorDeploymentId(), deploymentContextService.buildTopologyDeploymentContext(deployment, deploymentTopologyService.getLocations(topology), topology)); } return activeDeploymentContexts; } private Deployment[] getOrchestratorActiveDeployments(String orchestratorId) { Map<String, String[]> activeDeploymentFilters = MapUtil.newHashMap(new String[]{"orchestratorId", "endDate"}, new String[][]{new String[]{orchestratorId}, new String[]{null}}); GetMultipleDataResult<Deployment> dataResult = alienDao.search(Deployment.class, null, activeDeploymentFilters, 1); return dataResult.getData(); } public Map<String, Set<String>> getAllOrchestratorIdsAndOrchestratorDeploymentId(String applicationEnvironmentId) { Map<String, Set<String>> result = new HashMap<>(); Map<String, String[]> activeDeploymentFilters = MapUtil.newHashMap(new String[] { "environmentId" }, new String[][] { new String[] { applicationEnvironmentId }}); GetMultipleDataResult<Deployment> dataResult = alienDao.search(Deployment.class, null, activeDeploymentFilters, Integer.MAX_VALUE); if (dataResult.getData() != null && dataResult.getData().length > 0) { for (Deployment deployment : dataResult.getData()) { if (!result.containsKey(deployment.getOrchestratorId())) { result.put(deployment.getOrchestratorId(), new HashSet<String>()); } result.get(deployment.getOrchestratorId()).add(deployment.getOrchestratorDeploymentId()); } } return result; } }
ALIEN-1666: add a method to get a deployment (maybe undeployed) by appEnvId
alien4cloud-core/src/main/java/alien4cloud/deployment/DeploymentService.java
ALIEN-1666: add a method to get a deployment (maybe undeployed) by appEnvId
<ide><path>lien4cloud-core/src/main/java/alien4cloud/deployment/DeploymentService.java <ide> return deployment; <ide> } <ide> <add> <add> /** <add> * Get a deployment for a given environment <add> * <add> * @param applicationEnvironmentId id of the environment <add> * @return active deployment or null if not exist <add> */ <add> public Deployment getDeployment(String applicationEnvironmentId) { <add> Map<String, String[]> activeDeploymentFilters = MapUtil.newHashMap(new String[] { "environmentId" }, <add> new String[][] { new String[] { applicationEnvironmentId } }); <add> GetMultipleDataResult<Deployment> dataResult = alienDao.search(Deployment.class, null, activeDeploymentFilters, 1); <add> if (dataResult.getData() != null && dataResult.getData().length > 0) { <add> return dataResult.getData()[0]; <add> } <add> return null; <add> } <add> <ide> /** <ide> * Get an active deployment for a given environment <ide> *
Java
apache-2.0
0f0efd6ef0155e95739a8ad74f7df5e5094ba548
0
APriestman/autopsy,rcordovano/autopsy,millmanorama/autopsy,APriestman/autopsy,millmanorama/autopsy,APriestman/autopsy,esaunders/autopsy,APriestman/autopsy,APriestman/autopsy,rcordovano/autopsy,rcordovano/autopsy,wschaeferB/autopsy,wschaeferB/autopsy,esaunders/autopsy,dgrove727/autopsy,rcordovano/autopsy,millmanorama/autopsy,esaunders/autopsy,wschaeferB/autopsy,dgrove727/autopsy,wschaeferB/autopsy,wschaeferB/autopsy,dgrove727/autopsy,rcordovano/autopsy,millmanorama/autopsy,APriestman/autopsy,APriestman/autopsy,rcordovano/autopsy,esaunders/autopsy,esaunders/autopsy
Core/src/org/sleuthkit/autopsy/casemodule/MultiUserCase.java
/* * Autopsy Forensic Browser * * Copyright 2015-2017 Basis Technology Corp. * Contact: carrier <at> sleuthkit <dot> org * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.sleuthkit.autopsy.casemodule; import java.io.File; import java.io.IOException; import java.nio.file.Files; import java.nio.file.Path; import java.nio.file.Paths; import java.nio.file.attribute.BasicFileAttributes; import java.util.Comparator; import java.util.Date; import java.util.Objects; import java.util.logging.Level; import org.sleuthkit.autopsy.coreutils.Logger; import org.sleuthkit.autopsy.coreutils.TimeStampUtils; /** * A representation of a case created by automated ingest. */ class MultiUserCase implements Comparable<MultiUserCase> { private static final Logger logger = Logger.getLogger(MultiUserCase.class.getName()); private final Path caseDirectoryPath; private final String caseName; private final Path metadataFilePath; private final Date createDate; private final Date lastAccessedDate; /** * Constructs a representation of case created by automated ingest. * * @param caseDirectoryPath The case directory path. * * @throws CaseMetadata.CaseMetadataException If the CaseMetadata object * cannot be constructed for the * case display name. * @throws MultiUserCaseException If no case metadata (.aut) * file is found in the case * directory. */ MultiUserCase(Path caseDirectoryPath) throws CaseMetadata.CaseMetadataException, MultiUserCaseException { CaseMetadata caseMetadata = null; try { caseMetadata = getCaseMetadataFromCaseDirectoryPath(caseDirectoryPath); } catch (CaseMetadata.CaseMetadataException ex) { logger.log(Level.SEVERE, String.format("Error reading the case metadata for %s.", caseDirectoryPath), ex); throw ex; } this.caseDirectoryPath = caseDirectoryPath; caseName = caseMetadata.getCaseDisplayName(); metadataFilePath = caseMetadata.getFilePath(); BasicFileAttributes fileAttrs = null; try { fileAttrs = Files.readAttributes(metadataFilePath, BasicFileAttributes.class); } catch (IOException ex) { logger.log(Level.SEVERE, String.format("Error reading file attributes of case metadata file in %s, will use current time for case createDate/lastModfiedDate", caseDirectoryPath), ex); } if (null != fileAttrs) { createDate = new Date(fileAttrs.creationTime().toMillis()); lastAccessedDate = new Date(fileAttrs.lastAccessTime().toMillis()); } else { createDate = new Date(); lastAccessedDate = new Date(); } } /** * Gets the case directory path. * * @return The case directory path. */ Path getCaseDirectoryPath() { return this.caseDirectoryPath; } /** * Gets the case name. * * @return The case name. */ String getCaseName() { return this.caseName; } /** * Gets the creation date for the case, defined as the create time of the * case metadata file. * * @return The case creation date. */ Date getCreationDate() { return this.createDate; } /** * Gets the last accessed date for the case, defined as the last accessed * time of the case metadata file. * * @return The last accessed date. */ Date getLastAccessedDate() { return this.lastAccessedDate; } /** * Gets the full path of the metadata (.aut) file. * * @return The metadata file path. */ Path getMetadataFilePath() { return this.metadataFilePath; } /** * Gets the status of this case based on the auto ingest result file in the * case directory. * * @return See CaseStatus enum definition. */ CaseStatus getStatus() { if(caseDirectoryPath.resolve("autoingest.alert").toFile().exists()) { return CaseStatus.ALERT; } else { return CaseStatus.OK; } } /** * Gets the case metadata from a case directory path. * * @param caseDirectoryPath The case directory path. * * @return Case metadata. * * @throws CaseMetadata.CaseMetadataException If the CaseMetadata object * cannot be constructed. * @throws MultiUserCaseException If no case metadata (.aut) * file is found in the case * directory. */ private static CaseMetadata getCaseMetadataFromCaseDirectoryPath(Path caseDirectoryPath) throws CaseMetadata.CaseMetadataException, MultiUserCaseException { CaseMetadata caseMetadata = null; File directory = new File(caseDirectoryPath.toString()); if (directory.isDirectory()) { String fileNamePrefix = directory.getName(); if (TimeStampUtils.endsWithTimeStamp(fileNamePrefix)) { fileNamePrefix = fileNamePrefix.substring(0, fileNamePrefix.length() - TimeStampUtils.getTimeStampLength()); } File autFile = null; /* * Attempt to find an AUT file via a directory scan. */ for (File file : directory.listFiles()) { if (file.getName().toLowerCase().endsWith(CaseMetadata.getFileExtension()) && file.isFile()) { autFile = file; break; } } if(autFile == null || !autFile.isFile()) { throw new MultiUserCaseException(String.format("No case metadata (.aut) file found in the case directory '%s'.", caseDirectoryPath.toString())); } caseMetadata = new CaseMetadata(Paths.get(autFile.getAbsolutePath())); } return caseMetadata; } /** * Indicates whether or not some other object is "equal to" this * MultiUserCase object. * * @param other The other object. * * @return True or false. */ @Override public boolean equals(Object other) { if (!(other instanceof MultiUserCase)) { return false; } if (other == this) { return true; } return this.caseDirectoryPath.toString().equals(((MultiUserCase) other).caseDirectoryPath.toString()); } /** * Returns a hash code value for this MultiUserCase object. * * @return The has code. */ @Override public int hashCode() { int hash = 7; hash = 71 * hash + Objects.hashCode(this.caseDirectoryPath); hash = 71 * hash + Objects.hashCode(this.createDate); hash = 71 * hash + Objects.hashCode(this.caseName); return hash; } /** * Compares this AutopIngestCase object with abnother MultiUserCase object * for order. */ @Override public int compareTo(MultiUserCase other) { return -this.lastAccessedDate.compareTo(other.getLastAccessedDate()); } /** * Comparator for a descending order sort on date created. */ static class LastAccessedDateDescendingComparator implements Comparator<MultiUserCase> { /** * Compares two MultiUserCase objects for order based on last accessed * date (descending). * * @param object The first MultiUserCase object * @param otherObject The second AuotIngestCase object. * * @return A negative integer, zero, or a positive integer as the first * argument is less than, equal to, or greater than the second. */ @Override public int compare(MultiUserCase object, MultiUserCase otherObject) { return -object.getLastAccessedDate().compareTo(otherObject.getLastAccessedDate()); } } /** * Exception thrown when there is a problem creating a multi-user case. */ final static class MultiUserCaseException extends Exception { private static final long serialVersionUID = 1L; /** * Constructs an exception to throw when there is a problem creating a * multi-user case. * * @param message The exception message. */ private MultiUserCaseException(String message) { super(message); } /** * Constructs an exception to throw when there is a problem creating a * multi-user case. * * @param message The exception message. * @param cause The cause of the exception, if it was an exception. */ private MultiUserCaseException(String message, Throwable cause) { super(message, cause); } } enum CaseStatus { OK, ALERT } }
Removed MultIuserCase class.
Core/src/org/sleuthkit/autopsy/casemodule/MultiUserCase.java
Removed MultIuserCase class.
<ide><path>ore/src/org/sleuthkit/autopsy/casemodule/MultiUserCase.java <del>/* <del> * Autopsy Forensic Browser <del> * <del> * Copyright 2015-2017 Basis Technology Corp. <del> * Contact: carrier <at> sleuthkit <dot> org <del> * <del> * Licensed under the Apache License, Version 2.0 (the "License"); <del> * you may not use this file except in compliance with the License. <del> * You may obtain a copy of the License at <del> * <del> * http://www.apache.org/licenses/LICENSE-2.0 <del> * <del> * Unless required by applicable law or agreed to in writing, software <del> * distributed under the License is distributed on an "AS IS" BASIS, <del> * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. <del> * See the License for the specific language governing permissions and <del> * limitations under the License. <del> */ <del>package org.sleuthkit.autopsy.casemodule; <del> <del>import java.io.File; <del>import java.io.IOException; <del>import java.nio.file.Files; <del>import java.nio.file.Path; <del>import java.nio.file.Paths; <del>import java.nio.file.attribute.BasicFileAttributes; <del>import java.util.Comparator; <del>import java.util.Date; <del>import java.util.Objects; <del>import java.util.logging.Level; <del>import org.sleuthkit.autopsy.coreutils.Logger; <del>import org.sleuthkit.autopsy.coreutils.TimeStampUtils; <del> <del>/** <del> * A representation of a case created by automated ingest. <del> */ <del>class MultiUserCase implements Comparable<MultiUserCase> { <del> <del> private static final Logger logger = Logger.getLogger(MultiUserCase.class.getName()); <del> private final Path caseDirectoryPath; <del> private final String caseName; <del> private final Path metadataFilePath; <del> private final Date createDate; <del> private final Date lastAccessedDate; <del> <del> /** <del> * Constructs a representation of case created by automated ingest. <del> * <del> * @param caseDirectoryPath The case directory path. <del> * <del> * @throws CaseMetadata.CaseMetadataException If the CaseMetadata object <del> * cannot be constructed for the <del> * case display name. <del> * @throws MultiUserCaseException If no case metadata (.aut) <del> * file is found in the case <del> * directory. <del> */ <del> MultiUserCase(Path caseDirectoryPath) throws CaseMetadata.CaseMetadataException, MultiUserCaseException { <del> CaseMetadata caseMetadata = null; <del> <del> try { <del> caseMetadata = getCaseMetadataFromCaseDirectoryPath(caseDirectoryPath); <del> } catch (CaseMetadata.CaseMetadataException ex) { <del> logger.log(Level.SEVERE, String.format("Error reading the case metadata for %s.", caseDirectoryPath), ex); <del> throw ex; <del> } <del> <del> this.caseDirectoryPath = caseDirectoryPath; <del> caseName = caseMetadata.getCaseDisplayName(); <del> metadataFilePath = caseMetadata.getFilePath(); <del> BasicFileAttributes fileAttrs = null; <del> try { <del> fileAttrs = Files.readAttributes(metadataFilePath, BasicFileAttributes.class); <del> } catch (IOException ex) { <del> logger.log(Level.SEVERE, String.format("Error reading file attributes of case metadata file in %s, will use current time for case createDate/lastModfiedDate", caseDirectoryPath), ex); <del> } <del> if (null != fileAttrs) { <del> createDate = new Date(fileAttrs.creationTime().toMillis()); <del> lastAccessedDate = new Date(fileAttrs.lastAccessTime().toMillis()); <del> } else { <del> createDate = new Date(); <del> lastAccessedDate = new Date(); <del> } <del> } <del> <del> /** <del> * Gets the case directory path. <del> * <del> * @return The case directory path. <del> */ <del> Path getCaseDirectoryPath() { <del> return this.caseDirectoryPath; <del> } <del> <del> /** <del> * Gets the case name. <del> * <del> * @return The case name. <del> */ <del> String getCaseName() { <del> return this.caseName; <del> } <del> <del> /** <del> * Gets the creation date for the case, defined as the create time of the <del> * case metadata file. <del> * <del> * @return The case creation date. <del> */ <del> Date getCreationDate() { <del> return this.createDate; <del> } <del> <del> /** <del> * Gets the last accessed date for the case, defined as the last accessed <del> * time of the case metadata file. <del> * <del> * @return The last accessed date. <del> */ <del> Date getLastAccessedDate() { <del> return this.lastAccessedDate; <del> } <del> <del> /** <del> * Gets the full path of the metadata (.aut) file. <del> * <del> * @return The metadata file path. <del> */ <del> Path getMetadataFilePath() { <del> return this.metadataFilePath; <del> } <del> <del> /** <del> * Gets the status of this case based on the auto ingest result file in the <del> * case directory. <del> * <del> * @return See CaseStatus enum definition. <del> */ <del> CaseStatus getStatus() { <del> if(caseDirectoryPath.resolve("autoingest.alert").toFile().exists()) { <del> return CaseStatus.ALERT; <del> } else { <del> return CaseStatus.OK; <del> } <del> } <del> <del> /** <del> * Gets the case metadata from a case directory path. <del> * <del> * @param caseDirectoryPath The case directory path. <del> * <del> * @return Case metadata. <del> * <del> * @throws CaseMetadata.CaseMetadataException If the CaseMetadata object <del> * cannot be constructed. <del> * @throws MultiUserCaseException If no case metadata (.aut) <del> * file is found in the case <del> * directory. <del> */ <del> private static CaseMetadata getCaseMetadataFromCaseDirectoryPath(Path caseDirectoryPath) throws CaseMetadata.CaseMetadataException, MultiUserCaseException { <del> CaseMetadata caseMetadata = null; <del> <del> File directory = new File(caseDirectoryPath.toString()); <del> if (directory.isDirectory()) { <del> String fileNamePrefix = directory.getName(); <del> if (TimeStampUtils.endsWithTimeStamp(fileNamePrefix)) { <del> fileNamePrefix = fileNamePrefix.substring(0, fileNamePrefix.length() - TimeStampUtils.getTimeStampLength()); <del> } <del> <del> File autFile = null; <del> <del> /* <del> * Attempt to find an AUT file via a directory scan. <del> */ <del> for (File file : directory.listFiles()) { <del> if (file.getName().toLowerCase().endsWith(CaseMetadata.getFileExtension()) && file.isFile()) { <del> autFile = file; <del> break; <del> } <del> } <del> <del> if(autFile == null || !autFile.isFile()) { <del> throw new MultiUserCaseException(String.format("No case metadata (.aut) file found in the case directory '%s'.", caseDirectoryPath.toString())); <del> } <del> <del> caseMetadata = new CaseMetadata(Paths.get(autFile.getAbsolutePath())); <del> } <del> <del> return caseMetadata; <del> } <del> <del> /** <del> * Indicates whether or not some other object is "equal to" this <del> * MultiUserCase object. <del> * <del> * @param other The other object. <del> * <del> * @return True or false. <del> */ <del> @Override <del> public boolean equals(Object other) { <del> if (!(other instanceof MultiUserCase)) { <del> return false; <del> } <del> if (other == this) { <del> return true; <del> } <del> return this.caseDirectoryPath.toString().equals(((MultiUserCase) other).caseDirectoryPath.toString()); <del> } <del> <del> /** <del> * Returns a hash code value for this MultiUserCase object. <del> * <del> * @return The has code. <del> */ <del> @Override <del> public int hashCode() { <del> int hash = 7; <del> hash = 71 * hash + Objects.hashCode(this.caseDirectoryPath); <del> hash = 71 * hash + Objects.hashCode(this.createDate); <del> hash = 71 * hash + Objects.hashCode(this.caseName); <del> return hash; <del> } <del> <del> /** <del> * Compares this AutopIngestCase object with abnother MultiUserCase object <del> * for order. <del> */ <del> @Override <del> public int compareTo(MultiUserCase other) { <del> return -this.lastAccessedDate.compareTo(other.getLastAccessedDate()); <del> } <del> <del> /** <del> * Comparator for a descending order sort on date created. <del> */ <del> static class LastAccessedDateDescendingComparator implements Comparator<MultiUserCase> { <del> <del> /** <del> * Compares two MultiUserCase objects for order based on last accessed <del> * date (descending). <del> * <del> * @param object The first MultiUserCase object <del> * @param otherObject The second AuotIngestCase object. <del> * <del> * @return A negative integer, zero, or a positive integer as the first <del> * argument is less than, equal to, or greater than the second. <del> */ <del> @Override <del> public int compare(MultiUserCase object, MultiUserCase otherObject) { <del> return -object.getLastAccessedDate().compareTo(otherObject.getLastAccessedDate()); <del> } <del> } <del> <del> /** <del> * Exception thrown when there is a problem creating a multi-user case. <del> */ <del> final static class MultiUserCaseException extends Exception { <del> <del> private static final long serialVersionUID = 1L; <del> <del> /** <del> * Constructs an exception to throw when there is a problem creating a <del> * multi-user case. <del> * <del> * @param message The exception message. <del> */ <del> private MultiUserCaseException(String message) { <del> super(message); <del> } <del> <del> /** <del> * Constructs an exception to throw when there is a problem creating a <del> * multi-user case. <del> * <del> * @param message The exception message. <del> * @param cause The cause of the exception, if it was an exception. <del> */ <del> private MultiUserCaseException(String message, Throwable cause) { <del> super(message, cause); <del> } <del> } <del> <del> enum CaseStatus { <del> <del> OK, <del> ALERT <del> } <del> <del>}
JavaScript
mit
8b5329cd6e7915219fc12da42f2a26024d479f73
0
amaniak/vis,kamilik26/vis,Braincompiler/vis,antoniodesouza/vis,pryzm0/vis,Tooa/vis,nargetdev/vis,pryzm0/vis,samyamirou/vis,ricky6982/vis,chaoallsome/vis,vukk/vis,nargetdev/vis,marcortw/vis,Spencerooni/vis,antoniodesouza/vis,machinemetrics/vis,Braincompiler/vis,felixhayashi/vis,bsnote/vis,bsnote/vis,cdjackson/vis,eflexsystems/vis,Tooa/vis,ericvandever/vis,eyko/vis,PSyton/vis,yotamberk/vis,gpolyn/vis,besil/vis,sitexa/vis,brendon1982/vis,movestill/vis,tsakoyan/vis,amaniak/vis,blackslate/vis,amaniak/vis,besil/vis,eyko/vis,sitexa/vis,eflexsystems/vis,movestill/vis,cdjackson/vis,chaoallsome/vis,movestill/vis,drwebmaker/vis,drwebmaker/vis,PSyton/vis,blackslate/vis,kamilik26/vis,PSyton/vis,machinemetrics/vis,xchehub/vis,danpaulsmith/vis,marcortw/vis,brendon1982/vis,xchehub/vis,Braincompiler/vis,ericvandever/vis,danpaulsmith/vis,zallek/vis,ricky6982/vis,AlexVangelov/vis,vukk/vis,AlexVangelov/vis,Spencerooni/vis,Spencerooni/vis,yotamberk/vis,samyamirou/vis,cdjackson/vis,felixhayashi/vis,besil/vis,zallek/vis,danpaulsmith/vis,vukk/vis,glampr/vis,tsakoyan/vis,gpolyn/vis,glampr/vis
var Emitter = require('emitter-component'); var Hammer = require('../module/hammer'); var util = require('../util'); var DataSet = require('../DataSet'); var DataView = require('../DataView'); var Range = require('./Range'); var Core = require('./Core'); var TimeAxis = require('./component/TimeAxis'); var CurrentTime = require('./component/CurrentTime'); var CustomTime = require('./component/CustomTime'); var ItemSet = require('./component/ItemSet'); /** * Create a timeline visualization * @param {HTMLElement} container * @param {vis.DataSet | Array | google.visualization.DataTable} [items] * @param {vis.DataSet | Array | google.visualization.DataTable} [groups] * @param {Object} [options] See Timeline.setOptions for the available options. * @constructor * @extends Core */ function Timeline (container, items, groups, options) { if (!(this instanceof Timeline)) { throw new SyntaxError('Constructor must be called with the new operator'); } // if the third element is options, the forth is groups (optionally); if (!(Array.isArray(groups) || groups instanceof DataSet) && groups instanceof Object) { var forthArgument = options; options = groups; groups = forthArgument; } var me = this; this.defaultOptions = { start: null, end: null, autoResize: true, orientation: 'bottom', width: null, height: null, maxHeight: null, minHeight: null }; this.options = util.deepExtend({}, this.defaultOptions); // Create the DOM, props, and emitter this._create(container); // all components listed here will be repainted automatically this.components = []; this.body = { dom: this.dom, domProps: this.props, emitter: { on: this.on.bind(this), off: this.off.bind(this), emit: this.emit.bind(this) }, hiddenDates: [], util: { snap: null, // will be specified after TimeAxis is created toScreen: me._toScreen.bind(me), toGlobalScreen: me._toGlobalScreen.bind(me), // this refers to the root.width toTime: me._toTime.bind(me), toGlobalTime : me._toGlobalTime.bind(me) } }; // range this.range = new Range(this.body); this.components.push(this.range); this.body.range = this.range; // time axis this.timeAxis = new TimeAxis(this.body); this.components.push(this.timeAxis); this.body.util.snap = this.timeAxis.snap.bind(this.timeAxis); // current time bar this.currentTime = new CurrentTime(this.body); this.components.push(this.currentTime); // custom time bar // Note: time bar will be attached in this.setOptions when selected this.customTime = new CustomTime(this.body); this.components.push(this.customTime); // item set this.itemSet = new ItemSet(this.body); this.components.push(this.itemSet); this.itemsData = null; // DataSet this.groupsData = null; // DataSet // apply options if (options) { this.setOptions(options); } // IMPORTANT: THIS HAPPENS BEFORE SET ITEMS! if (groups) { this.setGroups(groups); } // create itemset if (items) { this.setItems(items); } else { this.redraw(); } } // Extend the functionality from Core Timeline.prototype = new Core(); /** * Set items * @param {vis.DataSet | Array | google.visualization.DataTable | null} items */ Timeline.prototype.setItems = function(items) { var initialLoad = (this.itemsData == null); // convert to type DataSet when needed var newDataSet; if (!items) { newDataSet = null; } else if (items instanceof DataSet || items instanceof DataView) { newDataSet = items; } else { // turn an array into a dataset newDataSet = new DataSet(items, { type: { start: 'Date', end: 'Date' } }); } // set items this.itemsData = newDataSet; this.itemSet && this.itemSet.setItems(newDataSet); if (initialLoad) { if (this.options.start != undefined || this.options.end != undefined) { if (this.options.start == undefined || this.options.end == undefined) { var dataRange = this._getDataRange(); } var start = this.options.start != undefined ? this.options.start : dataRange.start; var end = this.options.end != undefined ? this.options.end : dataRange.end; this.setWindow(start, end, {animate: false}); } else { this.fit({animate: false}); } } }; /** * Set groups * @param {vis.DataSet | Array | google.visualization.DataTable} groups */ Timeline.prototype.setGroups = function(groups) { // convert to type DataSet when needed var newDataSet; if (!groups) { newDataSet = null; } else if (groups instanceof DataSet || groups instanceof DataView) { newDataSet = groups; } else { // turn an array into a dataset newDataSet = new DataSet(groups); } this.groupsData = newDataSet; this.itemSet.setGroups(newDataSet); }; /** * Set selected items by their id. Replaces the current selection * Unknown id's are silently ignored. * @param {string[] | string} [ids] An array with zero or more id's of the items to be * selected. If ids is an empty array, all items will be * unselected. * @param {Object} [options] Available options: * `focus: boolean` * If true, focus will be set to the selected item(s) * `animate: boolean | number` * If true (default), the range is animated * smoothly to the new window. * If a number, the number is taken as duration * for the animation. Default duration is 500 ms. * Only applicable when option focus is true. */ Timeline.prototype.setSelection = function(ids, options) { this.itemSet && this.itemSet.setSelection(ids); if (options && options.focus) { this.focus(ids, options); } }; /** * Get the selected items by their id * @return {Array} ids The ids of the selected items */ Timeline.prototype.getSelection = function() { return this.itemSet && this.itemSet.getSelection() || []; }; /** * Adjust the visible window such that the selected item (or multiple items) * are centered on screen. * @param {String | String[]} id An item id or array with item ids * @param {Object} [options] Available options: * `animate: boolean | number` * If true (default), the range is animated * smoothly to the new window. * If a number, the number is taken as duration * for the animation. Default duration is 500 ms. * Only applicable when option focus is true */ Timeline.prototype.focus = function(id, options) { if (!this.itemsData || id == undefined) return; var ids = Array.isArray(id) ? id : [id]; // get the specified item(s) var itemsData = this.itemsData.getDataSet().get(ids, { type: { start: 'Date', end: 'Date' } }); // calculate minimum start and maximum end of specified items var start = null; var end = null; itemsData.forEach(function (itemData) { var s = itemData.start.valueOf(); var e = 'end' in itemData ? itemData.end.valueOf() : itemData.start.valueOf(); if (start === null || s < start) { start = s; } if (end === null || e > end) { end = e; } }); if (start !== null && end !== null) { // calculate the new middle and interval for the window var middle = (start + end) / 2; var interval = Math.max((this.range.end - this.range.start), (end - start) * 1.1); var animate = (options && options.animate !== undefined) ? options.animate : true; this.range.setRange(middle - interval / 2, middle + interval / 2, animate); } }; /** * Get the data range of the item set. * @returns {{min: Date, max: Date}} range A range with a start and end Date. * When no minimum is found, min==null * When no maximum is found, max==null */ Timeline.prototype.getItemRange = function() { // calculate min from start filed var dataset = this.itemsData.getDataSet(), min = null, max = null; if (dataset) { // calculate the minimum value of the field 'start' var minItem = dataset.min('start'); min = minItem ? util.convert(minItem.start, 'Date').valueOf() : null; // Note: we convert first to Date and then to number because else // a conversion from ISODate to Number will fail // calculate maximum value of fields 'start' and 'end' var maxStartItem = dataset.max('start'); if (maxStartItem) { max = util.convert(maxStartItem.start, 'Date').valueOf(); } var maxEndItem = dataset.max('end'); if (maxEndItem) { if (max == null) { max = util.convert(maxEndItem.end, 'Date').valueOf(); } else { max = Math.max(max, util.convert(maxEndItem.end, 'Date').valueOf()); } } } return { min: (min != null) ? new Date(min) : null, max: (max != null) ? new Date(max) : null }; }; module.exports = Timeline;
lib/timeline/Timeline.js
var Emitter = require('emitter-component'); var Hammer = require('../module/hammer'); var util = require('../util'); var DataSet = require('../DataSet'); var DataView = require('../DataView'); var Range = require('./Range'); var Core = require('./Core'); var TimeAxis = require('./component/TimeAxis'); var CurrentTime = require('./component/CurrentTime'); var CustomTime = require('./component/CustomTime'); var ItemSet = require('./component/ItemSet'); /** * Create a timeline visualization * @param {HTMLElement} container * @param {vis.DataSet | Array | google.visualization.DataTable} [items] * @param {vis.DataSet | Array | google.visualization.DataTable} [groups] * @param {Object} [options] See Timeline.setOptions for the available options. * @constructor * @extends Core */ function Timeline (container, items, groups, options) { if (!(this instanceof Timeline)) { throw new SyntaxError('Constructor must be called with the new operator'); } // if the third element is options, the forth is groups (optionally); if (!(Array.isArray(groups) || groups instanceof DataSet) && groups instanceof Object) { var forthArgument = options; options = groups; groups = forthArgument; } var me = this; this.defaultOptions = { start: null, end: null, autoResize: true, orientation: 'bottom', width: null, height: null, maxHeight: null, minHeight: null }; this.options = util.deepExtend({}, this.defaultOptions); // Create the DOM, props, and emitter this._create(container); // all components listed here will be repainted automatically this.components = []; this.body = { dom: this.dom, domProps: this.props, emitter: { on: this.on.bind(this), off: this.off.bind(this), emit: this.emit.bind(this) }, hiddenDates: [], util: { snap: null, // will be specified after TimeAxis is created toScreen: me._toScreen.bind(me), toGlobalScreen: me._toGlobalScreen.bind(me), // this refers to the root.width toTime: me._toTime.bind(me), toGlobalTime : me._toGlobalTime.bind(me) } }; // range this.range = new Range(this.body); this.components.push(this.range); this.body.range = this.range; // time axis this.timeAxis = new TimeAxis(this.body); this.components.push(this.timeAxis); this.body.util.snap = this.timeAxis.snap.bind(this.timeAxis); // current time bar this.currentTime = new CurrentTime(this.body); this.components.push(this.currentTime); // custom time bar // Note: time bar will be attached in this.setOptions when selected this.customTime = new CustomTime(this.body); this.components.push(this.customTime); // item set this.itemSet = new ItemSet(this.body); this.components.push(this.itemSet); this.itemsData = null; // DataSet this.groupsData = null; // DataSet // apply options if (options) { this.setOptions(options); } // IMPORTANT: THIS HAPPENS BEFORE SET ITEMS! if (groups) { this.setGroups(groups); } // create itemset if (items) { this.setItems(items); } else { this.redraw(); } } // Extend the functionality from Core Timeline.prototype = new Core(); /** * Set items * @param {vis.DataSet | Array | google.visualization.DataTable | null} items */ Timeline.prototype.setItems = function(items) { var initialLoad = (this.itemsData == null); // convert to type DataSet when needed var newDataSet; if (!items) { newDataSet = null; } else if (items instanceof DataSet || items instanceof DataView) { newDataSet = items; } else { // turn an array into a dataset newDataSet = new DataSet(items, { type: { start: 'Date', end: 'Date' } }); } // set items this.itemsData = newDataSet; this.itemSet && this.itemSet.setItems(newDataSet); if (initialLoad) { if (this.options.start != undefined || this.options.end != undefined) { if (this.options.start == undefined || this.options.end == undefined) { var dataRange = this._getDataRange(); } var start = this.options.start != undefined ? this.options.start : dataRange.start; var end = this.options.end != undefined ? this.options.end : dataRange.end; console.log(this.options.start, this.options.end, dataRange) this.setWindow(start, end, {animate: false}); } else { this.fit({animate: false}); } } }; /** * Set groups * @param {vis.DataSet | Array | google.visualization.DataTable} groups */ Timeline.prototype.setGroups = function(groups) { // convert to type DataSet when needed var newDataSet; if (!groups) { newDataSet = null; } else if (groups instanceof DataSet || groups instanceof DataView) { newDataSet = groups; } else { // turn an array into a dataset newDataSet = new DataSet(groups); } this.groupsData = newDataSet; this.itemSet.setGroups(newDataSet); }; /** * Set selected items by their id. Replaces the current selection * Unknown id's are silently ignored. * @param {string[] | string} [ids] An array with zero or more id's of the items to be * selected. If ids is an empty array, all items will be * unselected. * @param {Object} [options] Available options: * `focus: boolean` * If true, focus will be set to the selected item(s) * `animate: boolean | number` * If true (default), the range is animated * smoothly to the new window. * If a number, the number is taken as duration * for the animation. Default duration is 500 ms. * Only applicable when option focus is true. */ Timeline.prototype.setSelection = function(ids, options) { this.itemSet && this.itemSet.setSelection(ids); if (options && options.focus) { this.focus(ids, options); } }; /** * Get the selected items by their id * @return {Array} ids The ids of the selected items */ Timeline.prototype.getSelection = function() { return this.itemSet && this.itemSet.getSelection() || []; }; /** * Adjust the visible window such that the selected item (or multiple items) * are centered on screen. * @param {String | String[]} id An item id or array with item ids * @param {Object} [options] Available options: * `animate: boolean | number` * If true (default), the range is animated * smoothly to the new window. * If a number, the number is taken as duration * for the animation. Default duration is 500 ms. * Only applicable when option focus is true */ Timeline.prototype.focus = function(id, options) { if (!this.itemsData || id == undefined) return; var ids = Array.isArray(id) ? id : [id]; // get the specified item(s) var itemsData = this.itemsData.getDataSet().get(ids, { type: { start: 'Date', end: 'Date' } }); // calculate minimum start and maximum end of specified items var start = null; var end = null; itemsData.forEach(function (itemData) { var s = itemData.start.valueOf(); var e = 'end' in itemData ? itemData.end.valueOf() : itemData.start.valueOf(); if (start === null || s < start) { start = s; } if (end === null || e > end) { end = e; } }); if (start !== null && end !== null) { // calculate the new middle and interval for the window var middle = (start + end) / 2; var interval = Math.max((this.range.end - this.range.start), (end - start) * 1.1); var animate = (options && options.animate !== undefined) ? options.animate : true; this.range.setRange(middle - interval / 2, middle + interval / 2, animate); } }; /** * Get the data range of the item set. * @returns {{min: Date, max: Date}} range A range with a start and end Date. * When no minimum is found, min==null * When no maximum is found, max==null */ Timeline.prototype.getItemRange = function() { // calculate min from start filed var dataset = this.itemsData.getDataSet(), min = null, max = null; if (dataset) { // calculate the minimum value of the field 'start' var minItem = dataset.min('start'); min = minItem ? util.convert(minItem.start, 'Date').valueOf() : null; // Note: we convert first to Date and then to number because else // a conversion from ISODate to Number will fail // calculate maximum value of fields 'start' and 'end' var maxStartItem = dataset.max('start'); if (maxStartItem) { max = util.convert(maxStartItem.start, 'Date').valueOf(); } var maxEndItem = dataset.max('end'); if (maxEndItem) { if (max == null) { max = util.convert(maxEndItem.end, 'Date').valueOf(); } else { max = Math.max(max, util.convert(maxEndItem.end, 'Date').valueOf()); } } } return { min: (min != null) ? new Date(min) : null, max: (max != null) ? new Date(max) : null }; }; module.exports = Timeline;
whoops, cleaned up a console.log
lib/timeline/Timeline.js
whoops, cleaned up a console.log
<ide><path>ib/timeline/Timeline.js <ide> var start = this.options.start != undefined ? this.options.start : dataRange.start; <ide> var end = this.options.end != undefined ? this.options.end : dataRange.end; <ide> <del> console.log(this.options.start, this.options.end, dataRange) <del> <ide> this.setWindow(start, end, {animate: false}); <ide> } <ide> else {
Java
apache-2.0
54eba96419fb937b2f87e3aa840e94cc8daf3093
0
emrahkocaman/hazelcast,lmjacksoniii/hazelcast,juanavelez/hazelcast,mesutcelik/hazelcast,tombujok/hazelcast,mdogan/hazelcast,dbrimley/hazelcast,tkountis/hazelcast,dbrimley/hazelcast,tufangorel/hazelcast,dsukhoroslov/hazelcast,emre-aydin/hazelcast,dbrimley/hazelcast,dsukhoroslov/hazelcast,Donnerbart/hazelcast,emre-aydin/hazelcast,mesutcelik/hazelcast,tufangorel/hazelcast,Donnerbart/hazelcast,mdogan/hazelcast,tkountis/hazelcast,juanavelez/hazelcast,lmjacksoniii/hazelcast,tombujok/hazelcast,tkountis/hazelcast,Donnerbart/hazelcast,mdogan/hazelcast,tufangorel/hazelcast,mesutcelik/hazelcast,emrahkocaman/hazelcast,emre-aydin/hazelcast
/* * Copyright (c) 2007-2008, Hazel Ltd. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ package com.hazelcast.impl; import static com.hazelcast.impl.Constants.ResponseTypes.RESPONSE_SUCCESS; import static com.hazelcast.nio.IOUtil.toData; import static com.hazelcast.nio.IOUtil.toObject; import static com.hazelcast.impl.BaseManager.getInstanceType; import com.hazelcast.core.*; import com.hazelcast.core.Instance.InstanceType; import com.hazelcast.impl.BaseManager.EventTask; import com.hazelcast.impl.BaseManager.KeyValue; import com.hazelcast.impl.ConcurrentMapManager.Entries; import com.hazelcast.impl.FactoryImpl.CollectionProxyImpl; import com.hazelcast.impl.FactoryImpl.MProxy; import com.hazelcast.impl.FactoryImpl.CollectionProxyImpl.CollectionProxyReal; import com.hazelcast.nio.Connection; import com.hazelcast.nio.Data; import com.hazelcast.nio.Packet; import com.hazelcast.query.Predicate; import java.util.ArrayList; import java.util.Collection; import java.util.HashMap; import java.util.HashSet; import java.util.List; import java.util.Map; import java.util.concurrent.TimeUnit; public class ClientService { private final Node node; private final Map<Connection, ClientEndpoint> mapClientEndpoints = new HashMap<Connection, ClientEndpoint>(); private final ClientOperationHandler[] clientOperationHandlers = new ClientOperationHandler[300]; public ClientService(Node node) { this.node = node; clientOperationHandlers[ClusterOperation.CONCURRENT_MAP_PUT.getValue()] = new MapPutHandler(); clientOperationHandlers[ClusterOperation.CONCURRENT_MAP_PUT_IF_ABSENT.getValue()] = new MapPutIfAbsentHandler(); clientOperationHandlers[ClusterOperation.CONCURRENT_MAP_GET.getValue()] = new MapGetHandler(); clientOperationHandlers[ClusterOperation.CONCURRENT_MAP_REMOVE.getValue()] = new MapRemoveHandler(); clientOperationHandlers[ClusterOperation.CONCURRENT_MAP_REMOVE_IF_SAME.getValue()] = new MapRemoveIfSameHandler(); clientOperationHandlers[ClusterOperation.CONCURRENT_MAP_EVICT.getValue()] = new MapEvictHandler(); clientOperationHandlers[ClusterOperation.CONCURRENT_MAP_REPLACE_IF_NOT_NULL.getValue()] = new MapReplaceIfNotNullHandler(); clientOperationHandlers[ClusterOperation.CONCURRENT_MAP_REPLACE_IF_SAME.getValue()] = new MapReplaceIfSameHandler(); clientOperationHandlers[ClusterOperation.CONCURRENT_MAP_SIZE.getValue()] = new MapSizeHandler(); clientOperationHandlers[ClusterOperation.CONCURRENT_MAP_GET_MAP_ENTRY.getValue()] = new GetMapEntryHandler(); clientOperationHandlers[ClusterOperation.CONCURRENT_MAP_LOCK.getValue()] = new MapLockHandler(); clientOperationHandlers[ClusterOperation.CONCURRENT_MAP_UNLOCK.getValue()] = new MapUnlockHandler(); clientOperationHandlers[ClusterOperation.CONCURRENT_MAP_CONTAINS.getValue()] = new MapContainsHandler(); clientOperationHandlers[ClusterOperation.CONCURRENT_MAP_CONTAINS_VALUE.getValue()] = new MapContainsValueHandler(); clientOperationHandlers[ClusterOperation.CONCURRENT_MAP_ADD_TO_LIST.getValue()] = new ListAddHandler(); clientOperationHandlers[ClusterOperation.CONCURRENT_MAP_ADD_TO_SET.getValue()] = new SetAddHandler(); clientOperationHandlers[ClusterOperation.CONCURRENT_MAP_REMOVE_ITEM.getValue()] = new MapItemRemoveHandler(); clientOperationHandlers[ClusterOperation.CONCURRENT_MAP_ITERATE_KEYS.getValue()] = new MapIterateKeysHandler(); clientOperationHandlers[ClusterOperation.BLOCKING_QUEUE_OFFER.getValue()] = new QueueOfferHandler(); clientOperationHandlers[ClusterOperation.BLOCKING_QUEUE_POLL.getValue()] = new QueuePollHandler(); clientOperationHandlers[ClusterOperation.BLOCKING_QUEUE_REMOVE.getValue()] = new QueueRemoveHandler(); clientOperationHandlers[ClusterOperation.BLOCKING_QUEUE_PEEK.getValue()] = new QueuePeekHandler(); clientOperationHandlers[ClusterOperation.TRANSACTION_BEGIN.getValue()] = new TransactionBeginHandler(); clientOperationHandlers[ClusterOperation.TRANSACTION_COMMIT.getValue()] = new TransactionCommitHandler(); clientOperationHandlers[ClusterOperation.TRANSACTION_ROLLBACK.getValue()] = new TransactionRollbackHandler(); clientOperationHandlers[ClusterOperation.ADD_LISTENER.getValue()] = new AddListenerHandler(); clientOperationHandlers[ClusterOperation.REMOVE_LISTENER.getValue()] = new RemoveListenerHandler(); clientOperationHandlers[ClusterOperation.REMOTELY_PROCESS.getValue()] = new RemotelyProcessHandler(); clientOperationHandlers[ClusterOperation.DESTROY.getValue()] = new DestroyHandler(); clientOperationHandlers[ClusterOperation.GET_ID.getValue()] = new GetIdHandler(); clientOperationHandlers[ClusterOperation.ADD_INDEX.getValue()] = new AddIndexHandler(); } // always called by InThread public void handle(Packet packet) { ClientEndpoint clientEndpoint = getClientEndpoint(packet.conn); CallContext callContext = clientEndpoint.getCallContext(packet.threadId); ClientRequestHandler clientRequestHandler = new ClientRequestHandler(node, packet, callContext, clientOperationHandlers); if(!packet.operation.equals(ClusterOperation.CONCURRENT_MAP_UNLOCK)){ node.clusterManager.enqueueEvent(clientEndpoint.hashCode(), clientRequestHandler); } else{ node.executorManager.executeMigrationTask(clientRequestHandler); } } public ClientEndpoint getClientEndpoint(Connection conn) { ClientEndpoint clientEndpoint = mapClientEndpoints.get(conn); if (clientEndpoint == null) { clientEndpoint = new ClientEndpoint(conn); mapClientEndpoints.put(conn, clientEndpoint); } return clientEndpoint; } class ClientEndpoint implements EntryListener { final Connection conn; final private Map<Integer, CallContext> callContexts = new HashMap<Integer, CallContext>(); final Map<String, Map<Object, EntryEvent>> listeneds = new HashMap<String, Map<Object, EntryEvent>>(); ClientEndpoint(Connection conn) { this.conn = conn; } public CallContext getCallContext(int threadId) { CallContext context = callContexts.get(threadId); if (context == null) { int locallyMappedThreadId = ThreadContext.get().createNewThreadId(); context = new CallContext(locallyMappedThreadId, true); callContexts.put(threadId, context); } return context; } public void addThisAsListener(IMap map, Data key, boolean includeValue){ if (key == null) { map.addEntryListener(this, includeValue); } else { map.addEntryListener(this, key, includeValue); } } private Map<Object, EntryEvent> getEventProcessedLog(String name) { Map<Object, EntryEvent> eventProcessedLog = listeneds.get(name); if(eventProcessedLog == null){ synchronized (name) { if(eventProcessedLog == null){ eventProcessedLog = new HashMap<Object, EntryEvent>(); listeneds.put(name, eventProcessedLog); } } } return eventProcessedLog; } @Override public int hashCode() { return this.conn.hashCode(); } public void entryAdded(EntryEvent event) { processEvent(event); } public void entryEvicted(EntryEvent event) { processEvent(event); } public void entryRemoved(EntryEvent event) { processEvent(event); } public void entryUpdated(EntryEvent event) { processEvent(event); } private void processEvent(EntryEvent event) { Map<Object, EntryEvent> eventProcessedLog = getEventProcessedLog(event.getName()); if(eventProcessedLog.get(event.getKey())!=null && eventProcessedLog.get(event.getKey()) == event){ return; } eventProcessedLog.put(event.getKey(), event); Object key = listeneds.get(event.getName()); Packet packet = createEntryEventPacket(event); sendPacket(packet); } private void sendPacket(Packet packet) { if (conn != null && conn.live()) { conn.getWriteHandler().enqueuePacket(packet); } } private Packet createEntryEventPacket(EntryEvent event) { Packet packet = new Packet(); EventTask eventTask = (EventTask) event; packet.set(event.getName(), ClusterOperation.EVENT, eventTask.getDataKey(), eventTask.getDataValue()); packet.longValue = event.getEventType().getType(); return packet; } } public void reset() { mapClientEndpoints.clear(); } private class QueueOfferHandler extends ClientQueueOperationHandler{ public Data processQueueOp(IQueue<Object> queue, Data key, Data value) { long millis = (Long)toObject(value); try { if(millis==-1){ queue.put(key); return toData(true); } else if(millis == 0){ return toData(queue.offer(key)); }else{ return toData(queue.offer(key, (Long) toObject(value), TimeUnit.MILLISECONDS)); } } catch (InterruptedException e) { throw new RuntimeException(); } } } private class QueuePollHandler extends ClientQueueOperationHandler{ public Data processQueueOp(IQueue<Object> queue, Data key, Data value) { try { long millis = (Long)toObject(value); if(millis==-1){ return (Data)queue.take(); } else if(millis == 0){ return (Data)queue.poll(); }else{ return (Data)queue.poll((Long) millis, TimeUnit.MILLISECONDS); } } catch (InterruptedException e) { throw new RuntimeException(e); } } } private class QueueRemoveHandler extends ClientQueueOperationHandler{ public Data processQueueOp(IQueue<Object> queue, Data key, Data value) { return (Data)queue.remove(); } } private class QueuePeekHandler extends ClientQueueOperationHandler{ public Data processQueueOp(IQueue<Object> queue, Data key, Data value) { return (Data)queue.peek(); } } private class RemotelyProcessHandler extends ClientOperationHandler{ public void processCall(Node node, Packet packet) { node.clusterService.enqueueAndReturn(packet); } @Override protected void sendResponse(Packet request) { } } private class DestroyHandler extends ClientOperationHandler{ public void processCall(Node node, Packet packet) { Instance instance = (Instance)node.factory.getOrCreateProxyByName(packet.name); instance.destroy(); } } private class GetIdHandler extends ClientMapOperationHandler{ public Data processMapOp(IMap<Object, Object> map, Data key, Data value) { return toData(map.getId()); } } private class AddIndexHandler extends ClientMapOperationHandler{ public Data processMapOp(IMap<Object, Object> map, Data key, Data value) { map.addIndex((String)toObject(key), (Boolean)toObject(value)); return null; } } private class MapPutHandler extends ClientMapOperationHandler{ public Data processMapOp(IMap<Object, Object> map, Data key, Data value) { Object oldValue = map.put(key, value); return (oldValue==null)?null:(Data) oldValue; } } private class MapPutIfAbsentHandler extends ClientMapOperationHandler{ public Data processMapOp(IMap<Object, Object> map, Data key, Data value) { Object oldValue = map.putIfAbsent(key, value); return (oldValue==null)?null:(Data) oldValue; } } private class MapGetHandler extends ClientMapOperationHandler{ public Data processMapOp(IMap<Object, Object> map, Data key, Data value) { return (Data)map.get(key); } } private class MapRemoveHandler extends ClientMapOperationHandler{ public Data processMapOp(IMap<Object, Object> map, Data key, Data value) { return (Data) map.remove(key); } } private class MapRemoveIfSameHandler extends ClientMapOperationHandler{ public Data processMapOp(IMap<Object, Object> map, Data key, Data value) { return toData(map.remove(key, value)); } } private class MapEvictHandler extends ClientMapOperationHandler{ public Data processMapOp(IMap<Object, Object> map, Data key, Data value) { return toData(map.evict(key)); } } private class MapReplaceIfNotNullHandler extends ClientMapOperationHandler{ public Data processMapOp(IMap<Object, Object> map, Data key, Data value) { return (Data)map.replace(key, value); } } private class MapReplaceIfSameHandler extends ClientMapOperationHandler{ public Data processMapOp(IMap<Object, Object> map, Data key, Data value) { Object[] arr = (Object[]) toObject(value); return toData(map.replace(key, arr[0], arr[1])); } } private class MapContainsHandler extends ClientOperationHandler{ public void processCall(Node node, Packet packet) { if(getInstanceType(packet.name).equals(InstanceType.MAP)){ IMap<Object, Object> map = (IMap)node.factory.getOrCreateProxyByName(packet.name); packet.value = toData(map.containsKey(packet.key)); } else if (getInstanceType(packet.name).equals(InstanceType.LIST) || getInstanceType(packet.name).equals(InstanceType.SET)){ Collection<Object> collection = (Collection)node.factory.getOrCreateProxyByName(packet.name); packet.value = toData(collection.contains(packet.key)); } } } private class MapContainsValueHandler extends ClientMapOperationHandler{ public Data processMapOp(IMap<Object, Object> map, Data key, Data value) { return toData(map.containsValue(value)); } } private class MapSizeHandler extends ClientCollectionOperationHandler{ @Override public void doListOp(Node node, Packet packet) { IList<Object> list = (IList)node.factory.getOrCreateProxyByName(packet.name); packet.value = toData(list.size()); } @Override public void doMapOp(Node node, Packet packet) { IMap<Object, Object> map = (IMap)node.factory.getOrCreateProxyByName(packet.name); packet.value = toData(map.size()); } @Override public void doSetOp(Node node, Packet packet) { ISet<Object> set = (ISet)node.factory.getOrCreateProxyByName(packet.name); packet.value = toData(set.size()); } } private class GetMapEntryHandler extends ClientMapOperationHandler{ public Data processMapOp(IMap<Object, Object> map, Data key, Data value) { return toData(map.getMapEntry(key)); } } private class MapLockHandler extends ClientMapOperationHandler{ public Data processMapOp(IMap<Object, Object> map, Data key, Data value) { throw new RuntimeException("Shouldn't invoke this method"); } @Override public void processCall(Node node, Packet packet){ IMap<Object, Object> map = (IMap)node.factory.getOrCreateProxyByName(packet.name); long timeout = packet.timeout; Data value = null; if(timeout==-1){ map.lock(packet.key); value = null; } else if(timeout == 0){ value = toData(map.tryLock(packet.key)); } else{ value = toData(map.tryLock(packet.key, timeout,(TimeUnit) toObject(packet.value))); } packet.value = value; } } private class MapUnlockHandler extends ClientMapOperationHandler{ public Data processMapOp(IMap<Object, Object> map, Data key, Data value) { map.unlock(key); return null; } } private class TransactionBeginHandler extends ClientTransactionOperationHandler { public void processTransactionOp(Transaction transaction) { transaction.begin(); } } private class TransactionCommitHandler extends ClientTransactionOperationHandler { public void processTransactionOp(Transaction transaction) { transaction.commit(); } } private class TransactionRollbackHandler extends ClientTransactionOperationHandler { public void processTransactionOp(Transaction transaction) { transaction.rollback(); } } private class MapIterateKeysHandler extends ClientCollectionOperationHandler { public Data processMapOp(IMap<Object, Object> map, Data key, Data value, Collection<Data> collection) { ConcurrentMapManager.Entries entries = null; if(value==null){ entries = (Entries) map.keySet(); } else{ Predicate p = (Predicate)toObject(value); entries = (Entries) map.keySet(p); } List<Map.Entry> list = entries.getLsKeyValues(); Keys keys = new Keys(collection); for (Object obj : list) { KeyValue entry = (KeyValue) obj; keys.addKey(entry.key); } return toData(keys); } @Override public void doListOp(Node node, Packet packet) { CollectionProxyImpl collectionProxy = (CollectionProxyImpl)node.factory.getOrCreateProxyByName(packet.name); MProxy mapProxy = ((CollectionProxyReal)collectionProxy.getBase()).mapProxy; packet.value = processMapOp((IMap)mapProxy, packet.key, packet.value, new ArrayList<Data>()); } @Override public void doMapOp(Node node, Packet packet) { packet.value = processMapOp((IMap)node.factory.getOrCreateProxyByName(packet.name), packet.key, packet.value, new HashSet<Data>()); } @Override public void doSetOp(Node node, Packet packet) { CollectionProxyImpl collectionProxy = (CollectionProxyImpl)node.factory.getOrCreateProxyByName(packet.name); MProxy mapProxy = ((CollectionProxyReal)collectionProxy.getBase()).mapProxy; packet.value = processMapOp((IMap)mapProxy, packet.key, packet.value, new HashSet<Data>()); } } private class AddListenerHandler extends ClientOperationHandler { public void processCall(Node node, Packet packet) { ClientEndpoint clientEndpoint = node.clientService.getClientEndpoint(packet.conn); boolean includeValue = (int) packet.longValue == 1; if(getInstanceType(packet.name).equals(InstanceType.MAP)){ IMap<Object, Object> map = (IMap)node.factory.getOrCreateProxyByName(packet.name); clientEndpoint.addThisAsListener(map, packet.key, includeValue); } else if(getInstanceType(packet.name).equals(InstanceType.LIST) || getInstanceType(packet.name).equals(InstanceType.SET)){ CollectionProxyImpl collectionProxy = (CollectionProxyImpl)node.factory.getOrCreateProxyByName(packet.name); MProxy mapProxy = ((CollectionProxyReal)collectionProxy.getBase()).mapProxy; mapProxy.addEntryListener(clientEndpoint, includeValue); } } } private class RemoveListenerHandler extends ClientOperationHandler { public void processCall(Node node, Packet packet) { ClientEndpoint clientEndpoint = node.clientService.getClientEndpoint(packet.conn); IMap<Object, Object> map = (IMap)node.factory.getOrCreateProxyByName(packet.name); if (packet.key == null) { map.removeEntryListener(clientEndpoint); } else { map.removeEntryListener(clientEndpoint, packet.key); } } } private class ListAddHandler extends ClientOperationHandler{ @Override public void processCall(Node node, Packet packet) { IList list = (IList)node.factory.getOrCreateProxyByName(packet.name); packet.value = toData(list.add(packet.key)); } } private class SetAddHandler extends ClientOperationHandler{ @Override public void processCall(Node node, Packet packet) { ISet list = (ISet)node.factory.getOrCreateProxyByName(packet.name); packet.value = toData(list.add(packet.key)); } } private class MapItemRemoveHandler extends ClientOperationHandler{ public void processCall(Node node, Packet packet) { Collection collection = (Collection)node.factory.getOrCreateProxyByName(packet.name); packet.value = toData(collection.remove(packet.key)); } } public abstract class ClientOperationHandler{ public abstract void processCall(Node node, Packet packet); public void handle(Node node, Packet packet){ processCall(node,packet); sendResponse(packet); } protected void sendResponse(Packet request) { request.operation = ClusterOperation.RESPONSE; request.responseType = RESPONSE_SUCCESS; if (request.conn != null && request.conn.live()) { request.conn.getWriteHandler().enqueuePacket(request); } } } private abstract class ClientMapOperationHandler extends ClientOperationHandler{ public abstract Data processMapOp(IMap<Object, Object> map, Data key, Data value); public void processCall(Node node, Packet packet){ IMap<Object, Object> map = (IMap)node.factory.getOrCreateProxyByName(packet.name); Data value = processMapOp(map,packet.key, packet.value); packet.value = value; } } private abstract class ClientQueueOperationHandler extends ClientOperationHandler{ public abstract Data processQueueOp(IQueue<Object> queue, Data key, Data value); public void processCall(Node node, Packet packet){ IQueue<Object> queue = (IQueue)node.factory.getOrCreateProxyByName(packet.name); Data value = processQueueOp(queue,packet.key, packet.value); packet.value = value; } } private abstract class ClientCollectionOperationHandler extends ClientOperationHandler{ public abstract void doMapOp(Node node, Packet packet); public abstract void doListOp(Node node, Packet packet); public abstract void doSetOp(Node node, Packet packet); @Override public void processCall(Node node, Packet packet) { if(getInstanceType(packet.name).equals(InstanceType.LIST)){ doListOp(node, packet); } else if(getInstanceType(packet.name).equals(InstanceType.SET)){ doSetOp(node, packet); } else if(getInstanceType(packet.name).equals(InstanceType.MAP)){ doMapOp(node, packet); } } } private abstract class ClientTransactionOperationHandler extends ClientOperationHandler{ public abstract void processTransactionOp(Transaction transaction); public void processCall(Node node, Packet packet){ Transaction transaction = node.factory.getTransaction(); processTransactionOp(transaction); } } }
hazelcast/src/main/java/com/hazelcast/impl/ClientService.java
/* * Copyright (c) 2007-2008, Hazel Ltd. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ package com.hazelcast.impl; import static com.hazelcast.impl.Constants.ResponseTypes.RESPONSE_SUCCESS; import static com.hazelcast.nio.IOUtil.toData; import static com.hazelcast.nio.IOUtil.toObject; import static com.hazelcast.impl.BaseManager.getInstanceType; import com.hazelcast.core.EntryEvent; import com.hazelcast.core.EntryListener; import com.hazelcast.core.ICollection; import com.hazelcast.core.IList; import com.hazelcast.core.IMap; import com.hazelcast.core.ISet; import com.hazelcast.core.Instance; import com.hazelcast.core.Transaction; import com.hazelcast.core.Instance.InstanceType; import com.hazelcast.impl.BaseManager.EventTask; import com.hazelcast.impl.BaseManager.KeyValue; import com.hazelcast.impl.ConcurrentMapManager.Entries; import com.hazelcast.impl.FactoryImpl.CollectionProxyImpl; import com.hazelcast.impl.FactoryImpl.MProxy; import com.hazelcast.impl.FactoryImpl.CollectionProxyImpl.CollectionProxyReal; import com.hazelcast.nio.Connection; import com.hazelcast.nio.Data; import com.hazelcast.nio.Packet; import com.hazelcast.query.Predicate; import java.util.ArrayList; import java.util.Collection; import java.util.HashMap; import java.util.HashSet; import java.util.List; import java.util.Map; import java.util.concurrent.TimeUnit; public class ClientService { private final Node node; private final Map<Connection, ClientEndpoint> mapClientEndpoints = new HashMap<Connection, ClientEndpoint>(); private final ClientOperationHandler[] clientOperationHandlers = new ClientOperationHandler[300]; public ClientService(Node node) { this.node = node; clientOperationHandlers[ClusterOperation.CONCURRENT_MAP_PUT.getValue()] = new MapPutHandler(); clientOperationHandlers[ClusterOperation.CONCURRENT_MAP_PUT_IF_ABSENT.getValue()] = new MapPutIfAbsentHandler(); clientOperationHandlers[ClusterOperation.CONCURRENT_MAP_GET.getValue()] = new MapGetHandler(); clientOperationHandlers[ClusterOperation.CONCURRENT_MAP_REMOVE.getValue()] = new MapRemoveHandler(); clientOperationHandlers[ClusterOperation.CONCURRENT_MAP_REMOVE_IF_SAME.getValue()] = new MapRemoveIfSameHandler(); clientOperationHandlers[ClusterOperation.CONCURRENT_MAP_EVICT.getValue()] = new MapEvictHandler(); clientOperationHandlers[ClusterOperation.CONCURRENT_MAP_REPLACE_IF_NOT_NULL.getValue()] = new MapReplaceIfNotNullHandler(); clientOperationHandlers[ClusterOperation.CONCURRENT_MAP_REPLACE_IF_SAME.getValue()] = new MapReplaceIfSameHandler(); clientOperationHandlers[ClusterOperation.CONCURRENT_MAP_SIZE.getValue()] = new MapSizeHandler(); clientOperationHandlers[ClusterOperation.CONCURRENT_MAP_GET_MAP_ENTRY.getValue()] = new GetMapEntryHandler(); clientOperationHandlers[ClusterOperation.CONCURRENT_MAP_LOCK.getValue()] = new MapLockHandler(); clientOperationHandlers[ClusterOperation.CONCURRENT_MAP_UNLOCK.getValue()] = new MapUnlockHandler(); clientOperationHandlers[ClusterOperation.CONCURRENT_MAP_CONTAINS.getValue()] = new MapContainsHandler(); clientOperationHandlers[ClusterOperation.CONCURRENT_MAP_CONTAINS_VALUE.getValue()] = new MapContainsValueHandler(); clientOperationHandlers[ClusterOperation.TRANSACTION_BEGIN.getValue()] = new TransactionBeginHandler(); clientOperationHandlers[ClusterOperation.TRANSACTION_COMMIT.getValue()] = new TransactionCommitHandler(); clientOperationHandlers[ClusterOperation.TRANSACTION_ROLLBACK.getValue()] = new TransactionRollbackHandler(); clientOperationHandlers[ClusterOperation.CONCURRENT_MAP_ITERATE_KEYS.getValue()] = new MapIterateKeysHandler(); clientOperationHandlers[ClusterOperation.ADD_LISTENER.getValue()] = new AddListenerHandler(); clientOperationHandlers[ClusterOperation.REMOVE_LISTENER.getValue()] = new RemoveListenerHandler(); clientOperationHandlers[ClusterOperation.REMOTELY_PROCESS.getValue()] = new RemotelyProcessHandler(); clientOperationHandlers[ClusterOperation.DESTROY.getValue()] = new DestroyHandler(); clientOperationHandlers[ClusterOperation.GET_ID.getValue()] = new GetIdHandler(); clientOperationHandlers[ClusterOperation.ADD_INDEX.getValue()] = new AddIndexHandler(); clientOperationHandlers[ClusterOperation.CONCURRENT_MAP_ADD_TO_LIST.getValue()] = new ListAddHandler(); clientOperationHandlers[ClusterOperation.CONCURRENT_MAP_ADD_TO_SET.getValue()] = new SetAddHandler(); clientOperationHandlers[ClusterOperation.CONCURRENT_MAP_REMOVE_ITEM.getValue()] = new MapItemRemoveHandler(); } // always called by InThread public void handle(Packet packet) { ClientEndpoint clientEndpoint = getClientEndpoint(packet.conn); CallContext callContext = clientEndpoint.getCallContext(packet.threadId); ClientRequestHandler clientRequestHandler = new ClientRequestHandler(node, packet, callContext, clientOperationHandlers); if(!packet.operation.equals(ClusterOperation.CONCURRENT_MAP_UNLOCK)){ node.clusterManager.enqueueEvent(clientEndpoint.hashCode(), clientRequestHandler); } else{ node.executorManager.executeMigrationTask(clientRequestHandler); } } public ClientEndpoint getClientEndpoint(Connection conn) { ClientEndpoint clientEndpoint = mapClientEndpoints.get(conn); if (clientEndpoint == null) { clientEndpoint = new ClientEndpoint(conn); mapClientEndpoints.put(conn, clientEndpoint); } return clientEndpoint; } class ClientEndpoint implements EntryListener { final Connection conn; final private Map<Integer, CallContext> callContexts = new HashMap<Integer, CallContext>(); final Map<String, Map<Object, EntryEvent>> listeneds = new HashMap<String, Map<Object, EntryEvent>>(); ClientEndpoint(Connection conn) { this.conn = conn; } public CallContext getCallContext(int threadId) { CallContext context = callContexts.get(threadId); if (context == null) { int locallyMappedThreadId = ThreadContext.get().createNewThreadId(); context = new CallContext(locallyMappedThreadId, true); callContexts.put(threadId, context); } return context; } public void addThisAsListener(IMap map, Data key, boolean includeValue){ if (key == null) { map.addEntryListener(this, includeValue); } else { map.addEntryListener(this, key, includeValue); } } private Map<Object, EntryEvent> getEventProcessedLog(String name) { Map<Object, EntryEvent> eventProcessedLog = listeneds.get(name); if(eventProcessedLog == null){ synchronized (name) { if(eventProcessedLog == null){ eventProcessedLog = new HashMap<Object, EntryEvent>(); listeneds.put(name, eventProcessedLog); } } } return eventProcessedLog; } @Override public int hashCode() { return this.conn.hashCode(); } public void entryAdded(EntryEvent event) { processEvent(event); } public void entryEvicted(EntryEvent event) { processEvent(event); } public void entryRemoved(EntryEvent event) { processEvent(event); } public void entryUpdated(EntryEvent event) { processEvent(event); } private void processEvent(EntryEvent event) { Map<Object, EntryEvent> eventProcessedLog = getEventProcessedLog(event.getName()); if(eventProcessedLog.get(event.getKey())!=null && eventProcessedLog.get(event.getKey()) == event){ return; } eventProcessedLog.put(event.getKey(), event); Object key = listeneds.get(event.getName()); Packet packet = createEntryEventPacket(event); sendPacket(packet); } private void sendPacket(Packet packet) { if (conn != null && conn.live()) { conn.getWriteHandler().enqueuePacket(packet); } } private Packet createEntryEventPacket(EntryEvent event) { Packet packet = new Packet(); EventTask eventTask = (EventTask) event; packet.set(event.getName(), ClusterOperation.EVENT, eventTask.getDataKey(), eventTask.getDataValue()); packet.longValue = event.getEventType().getType(); return packet; } } public void reset() { mapClientEndpoints.clear(); } private class RemotelyProcessHandler extends ClientOperationHandler{ public void processCall(Node node, Packet packet) { node.clusterService.enqueueAndReturn(packet); } @Override protected void sendResponse(Packet request) { } } private class DestroyHandler extends ClientOperationHandler{ public void processCall(Node node, Packet packet) { Instance instance = (Instance)node.factory.getOrCreateProxyByName(packet.name); instance.destroy(); } } private class GetIdHandler extends ClientMapOperationHandler{ public Data processMapOp(IMap<Object, Object> map, Data key, Data value) { return toData(map.getId()); } } private class AddIndexHandler extends ClientMapOperationHandler{ public Data processMapOp(IMap<Object, Object> map, Data key, Data value) { map.addIndex((String)toObject(key), (Boolean)toObject(value)); return null; } } private class MapPutHandler extends ClientMapOperationHandler{ public Data processMapOp(IMap<Object, Object> map, Data key, Data value) { Object oldValue = map.put(key, value); return (oldValue==null)?null:(Data) oldValue; } } private class MapPutIfAbsentHandler extends ClientMapOperationHandler{ public Data processMapOp(IMap<Object, Object> map, Data key, Data value) { Object oldValue = map.putIfAbsent(key, value); return (oldValue==null)?null:(Data) oldValue; } } private class MapGetHandler extends ClientMapOperationHandler{ public Data processMapOp(IMap<Object, Object> map, Data key, Data value) { return (Data) map.get(key); } } private class MapRemoveHandler extends ClientMapOperationHandler{ public Data processMapOp(IMap<Object, Object> map, Data key, Data value) { return (Data) map.remove(key); } } private class MapRemoveIfSameHandler extends ClientMapOperationHandler{ public Data processMapOp(IMap<Object, Object> map, Data key, Data value) { return toData(map.remove(key, value)); } } private class MapEvictHandler extends ClientMapOperationHandler{ public Data processMapOp(IMap<Object, Object> map, Data key, Data value) { return toData(map.evict(key)); } } private class MapReplaceIfNotNullHandler extends ClientMapOperationHandler{ public Data processMapOp(IMap<Object, Object> map, Data key, Data value) { return (Data)map.replace(key, value); } } private class MapReplaceIfSameHandler extends ClientMapOperationHandler{ public Data processMapOp(IMap<Object, Object> map, Data key, Data value) { Object[] arr = (Object[]) toObject(value); return toData(map.replace(key, arr[0], arr[1])); } } private class MapContainsHandler extends ClientOperationHandler{ public void processCall(Node node, Packet packet) { if(getInstanceType(packet.name).equals(InstanceType.MAP)){ IMap<Object, Object> map = (IMap)node.factory.getOrCreateProxyByName(packet.name); packet.value = toData(map.containsKey(packet.key)); } else if (getInstanceType(packet.name).equals(InstanceType.LIST) || getInstanceType(packet.name).equals(InstanceType.SET)){ Collection<Object> collection = (Collection)node.factory.getOrCreateProxyByName(packet.name); packet.value = toData(collection.contains(packet.key)); } } } private class MapContainsValueHandler extends ClientMapOperationHandler{ public Data processMapOp(IMap<Object, Object> map, Data key, Data value) { return toData(map.containsValue(value)); } } private class MapSizeHandler extends ClientCollectionOperationHandler{ @Override public void doListOp(Node node, Packet packet) { IList<Object> list = (IList)node.factory.getOrCreateProxyByName(packet.name); packet.value = toData(list.size()); } @Override public void doMapOp(Node node, Packet packet) { IMap<Object, Object> map = (IMap)node.factory.getOrCreateProxyByName(packet.name); packet.value = toData(map.size()); } @Override public void doSetOp(Node node, Packet packet) { ISet<Object> set = (ISet)node.factory.getOrCreateProxyByName(packet.name); packet.value = toData(set.size()); } } private class GetMapEntryHandler extends ClientMapOperationHandler{ public Data processMapOp(IMap<Object, Object> map, Data key, Data value) { return toData(map.getMapEntry(key)); } } private class MapLockHandler extends ClientMapOperationHandler{ public Data processMapOp(IMap<Object, Object> map, Data key, Data value) { throw new RuntimeException("Shouldn't invoke this method"); } @Override public void processCall(Node node, Packet packet){ IMap<Object, Object> map = (IMap)node.factory.getOrCreateProxyByName(packet.name); long timeout = packet.timeout; Data value = null; if(timeout==-1){ map.lock(packet.key); value = null; } else if(timeout == 0){ value = toData(map.tryLock(packet.key)); } else{ value = toData(map.tryLock(packet.key, timeout,(TimeUnit) toObject(packet.value))); } packet.value = value; } } private class MapUnlockHandler extends ClientMapOperationHandler{ public Data processMapOp(IMap<Object, Object> map, Data key, Data value) { map.unlock(key); return null; } } private class TransactionBeginHandler extends ClientTransactionOperationHandler { public void processTransactionOp(Transaction transaction) { transaction.begin(); } } private class TransactionCommitHandler extends ClientTransactionOperationHandler { public void processTransactionOp(Transaction transaction) { transaction.commit(); } } private class TransactionRollbackHandler extends ClientTransactionOperationHandler { public void processTransactionOp(Transaction transaction) { transaction.rollback(); } } private class MapIterateKeysHandler extends ClientCollectionOperationHandler { public Data processMapOp(IMap<Object, Object> map, Data key, Data value, Collection<Data> collection) { ConcurrentMapManager.Entries entries = null; if(value==null){ entries = (Entries) map.keySet(); } else{ Predicate p = (Predicate)toObject(value); entries = (Entries) map.keySet(p); } List<Map.Entry> list = entries.getLsKeyValues(); Keys keys = new Keys(collection); for (Object obj : list) { KeyValue entry = (KeyValue) obj; keys.addKey(entry.key); } return toData(keys); } @Override public void doListOp(Node node, Packet packet) { CollectionProxyImpl collectionProxy = (CollectionProxyImpl)node.factory.getOrCreateProxyByName(packet.name); MProxy mapProxy = ((CollectionProxyReal)collectionProxy.getBase()).mapProxy; packet.value = processMapOp((IMap)mapProxy, packet.key, packet.value, new ArrayList<Data>()); } @Override public void doMapOp(Node node, Packet packet) { packet.value = processMapOp((IMap)node.factory.getOrCreateProxyByName(packet.name), packet.key, packet.value, new HashSet<Data>()); } @Override public void doSetOp(Node node, Packet packet) { CollectionProxyImpl collectionProxy = (CollectionProxyImpl)node.factory.getOrCreateProxyByName(packet.name); MProxy mapProxy = ((CollectionProxyReal)collectionProxy.getBase()).mapProxy; packet.value = processMapOp((IMap)mapProxy, packet.key, packet.value, new HashSet<Data>()); } } private class AddListenerHandler extends ClientOperationHandler { public void processCall(Node node, Packet packet) { ClientEndpoint clientEndpoint = node.clientService.getClientEndpoint(packet.conn); boolean includeValue = (int) packet.longValue == 1; if(getInstanceType(packet.name).equals(InstanceType.MAP)){ IMap<Object, Object> map = (IMap)node.factory.getOrCreateProxyByName(packet.name); clientEndpoint.addThisAsListener(map, packet.key, includeValue); } else if(getInstanceType(packet.name).equals(InstanceType.LIST) || getInstanceType(packet.name).equals(InstanceType.SET)){ CollectionProxyImpl collectionProxy = (CollectionProxyImpl)node.factory.getOrCreateProxyByName(packet.name); MProxy mapProxy = ((CollectionProxyReal)collectionProxy.getBase()).mapProxy; mapProxy.addEntryListener(clientEndpoint, includeValue); } } } private class RemoveListenerHandler extends ClientOperationHandler { public void processCall(Node node, Packet packet) { ClientEndpoint clientEndpoint = node.clientService.getClientEndpoint(packet.conn); IMap<Object, Object> map = (IMap)node.factory.getOrCreateProxyByName(packet.name); if (packet.key == null) { map.removeEntryListener(clientEndpoint); } else { map.removeEntryListener(clientEndpoint, packet.key); } } } private class ListAddHandler extends ClientOperationHandler{ @Override public void processCall(Node node, Packet packet) { IList list = (IList)node.factory.getOrCreateProxyByName(packet.name); packet.value = toData(list.add(packet.key)); } } private class SetAddHandler extends ClientOperationHandler{ @Override public void processCall(Node node, Packet packet) { ISet list = (ISet)node.factory.getOrCreateProxyByName(packet.name); packet.value = toData(list.add(packet.key)); } } private class MapItemRemoveHandler extends ClientOperationHandler{ public void processCall(Node node, Packet packet) { Collection collection = (Collection)node.factory.getOrCreateProxyByName(packet.name); packet.value = toData(collection.remove(packet.key)); } } public abstract class ClientOperationHandler{ public abstract void processCall(Node node, Packet packet); public void handle(Node node, Packet packet){ processCall(node,packet); sendResponse(packet); } protected void sendResponse(Packet request) { request.operation = ClusterOperation.RESPONSE; request.responseType = RESPONSE_SUCCESS; if (request.conn != null && request.conn.live()) { request.conn.getWriteHandler().enqueuePacket(request); } } } private abstract class ClientMapOperationHandler extends ClientOperationHandler{ public abstract Data processMapOp(IMap<Object, Object> map, Data key, Data value); public void processCall(Node node, Packet packet){ IMap<Object, Object> map = (IMap)node.factory.getOrCreateProxyByName(packet.name); Data value = processMapOp(map,packet.key, packet.value); packet.value = value; } } private abstract class ClientCollectionOperationHandler extends ClientOperationHandler{ public abstract void doMapOp(Node node, Packet packet); public abstract void doListOp(Node node, Packet packet); public abstract void doSetOp(Node node, Packet packet); @Override public void processCall(Node node, Packet packet) { if(getInstanceType(packet.name).equals(InstanceType.LIST)){ doListOp(node, packet); } else if(getInstanceType(packet.name).equals(InstanceType.SET)){ doSetOp(node, packet); } else if(getInstanceType(packet.name).equals(InstanceType.MAP)){ doMapOp(node, packet); } } } private abstract class ClientTransactionOperationHandler extends ClientOperationHandler{ public abstract void processTransactionOp(Transaction transaction); public void processCall(Node node, Packet packet){ Transaction transaction = node.factory.getTransaction(); processTransactionOp(transaction); } } }
Server side Queue implementation for Hazelcast Client git-svn-id: 505f71283407c412190d59965c6d67c623df2891@703 3f8e66b6-ca9d-11dd-a2b5-e5f827957e07
hazelcast/src/main/java/com/hazelcast/impl/ClientService.java
Server side Queue implementation for Hazelcast Client
<ide><path>azelcast/src/main/java/com/hazelcast/impl/ClientService.java <ide> import static com.hazelcast.nio.IOUtil.toObject; <ide> import static com.hazelcast.impl.BaseManager.getInstanceType; <ide> <del>import com.hazelcast.core.EntryEvent; <del>import com.hazelcast.core.EntryListener; <del>import com.hazelcast.core.ICollection; <del>import com.hazelcast.core.IList; <del>import com.hazelcast.core.IMap; <del>import com.hazelcast.core.ISet; <del>import com.hazelcast.core.Instance; <del>import com.hazelcast.core.Transaction; <add>import com.hazelcast.core.*; <ide> import com.hazelcast.core.Instance.InstanceType; <ide> import com.hazelcast.impl.BaseManager.EventTask; <ide> import com.hazelcast.impl.BaseManager.KeyValue; <ide> clientOperationHandlers[ClusterOperation.CONCURRENT_MAP_UNLOCK.getValue()] = new MapUnlockHandler(); <ide> clientOperationHandlers[ClusterOperation.CONCURRENT_MAP_CONTAINS.getValue()] = new MapContainsHandler(); <ide> clientOperationHandlers[ClusterOperation.CONCURRENT_MAP_CONTAINS_VALUE.getValue()] = new MapContainsValueHandler(); <add> clientOperationHandlers[ClusterOperation.CONCURRENT_MAP_ADD_TO_LIST.getValue()] = new ListAddHandler(); <add> clientOperationHandlers[ClusterOperation.CONCURRENT_MAP_ADD_TO_SET.getValue()] = new SetAddHandler(); <add> clientOperationHandlers[ClusterOperation.CONCURRENT_MAP_REMOVE_ITEM.getValue()] = new MapItemRemoveHandler(); <add> clientOperationHandlers[ClusterOperation.CONCURRENT_MAP_ITERATE_KEYS.getValue()] = new MapIterateKeysHandler(); <add> clientOperationHandlers[ClusterOperation.BLOCKING_QUEUE_OFFER.getValue()] = new QueueOfferHandler(); <add> clientOperationHandlers[ClusterOperation.BLOCKING_QUEUE_POLL.getValue()] = new QueuePollHandler(); <add> clientOperationHandlers[ClusterOperation.BLOCKING_QUEUE_REMOVE.getValue()] = new QueueRemoveHandler(); <add> clientOperationHandlers[ClusterOperation.BLOCKING_QUEUE_PEEK.getValue()] = new QueuePeekHandler(); <add> <ide> clientOperationHandlers[ClusterOperation.TRANSACTION_BEGIN.getValue()] = new TransactionBeginHandler(); <ide> clientOperationHandlers[ClusterOperation.TRANSACTION_COMMIT.getValue()] = new TransactionCommitHandler(); <ide> clientOperationHandlers[ClusterOperation.TRANSACTION_ROLLBACK.getValue()] = new TransactionRollbackHandler(); <del> clientOperationHandlers[ClusterOperation.CONCURRENT_MAP_ITERATE_KEYS.getValue()] = new MapIterateKeysHandler(); <ide> clientOperationHandlers[ClusterOperation.ADD_LISTENER.getValue()] = new AddListenerHandler(); <ide> clientOperationHandlers[ClusterOperation.REMOVE_LISTENER.getValue()] = new RemoveListenerHandler(); <add> <ide> clientOperationHandlers[ClusterOperation.REMOTELY_PROCESS.getValue()] = new RemotelyProcessHandler(); <ide> clientOperationHandlers[ClusterOperation.DESTROY.getValue()] = new DestroyHandler(); <ide> clientOperationHandlers[ClusterOperation.GET_ID.getValue()] = new GetIdHandler(); <ide> clientOperationHandlers[ClusterOperation.ADD_INDEX.getValue()] = new AddIndexHandler(); <del> clientOperationHandlers[ClusterOperation.CONCURRENT_MAP_ADD_TO_LIST.getValue()] = new ListAddHandler(); <del> clientOperationHandlers[ClusterOperation.CONCURRENT_MAP_ADD_TO_SET.getValue()] = new SetAddHandler(); <del> clientOperationHandlers[ClusterOperation.CONCURRENT_MAP_REMOVE_ITEM.getValue()] = new MapItemRemoveHandler(); <ide> } <ide> <ide> // always called by InThread <ide> <ide> <ide> <del> <add> private class QueueOfferHandler extends ClientQueueOperationHandler{ <add> public Data processQueueOp(IQueue<Object> queue, Data key, Data value) { <add> long millis = (Long)toObject(value); <add> try { <add> if(millis==-1){ <add> queue.put(key); <add> return toData(true); <add> } <add> else if(millis == 0){ <add> return toData(queue.offer(key)); <add> }else{ <add> return toData(queue.offer(key, (Long) toObject(value), TimeUnit.MILLISECONDS)); <add> } <add> } catch (InterruptedException e) { <add> throw new RuntimeException(); <add> } <add> } <add> } <add> <add> private class QueuePollHandler extends ClientQueueOperationHandler{ <add> public Data processQueueOp(IQueue<Object> queue, Data key, Data value) { <add> try { <add> long millis = (Long)toObject(value); <add> if(millis==-1){ <add> return (Data)queue.take(); <add> } <add> else if(millis == 0){ <add> return (Data)queue.poll(); <add> }else{ <add> return (Data)queue.poll((Long) millis, TimeUnit.MILLISECONDS); <add> } <add> } catch (InterruptedException e) { <add> throw new RuntimeException(e); <add> } <add> <add> } <add> } <add> <add> private class QueueRemoveHandler extends ClientQueueOperationHandler{ <add> public Data processQueueOp(IQueue<Object> queue, Data key, Data value) { <add> return (Data)queue.remove(); <add> } <add> } <add> <add> private class QueuePeekHandler extends ClientQueueOperationHandler{ <add> public Data processQueueOp(IQueue<Object> queue, Data key, Data value) { <add> return (Data)queue.peek(); <add> } <add> } <ide> <ide> private class RemotelyProcessHandler extends ClientOperationHandler{ <ide> public void processCall(Node node, Packet packet) { <ide> } <ide> private class MapGetHandler extends ClientMapOperationHandler{ <ide> public Data processMapOp(IMap<Object, Object> map, Data key, Data value) { <del> return (Data) map.get(key); <add> return (Data)map.get(key); <ide> } <ide> } <ide> private class MapRemoveHandler extends ClientMapOperationHandler{ <ide> packet.value = value; <ide> } <ide> } <add> <add> private abstract class ClientQueueOperationHandler extends ClientOperationHandler{ <add> public abstract Data processQueueOp(IQueue<Object> queue, Data key, Data value); <add> public void processCall(Node node, Packet packet){ <add> IQueue<Object> queue = (IQueue)node.factory.getOrCreateProxyByName(packet.name); <add> Data value = processQueueOp(queue,packet.key, packet.value); <add> packet.value = value; <add> } <add> } <ide> <ide> private abstract class ClientCollectionOperationHandler extends ClientOperationHandler{ <ide>
Java
mit
853fc4c75d9bf47180ea8a8bbe5e490e2f5e54d0
0
bcvsolutions/CzechIdMng,bcvsolutions/CzechIdMng,bcvsolutions/CzechIdMng,bcvsolutions/CzechIdMng
package eu.bcvsolutions.idm.acc.security.authentication.impl; import java.io.IOException; import java.text.MessageFormat; import java.util.Date; import java.util.List; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.context.annotation.Description; import org.springframework.stereotype.Component; import org.springframework.util.Assert; import com.google.common.collect.ImmutableMap; import eu.bcvsolutions.idm.acc.AccModuleDescriptor; import eu.bcvsolutions.idm.acc.domain.AccResultCode; import eu.bcvsolutions.idm.acc.domain.SystemEntityType; import eu.bcvsolutions.idm.acc.entity.AccAccount; import eu.bcvsolutions.idm.acc.entity.SysSystem; import eu.bcvsolutions.idm.acc.entity.SysSystemAttributeMapping; import eu.bcvsolutions.idm.acc.service.api.AccAccountService; import eu.bcvsolutions.idm.acc.service.api.ProvisioningService; import eu.bcvsolutions.idm.acc.service.api.SysSystemAttributeMappingService; import eu.bcvsolutions.idm.acc.service.api.SysSystemService; import eu.bcvsolutions.idm.core.api.domain.CoreResultCode; import eu.bcvsolutions.idm.core.api.dto.IdentityDto; import eu.bcvsolutions.idm.core.api.exception.ResultCodeException; import eu.bcvsolutions.idm.core.api.service.ConfigurationService; import eu.bcvsolutions.idm.core.api.utils.EntityUtils; import eu.bcvsolutions.idm.core.model.entity.IdmIdentity; import eu.bcvsolutions.idm.core.model.service.api.IdmIdentityService; import eu.bcvsolutions.idm.core.security.api.authentication.AbstractAuthenticator; import eu.bcvsolutions.idm.core.security.api.authentication.Authenticator; import eu.bcvsolutions.idm.core.security.api.domain.AuthenticationResponseEnum; import eu.bcvsolutions.idm.core.security.api.domain.Enabled; import eu.bcvsolutions.idm.core.security.api.domain.IdmJwtAuthentication; import eu.bcvsolutions.idm.core.security.api.dto.IdmJwtAuthenticationDto; import eu.bcvsolutions.idm.core.security.api.dto.LoginDto; import eu.bcvsolutions.idm.core.security.exception.IdmAuthenticationException; import eu.bcvsolutions.idm.core.security.service.GrantedAuthoritiesFactory; import eu.bcvsolutions.idm.core.security.service.impl.DefaultLoginService; import eu.bcvsolutions.idm.core.security.service.impl.JwtAuthenticationMapper; import eu.bcvsolutions.idm.core.security.service.impl.OAuthAuthenticationManager; import eu.bcvsolutions.idm.ic.api.IcAttribute; import eu.bcvsolutions.idm.ic.api.IcConnectorObject; import eu.bcvsolutions.idm.ic.api.IcUidAttribute; import eu.bcvsolutions.idm.ic.impl.IcUidAttributeImpl; /** * Component for authenticate over system * * @author Ondrej Kopr <[email protected]> * */ @Component @Enabled(AccModuleDescriptor.MODULE_ID) @Description("ACC module authenticator, authenticate over system defined by properties.") public class DefaultAccAuthenticator extends AbstractAuthenticator implements Authenticator { private static final org.slf4j.Logger LOG = org.slf4j.LoggerFactory.getLogger(DefaultAccAuthenticator.class); public static final String PROPERTY_AUTH_SYSTEM_ID = "idm.sec.security.auth.systemId"; private static final String AUTHENTICATOR_NAME = "acc-authenticator"; private final ConfigurationService configurationService; private final SysSystemService systemService; private final ProvisioningService provisioningService; private final AccAccountService accountService; private final IdmIdentityService identityService; private final SysSystemAttributeMappingService systemAttributeMappingService; private final JwtAuthenticationMapper jwtTokenMapper; private final GrantedAuthoritiesFactory grantedAuthoritiesFactory; private final OAuthAuthenticationManager authenticationManager; @Autowired public DefaultAccAuthenticator(ConfigurationService configurationService, SysSystemService systemService, ProvisioningService provisioningService, AccAccountService accountService, IdmIdentityService identityService, SysSystemAttributeMappingService systemAttributeMappingService, JwtAuthenticationMapper jwtTokenMapper, GrantedAuthoritiesFactory grantedAuthoritiesFactory, OAuthAuthenticationManager authenticationManager) { // Assert.notNull(accountService); Assert.notNull(configurationService); Assert.notNull(systemService); Assert.notNull(provisioningService); Assert.notNull(identityService); Assert.notNull(systemAttributeMappingService); Assert.notNull(jwtTokenMapper); Assert.notNull(grantedAuthoritiesFactory); Assert.notNull(authenticationManager); // this.systemService = systemService; this.configurationService = configurationService; this.provisioningService = provisioningService; this.accountService = accountService; this.identityService = identityService; this.systemAttributeMappingService = systemAttributeMappingService; this.jwtTokenMapper = jwtTokenMapper; this.grantedAuthoritiesFactory = grantedAuthoritiesFactory; this.authenticationManager = authenticationManager; } @Override public int getOrder() { return DEFAULT_AUTHENTICATOR_ORDER + 10; } @Override public String getName() { return DefaultAccAuthenticator.AUTHENTICATOR_NAME; } @Override public String getModule() { return EntityUtils.getModule(this.getClass()); } @Override public LoginDto authenticate(LoginDto loginDto) { // temporary solution for get system id, this is not nice. String systemId = configurationService.getValue(PROPERTY_AUTH_SYSTEM_ID); if (systemId == null || systemId.isEmpty()) { return null; // without system can't check } // SysSystem system = systemService.get(systemId); // if (system == null) { return null; // system dont exist } IdmIdentity identity = identityService.getByName(loginDto.getUsername()); if (identity == null) { throw new IdmAuthenticationException(MessageFormat.format("Check identity can login: The identity [{0}] either doesn't exist or is deleted.", loginDto.getUsername())); } // // search authentication attribute for system with provisioning mapping SysSystemAttributeMapping attribute = systemAttributeMappingService.getAuthenticationAttribute(system.getId()); // if (attribute == null) { // attribute MUST exist throw new ResultCodeException(AccResultCode.AUTHENTICATION_AUTHENTICATION_ATTRIBUTE_DONT_SET, ImmutableMap.of("name", system.getName())); } // // find if identity has account on system List<AccAccount> accounts = accountService.getAccouts(system.getId(), identity.getId()); if (accounts.isEmpty()) { // user hasn't account on system, continue return null; } // ResultCodeException authFailedException = null; IcUidAttribute auth = null; // // authenticate over all accounts find first, or throw error for (AccAccount account : accounts) { IcConnectorObject connectorObject = systemService.readObject(system, attribute.getSystemMapping(), new IcUidAttributeImpl(null, account.getSystemEntity().getUid(), null)); // if (connectorObject == null) { continue; } // String transformUsername = null; // iterate over all attributes to find authentication attribute for (IcAttribute icAttribute : connectorObject.getAttributes()) { if (icAttribute.getName().equals(attribute.getSchemaAttribute().getName())) { transformUsername = String.valueOf(icAttribute.getValue()); break; } } if (transformUsername == null) { throw new ResultCodeException(AccResultCode.AUTHENTICATION_USERNAME_DONT_EXISTS, ImmutableMap.of("username", loginDto.getUsername() ,"name", system.getName())); } // other method to get username for system: String.valueOf(systemAttributeMappingService.transformValueToResource(loginDto.getUsername(), attribute, identity)); // // authentication over system, when password or username not exist or bad credentials - throw error try { // authentication against system auth = provisioningService.authenticate(transformUsername, loginDto.getPassword(), system, SystemEntityType.IDENTITY); authFailedException = null; // check auth if (auth == null || auth.getValue() == null) { authFailedException = new ResultCodeException(AccResultCode.AUTHENTICATION_AGAINST_SYSTEM_FAILED, ImmutableMap.of("name", system.getName(), "username", loginDto.getUsername())); // failed, continue to another break; } // everything success break break; } catch (ResultCodeException e) { // failed, continue to another authFailedException = new ResultCodeException(CoreResultCode.AUTH_FAILED, "Invalid login or password.", e); } } if (auth == null || auth.getValue() == null) { authFailedException = new ResultCodeException(AccResultCode.AUTHENTICATION_AGAINST_SYSTEM_FAILED, ImmutableMap.of("name", system.getName(), "username", loginDto.getUsername())); } // if (authFailedException != null) { throw authFailedException; } // // new expiration date Date expiration = new Date(System.currentTimeMillis() + configurationService.getIntegerValue(DefaultLoginService.PROPERTY_EXPIRATION_TIMEOUT, DefaultLoginService.DEFAULT_EXPIRATION_TIMEOUT)); // IdmJwtAuthentication authentication = new IdmJwtAuthentication( new IdentityDto(identity, identity.getUsername()), expiration, grantedAuthoritiesFactory.getGrantedAuthorities(loginDto.getUsername()), this.getModule()); // authenticationManager.authenticate(authentication); // LOG.info("Identity with username [{}] is authenticated on system [{}]", loginDto.getUsername(), system.getName()); // IdmJwtAuthenticationDto authenticationDto = jwtTokenMapper.toDto(authentication); // try { // set authentication module loginDto.setAuthenticationModule(this.getModule()); loginDto.setAuthentication(authenticationDto); loginDto.setToken(jwtTokenMapper.writeToken(authenticationDto)); return loginDto; } catch (IOException ex) { throw new IdmAuthenticationException(ex.getMessage(), ex); } } @Override public AuthenticationResponseEnum getExceptedResult() { return AuthenticationResponseEnum.SUFFICIENT; } }
Realization/backend/acc/src/main/java/eu/bcvsolutions/idm/acc/security/authentication/impl/DefaultAccAuthenticator.java
package eu.bcvsolutions.idm.acc.security.authentication.impl; import java.io.IOException; import java.text.MessageFormat; import java.util.Date; import java.util.List; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.context.annotation.Description; import org.springframework.stereotype.Component; import org.springframework.util.Assert; import com.google.common.collect.ImmutableMap; import eu.bcvsolutions.idm.acc.AccModuleDescriptor; import eu.bcvsolutions.idm.acc.domain.AccResultCode; import eu.bcvsolutions.idm.acc.domain.SystemEntityType; import eu.bcvsolutions.idm.acc.entity.AccAccount; import eu.bcvsolutions.idm.acc.entity.SysSystem; import eu.bcvsolutions.idm.acc.entity.SysSystemAttributeMapping; import eu.bcvsolutions.idm.acc.service.api.AccAccountService; import eu.bcvsolutions.idm.acc.service.api.ProvisioningService; import eu.bcvsolutions.idm.acc.service.api.SysSystemAttributeMappingService; import eu.bcvsolutions.idm.acc.service.api.SysSystemService; import eu.bcvsolutions.idm.core.api.domain.CoreResultCode; import eu.bcvsolutions.idm.core.api.dto.IdentityDto; import eu.bcvsolutions.idm.core.api.exception.ResultCodeException; import eu.bcvsolutions.idm.core.api.service.ConfigurationService; import eu.bcvsolutions.idm.core.api.utils.EntityUtils; import eu.bcvsolutions.idm.core.model.entity.IdmIdentity; import eu.bcvsolutions.idm.core.model.service.api.IdmIdentityService; import eu.bcvsolutions.idm.core.security.api.authentication.AbstractAuthenticator; import eu.bcvsolutions.idm.core.security.api.authentication.Authenticator; import eu.bcvsolutions.idm.core.security.api.domain.AuthenticationResponseEnum; import eu.bcvsolutions.idm.core.security.api.domain.Enabled; import eu.bcvsolutions.idm.core.security.api.domain.IdmJwtAuthentication; import eu.bcvsolutions.idm.core.security.api.dto.IdmJwtAuthenticationDto; import eu.bcvsolutions.idm.core.security.api.dto.LoginDto; import eu.bcvsolutions.idm.core.security.exception.IdmAuthenticationException; import eu.bcvsolutions.idm.core.security.service.GrantedAuthoritiesFactory; import eu.bcvsolutions.idm.core.security.service.impl.DefaultLoginService; import eu.bcvsolutions.idm.core.security.service.impl.JwtAuthenticationMapper; import eu.bcvsolutions.idm.core.security.service.impl.OAuthAuthenticationManager; import eu.bcvsolutions.idm.ic.api.IcAttribute; import eu.bcvsolutions.idm.ic.api.IcConnectorObject; import eu.bcvsolutions.idm.ic.api.IcUidAttribute; import eu.bcvsolutions.idm.ic.impl.IcUidAttributeImpl; /** * Component for authenticate over system * * @author Ondrej Kopr <[email protected]> * */ @Component @Enabled(AccModuleDescriptor.MODULE_ID) @Description("ACC module authenticator, authenticate over system defined by properties.") public class DefaultAccAuthenticator extends AbstractAuthenticator implements Authenticator { private static final org.slf4j.Logger LOG = org.slf4j.LoggerFactory.getLogger(DefaultAccAuthenticator.class); public static final String PROPERTY_AUTH_SYSTEM_ID = "idm.sec.security.auth.systemId"; private static final String AUTHENTICATOR_NAME = "acc-authenticator"; private final ConfigurationService configurationService; private final SysSystemService systemService; private final ProvisioningService provisioningService; private final AccAccountService accountService; private final IdmIdentityService identityService; private final SysSystemAttributeMappingService systemAttributeMappingService; private final JwtAuthenticationMapper jwtTokenMapper; private final GrantedAuthoritiesFactory grantedAuthoritiesFactory; private final OAuthAuthenticationManager authenticationManager; @Autowired public DefaultAccAuthenticator(ConfigurationService configurationService, SysSystemService systemService, ProvisioningService provisioningService, AccAccountService accountService, IdmIdentityService identityService, SysSystemAttributeMappingService systemAttributeMappingService, JwtAuthenticationMapper jwtTokenMapper, GrantedAuthoritiesFactory grantedAuthoritiesFactory, OAuthAuthenticationManager authenticationManager) { // Assert.notNull(accountService); Assert.notNull(configurationService); Assert.notNull(systemService); Assert.notNull(provisioningService); Assert.notNull(identityService); Assert.notNull(systemAttributeMappingService); Assert.notNull(jwtTokenMapper); Assert.notNull(grantedAuthoritiesFactory); Assert.notNull(authenticationManager); // this.systemService = systemService; this.configurationService = configurationService; this.provisioningService = provisioningService; this.accountService = accountService; this.identityService = identityService; this.systemAttributeMappingService = systemAttributeMappingService; this.jwtTokenMapper = jwtTokenMapper; this.grantedAuthoritiesFactory = grantedAuthoritiesFactory; this.authenticationManager = authenticationManager; } @Override public int getOrder() { return DEFAULT_AUTHENTICATOR_ORDER + 10; } @Override public String getName() { return DefaultAccAuthenticator.AUTHENTICATOR_NAME; } @Override public String getModule() { return EntityUtils.getModule(this.getClass()); } @Override public LoginDto authenticate(LoginDto loginDto) { // temporary solution for get system id, this is not nice. String systemId = configurationService.getValue(PROPERTY_AUTH_SYSTEM_ID); if (systemId == null || systemId.isEmpty()) { return null; // without system can't check } // SysSystem system = systemService.get(systemId); // if (system == null) { return null; // system dont exist } IdmIdentity identity = identityService.getByName(loginDto.getUsername()); if (identity == null) { throw new IdmAuthenticationException(MessageFormat.format("Check identity can login: The identity [{0}] either doesn't exist or is deleted.", loginDto.getUsername())); } // // search authentication attribute for system with provisioning mapping SysSystemAttributeMapping attribute = systemAttributeMappingService.getAuthenticationAttribute(system.getId()); // if (attribute == null) { // attribute MUST exist throw new ResultCodeException(AccResultCode.AUTHENTICATION_AUTHENTICATION_ATTRIBUTE_DONT_SET, ImmutableMap.of("name", system.getName())); } // // find if identity has account on system List<AccAccount> accounts = accountService.getAccouts(system.getId(), identity.getId()); if (accounts.isEmpty()) { // user hasn't account on system, continue return null; } // ResultCodeException authFailedException = null; IcUidAttribute auth = null; // // authenticate over all accounts find first, or throw error for (AccAccount account : accounts) { IcConnectorObject attributes = systemService.readObject(system, attribute.getSystemMapping(), new IcUidAttributeImpl(null, account.getSystemEntity().getUid(), null)); // if (attributes == null) { continue; } // String transformUsername = null; // iterate over all attributes to find authentication attribute for (IcAttribute icAttribute : attributes.getAttributes()) { if (icAttribute.getName().equals(attribute.getName())) { transformUsername = String.valueOf(icAttribute.getValue()); break; } } if (transformUsername == null) { throw new ResultCodeException(AccResultCode.AUTHENTICATION_USERNAME_DONT_EXISTS, ImmutableMap.of("username", loginDto.getUsername() ,"name", system.getName())); } // other method to get username for system: String.valueOf(systemAttributeMappingService.transformValueToResource(loginDto.getUsername(), attribute, identity)); // // authentication over system, when password or username not exist or bad credentials - throw error try { // authentication against system auth = provisioningService.authenticate(transformUsername, loginDto.getPassword(), system, SystemEntityType.IDENTITY); authFailedException = null; // check auth if (auth == null || auth.getValue() == null) { authFailedException = new ResultCodeException(AccResultCode.AUTHENTICATION_AGAINST_SYSTEM_FAILED, ImmutableMap.of("name", system.getName(), "username", loginDto.getUsername())); // failed, continue to another break; } // everything success break break; } catch (ResultCodeException e) { // failed, continue to another authFailedException = new ResultCodeException(CoreResultCode.AUTH_FAILED, "Invalid login or password.", e); } } if (auth == null || auth.getValue() == null) { authFailedException = new ResultCodeException(AccResultCode.AUTHENTICATION_AGAINST_SYSTEM_FAILED, ImmutableMap.of("name", system.getName(), "username", loginDto.getUsername())); } // if (authFailedException != null) { throw authFailedException; } // // new expiration date Date expiration = new Date(System.currentTimeMillis() + configurationService.getIntegerValue(DefaultLoginService.PROPERTY_EXPIRATION_TIMEOUT, DefaultLoginService.DEFAULT_EXPIRATION_TIMEOUT)); // IdmJwtAuthentication authentication = new IdmJwtAuthentication( new IdentityDto(identity, identity.getUsername()), expiration, grantedAuthoritiesFactory.getGrantedAuthorities(loginDto.getUsername()), this.getModule()); // authenticationManager.authenticate(authentication); // LOG.info("Identity with username [{}] is authenticated on system [{}]", loginDto.getUsername(), system.getName()); // IdmJwtAuthenticationDto authenticationDto = jwtTokenMapper.toDto(authentication); // try { // set authentication module loginDto.setAuthenticationModule(this.getModule()); loginDto.setAuthentication(authenticationDto); loginDto.setToken(jwtTokenMapper.writeToken(authenticationDto)); return loginDto; } catch (IOException ex) { throw new IdmAuthenticationException(ex.getMessage(), ex); } } @Override public AuthenticationResponseEnum getExceptedResult() { return AuthenticationResponseEnum.SUFFICIENT; } }
Fix get name for attribute in authenticator
Realization/backend/acc/src/main/java/eu/bcvsolutions/idm/acc/security/authentication/impl/DefaultAccAuthenticator.java
Fix get name for attribute in authenticator
<ide><path>ealization/backend/acc/src/main/java/eu/bcvsolutions/idm/acc/security/authentication/impl/DefaultAccAuthenticator.java <ide> // <ide> // authenticate over all accounts find first, or throw error <ide> for (AccAccount account : accounts) { <del> IcConnectorObject attributes = systemService.readObject(system, attribute.getSystemMapping(), <add> IcConnectorObject connectorObject = systemService.readObject(system, attribute.getSystemMapping(), <ide> new IcUidAttributeImpl(null, account.getSystemEntity().getUid(), null)); <ide> // <del> if (attributes == null) { <add> if (connectorObject == null) { <ide> continue; <ide> } <ide> // <ide> String transformUsername = null; <ide> // iterate over all attributes to find authentication attribute <del> for (IcAttribute icAttribute : attributes.getAttributes()) { <del> if (icAttribute.getName().equals(attribute.getName())) { <add> for (IcAttribute icAttribute : connectorObject.getAttributes()) { <add> if (icAttribute.getName().equals(attribute.getSchemaAttribute().getName())) { <ide> transformUsername = String.valueOf(icAttribute.getValue()); <ide> break; <ide> }
Java
apache-2.0
d5728c1ff891ea3cdc4a0d7d7272fcc28a955a03
0
GoogleCloudPlatform/jetty-runtime,GoogleCloudPlatform/openjdk-runtime,GoogleCloudPlatform/jetty-runtime,GoogleCloudPlatform/openjdk-runtime,GoogleCloudPlatform/openjdk-runtime,GoogleCloudPlatform/jetty-runtime,GoogleCloudPlatform/jetty-runtime
/* * Copyright 2016 Google Inc. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.apphosting.vmruntime; import static java.lang.String.valueOf; import com.google.apphosting.api.ApiProxy; import com.google.apphosting.api.ApiProxy.ApiProxyException; import com.google.apphosting.api.ApiProxy.LogRecord; import com.google.apphosting.runtime.timer.Timer; import com.google.apphosting.utils.http.HttpRequest; import java.util.Collections; import java.util.HashMap; import java.util.Map; import java.util.concurrent.Executors; import java.util.concurrent.Semaphore; import java.util.concurrent.TimeUnit; /** * Implements the ApiProxy environment when running in a Google Compute Engine VM. * * Supports instantiation within a request as well as outside the context of a request. * * Instances should be registered using ApiProxy.setEnvironmentForCurrentThread(Environment). * */ public class VmApiProxyEnvironment implements ApiProxy.Environment { public static final String USE_GLOBAL_TICKET_KEY = "GAE_USE_GLOBAL_TICKET"; public static final String CLEAR_REQUEST_TICKET_KEY = "GAE_CLEAR_REQUEST_TICKET"; // TODO(user): remove old metadata attributes once we set environment variables everywhere. public static final String PROJECT_ATTRIBUTE = "attributes/gae_project"; // A long app id is the app_id minus the partition. public static final String LONG_APP_ID_KEY = "GAE_LONG_APP_ID"; public static final String PARTITION_ATTRIBUTE = "attributes/gae_partition"; public static final String PARTITION_KEY = "GAE_PARTITION"; // the port number of the server, passed as a system env. // This is needed for the Cloud SDK to pass the real server port which is by // default 8080. In case of the real runtime this port number(appspot.com is 80). public static final String GAE_SERVER_PORT = "GAE_SERVER_PORT"; // TODO(user): Change the name to MODULE_ATTRIBUTE, as the field contains the name of the // App Engine Module. public static final String BACKEND_ATTRIBUTE = "attributes/gae_backend_name"; public static final String MODULE_NAME_KEY = "GAE_MODULE_NAME"; public static final String VERSION_ATTRIBUTE = "attributes/gae_backend_version"; public static final String VERSION_KEY = "GAE_MODULE_VERSION"; // Note: This environment variable is not set in prod and we still need to rely on metadata. public static final String INSTANCE_ATTRIBUTE = "attributes/gae_backend_instance"; public static final String INSTANCE_KEY = "GAE_MODULE_INSTANCE"; public static final String MINOR_VERSION_KEY = "GAE_MINOR_VERSION"; public static final String APPENGINE_HOSTNAME_ATTRIBUTE = "attributes/gae_appengine_hostname"; public static final String APPENGINE_HOSTNAME_KEY = "GAE_APPENGINE_HOSTNAME"; // Attribute is only for testing. public static final String USE_MVM_AGENT_ATTRIBUTE = "attributes/gae_use_nginx_proxy"; public static final String USE_MVM_AGENT_KEY = "USE_MVM_AGENT"; public static final String AFFINITY_ATTRIBUTE = "attributes/gae_affinity"; public static final String AFFINITY_ENV_KEY = "GAE_AFFINITY"; public static final String TICKET_HEADER = "X-AppEngine-Api-Ticket"; public static final String EMAIL_HEADER = "X-AppEngine-User-Email"; public static final String IS_ADMIN_HEADER = "X-AppEngine-User-Is-Admin"; public static final String AUTH_DOMAIN_HEADER = "X-AppEngine-Auth-Domain"; public static final String HTTPS_HEADER = "X-AppEngine-Https"; // Google specific annotations are commented out so we don't have to take a dependency // on the annotations lib. Please don't use these constants except for testing this class. public static final String BACKEND_ID_KEY = "com.google.appengine.backend.id"; public static final String INSTANCE_ID_KEY = "com.google.appengine.instance.id"; public static final String AFFINITY_KEY = "com.google.appengine.affinity"; public static final String REQUEST_THREAD_FACTORY_ATTR = "com.google.appengine.api.ThreadManager.REQUEST_THREAD_FACTORY"; public static final String BACKGROUND_THREAD_FACTORY_ATTR = "com.google.appengine.api.ThreadManager.BACKGROUND_THREAD_FACTORY"; // If the "X-AppEngine-Federated-Identity" header is included in the request this attribute // should be set to the boolean true, otherwise it should be set to false. public static final String IS_FEDERATED_USER_KEY = "com.google.appengine.api.users.UserService.is_federated_user"; // If the app is trusted AND the "X-AppEngine-Trusted-IP-Request" header is "1" this attribute // should be set the the boolean true, otherwise it should be set to false. public static final String IS_TRUSTED_IP_KEY = "com.google.appengine.runtime.is_trusted_ip"; public static final String IS_TRUSTED_IP_HEADER = "X-AppEngine-Trusted-IP-Request"; // Set from the nginx proxy if running. public static final String REAL_IP_HEADER = "X-Google-Real-IP"; // See flags in: java/com/google/apphosting/runtime/JavaRuntimeFactory.java // Log flush byte count boosted from 100K to 1M (same as python) to improve logging throughput. private static final long DEFAULT_FLUSH_APP_LOGS_EVERY_BYTE_COUNT = 1024 * 1024L; private static final int MAX_LOG_FLUSH_SECONDS = 60; // Keep in sync with flag in: apphosting/base/app_logs_util.cc private static final int DEFAULT_MAX_LOG_LINE_SIZE = 8 * 1024; // Control the maximum number of concurrent API calls. // https://developers.google.com/appengine/docs/python/backends/#Python_Billing_quotas_and_limits static final int MAX_CONCURRENT_API_CALLS = 100; static final int MAX_PENDING_API_CALLS = 1000; /** * Mapping from HTTP header keys to attribute keys. */ enum AttributeMapping { USER_ID( "X-AppEngine-User-Id", "com.google.appengine.api.users.UserService.user_id_key", "", false), USER_ORGANIZATION( "X-AppEngine-User-Organization", "com.google.appengine.api.users.UserService.user_organization", "", false), FEDERATED_IDENTITY( "X-AppEngine-Federated-Identity", "com.google.appengine.api.users.UserService.federated_identity", "", false), FEDERATED_PROVIDER( "X-AppEngine-Federated-Provider", "com.google.appengine.api.users.UserService.federated_authority", "", false), DATACENTER( "X-AppEngine-Datacenter", "com.google.apphosting.api.ApiProxy.datacenter", "", false), REQUEST_ID_HASH( "X-AppEngine-Request-Id-Hash", "com.google.apphosting.api.ApiProxy.request_id_hash", null, false), REQUEST_LOG_ID( "X-AppEngine-Request-Log-Id", "com.google.appengine.runtime.request_log_id", null, false), DAPPER_ID("X-Google-DapperTraceInfo", "com.google.appengine.runtime.dapper_id", null, false), CLOUD_TRACE_CONTEXT( "X-Cloud-Trace-Context", "com.google.appengine.runtime.cloud_trace_context", null, false), DEFAULT_VERSION_HOSTNAME( "X-AppEngine-Default-Version-Hostname", "com.google.appengine.runtime.default_version_hostname", null, false), DEFAULT_NAMESPACE_HEADER( "X-AppEngine-Default-Namespace", "com.google.appengine.api.NamespaceManager.appsNamespace", null, false), CURRENT_NAMESPACE_HEADER( "X-AppEngine-Current-Namespace", "com.google.appengine.api.NamespaceManager.currentNamespace", null, false), // ########## Trusted app attributes below. ############## LOAS_PEER_USERNAME( "X-AppEngine-LOAS-Peer-Username", "com.google.net.base.peer.loas_peer_username", "", true), GAIA_ID("X-AppEngine-Gaia-Id", "com.google.appengine.runtime.gaia_id", "", true), GAIA_AUTHUSER( "X-AppEngine-Gaia-Authuser", "com.google.appengine.runtime.gaia_authuser", "", true), GAIA_SESSION("X-AppEngine-Gaia-Session", "com.google.appengine.runtime.gaia_session", "", true), APPSERVER_DATACENTER( "X-AppEngine-Appserver-Datacenter", "com.google.appengine.runtime.appserver_datacenter", "", true), APPSERVER_TASK_BNS( "X-AppEngine-Appserver-Task-Bns", "com.google.appengine.runtime.appserver_task_bns", "", true), HTTPS(HTTPS_HEADER, "com.google.appengine.runtime.https", "off", false), HOST("Host", "com.google.appengine.runtime.host", null, false), ; String headerKey; String attributeKey; Object defaultValue; private final boolean trustedAppOnly; /** * Creates a mapping between an incoming request header and the thread local request attribute * corresponding to that header. * * @param headerKey The HTTP header key. * @param attributeKey The attribute key. * @param defaultValue The default value to set if the header is missing, or null if no * attribute should be set when the header is missing. * @param trustedAppOnly If true the attribute should only be set for trusted apps. */ AttributeMapping( String headerKey, String attributeKey, Object defaultValue, boolean trustedAppOnly) { this.headerKey = headerKey; this.attributeKey = attributeKey; this.defaultValue = defaultValue; this.trustedAppOnly = trustedAppOnly; } } /** * Helper method to use during the transition from metadata to environment variables. * * @param environmentMap the environment * @param envKey the name of the environment variable to check first. * @param metadataPath the path of the metadata server entry to use as fallback. * @param cache the metadata server cache. * @return If set the environment variable corresponding to envKey, the metadata entry otherwise. */ public static String getEnvOrMetadata( Map<String, String> environmentMap, VmMetadataCache cache, String envKey, String metadataPath) { String envValue = environmentMap.get(envKey); return envValue != null ? envValue : cache.getMetadata(metadataPath); } /** * Helper method to get a System Property or if not found, an Env variable or if * not found a default value. * * @param environmentMap the environment * @param envKey the name of the environment variable and System Property * @param dftValue the default value * @return the System property or Env variable is true */ public static String getSystemPropertyOrEnv( Map<String, String> environmentMap, String envKey, String dftValue) { return System.getProperty(envKey, environmentMap.getOrDefault(envKey, dftValue)); } /** * Helper method to get a boolean from a System Property or if not found, an Env * variable or if not found a default value. * * @param environmentMap the environment * @param envKey the name of the environment variable and System Property * @param dftValue the default value * @return true if the System property or Env variable is true */ public static boolean getSystemPropertyOrEnvBoolean( Map<String, String> environmentMap, String envKey, boolean dftValue) { return Boolean.valueOf(getSystemPropertyOrEnv(environmentMap, envKey, valueOf(dftValue))); } /** * Creates an environment for AppEngine API calls outside the context of a request. * * @param envMap a map containing environment variables (from System.getenv()). * @param cache the VM meta-data cache used to retrieve VM attributes. * @param server the host:port where the VMs API proxy is bound to. * @param wallTimer optional wall clock timer for the current request (required for deadline). * @param millisUntilSoftDeadline optional soft deadline in milliseconds relative to 'wallTimer'. * @param appDir the canonical folder of the application. * @return the created Environment object which can be registered with the ApiProxy. */ public static VmApiProxyEnvironment createDefaultContext( Map<String, String> envMap, VmMetadataCache cache, String server, Timer wallTimer, Long millisUntilSoftDeadline, String appDir) { final String longAppId = getEnvOrMetadata(envMap, cache, LONG_APP_ID_KEY, PROJECT_ATTRIBUTE); final String partition = getEnvOrMetadata(envMap, cache, PARTITION_KEY, PARTITION_ATTRIBUTE); final String module = getEnvOrMetadata(envMap, cache, MODULE_NAME_KEY, BACKEND_ATTRIBUTE); final String majorVersion = getEnvOrMetadata(envMap, cache, VERSION_KEY, VERSION_ATTRIBUTE); String minorVersion = envMap.get(MINOR_VERSION_KEY); if (minorVersion == null) { minorVersion = VmRuntimeUtils.getMinorVersionFromPath(majorVersion, appDir); } final String instance = getEnvOrMetadata(envMap, cache, INSTANCE_KEY, INSTANCE_ATTRIBUTE); final String affinity = getEnvOrMetadata(envMap, cache, AFFINITY_ENV_KEY, AFFINITY_ATTRIBUTE); final String appengineHostname = getEnvOrMetadata(envMap, cache, APPENGINE_HOSTNAME_KEY, APPENGINE_HOSTNAME_ATTRIBUTE); final String ticket = null; final String email = null; final boolean admin = false; final String authDomain = null; final boolean useMvmAgent = Boolean.parseBoolean( getEnvOrMetadata(envMap, cache, USE_MVM_AGENT_KEY, USE_MVM_AGENT_ATTRIBUTE)); Map<String, Object> attributes = new HashMap<>(); // Fill in default attributes values. for (AttributeMapping mapping : AttributeMapping.values()) { if (mapping.trustedAppOnly) { continue; } if (mapping.defaultValue == null) { continue; } attributes.put(mapping.attributeKey, mapping.defaultValue); } attributes.put(IS_FEDERATED_USER_KEY, Boolean.FALSE); attributes.put(BACKEND_ID_KEY, module); attributes.put(INSTANCE_ID_KEY, instance); attributes.put(AFFINITY_KEY, affinity); VmApiProxyEnvironment defaultEnvironment = new VmApiProxyEnvironment( server, ticket, longAppId, partition, module, majorVersion, minorVersion, instance, appengineHostname, email, admin, authDomain, useMvmAgent, wallTimer, millisUntilSoftDeadline, attributes); // Add the thread factories required by the threading API. attributes.put(REQUEST_THREAD_FACTORY_ATTR, new VmRequestThreadFactory(null)); // Since we register VmEnvironmentFactory with ApiProxy in VmRuntimeWebAppContext, // we can use the default thread factory here and don't require any special logic. attributes.put(BACKGROUND_THREAD_FACTORY_ATTR, Executors.defaultThreadFactory()); return defaultEnvironment; } /** * Create an environment for AppEngine API calls in the context of a request. * * @param envMap a map containing environment variables (from System.getenv()). * @param cache the VM meta-data cache used to retrieve VM attributes. * @param request the HTTP request to get header values from. * @param server the host:port where the VMs API proxy is bound to. * @param wallTimer optional wall clock timer for the current request (required for deadline). * @param millisUntilSoftDeadline optional soft deadline in milliseconds relative to 'wallTimer'. * @return the created Environment object which can be registered with the ApiProxy. */ public static VmApiProxyEnvironment createFromHeaders( Map<String, String> envMap, VmMetadataCache cache, HttpRequest request, String server, Timer wallTimer, Long millisUntilSoftDeadline, VmApiProxyEnvironment defaultEnvironment) { final String longAppId = getEnvOrMetadata(envMap, cache, LONG_APP_ID_KEY, PROJECT_ATTRIBUTE); final String partition = getEnvOrMetadata(envMap, cache, PARTITION_KEY, PARTITION_ATTRIBUTE); final String module = getEnvOrMetadata(envMap, cache, MODULE_NAME_KEY, BACKEND_ATTRIBUTE); final String majorVersion = defaultEnvironment.getMajorVersion(); final String minorVersion = defaultEnvironment.getMinorVersion(); final String appengineHostname = defaultEnvironment.getAppengineHostname(); final boolean useMvmAgent = defaultEnvironment.getUseMvmAgent(); final String instance = getEnvOrMetadata(envMap, cache, INSTANCE_KEY, INSTANCE_ATTRIBUTE); final String affinity = getEnvOrMetadata(envMap, cache, AFFINITY_ENV_KEY, AFFINITY_ATTRIBUTE); final String ticket = getSystemPropertyOrEnvBoolean(envMap, USE_GLOBAL_TICKET_KEY, true) ? null : request.getHeader(TICKET_HEADER); final String email = request.getHeader(EMAIL_HEADER); boolean admin = false; String value = request.getHeader(IS_ADMIN_HEADER); if (value != null && !value.trim().isEmpty()) { try { admin = Integer.parseInt(value.trim()) != 0; } catch (NumberFormatException e) { throw new IllegalArgumentException(e.getMessage(), e); } } final String authDomain = request.getHeader(AUTH_DOMAIN_HEADER); boolean trustedApp = request.getHeader(IS_TRUSTED_IP_HEADER) != null; Map<String, Object> attributes = new HashMap<>(); // Fill in the attributes from the AttributeMapping. for (AttributeMapping mapping : AttributeMapping.values()) { if (mapping.trustedAppOnly && !trustedApp) { // Do not fill in any trusted app attributes unless the app is trusted. continue; } String headerValue = request.getHeader(mapping.headerKey); if (headerValue != null) { attributes.put(mapping.attributeKey, headerValue); } else if (mapping.defaultValue != null) { attributes.put(mapping.attributeKey, mapping.defaultValue); } // else: The attribute is expected to be missing if the header is not set. } // Fill in the special attributes that do not fit the simple mapping model. boolean federatedId = request.getHeader(AttributeMapping.FEDERATED_IDENTITY.headerKey) != null; attributes.put(IS_FEDERATED_USER_KEY, federatedId); attributes.put(BACKEND_ID_KEY, module); attributes.put(INSTANCE_ID_KEY, instance); attributes.put(AFFINITY_KEY, affinity); if (trustedApp) { // The trusted IP attribute is a boolean. boolean trustedIp = "1".equals(request.getHeader(IS_TRUSTED_IP_HEADER)); attributes.put(IS_TRUSTED_IP_KEY, trustedIp); } VmApiProxyEnvironment requestEnvironment = new VmApiProxyEnvironment( server, ticket, longAppId, partition, module, majorVersion, minorVersion, instance, appengineHostname, email, admin, authDomain, useMvmAgent, wallTimer, millisUntilSoftDeadline, attributes); // Add the thread factories required by the threading API. attributes.put(REQUEST_THREAD_FACTORY_ATTR, new VmRequestThreadFactory(requestEnvironment)); // Since we register VmEnvironmentFactory with ApiProxy in VmRuntimeWebAppContext, // we can use the default thread factory here and don't require any special logic. attributes.put(BACKGROUND_THREAD_FACTORY_ATTR, Executors.defaultThreadFactory()); return requestEnvironment; } private final String server; private volatile String ticket; // request ticket is only valid until response is committed. private volatile String globalTicket; // global ticket is always valid private final int serverPort; private final String partition; private final String appId; private final String module; private final String majorVersion; private final String minorVersion; private final String versionId; private final String appengineHostname; private final String l7UnsafeRedirectUrl; private final String email; private final boolean admin; private final String authDomain; private final boolean useMvmAgent; private final Map<String, Object> attributes; private ThreadLocal<Map<String, Object>> threadLocalAttributes; private final Timer wallTimer; // may be null if millisUntilSoftDeadline is null. private final Long millisUntilSoftDeadline; // may be null (no deadline). final Semaphore pendingApiCallSemaphore; final Semaphore runningApiCallSemaphore; /** * Constructs a VM AppEngine API environment. * * @param server the host:port address of the VM's HTTP proxy server. * @param ticket the request ticket (if null the default one will be computed). * @param appId the application ID (required if ticket is null). * @param partition the partition name. * @param module the module name (required if ticket is null). * @param majorVersion the major application version (required if ticket is null). * @param minorVersion the minor application version. * @param instance the VM instance ID (required if ticket is null). * @param appengineHostname the app's appengine hostname. * @param email the user's e-mail address (may be null). * @param admin true if the user is an administrator. * @param authDomain the user's authentication domain (may be null). * @param useMvmAgent if true, the mvm agent is in use. * @param wallTimer optional wall clock timer for the current request (required for deadline). * @param millisUntilSoftDeadline optional soft deadline in milliseconds relative to 'wallTimer'. * @param attributes map containing any attributes set on this environment. */ private VmApiProxyEnvironment( String server, String ticket, String appId, String partition, String module, String majorVersion, String minorVersion, String instance, String appengineHostname, String email, boolean admin, String authDomain, boolean useMvmAgent, Timer wallTimer, Long millisUntilSoftDeadline, Map<String, Object> attributes) { if (server == null || server.isEmpty()) { throw new IllegalArgumentException("proxy server host:port must be specified"); } if (millisUntilSoftDeadline != null && wallTimer == null) { throw new IllegalArgumentException("wallTimer required when setting millisUntilSoftDeadline"); } this.ticket = ticket; if ((appId == null || appId.isEmpty()) || (module == null || module.isEmpty()) || (majorVersion == null || majorVersion.isEmpty()) || (instance == null || instance.isEmpty())) { throw new IllegalArgumentException( "When ticket == null, the following must be specified: appId=" + appId + ", module=" + module + ", version=" + majorVersion + ", instance=" + instance); } String escapedAppId = appId.replace(':', '_').replace('.', '_'); this.globalTicket = escapedAppId + '/' + module + '.' + majorVersion + "." + instance; this.server = server; this.partition = partition; String port = System.getenv(GAE_SERVER_PORT) == null ? System.getProperty("GAE_SERVER_PORT", "80") : System.getenv(GAE_SERVER_PORT); this.serverPort = Integer.decode(port); this.appId = partition + "~" + appId; this.module = module == null ? "default" : module; this.majorVersion = majorVersion == null ? "" : majorVersion; this.minorVersion = minorVersion == null ? "" : minorVersion; this.versionId = String.format("%s.%s", this.majorVersion, this.minorVersion); this.appengineHostname = appengineHostname; this.l7UnsafeRedirectUrl = String.format( "https://%s-dot-%s-dot-%s", this.majorVersion, this.module, this.appengineHostname); this.email = email == null ? "" : email; this.admin = admin; this.authDomain = authDomain == null ? "" : authDomain; this.useMvmAgent = useMvmAgent; this.wallTimer = wallTimer; this.millisUntilSoftDeadline = millisUntilSoftDeadline; // Environments are associated with requests, and can be // shared across more than one thread. We'll synchronize all // individual calls which should be sufficient. this.attributes = Collections.synchronizedMap(attributes); // TODO(user): forward app_log_line_size, app_log_group_size, max_log_flush_seconds // from clone_settings so these can be overridden per app. this.pendingApiCallSemaphore = new Semaphore(MAX_PENDING_API_CALLS); this.runningApiCallSemaphore = new Semaphore(MAX_CONCURRENT_API_CALLS); } @Deprecated public void addLogRecord(LogRecord record) {} @Deprecated public int flushLogs() { return -1; } public String getMajorVersion() { return majorVersion; } public String getMinorVersion() { return minorVersion; } public String getAppengineHostname() { return appengineHostname; } public String getL7UnsafeRedirectUrl() { return l7UnsafeRedirectUrl; } public String getServer() { return server; } public void clearTicket() { ticket = null; } public boolean isRequestTicket() { String requestTicket = ticket; return requestTicket != null && !requestTicket.isEmpty(); } public String getTicket() { String requestTicket = ticket; return (requestTicket != null && !requestTicket.isEmpty()) ? requestTicket : globalTicket; } public String getPartition() { return partition; } public int getServerPort() { return serverPort; } @Override public String getAppId() { return appId; } @Override public String getModuleId() { return module; } @Override public String getVersionId() { return versionId; } @Override public String getEmail() { return email; } @Override public boolean isLoggedIn() { return getEmail() != null && !getEmail().trim().isEmpty(); } @Override public boolean isAdmin() { return admin; } @Override public String getAuthDomain() { return authDomain; } public boolean getUseMvmAgent() { return useMvmAgent; } @Deprecated @Override public String getRequestNamespace() { Object currentNamespace = attributes.get(AttributeMapping.CURRENT_NAMESPACE_HEADER.attributeKey); if (currentNamespace instanceof String) { return (String) currentNamespace; } return ""; } /*** * Create a thread-local copy of the attributes. Used for the instance of this class that is * shared among all the background threads. They each may mutate the attributes independently. */ public synchronized void setThreadLocalAttributes() { if (threadLocalAttributes == null) { threadLocalAttributes = new ThreadLocal<>(); } threadLocalAttributes.set(new HashMap<>(attributes)); } @Override public Map<String, Object> getAttributes() { if (threadLocalAttributes != null && threadLocalAttributes.get() != null) { // If a thread-local copy of the attributes exists, return it. return threadLocalAttributes.get(); } else { // Otherwise this is not a shared instance and/or we were never told to store // a thread-local copy. So we just return the attributes that were used to originally // construct the instance. return attributes; } } @Override public long getRemainingMillis() { if (millisUntilSoftDeadline == null) { return Long.MAX_VALUE; } return millisUntilSoftDeadline - (wallTimer.getNanoseconds() / 1000000L); } /** * Notifies the environment that an API call was queued up. */ void asyncApiCallAdded(long maxWaitMs) throws ApiProxyException { try { if (pendingApiCallSemaphore.tryAcquire(maxWaitMs, TimeUnit.MILLISECONDS)) { return; // All good. } throw new ApiProxyException("Timed out while acquiring a pending API call semaphore."); } catch (InterruptedException e) { throw new ApiProxyException( "Thread interrupted while acquiring a pending API call semaphore."); } } /** * Notifies the environment that an API call was started. * * @param releasePendingCall If true a pending call semaphore will be released (required if this * API call was requested asynchronously). * * @throws ApiProxyException If the thread was interrupted while waiting for a semaphore. */ void apiCallStarted(long maxWaitMs, boolean releasePendingCall) throws ApiProxyException { try { if (runningApiCallSemaphore.tryAcquire(maxWaitMs, TimeUnit.MILLISECONDS)) { return; // All good. } throw new ApiProxyException("Timed out while acquiring an API call semaphore."); } catch (InterruptedException e) { throw new ApiProxyException("Thread interrupted while acquiring an API call semaphore."); } finally { if (releasePendingCall) { pendingApiCallSemaphore.release(); } } } /** * Notifies the environment that an API call completed. */ void apiCallCompleted() { runningApiCallSemaphore.release(); } /** * Waits for up to {@code maxWaitMs} ms for all outstanding API calls to complete. * * @param maxWaitMs The maximum time to wait. * @return True if the all calls completed before the timeout fired or the thread was interrupted. * False otherwise. */ public boolean waitForAllApiCallsToComplete(long maxWaitMs) { try { long startTime = System.currentTimeMillis(); if (pendingApiCallSemaphore.tryAcquire( MAX_PENDING_API_CALLS, maxWaitMs, TimeUnit.MILLISECONDS)) { // Release the acquired semaphores in finally {} to guarantee that they are returned. try { long remaining = maxWaitMs - (System.currentTimeMillis() - startTime); if (runningApiCallSemaphore.tryAcquire( MAX_CONCURRENT_API_CALLS, remaining, TimeUnit.MILLISECONDS)) { runningApiCallSemaphore.release(MAX_CONCURRENT_API_CALLS); return true; } } finally { pendingApiCallSemaphore.release(MAX_PENDING_API_CALLS); } } } catch (InterruptedException ignored) { // The error message is printed by the caller. } return false; } public String getTraceId() { Object value = getAttributes() .get(VmApiProxyEnvironment.AttributeMapping.CLOUD_TRACE_CONTEXT.attributeKey); if (!(value instanceof String)) { return null; } String fullTraceId = (String) value; // Extract the trace id from the header. // TODO(user, qike): Use the code from the Trace SDK when it's available in /third_party. if (fullTraceId.isEmpty() || Character.digit(fullTraceId.charAt(0), 16) < 0) { return null; } for (int index = 1; index < fullTraceId.length(); index++) { char ch = fullTraceId.charAt(index); if (Character.digit(ch, 16) < 0) { return fullTraceId.substring(0, index); } } return null; } }
appengine-managed-runtime/src/main/java/com/google/apphosting/vmruntime/VmApiProxyEnvironment.java
/* * Copyright 2016 Google Inc. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.apphosting.vmruntime; import static java.lang.String.valueOf; import com.google.apphosting.api.ApiProxy; import com.google.apphosting.api.ApiProxy.ApiProxyException; import com.google.apphosting.api.ApiProxy.LogRecord; import com.google.apphosting.runtime.timer.Timer; import com.google.apphosting.utils.http.HttpRequest; import java.util.Collections; import java.util.HashMap; import java.util.Map; import java.util.concurrent.Executors; import java.util.concurrent.Semaphore; import java.util.concurrent.TimeUnit; /** * Implements the ApiProxy environment when running in a Google Compute Engine VM. * * Supports instantiation within a request as well as outside the context of a request. * * Instances should be registered using ApiProxy.setEnvironmentForCurrentThread(Environment). * */ public class VmApiProxyEnvironment implements ApiProxy.Environment { public static final String USE_GLOBAL_TICKET_KEY = "GAE_USE_GLOBAL_TICKET"; public static final String CLEAR_REQUEST_TICKET_KEY = "GAE_CLEAR_REQUEST_TICKET"; // TODO(user): remove old metadata attributes once we set environment variables everywhere. public static final String PROJECT_ATTRIBUTE = "attributes/gae_project"; // A long app id is the app_id minus the partition. public static final String LONG_APP_ID_KEY = "GAE_LONG_APP_ID"; public static final String PARTITION_ATTRIBUTE = "attributes/gae_partition"; public static final String PARTITION_KEY = "GAE_PARTITION"; // the port number of the server, passed as a system env. // This is needed for the Cloud SDK to pass the real server port which is by // default 8080. In case of the real runtime this port number(appspot.com is 80). public static final String GAE_SERVER_PORT = "GAE_SERVER_PORT"; // TODO(user): Change the name to MODULE_ATTRIBUTE, as the field contains the name of the // App Engine Module. public static final String BACKEND_ATTRIBUTE = "attributes/gae_backend_name"; public static final String MODULE_NAME_KEY = "GAE_MODULE_NAME"; public static final String VERSION_ATTRIBUTE = "attributes/gae_backend_version"; public static final String VERSION_KEY = "GAE_MODULE_VERSION"; // Note: This environment variable is not set in prod and we still need to rely on metadata. public static final String INSTANCE_ATTRIBUTE = "attributes/gae_backend_instance"; public static final String INSTANCE_KEY = "GAE_MODULE_INSTANCE"; public static final String MINOR_VERSION_KEY = "GAE_MINOR_VERSION"; public static final String APPENGINE_HOSTNAME_ATTRIBUTE = "attributes/gae_appengine_hostname"; public static final String APPENGINE_HOSTNAME_KEY = "GAE_APPENGINE_HOSTNAME"; // Attribute is only for testing. public static final String USE_MVM_AGENT_ATTRIBUTE = "attributes/gae_use_nginx_proxy"; public static final String USE_MVM_AGENT_KEY = "USE_MVM_AGENT"; public static final String AFFINITY_ATTRIBUTE = "attributes/gae_affinity"; public static final String AFFINITY_ENV_KEY = "GAE_AFFINITY"; public static final String TICKET_HEADER = "X-AppEngine-Api-Ticket"; public static final String EMAIL_HEADER = "X-AppEngine-User-Email"; public static final String IS_ADMIN_HEADER = "X-AppEngine-User-Is-Admin"; public static final String AUTH_DOMAIN_HEADER = "X-AppEngine-Auth-Domain"; public static final String HTTPS_HEADER = "X-AppEngine-Https"; // Google specific annotations are commented out so we don't have to take a dependency // on the annotations lib. Please don't use these constants except for testing this class. public static final String BACKEND_ID_KEY = "com.google.appengine.backend.id"; public static final String INSTANCE_ID_KEY = "com.google.appengine.instance.id"; public static final String AFFINITY_KEY = "com.google.appengine.affinity"; public static final String REQUEST_THREAD_FACTORY_ATTR = "com.google.appengine.api.ThreadManager.REQUEST_THREAD_FACTORY"; public static final String BACKGROUND_THREAD_FACTORY_ATTR = "com.google.appengine.api.ThreadManager.BACKGROUND_THREAD_FACTORY"; // If the "X-AppEngine-Federated-Identity" header is included in the request this attribute // should be set to the boolean true, otherwise it should be set to false. public static final String IS_FEDERATED_USER_KEY = "com.google.appengine.api.users.UserService.is_federated_user"; // If the app is trusted AND the "X-AppEngine-Trusted-IP-Request" header is "1" this attribute // should be set the the boolean true, otherwise it should be set to false. public static final String IS_TRUSTED_IP_KEY = "com.google.appengine.runtime.is_trusted_ip"; public static final String IS_TRUSTED_IP_HEADER = "X-AppEngine-Trusted-IP-Request"; // Set from the nginx proxy if running. public static final String REAL_IP_HEADER = "X-Google-Real-IP"; // See flags in: java/com/google/apphosting/runtime/JavaRuntimeFactory.java // Log flush byte count boosted from 100K to 1M (same as python) to improve logging throughput. private static final long DEFAULT_FLUSH_APP_LOGS_EVERY_BYTE_COUNT = 1024 * 1024L; private static final int MAX_LOG_FLUSH_SECONDS = 60; // Keep in sync with flag in: apphosting/base/app_logs_util.cc private static final int DEFAULT_MAX_LOG_LINE_SIZE = 8 * 1024; // Control the maximum number of concurrent API calls. // https://developers.google.com/appengine/docs/python/backends/#Python_Billing_quotas_and_limits static final int MAX_CONCURRENT_API_CALLS = 100; static final int MAX_PENDING_API_CALLS = 1000; /** * Mapping from HTTP header keys to attribute keys. */ enum AttributeMapping { USER_ID( "X-AppEngine-User-Id", "com.google.appengine.api.users.UserService.user_id_key", "", false), USER_ORGANIZATION( "X-AppEngine-User-Organization", "com.google.appengine.api.users.UserService.user_organization", "", false), FEDERATED_IDENTITY( "X-AppEngine-Federated-Identity", "com.google.appengine.api.users.UserService.federated_identity", "", false), FEDERATED_PROVIDER( "X-AppEngine-Federated-Provider", "com.google.appengine.api.users.UserService.federated_authority", "", false), DATACENTER( "X-AppEngine-Datacenter", "com.google.apphosting.api.ApiProxy.datacenter", "", false), REQUEST_ID_HASH( "X-AppEngine-Request-Id-Hash", "com.google.apphosting.api.ApiProxy.request_id_hash", null, false), REQUEST_LOG_ID( "X-AppEngine-Request-Log-Id", "com.google.appengine.runtime.request_log_id", null, false), DAPPER_ID("X-Google-DapperTraceInfo", "com.google.appengine.runtime.dapper_id", null, false), CLOUD_TRACE_CONTEXT( "X-Cloud-Trace-Context", "com.google.appengine.runtime.cloud_trace_context", null, false), DEFAULT_VERSION_HOSTNAME( "X-AppEngine-Default-Version-Hostname", "com.google.appengine.runtime.default_version_hostname", null, false), DEFAULT_NAMESPACE_HEADER( "X-AppEngine-Default-Namespace", "com.google.appengine.api.NamespaceManager.appsNamespace", null, false), CURRENT_NAMESPACE_HEADER( "X-AppEngine-Current-Namespace", "com.google.appengine.api.NamespaceManager.currentNamespace", null, false), // ########## Trusted app attributes below. ############## LOAS_PEER_USERNAME( "X-AppEngine-LOAS-Peer-Username", "com.google.net.base.peer.loas_peer_username", "", true), GAIA_ID("X-AppEngine-Gaia-Id", "com.google.appengine.runtime.gaia_id", "", true), GAIA_AUTHUSER( "X-AppEngine-Gaia-Authuser", "com.google.appengine.runtime.gaia_authuser", "", true), GAIA_SESSION("X-AppEngine-Gaia-Session", "com.google.appengine.runtime.gaia_session", "", true), APPSERVER_DATACENTER( "X-AppEngine-Appserver-Datacenter", "com.google.appengine.runtime.appserver_datacenter", "", true), APPSERVER_TASK_BNS( "X-AppEngine-Appserver-Task-Bns", "com.google.appengine.runtime.appserver_task_bns", "", true), HTTPS(HTTPS_HEADER, "com.google.appengine.runtime.https", "off", false), HOST("Host", "com.google.appengine.runtime.host", null, false), ; String headerKey; String attributeKey; Object defaultValue; private final boolean trustedAppOnly; /** * Creates a mapping between an incoming request header and the thread local request attribute * corresponding to that header. * * @param headerKey The HTTP header key. * @param attributeKey The attribute key. * @param defaultValue The default value to set if the header is missing, or null if no * attribute should be set when the header is missing. * @param trustedAppOnly If true the attribute should only be set for trusted apps. */ AttributeMapping( String headerKey, String attributeKey, Object defaultValue, boolean trustedAppOnly) { this.headerKey = headerKey; this.attributeKey = attributeKey; this.defaultValue = defaultValue; this.trustedAppOnly = trustedAppOnly; } } /** * Helper method to use during the transition from metadata to environment variables. * * @param environmentMap the environment * @param envKey the name of the environment variable to check first. * @param metadataPath the path of the metadata server entry to use as fallback. * @param cache the metadata server cache. * @return If set the environment variable corresponding to envKey, the metadata entry otherwise. */ public static String getEnvOrMetadata( Map<String, String> environmentMap, VmMetadataCache cache, String envKey, String metadataPath) { String envValue = environmentMap.get(envKey); return envValue != null ? envValue : cache.getMetadata(metadataPath); } /** * Helper method to get a System Property or if not found, an Env variable or if * not found a default value. * * @param environmentMap the environment * @param envKey the name of the environment variable and System Property * @param dftValue the default value * @return the System property or Env variable is true */ public static String getSystemPropertyOrEnv( Map<String, String> environmentMap, String envKey, String dftValue) { return System.getProperty(envKey, environmentMap.getOrDefault(envKey, dftValue)); } /** * Helper method to get a boolean from a System Property or if not found, an Env * variable or if not found a default value. * * @param environmentMap the environment * @param envKey the name of the environment variable and System Property * @param dftValue the default value * @return true if the System property or Env variable is true */ public static boolean getSystemPropertyOrEnvBoolean( Map<String, String> environmentMap, String envKey, boolean dftValue) { return Boolean.valueOf(getSystemPropertyOrEnv(environmentMap, envKey, valueOf(dftValue))); } /** * Creates an environment for AppEngine API calls outside the context of a request. * * @param envMap a map containing environment variables (from System.getenv()). * @param cache the VM meta-data cache used to retrieve VM attributes. * @param server the host:port where the VMs API proxy is bound to. * @param wallTimer optional wall clock timer for the current request (required for deadline). * @param millisUntilSoftDeadline optional soft deadline in milliseconds relative to 'wallTimer'. * @param appDir the canonical folder of the application. * @return the created Environment object which can be registered with the ApiProxy. */ public static VmApiProxyEnvironment createDefaultContext( Map<String, String> envMap, VmMetadataCache cache, String server, Timer wallTimer, Long millisUntilSoftDeadline, String appDir) { final String longAppId = getEnvOrMetadata(envMap, cache, LONG_APP_ID_KEY, PROJECT_ATTRIBUTE); final String partition = getEnvOrMetadata(envMap, cache, PARTITION_KEY, PARTITION_ATTRIBUTE); final String module = getEnvOrMetadata(envMap, cache, MODULE_NAME_KEY, BACKEND_ATTRIBUTE); final String majorVersion = getEnvOrMetadata(envMap, cache, VERSION_KEY, VERSION_ATTRIBUTE); String minorVersion = envMap.get(MINOR_VERSION_KEY); if (minorVersion == null) { minorVersion = VmRuntimeUtils.getMinorVersionFromPath(majorVersion, appDir); } final String instance = getEnvOrMetadata(envMap, cache, INSTANCE_KEY, INSTANCE_ATTRIBUTE); final String affinity = getEnvOrMetadata(envMap, cache, AFFINITY_ENV_KEY, AFFINITY_ATTRIBUTE); final String appengineHostname = getEnvOrMetadata(envMap, cache, APPENGINE_HOSTNAME_KEY, APPENGINE_HOSTNAME_ATTRIBUTE); final String ticket = null; final String email = null; final boolean admin = false; final String authDomain = null; final boolean useMvmAgent = Boolean.parseBoolean( getEnvOrMetadata(envMap, cache, USE_MVM_AGENT_KEY, USE_MVM_AGENT_ATTRIBUTE)); Map<String, Object> attributes = new HashMap<>(); // Fill in default attributes values. for (AttributeMapping mapping : AttributeMapping.values()) { if (mapping.trustedAppOnly) { continue; } if (mapping.defaultValue == null) { continue; } attributes.put(mapping.attributeKey, mapping.defaultValue); } attributes.put(IS_FEDERATED_USER_KEY, Boolean.FALSE); attributes.put(BACKEND_ID_KEY, module); attributes.put(INSTANCE_ID_KEY, instance); attributes.put(AFFINITY_KEY, affinity); VmApiProxyEnvironment defaultEnvironment = new VmApiProxyEnvironment( server, ticket, longAppId, partition, module, majorVersion, minorVersion, instance, appengineHostname, email, admin, authDomain, useMvmAgent, wallTimer, millisUntilSoftDeadline, attributes); // Add the thread factories required by the threading API. attributes.put(REQUEST_THREAD_FACTORY_ATTR, new VmRequestThreadFactory(null)); // Since we register VmEnvironmentFactory with ApiProxy in VmRuntimeWebAppContext, // we can use the default thread factory here and don't require any special logic. attributes.put(BACKGROUND_THREAD_FACTORY_ATTR, Executors.defaultThreadFactory()); return defaultEnvironment; } /** * Create an environment for AppEngine API calls in the context of a request. * * @param envMap a map containing environment variables (from System.getenv()). * @param cache the VM meta-data cache used to retrieve VM attributes. * @param request the HTTP request to get header values from. * @param server the host:port where the VMs API proxy is bound to. * @param wallTimer optional wall clock timer for the current request (required for deadline). * @param millisUntilSoftDeadline optional soft deadline in milliseconds relative to 'wallTimer'. * @return the created Environment object which can be registered with the ApiProxy. */ public static VmApiProxyEnvironment createFromHeaders( Map<String, String> envMap, VmMetadataCache cache, HttpRequest request, String server, Timer wallTimer, Long millisUntilSoftDeadline, VmApiProxyEnvironment defaultEnvironment) { final String longAppId = getEnvOrMetadata(envMap, cache, LONG_APP_ID_KEY, PROJECT_ATTRIBUTE); final String partition = getEnvOrMetadata(envMap, cache, PARTITION_KEY, PARTITION_ATTRIBUTE); final String module = getEnvOrMetadata(envMap, cache, MODULE_NAME_KEY, BACKEND_ATTRIBUTE); final String majorVersion = defaultEnvironment.getMajorVersion(); final String minorVersion = defaultEnvironment.getMinorVersion(); final String appengineHostname = defaultEnvironment.getAppengineHostname(); final boolean useMvmAgent = defaultEnvironment.getUseMvmAgent(); final String instance = getEnvOrMetadata(envMap, cache, INSTANCE_KEY, INSTANCE_ATTRIBUTE); final String affinity = getEnvOrMetadata(envMap, cache, AFFINITY_ENV_KEY, AFFINITY_ATTRIBUTE); final String ticket = getSystemPropertyOrEnvBoolean(envMap, USE_GLOBAL_TICKET_KEY, false) ? null : request.getHeader(TICKET_HEADER); final String email = request.getHeader(EMAIL_HEADER); boolean admin = false; String value = request.getHeader(IS_ADMIN_HEADER); if (value != null && !value.trim().isEmpty()) { try { admin = Integer.parseInt(value.trim()) != 0; } catch (NumberFormatException e) { throw new IllegalArgumentException(e.getMessage(), e); } } final String authDomain = request.getHeader(AUTH_DOMAIN_HEADER); boolean trustedApp = request.getHeader(IS_TRUSTED_IP_HEADER) != null; Map<String, Object> attributes = new HashMap<>(); // Fill in the attributes from the AttributeMapping. for (AttributeMapping mapping : AttributeMapping.values()) { if (mapping.trustedAppOnly && !trustedApp) { // Do not fill in any trusted app attributes unless the app is trusted. continue; } String headerValue = request.getHeader(mapping.headerKey); if (headerValue != null) { attributes.put(mapping.attributeKey, headerValue); } else if (mapping.defaultValue != null) { attributes.put(mapping.attributeKey, mapping.defaultValue); } // else: The attribute is expected to be missing if the header is not set. } // Fill in the special attributes that do not fit the simple mapping model. boolean federatedId = request.getHeader(AttributeMapping.FEDERATED_IDENTITY.headerKey) != null; attributes.put(IS_FEDERATED_USER_KEY, federatedId); attributes.put(BACKEND_ID_KEY, module); attributes.put(INSTANCE_ID_KEY, instance); attributes.put(AFFINITY_KEY, affinity); if (trustedApp) { // The trusted IP attribute is a boolean. boolean trustedIp = "1".equals(request.getHeader(IS_TRUSTED_IP_HEADER)); attributes.put(IS_TRUSTED_IP_KEY, trustedIp); } VmApiProxyEnvironment requestEnvironment = new VmApiProxyEnvironment( server, ticket, longAppId, partition, module, majorVersion, minorVersion, instance, appengineHostname, email, admin, authDomain, useMvmAgent, wallTimer, millisUntilSoftDeadline, attributes); // Add the thread factories required by the threading API. attributes.put(REQUEST_THREAD_FACTORY_ATTR, new VmRequestThreadFactory(requestEnvironment)); // Since we register VmEnvironmentFactory with ApiProxy in VmRuntimeWebAppContext, // we can use the default thread factory here and don't require any special logic. attributes.put(BACKGROUND_THREAD_FACTORY_ATTR, Executors.defaultThreadFactory()); return requestEnvironment; } private final String server; private volatile String ticket; // request ticket is only valid until response is committed. private volatile String globalTicket; // global ticket is always valid private final int serverPort; private final String partition; private final String appId; private final String module; private final String majorVersion; private final String minorVersion; private final String versionId; private final String appengineHostname; private final String l7UnsafeRedirectUrl; private final String email; private final boolean admin; private final String authDomain; private final boolean useMvmAgent; private final Map<String, Object> attributes; private ThreadLocal<Map<String, Object>> threadLocalAttributes; private final Timer wallTimer; // may be null if millisUntilSoftDeadline is null. private final Long millisUntilSoftDeadline; // may be null (no deadline). final Semaphore pendingApiCallSemaphore; final Semaphore runningApiCallSemaphore; /** * Constructs a VM AppEngine API environment. * * @param server the host:port address of the VM's HTTP proxy server. * @param ticket the request ticket (if null the default one will be computed). * @param appId the application ID (required if ticket is null). * @param partition the partition name. * @param module the module name (required if ticket is null). * @param majorVersion the major application version (required if ticket is null). * @param minorVersion the minor application version. * @param instance the VM instance ID (required if ticket is null). * @param appengineHostname the app's appengine hostname. * @param email the user's e-mail address (may be null). * @param admin true if the user is an administrator. * @param authDomain the user's authentication domain (may be null). * @param useMvmAgent if true, the mvm agent is in use. * @param wallTimer optional wall clock timer for the current request (required for deadline). * @param millisUntilSoftDeadline optional soft deadline in milliseconds relative to 'wallTimer'. * @param attributes map containing any attributes set on this environment. */ private VmApiProxyEnvironment( String server, String ticket, String appId, String partition, String module, String majorVersion, String minorVersion, String instance, String appengineHostname, String email, boolean admin, String authDomain, boolean useMvmAgent, Timer wallTimer, Long millisUntilSoftDeadline, Map<String, Object> attributes) { if (server == null || server.isEmpty()) { throw new IllegalArgumentException("proxy server host:port must be specified"); } if (millisUntilSoftDeadline != null && wallTimer == null) { throw new IllegalArgumentException("wallTimer required when setting millisUntilSoftDeadline"); } this.ticket = ticket; if ((appId == null || appId.isEmpty()) || (module == null || module.isEmpty()) || (majorVersion == null || majorVersion.isEmpty()) || (instance == null || instance.isEmpty())) { throw new IllegalArgumentException( "When ticket == null, the following must be specified: appId=" + appId + ", module=" + module + ", version=" + majorVersion + ", instance=" + instance); } String escapedAppId = appId.replace(':', '_').replace('.', '_'); this.globalTicket = escapedAppId + '/' + module + '.' + majorVersion + "." + instance; this.server = server; this.partition = partition; String port = System.getenv(GAE_SERVER_PORT) == null ? System.getProperty("GAE_SERVER_PORT", "80") : System.getenv(GAE_SERVER_PORT); this.serverPort = Integer.decode(port); this.appId = partition + "~" + appId; this.module = module == null ? "default" : module; this.majorVersion = majorVersion == null ? "" : majorVersion; this.minorVersion = minorVersion == null ? "" : minorVersion; this.versionId = String.format("%s.%s", this.majorVersion, this.minorVersion); this.appengineHostname = appengineHostname; this.l7UnsafeRedirectUrl = String.format( "https://%s-dot-%s-dot-%s", this.majorVersion, this.module, this.appengineHostname); this.email = email == null ? "" : email; this.admin = admin; this.authDomain = authDomain == null ? "" : authDomain; this.useMvmAgent = useMvmAgent; this.wallTimer = wallTimer; this.millisUntilSoftDeadline = millisUntilSoftDeadline; // Environments are associated with requests, and can be // shared across more than one thread. We'll synchronize all // individual calls which should be sufficient. this.attributes = Collections.synchronizedMap(attributes); // TODO(user): forward app_log_line_size, app_log_group_size, max_log_flush_seconds // from clone_settings so these can be overridden per app. this.pendingApiCallSemaphore = new Semaphore(MAX_PENDING_API_CALLS); this.runningApiCallSemaphore = new Semaphore(MAX_CONCURRENT_API_CALLS); } @Deprecated public void addLogRecord(LogRecord record) {} @Deprecated public int flushLogs() { return -1; } public String getMajorVersion() { return majorVersion; } public String getMinorVersion() { return minorVersion; } public String getAppengineHostname() { return appengineHostname; } public String getL7UnsafeRedirectUrl() { return l7UnsafeRedirectUrl; } public String getServer() { return server; } public void clearTicket() { ticket = null; } public boolean isRequestTicket() { String requestTicket = ticket; return requestTicket != null && !requestTicket.isEmpty(); } public String getTicket() { String requestTicket = ticket; return (requestTicket != null && !requestTicket.isEmpty()) ? requestTicket : globalTicket; } public String getPartition() { return partition; } public int getServerPort() { return serverPort; } @Override public String getAppId() { return appId; } @Override public String getModuleId() { return module; } @Override public String getVersionId() { return versionId; } @Override public String getEmail() { return email; } @Override public boolean isLoggedIn() { return getEmail() != null && !getEmail().trim().isEmpty(); } @Override public boolean isAdmin() { return admin; } @Override public String getAuthDomain() { return authDomain; } public boolean getUseMvmAgent() { return useMvmAgent; } @Deprecated @Override public String getRequestNamespace() { Object currentNamespace = attributes.get(AttributeMapping.CURRENT_NAMESPACE_HEADER.attributeKey); if (currentNamespace instanceof String) { return (String) currentNamespace; } return ""; } /*** * Create a thread-local copy of the attributes. Used for the instance of this class that is * shared among all the background threads. They each may mutate the attributes independently. */ public synchronized void setThreadLocalAttributes() { if (threadLocalAttributes == null) { threadLocalAttributes = new ThreadLocal<>(); } threadLocalAttributes.set(new HashMap<>(attributes)); } @Override public Map<String, Object> getAttributes() { if (threadLocalAttributes != null && threadLocalAttributes.get() != null) { // If a thread-local copy of the attributes exists, return it. return threadLocalAttributes.get(); } else { // Otherwise this is not a shared instance and/or we were never told to store // a thread-local copy. So we just return the attributes that were used to originally // construct the instance. return attributes; } } @Override public long getRemainingMillis() { if (millisUntilSoftDeadline == null) { return Long.MAX_VALUE; } return millisUntilSoftDeadline - (wallTimer.getNanoseconds() / 1000000L); } /** * Notifies the environment that an API call was queued up. */ void asyncApiCallAdded(long maxWaitMs) throws ApiProxyException { try { if (pendingApiCallSemaphore.tryAcquire(maxWaitMs, TimeUnit.MILLISECONDS)) { return; // All good. } throw new ApiProxyException("Timed out while acquiring a pending API call semaphore."); } catch (InterruptedException e) { throw new ApiProxyException( "Thread interrupted while acquiring a pending API call semaphore."); } } /** * Notifies the environment that an API call was started. * * @param releasePendingCall If true a pending call semaphore will be released (required if this * API call was requested asynchronously). * * @throws ApiProxyException If the thread was interrupted while waiting for a semaphore. */ void apiCallStarted(long maxWaitMs, boolean releasePendingCall) throws ApiProxyException { try { if (runningApiCallSemaphore.tryAcquire(maxWaitMs, TimeUnit.MILLISECONDS)) { return; // All good. } throw new ApiProxyException("Timed out while acquiring an API call semaphore."); } catch (InterruptedException e) { throw new ApiProxyException("Thread interrupted while acquiring an API call semaphore."); } finally { if (releasePendingCall) { pendingApiCallSemaphore.release(); } } } /** * Notifies the environment that an API call completed. */ void apiCallCompleted() { runningApiCallSemaphore.release(); } /** * Waits for up to {@code maxWaitMs} ms for all outstanding API calls to complete. * * @param maxWaitMs The maximum time to wait. * @return True if the all calls completed before the timeout fired or the thread was interrupted. * False otherwise. */ public boolean waitForAllApiCallsToComplete(long maxWaitMs) { try { long startTime = System.currentTimeMillis(); if (pendingApiCallSemaphore.tryAcquire( MAX_PENDING_API_CALLS, maxWaitMs, TimeUnit.MILLISECONDS)) { // Release the acquired semaphores in finally {} to guarantee that they are returned. try { long remaining = maxWaitMs - (System.currentTimeMillis() - startTime); if (runningApiCallSemaphore.tryAcquire( MAX_CONCURRENT_API_CALLS, remaining, TimeUnit.MILLISECONDS)) { runningApiCallSemaphore.release(MAX_CONCURRENT_API_CALLS); return true; } } finally { pendingApiCallSemaphore.release(MAX_PENDING_API_CALLS); } } } catch (InterruptedException ignored) { // The error message is printed by the caller. } return false; } public String getTraceId() { Object value = getAttributes() .get(VmApiProxyEnvironment.AttributeMapping.CLOUD_TRACE_CONTEXT.attributeKey); if (!(value instanceof String)) { return null; } String fullTraceId = (String) value; // Extract the trace id from the header. // TODO(user, qike): Use the code from the Trace SDK when it's available in /third_party. if (fullTraceId.isEmpty() || Character.digit(fullTraceId.charAt(0), 16) < 0) { return null; } for (int index = 1; index < fullTraceId.length(); index++) { char ch = fullTraceId.charAt(index); if (Character.digit(ch, 16) < 0) { return fullTraceId.substring(0, index); } } return null; } }
Fix #277 default to global ticket (#285) default to global ticket
appengine-managed-runtime/src/main/java/com/google/apphosting/vmruntime/VmApiProxyEnvironment.java
Fix #277 default to global ticket (#285)
<ide><path>ppengine-managed-runtime/src/main/java/com/google/apphosting/vmruntime/VmApiProxyEnvironment.java <ide> final String instance = getEnvOrMetadata(envMap, cache, INSTANCE_KEY, INSTANCE_ATTRIBUTE); <ide> final String affinity = getEnvOrMetadata(envMap, cache, AFFINITY_ENV_KEY, AFFINITY_ATTRIBUTE); <ide> final String ticket = <del> getSystemPropertyOrEnvBoolean(envMap, USE_GLOBAL_TICKET_KEY, false) <add> getSystemPropertyOrEnvBoolean(envMap, USE_GLOBAL_TICKET_KEY, true) <ide> ? null <ide> : request.getHeader(TICKET_HEADER); <ide> final String email = request.getHeader(EMAIL_HEADER);
Java
epl-1.0
d4a2c50453e66d5f7b7fac75cf604d1af88702aa
0
Charling-Huang/birt,Charling-Huang/birt,sguan-actuate/birt,rrimmana/birt-1,rrimmana/birt-1,Charling-Huang/birt,sguan-actuate/birt,rrimmana/birt-1,Charling-Huang/birt,sguan-actuate/birt,rrimmana/birt-1,Charling-Huang/birt,sguan-actuate/birt,rrimmana/birt-1,sguan-actuate/birt
/******************************************************************************* * Copyright (c) 2005 Actuate Corporation. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/epl-v10.html * * Contributors: * Actuate Corporation - initial API and implementation *******************************************************************************/ package org.eclipse.birt.report.designer.ui.cubebuilder.joins.editparts; import java.util.ArrayList; import java.util.List; import java.util.Random; import org.eclipse.birt.report.designer.internal.ui.util.ExceptionHandler; import org.eclipse.birt.report.designer.ui.cubebuilder.joins.editpolicies.TableSelectionEditPolicy; import org.eclipse.birt.report.designer.ui.cubebuilder.joins.figures.TableNodeFigure; import org.eclipse.birt.report.designer.ui.cubebuilder.joins.figures.TablePaneFigure; import org.eclipse.birt.report.designer.ui.cubebuilder.util.BuilderConstancts; import org.eclipse.birt.report.designer.ui.cubebuilder.util.OlapUtil; import org.eclipse.birt.report.designer.ui.cubebuilder.util.UIHelper; import org.eclipse.birt.report.model.api.DataSetHandle; import org.eclipse.birt.report.model.api.DesignElementHandle; import org.eclipse.birt.report.model.api.ReportElementHandle; import org.eclipse.birt.report.model.api.ResultSetColumnHandle; import org.eclipse.birt.report.model.api.activity.NotificationEvent; import org.eclipse.birt.report.model.api.activity.SemanticException; import org.eclipse.birt.report.model.api.core.Listener; import org.eclipse.birt.report.model.api.olap.TabularCubeHandle; import org.eclipse.birt.report.model.api.olap.TabularDimensionHandle; import org.eclipse.birt.report.model.api.olap.TabularHierarchyHandle; import org.eclipse.birt.report.model.elements.interfaces.ICubeModel; import org.eclipse.draw2d.IFigure; import org.eclipse.draw2d.Polygon; import org.eclipse.draw2d.geometry.Point; import org.eclipse.draw2d.geometry.Rectangle; import org.eclipse.gef.DragTracker; import org.eclipse.gef.EditPart; import org.eclipse.gef.EditPolicy; import org.eclipse.gef.GraphicalEditPart; import org.eclipse.gef.Request; import org.eclipse.gef.tools.DragEditPartsTracker; import org.eclipse.swt.widgets.Display; /** * Edit Part corresponding to a Table object. * */ public class HierarchyNodeEditPart extends NodeEditPartHelper implements Listener { public TablePaneFigure scrollPane; public TableNodeFigure tableNode; private TabularCubeHandle cube; private DataSetHandle dataset; private TabularDimensionHandle dimension; /** * @param impl */ public HierarchyNodeEditPart( EditPart parent, TabularHierarchyHandle hierarchy ) { setModel( hierarchy ); setParent( parent ); hierarchy.getModuleHandle( ).addListener( this ); this.dimension = (TabularDimensionHandle) hierarchy.getContainer( ); this.cube = (TabularCubeHandle) parent.getModel( ); this.dataset = hierarchy.getDataSet( ); } /* * (non-Javadoc) * * @see org.eclipse.gef.editparts.AbstractGraphicalEditPart#createFigure() */ protected IFigure createFigure( ) { String name = ( (DataSetHandle) dataset ).getName( ) + "(" + dimension.getName( ) + ")"; tableNode = new TableNodeFigure( name ); scrollPane = new TablePaneFigure( name ); scrollPane.setContents( tableNode ); return scrollPane; } /*************************************************************************** * Returns the Children for this Edit Part. It returns a List of * ColumnEditParts * * @see org.eclipse.gef.editparts.AbstractEditPart#getModelChildren() */ protected List getModelChildren( ) { List childList = new ArrayList( ); ResultSetColumnHandle[] columns = OlapUtil.getDataFields( dataset ); if ( columns != null ) { for ( int i = 0; i < columns.length; i++ ) { childList.add( columns[i] ); } } // childrenColumnNumber = childList.size( ); return childList; } /* * (non-Javadoc) * * @see org.eclipse.gef.editparts.AbstractEditPart#refreshVisuals() */ protected void refreshVisuals( ) { Rectangle r; if ( !UIHelper.existIntProperty( ( (ReportElementHandle) getModel( ) ).getModuleHandle( ), UIHelper.getId( getModel( ), cube ), BuilderConstancts.POSITION_X ) ) { int displayWidth = Display.getCurrent( ).getBounds( ).width - 60; int displayHeight = Display.getCurrent( ).getBounds( ).height - 20 - 150; List childList = new ArrayList( ); if ( getCube( ) != null ) { childList.add( getCube( ).getDataSet( ) ); TabularDimensionHandle[] dimensions = (TabularDimensionHandle[]) getCube( ).getContents( ICubeModel.DIMENSIONS_PROP ) .toArray( new TabularDimensionHandle[0] ); for ( int i = 0; i < dimensions.length; i++ ) { TabularHierarchyHandle hierarchy = (TabularHierarchyHandle) dimensions[i].getDefaultHierarchy( ); if ( hierarchy != null && hierarchy.getDataSet( ) != null ) childList.add( hierarchy ); } } List polygonList = new ArrayList( ); for ( int i = 0; i < childList.size( ); i++ ) { if ( existPosX( childList.get( i ) ) ) polygonList.add( getPolygon( childList.get( i ) ) ); } int width = getWidth( getModel( ) ); int height = getHeight( getModel( ) ); boolean contain = false; int x = 0, y = 0; for ( int i = 0; i < 100; i++ ) { x = new Random( ).nextInt( displayWidth - width ); y = new Random( ).nextInt( displayHeight - height ); for ( int j = 0; j < polygonList.size( ); j++ ) { contain = true; Polygon polygon = (Polygon) polygonList.get( j ); if ( polygon.containsPoint( x, y ) ) break; if ( polygon.containsPoint( x + width, y ) ) break; if ( polygon.containsPoint( x + width, y + height ) ) break; if ( polygon.containsPoint( x, y + height ) ) break; contain = false; } if ( !contain ){ break; } } polygonList.clear( ); childList.clear( ); if ( !contain ) r = new Rectangle( setPosX( x ), setPosY( y ), width, height ); else r = new Rectangle( getPosX( getModel( ) ), getPosY( getModel( ) ), getWidth( getModel( ) ), getHeight( getModel( ) ) ); } else r = new Rectangle( getPosX( getModel( ) ), getPosY( getModel( ) ), getWidth( getModel( ) ), getHeight( getModel( ) ) ); getFigure( ).setBounds( r ); ( (GraphicalEditPart) getParent( ) ).setLayoutConstraint( this, getFigure( ), r ); } private Polygon getPolygon( Object model ) { Polygon polygon = new Polygon( ); int x = getPosX( model ); int y = getPosY( model ); int width = getWidth( model ); int height = getHeight( model ); polygon.addPoint( new Point( x-50, y-50 ) ); polygon.addPoint( new Point( x + width+50, y-50 ) ); polygon.addPoint( new Point( x + width+50, y + height+50 ) ); polygon.addPoint( new Point( x-50, y + height+50 ) ); return polygon; } private int getWidth( Object model ) { int width = UIHelper.getIntProperty( ( (ReportElementHandle) model ).getModuleHandle( ), UIHelper.getId( model, cube ), BuilderConstancts.SIZE_WIDTH ); return width == 0 ? 150 : width; } private int getHeight( Object model ) { int height = UIHelper.getIntProperty( ( (ReportElementHandle) model ).getModuleHandle( ), UIHelper.getId( model, cube ), BuilderConstancts.SIZE_HEIGHT ); return height == 0 ? 200 : height; } private int getPosX( Object model ) { int x = UIHelper.getIntProperty( ( (ReportElementHandle) model ).getModuleHandle( ), UIHelper.getId( model, cube ), BuilderConstancts.POSITION_X ); return x; } private int getPosY( Object model ) { int y = UIHelper.getIntProperty( ( (ReportElementHandle) model ).getModuleHandle( ), UIHelper.getId( model, cube ), BuilderConstancts.POSITION_Y ); return y; } private int setPosX( int x ) { try { UIHelper.setIntProperty( ( (ReportElementHandle) getModel( ) ).getModuleHandle( ), UIHelper.getId( getModel( ), cube ), BuilderConstancts.POSITION_X, x ); } catch ( SemanticException e ) { ExceptionHandler.handle( e ); } return x; } private int setPosY( int y ) { try { UIHelper.setIntProperty( ( (ReportElementHandle) getModel( ) ).getModuleHandle( ), UIHelper.getId( getModel( ), cube ), BuilderConstancts.POSITION_Y, y ); } catch ( SemanticException e ) { ExceptionHandler.handle( e ); } return y; } private boolean existPosX( Object model ) { return UIHelper.existIntProperty( ( (ReportElementHandle) model ).getModuleHandle( ), UIHelper.getId( model, cube ), BuilderConstancts.POSITION_X ); } /* * (non-Javadoc) * * @see org.eclipse.gef.editparts.AbstractEditPart#createEditPolicies() */ protected void createEditPolicies( ) { installEditPolicy( EditPolicy.SELECTION_FEEDBACK_ROLE, new TableSelectionEditPolicy( ) ); } /* * (non-Javadoc) * * @see org.eclipse.birt.report.data.oda.jdbc.ui.editors.graphical.editparts.NodeEditPartHelper#getChopFigure() */ public IFigure getChopFigure( ) { // TODO Auto-generated method stub return null; } /* * (non-Javadoc) * * @see org.eclipse.gef.GraphicalEditPart#getContentPane() */ public IFigure getContentPane( ) { return tableNode; } public void elementChanged( DesignElementHandle focus, NotificationEvent ev ) { if ( getRoot( ).getViewer( ).getControl( ) == null || getRoot( ).getViewer( ).getControl( ).isDisposed( ) ) { ( (ReportElementHandle) getModel( ) ).getModuleHandle( ) .removeListener( this ); } else refreshVisuals( ); } public DragTracker getDragTracker( Request req ) { DragEditPartsTracker track = new DragEditPartsTracker( this ); return track; } public DataSetHandle getDataset( ) { return dataset; } public TabularCubeHandle getCube( ) { return cube; } }
UI/org.eclipse.birt.report.designer.ui.cubebuilder/src/org/eclipse/birt/report/designer/ui/cubebuilder/joins/editparts/HierarchyNodeEditPart.java
/******************************************************************************* * Copyright (c) 2005 Actuate Corporation. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/epl-v10.html * * Contributors: * Actuate Corporation - initial API and implementation *******************************************************************************/ package org.eclipse.birt.report.designer.ui.cubebuilder.joins.editparts; import java.util.ArrayList; import java.util.List; import java.util.Random; import org.eclipse.birt.report.designer.internal.ui.util.ExceptionHandler; import org.eclipse.birt.report.designer.ui.cubebuilder.joins.editpolicies.TableSelectionEditPolicy; import org.eclipse.birt.report.designer.ui.cubebuilder.joins.figures.TableNodeFigure; import org.eclipse.birt.report.designer.ui.cubebuilder.joins.figures.TablePaneFigure; import org.eclipse.birt.report.designer.ui.cubebuilder.util.BuilderConstancts; import org.eclipse.birt.report.designer.ui.cubebuilder.util.OlapUtil; import org.eclipse.birt.report.designer.ui.cubebuilder.util.UIHelper; import org.eclipse.birt.report.model.api.DataSetHandle; import org.eclipse.birt.report.model.api.DesignElementHandle; import org.eclipse.birt.report.model.api.ReportElementHandle; import org.eclipse.birt.report.model.api.ResultSetColumnHandle; import org.eclipse.birt.report.model.api.activity.NotificationEvent; import org.eclipse.birt.report.model.api.activity.SemanticException; import org.eclipse.birt.report.model.api.core.Listener; import org.eclipse.birt.report.model.api.olap.TabularCubeHandle; import org.eclipse.birt.report.model.api.olap.TabularDimensionHandle; import org.eclipse.birt.report.model.api.olap.TabularHierarchyHandle; import org.eclipse.birt.report.model.elements.interfaces.ICubeModel; import org.eclipse.draw2d.IFigure; import org.eclipse.draw2d.Polygon; import org.eclipse.draw2d.geometry.Point; import org.eclipse.draw2d.geometry.Rectangle; import org.eclipse.gef.DragTracker; import org.eclipse.gef.EditPart; import org.eclipse.gef.EditPolicy; import org.eclipse.gef.GraphicalEditPart; import org.eclipse.gef.Request; import org.eclipse.gef.tools.DragEditPartsTracker; import org.eclipse.swt.widgets.Display; /** * Edit Part corresponding to a Table object. * */ public class HierarchyNodeEditPart extends NodeEditPartHelper implements Listener { public TablePaneFigure scrollPane; public TableNodeFigure tableNode; private TabularCubeHandle cube; private DataSetHandle dataset; private TabularDimensionHandle dimension; /** * @param impl */ public HierarchyNodeEditPart( EditPart parent, TabularHierarchyHandle hierarchy ) { setModel( hierarchy ); setParent( parent ); hierarchy.getModuleHandle( ).addListener( this ); this.dimension = (TabularDimensionHandle) hierarchy.getContainer( ); this.cube = (TabularCubeHandle) parent.getModel( ); this.dataset = hierarchy.getDataSet( ); } /* * (non-Javadoc) * * @see org.eclipse.gef.editparts.AbstractGraphicalEditPart#createFigure() */ protected IFigure createFigure( ) { String name = ( (DataSetHandle) dataset ).getName( ) + "(" + dimension.getName( ) + ")"; tableNode = new TableNodeFigure( name ); scrollPane = new TablePaneFigure( name ); scrollPane.setContents( tableNode ); return scrollPane; } /*************************************************************************** * Returns the Children for this Edit Part. It returns a List of * ColumnEditParts * * @see org.eclipse.gef.editparts.AbstractEditPart#getModelChildren() */ protected List getModelChildren( ) { List childList = new ArrayList( ); ResultSetColumnHandle[] columns = OlapUtil.getDataFields( dataset ); if ( columns != null ) { for ( int i = 0; i < columns.length; i++ ) { childList.add( columns[i] ); } } // childrenColumnNumber = childList.size( ); return childList; } /* * (non-Javadoc) * * @see org.eclipse.gef.editparts.AbstractEditPart#refreshVisuals() */ protected void refreshVisuals( ) { Rectangle r; if ( !UIHelper.existIntProperty( ( (ReportElementHandle) getModel( ) ).getModuleHandle( ), UIHelper.getId( getModel( ), cube ), BuilderConstancts.POSITION_X ) ) { int displayWidth = Display.getCurrent( ).getBounds( ).width - 60; int displayHeight = Display.getCurrent( ).getBounds( ).height - 20 - 150; List childList = new ArrayList( ); if ( getCube( ) != null ) { childList.add( getCube( ).getDataSet( ) ); TabularDimensionHandle[] dimensions = (TabularDimensionHandle[]) getCube( ).getContents( ICubeModel.DIMENSIONS_PROP ) .toArray( new TabularDimensionHandle[0] ); for ( int i = 0; i < dimensions.length; i++ ) { TabularHierarchyHandle hierarchy = (TabularHierarchyHandle) dimensions[i].getDefaultHierarchy( ); if ( hierarchy != null && hierarchy.getDataSet( ) != null ) childList.add( hierarchy ); } } List polygonList = new ArrayList( ); for ( int i = 0; i < childList.size( ); i++ ) { if ( existPosX( childList.get( i ) ) ) polygonList.add( getPolygon( childList.get( i ) ) ); } int width = getWidth( getModel( ) ); int height = getHeight( getModel( ) ); boolean contain = false; int x = 0, y = 0; for ( int i = 0; i < 100; i++ ) { x = new Random( ).nextInt( displayWidth - width ); y = new Random( ).nextInt( displayHeight - height ); for ( int j = 0; j < polygonList.size( ); j++ ) { contain = true; Polygon polygon = (Polygon) polygonList.get( j ); if ( polygon.containsPoint( x, y ) ) break; if ( polygon.containsPoint( x + width, y ) ) break; if ( polygon.containsPoint( x + width, y + height ) ) break; if ( polygon.containsPoint( x, y + height ) ) break; contain = false; } if ( !contain ){ break; } } if ( !contain ) r = new Rectangle( setPosX( x ), setPosY( y ), width, height ); else r = new Rectangle( getPosX( getModel( ) ), getPosY( getModel( ) ), getWidth( getModel( ) ), getHeight( getModel( ) ) ); } else r = new Rectangle( getPosX( getModel( ) ), getPosY( getModel( ) ), getWidth( getModel( ) ), getHeight( getModel( ) ) ); getFigure( ).setBounds( r ); ( (GraphicalEditPart) getParent( ) ).setLayoutConstraint( this, getFigure( ), r ); } private Polygon getPolygon( Object model ) { Polygon polygon = new Polygon( ); int x = getPosX( model ); int y = getPosY( model ); int width = getWidth( model ); int height = getHeight( model ); polygon.addPoint( new Point( x-50, y-50 ) ); polygon.addPoint( new Point( x + width+50, y-50 ) ); polygon.addPoint( new Point( x + width+50, y + height+50 ) ); polygon.addPoint( new Point( x-50, y + height+50 ) ); return polygon; } private int getWidth( Object model ) { int width = UIHelper.getIntProperty( ( (ReportElementHandle) model ).getModuleHandle( ), UIHelper.getId( model, cube ), BuilderConstancts.SIZE_WIDTH ); return width == 0 ? 150 : width; } private int getHeight( Object model ) { int height = UIHelper.getIntProperty( ( (ReportElementHandle) model ).getModuleHandle( ), UIHelper.getId( model, cube ), BuilderConstancts.SIZE_HEIGHT ); return height == 0 ? 200 : height; } private int getPosX( Object model ) { int x = UIHelper.getIntProperty( ( (ReportElementHandle) model ).getModuleHandle( ), UIHelper.getId( model, cube ), BuilderConstancts.POSITION_X ); return x; } private int getPosY( Object model ) { int y = UIHelper.getIntProperty( ( (ReportElementHandle) model ).getModuleHandle( ), UIHelper.getId( model, cube ), BuilderConstancts.POSITION_Y ); return y; } private int setPosX( int x ) { try { UIHelper.setIntProperty( ( (ReportElementHandle) getModel( ) ).getModuleHandle( ), UIHelper.getId( getModel( ), cube ), BuilderConstancts.POSITION_X, x ); } catch ( SemanticException e ) { ExceptionHandler.handle( e ); } return x; } private int setPosY( int y ) { try { UIHelper.setIntProperty( ( (ReportElementHandle) getModel( ) ).getModuleHandle( ), UIHelper.getId( getModel( ), cube ), BuilderConstancts.POSITION_Y, y ); } catch ( SemanticException e ) { ExceptionHandler.handle( e ); } return y; } private boolean existPosX( Object model ) { return UIHelper.existIntProperty( ( (ReportElementHandle) model ).getModuleHandle( ), UIHelper.getId( model, cube ), BuilderConstancts.POSITION_X ); } /* * (non-Javadoc) * * @see org.eclipse.gef.editparts.AbstractEditPart#createEditPolicies() */ protected void createEditPolicies( ) { installEditPolicy( EditPolicy.SELECTION_FEEDBACK_ROLE, new TableSelectionEditPolicy( ) ); } /* * (non-Javadoc) * * @see org.eclipse.birt.report.data.oda.jdbc.ui.editors.graphical.editparts.NodeEditPartHelper#getChopFigure() */ public IFigure getChopFigure( ) { // TODO Auto-generated method stub return null; } /* * (non-Javadoc) * * @see org.eclipse.gef.GraphicalEditPart#getContentPane() */ public IFigure getContentPane( ) { return tableNode; } public void elementChanged( DesignElementHandle focus, NotificationEvent ev ) { if ( getRoot( ).getViewer( ).getControl( ) == null || getRoot( ).getViewer( ).getControl( ).isDisposed( ) ) { ( (ReportElementHandle) getModel( ) ).getModuleHandle( ) .removeListener( this ); } else refreshVisuals( ); } public DragTracker getDragTracker( Request req ) { DragEditPartsTracker track = new DragEditPartsTracker( this ); return track; } public DataSetHandle getDataset( ) { return dataset; } public TabularCubeHandle getCube( ) { return cube; } }
- Summary: BIRT Designer - Cube builder UI to support multiple dataset - Bugzilla Bug (s) Resolved: 178438 - Description: BIRT Designer - Cube builder UI to support multiple dataset - Tests Description: Manual test. - Notes to Build Team: - Notes to Developers: - Notes to QA: - Notes to Documentation: - Files Added: - Files Edited: - Files Deleted:
UI/org.eclipse.birt.report.designer.ui.cubebuilder/src/org/eclipse/birt/report/designer/ui/cubebuilder/joins/editparts/HierarchyNodeEditPart.java
- Summary: BIRT Designer - Cube builder UI to support multiple dataset
<ide><path>I/org.eclipse.birt.report.designer.ui.cubebuilder/src/org/eclipse/birt/report/designer/ui/cubebuilder/joins/editparts/HierarchyNodeEditPart.java <ide> break; <ide> } <ide> } <add> polygonList.clear( ); <add> childList.clear( ); <ide> if ( !contain ) <ide> r = new Rectangle( setPosX( x ), setPosY( y ), width, height ); <ide> else
Java
lgpl-2.1
61c72fd8f10b030a08e73164c3e7435e34ff3420
0
gunnarmorling/hibernate-ogm,DavideD/hibernate-ogm-cassandra,Sanne/hibernate-ogm,mp911de/hibernate-ogm,DavideD/hibernate-ogm-cassandra,DavideD/hibernate-ogm,emmanuelbernard/hibernate-ogm,hibernate/hibernate-ogm,tempbottle/hibernate-ogm,jhalliday/hibernate-ogm,jhalliday/hibernate-ogm,DavideD/hibernate-ogm,hferentschik/hibernate-ogm,tempbottle/hibernate-ogm,emmanuelbernard/hibernate-ogm-old,hibernate/hibernate-ogm,mp911de/hibernate-ogm,DavideD/hibernate-ogm-contrib,gunnarmorling/hibernate-ogm,hibernate/hibernate-ogm,Sanne/hibernate-ogm,uugaa/hibernate-ogm,ZJaffee/hibernate-ogm,schernolyas/hibernate-ogm,Sanne/hibernate-ogm,jhalliday/hibernate-ogm,ZJaffee/hibernate-ogm,schernolyas/hibernate-ogm,DavideD/hibernate-ogm,Sanne/hibernate-ogm,tempbottle/hibernate-ogm,schernolyas/hibernate-ogm,hibernate/hibernate-ogm,DavideD/hibernate-ogm-cassandra,DavideD/hibernate-ogm-contrib,DavideD/hibernate-ogm-contrib,mp911de/hibernate-ogm,ZJaffee/hibernate-ogm,uugaa/hibernate-ogm,gunnarmorling/hibernate-ogm,DavideD/hibernate-ogm,uugaa/hibernate-ogm
/* * Hibernate, Relational Persistence for Idiomatic Java * * Copyright (c) 2010, Red Hat, Inc. and/or its affiliates or third-party contributors as * indicated by the @author tags or express copyright attribution * statements applied by the authors. All third-party contributions are * distributed under license by Red Hat, Inc. * * This copyrighted material is made available to anyone wishing to use, modify, * copy, or redistribute it subject to the terms and conditions of the GNU * Lesser 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 Lesser General Public License * for more details. * * You should have received a copy of the GNU Lesser General Public License * along with this distribution; if not, write to: * Free Software Foundation, Inc. * 51 Franklin Street, Fifth Floor * Boston, MA 02110-1301 USA */ package org.hibernate.ogm.test.simpleentity; import javax.persistence.Entity; import javax.persistence.GeneratedValue; import javax.persistence.Id; import org.hibernate.annotations.GenericGenerator; import org.hibernate.annotations.Persister; import org.hibernate.ogm.persister.OgmEntityPersister; /** * @author Emmanuel Bernard */ @Entity @Persister( impl = OgmEntityPersister.class) public class Helicopter { @Id @GeneratedValue(generator = "uuid") @GenericGenerator( name="uuid", strategy = "uuid2") public String getUUID() { return uuid; } public void setUUID(String uuid) { this.uuid = uuid; } private String uuid; public String getName() { return name; } public void setName(String name) { this.name = name; } private String name; }
hibernate-ogm-core/src/test/java/org/hibernate/ogm/test/simpleentity/Helicopter.java
/* * Hibernate, Relational Persistence for Idiomatic Java * * Copyright (c) 2010, Red Hat, Inc. and/or its affiliates or third-party contributors as * indicated by the @author tags or express copyright attribution * statements applied by the authors. All third-party contributions are * distributed under license by Red Hat, Inc. * * This copyrighted material is made available to anyone wishing to use, modify, * copy, or redistribute it subject to the terms and conditions of the GNU * Lesser 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 Lesser General Public License * for more details. * * You should have received a copy of the GNU Lesser General Public License * along with this distribution; if not, write to: * Free Software Foundation, Inc. * 51 Franklin Street, Fifth Floor * Boston, MA 02110-1301 USA */ package org.hibernate.ogm.test.simpleentity; import javax.persistence.Entity; import javax.persistence.GeneratedValue; import javax.persistence.Id; import org.hibernate.annotations.GenericGenerator; import org.hibernate.annotations.Persister; import org.hibernate.ogm.persister.OgmEntityPersister; /** * @author Emmanuel Bernard */ @Entity @Persister( impl = OgmEntityPersister.class) public class Helicopter { @Id @GeneratedValue(generator = "uuid") @GenericGenerator( name="uuid", strategy = "uuid2") public String getUUID() { return uuid; } public void setUUID(String uuid) { this.uuid = uuid; } private String uuid; public String getName() { return name; } public void setName(String name) { this.name = name; } private String name; }
Style fix.
hibernate-ogm-core/src/test/java/org/hibernate/ogm/test/simpleentity/Helicopter.java
Style fix.
<ide><path>ibernate-ogm-core/src/test/java/org/hibernate/ogm/test/simpleentity/Helicopter.java <ide> /** <ide> * @author Emmanuel Bernard <ide> */ <del>@Entity @Persister( impl = OgmEntityPersister.class) <add>@Entity <add>@Persister( impl = OgmEntityPersister.class) <ide> public class Helicopter { <ide> @Id @GeneratedValue(generator = "uuid") @GenericGenerator( name="uuid", strategy = "uuid2") <ide> public String getUUID() { return uuid; }
Java
agpl-3.0
442e8f12f30a9d8667c94b006f14246e75f58b29
0
VolumetricPixels/Politics
/* * This file is part of Politics. * * Copyright (c) 2012-2012, VolumetricPixels <http://volumetricpixels.com/> * Politics is licensed under the Affero General Public License Version 3. * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU Affero General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Affero General Public License for more details. * * You should have received a copy of the GNU Affero General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ package com.volumetricpixels.politics.event.group; import com.volumetricpixels.politics.group.Group; import org.spout.api.event.HandlerList; /** * Called when a property is set. Note that transforms, points, and blocks will * all be strings. */ public class GroupPropertySetEvent extends GroupEvent { private static final HandlerList handlers = new HandlerList(); /** * The property that was set. */ private final int property; /** * The value of the property. */ private final Object value; /** * C'tor * * @param group * @param value The value */ public GroupPropertySetEvent(Group group, int property, Object value) { super(group); this.property = property; this.value = value; } /** * Gets the property that will be set. * * @return */ public int getProperty() { return property; } /** * Gets the value that the property will be set to. * * @return */ public Object getValue() { return value; } @Override public HandlerList getHandlers() { return handlers; } /** * Gets the HandlerList of the event. * * @return */ public static HandlerList getHandlerList() { return handlers; } }
src/main/java/com/volumetricpixels/politics/event/group/GroupPropertySetEvent.java
/* * This file is part of Politics. * * Copyright (c) 2012-2012, VolumetricPixels <http://volumetricpixels.com/> * Politics is licensed under the Affero General Public License Version 3. * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU Affero General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Affero General Public License for more details. * * You should have received a copy of the GNU Affero General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ package com.volumetricpixels.politics.event.group; import com.volumetricpixels.politics.group.Group; import com.volumetricpixels.politics.plot.Plot; import org.spout.api.event.Cancellable; import org.spout.api.event.HandlerList; /** * Called when a property is set. Note that transforms, points, and blocks will * all be strings. */ public class GroupPropertySetEvent extends GroupEvent { private static final HandlerList handlers = new HandlerList(); /** * The property that was set. */ private final int property; /** * The value of the property. */ private final Object value; /** * C'tor * * @param group * @param value The value */ public GroupPropertySetEvent(Group group, int property, Object value) { super(group); this.property = property; this.value = value; } /** * Gets the property that will be set. * * @return */ public int getProperty() { return property; } /** * Gets the value that the property will be set to. * * @return */ public Object getValue() { return value; } @Override public HandlerList getHandlers() { return handlers; } /** * Gets the HandlerList of the event. * * @return */ public static HandlerList getHandlerList() { return handlers; } }
Clean up some crap Signed-off-by: Ian Macalinao <[email protected]>
src/main/java/com/volumetricpixels/politics/event/group/GroupPropertySetEvent.java
Clean up some crap Signed-off-by: Ian Macalinao <[email protected]>
<ide><path>rc/main/java/com/volumetricpixels/politics/event/group/GroupPropertySetEvent.java <ide> package com.volumetricpixels.politics.event.group; <ide> <ide> import com.volumetricpixels.politics.group.Group; <del>import com.volumetricpixels.politics.plot.Plot; <del>import org.spout.api.event.Cancellable; <ide> import org.spout.api.event.HandlerList; <ide> <ide> /**
Java
agpl-3.0
740d06f06524d3d4645dd303cd23d62c227fc293
0
xmao/cbioportal,adamabeshouse/cbioportal,sheridancbio/cbioportal,HectorWon/cbioportal,leedonghn4/cbio-portal-webgl,inodb/cbioportal,pughlab/cbioportal,sheridancbio/cbioportal,IntersectAustralia/cbioportal,shrumit/cbioportal-gsoc-final,zheins/cbioportal,zhx828/cbioportal,angelicaochoa/cbioportal,d3b-center/pedcbioportal,zheins/cbioportal,xmao/cbioportal,onursumer/cbioportal,IntersectAustralia/cbioportal,angelicaochoa/cbioportal,HectorWon/cbioportal,d3b-center/pedcbioportal,bihealth/cbioportal,inodb/cbioportal,yichaoS/cbioportal,inodb/cbioportal,kalletlak/cbioportal,zheins/cbioportal,bihealth/cbioportal,j-hudecek/cbioportal,xmao/cbioportal,pughlab/cbioportal,holtgrewe/cbioportal,bengusty/cbioportal,bengusty/cbioportal,zheins/cbioportal,jjgao/cbioportal,bihealth/cbioportal,bihealth/cbioportal,kalletlak/cbioportal,onursumer/cbioportal,onursumer/cbioportal,sheridancbio/cbioportal,gsun83/cbioportal,jjgao/cbioportal,yichaoS/cbioportal,adamabeshouse/cbioportal,d3b-center/pedcbioportal,jjgao/cbioportal,n1zea144/cbioportal,mandawilson/cbioportal,cBioPortal/cbioportal,leedonghn4/cbio-portal-webgl,leedonghn4/cbioportal,zhx828/cbioportal,j-hudecek/cbioportal,kalletlak/cbioportal,bengusty/cbioportal,IntersectAustralia/cbioportal,leedonghn4/cbioportal,jjgao/cbioportal,kalletlak/cbioportal,istemi-bahceci/cbioportal,IntersectAustralia/cbioportal,angelicaochoa/cbioportal,zhx828/cbioportal,holtgrewe/cbioportal,n1zea144/cbioportal,istemi-bahceci/cbioportal,shrumit/cbioportal-gsoc-final,jjgao/cbioportal,mandawilson/cbioportal,mandawilson/cbioportal,leedonghn4/cbioportal,fcriscuo/cbioportal,xmao/cbioportal,yichaoS/cbioportal,inodb/cbioportal,yichaoS/cbioportal,adamabeshouse/cbioportal,gsun83/cbioportal,bengusty/cbioportal,cBioPortal/cbioportal,zheins/cbioportal,zhx828/cbioportal,pughlab/cbioportal,shrumit/cbioportal-gsoc-final,n1zea144/cbioportal,j-hudecek/cbioportal,inodb/cbioportal,shrumit/cbioportal-gsoc-final,gsun83/cbioportal,j-hudecek/cbioportal,shrumit/cbioportal-gsoc-final,shrumit/cbioportal-gsoc-final,n1zea144/cbioportal,n1zea144/cbioportal,IntersectAustralia/cbioportal,bengusty/cbioportal,mandawilson/cbioportal,leedonghn4/cbioportal,istemi-bahceci/cbioportal,sheridancbio/cbioportal,gsun83/cbioportal,leedonghn4/cbio-portal-webgl,kalletlak/cbioportal,istemi-bahceci/cbioportal,sheridancbio/cbioportal,fcriscuo/cbioportal,leedonghn4/cbioportal,adamabeshouse/cbioportal,leedonghn4/cbio-portal-webgl,jjgao/cbioportal,j-hudecek/cbioportal,mandawilson/cbioportal,HectorWon/cbioportal,n1zea144/cbioportal,fcriscuo/cbioportal,cBioPortal/cbioportal,xmao/cbioportal,j-hudecek/cbioportal,fcriscuo/cbioportal,jjgao/cbioportal,zhx828/cbioportal,d3b-center/pedcbioportal,pughlab/cbioportal,cBioPortal/cbioportal,yichaoS/cbioportal,angelicaochoa/cbioportal,yichaoS/cbioportal,yichaoS/cbioportal,bihealth/cbioportal,kalletlak/cbioportal,IntersectAustralia/cbioportal,adamabeshouse/cbioportal,onursumer/cbioportal,inodb/cbioportal,d3b-center/pedcbioportal,zhx828/cbioportal,HectorWon/cbioportal,leedonghn4/cbioportal,mandawilson/cbioportal,kalletlak/cbioportal,holtgrewe/cbioportal,bengusty/cbioportal,angelicaochoa/cbioportal,adamabeshouse/cbioportal,bihealth/cbioportal,pughlab/cbioportal,xmao/cbioportal,d3b-center/pedcbioportal,d3b-center/pedcbioportal,zhx828/cbioportal,onursumer/cbioportal,bihealth/cbioportal,fcriscuo/cbioportal,leedonghn4/cbio-portal-webgl,holtgrewe/cbioportal,gsun83/cbioportal,n1zea144/cbioportal,cBioPortal/cbioportal,adamabeshouse/cbioportal,leedonghn4/cbio-portal-webgl,cBioPortal/cbioportal,inodb/cbioportal,pughlab/cbioportal,HectorWon/cbioportal,fcriscuo/cbioportal,sheridancbio/cbioportal,gsun83/cbioportal,angelicaochoa/cbioportal,angelicaochoa/cbioportal,zheins/cbioportal,holtgrewe/cbioportal,holtgrewe/cbioportal,mandawilson/cbioportal,pughlab/cbioportal,shrumit/cbioportal-gsoc-final,IntersectAustralia/cbioportal,istemi-bahceci/cbioportal,HectorWon/cbioportal,gsun83/cbioportal,onursumer/cbioportal,istemi-bahceci/cbioportal
/** Copyright (c) 2012 Memorial Sloan-Kettering Cancer Center. ** ** 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 ** 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. The software and ** documentation provided hereunder is on an "as is" basis, and ** Memorial Sloan-Kettering Cancer Center ** has no obligations to provide maintenance, support, ** updates, enhancements or modifications. In no event shall ** Memorial Sloan-Kettering Cancer Center ** 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 ** Memorial Sloan-Kettering Cancer Center ** has been advised of the possibility of such damage. 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.mskcc.cbio.cgds.scripts; import org.mskcc.cbio.cgds.dao.*; import org.mskcc.cbio.cgds.model.CanonicalGene; import org.mskcc.cbio.cgds.model.ExtendedMutation; import org.mskcc.cbio.cgds.util.ConsoleUtil; import org.mskcc.cbio.cgds.util.ProgressMonitor; import org.mskcc.cbio.maf.FusionFileUtil; import org.mskcc.cbio.maf.FusionRecord; import org.mskcc.cbio.maf.TabDelimitedFileUtil; import org.mskcc.cbio.portal.util.ExtendedMutationUtil; import java.io.BufferedReader; import java.io.File; import java.io.FileReader; import java.io.IOException; /** * Imports a fusion file. * Columns may be in any order. * Creates an ExtendedMutation instances for each row. * * @author Selcuk Onur Sumer */ public class ImportFusionData { public static final String FUSION = "Fusion"; private ProgressMonitor pMonitor; private File fusionFile; private int geneticProfileId; public ImportFusionData(File fusionFile, int geneticProfileId, ProgressMonitor pMonitor) { this.fusionFile = fusionFile; this.geneticProfileId = geneticProfileId; this.pMonitor = pMonitor; } public void importData() throws IOException, DaoException { FileReader reader = new FileReader(this.fusionFile); BufferedReader buf = new BufferedReader(reader); DaoGeneOptimized daoGene = DaoGeneOptimized.getInstance(); // The MAF File Changes fairly frequently, and we cannot use column index constants. String line = buf.readLine(); line = line.trim(); FusionFileUtil fusionUtil = new FusionFileUtil(line); boolean addEvent = true; while ((line = buf.readLine()) != null) { if( pMonitor != null) { pMonitor.incrementCurValue(); ConsoleUtil.showProgress(pMonitor); } if( !line.startsWith("#") && line.trim().length() > 0) { FusionRecord record = fusionUtil.parseRecord(line); // process case id String barCode = record.getTumorSampleID(); String caseId = ExtendedMutationUtil.getCaseId(barCode); if (!DaoCaseProfile.caseExistsInGeneticProfile(caseId, geneticProfileId)) { DaoCaseProfile.addCaseProfile(caseId, geneticProfileId); } // Assume we are dealing with Entrez Gene Ids (this is the best / most stable option) String geneSymbol = record.getHugoGeneSymbol(); long entrezGeneId = record.getEntrezGeneId(); CanonicalGene gene = null; if (entrezGeneId != TabDelimitedFileUtil.NA_LONG) { gene = daoGene.getGene(entrezGeneId); } if (gene == null) { // If Entrez Gene ID Fails, try Symbol. gene = daoGene.getNonAmbiguousGene(geneSymbol); } if(gene == null) { pMonitor.logWarning("Gene not found: " + geneSymbol + " [" + entrezGeneId + "]. Ignoring it " + "and all fusion data associated with it!"); } else { // create a mutation instance with default values ExtendedMutation mutation = ExtendedMutationUtil.newMutation(); mutation.setGeneticProfileId(geneticProfileId); mutation.setCaseId(caseId); mutation.setGene(gene); mutation.setSequencingCenter(record.getCenter()); mutation.setProteinChange(record.getFusion()); // TODO we may need get mutation type from the file // instead of defining a constant mutation.setMutationType(FUSION); // add mutation (but add mutation event only once since it is a dummy event) DaoMutation.addMutation(mutation, addEvent); addEvent = false; } } } buf.close(); if( MySQLbulkLoader.isBulkLoad()) { MySQLbulkLoader.flushAll(); } } }
core/src/main/java/org/mskcc/cbio/cgds/scripts/ImportFusionData.java
/** Copyright (c) 2012 Memorial Sloan-Kettering Cancer Center. ** ** 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 ** 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. The software and ** documentation provided hereunder is on an "as is" basis, and ** Memorial Sloan-Kettering Cancer Center ** has no obligations to provide maintenance, support, ** updates, enhancements or modifications. In no event shall ** Memorial Sloan-Kettering Cancer Center ** 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 ** Memorial Sloan-Kettering Cancer Center ** has been advised of the possibility of such damage. 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.mskcc.cbio.cgds.scripts; import org.mskcc.cbio.cgds.dao.*; import org.mskcc.cbio.cgds.model.CanonicalGene; import org.mskcc.cbio.cgds.model.ExtendedMutation; import org.mskcc.cbio.cgds.util.ConsoleUtil; import org.mskcc.cbio.cgds.util.ProgressMonitor; import org.mskcc.cbio.maf.FusionFileUtil; import org.mskcc.cbio.maf.FusionRecord; import org.mskcc.cbio.maf.TabDelimitedFileUtil; import org.mskcc.cbio.portal.util.ExtendedMutationUtil; import java.io.BufferedReader; import java.io.File; import java.io.FileReader; import java.io.IOException; /** * Imports a fusion file. * Columns may be in any order. * * @author Selcuk Onur Sumer */ public class ImportFusionData { private ProgressMonitor pMonitor; private File fusionFile; private int geneticProfileId; public ImportFusionData(File fusionFile, int geneticProfileId, ProgressMonitor pMonitor) { this.fusionFile = fusionFile; this.geneticProfileId = geneticProfileId; this.pMonitor = pMonitor; } public void importData() throws IOException, DaoException { FileReader reader = new FileReader(this.fusionFile); BufferedReader buf = new BufferedReader(reader); DaoGeneOptimized daoGene = DaoGeneOptimized.getInstance(); // The MAF File Changes fairly frequently, and we cannot use column index constants. String line = buf.readLine(); line = line.trim(); FusionFileUtil fusionUtil = new FusionFileUtil(line); boolean addEvent = true; while ((line = buf.readLine()) != null) { if( pMonitor != null) { pMonitor.incrementCurValue(); ConsoleUtil.showProgress(pMonitor); } if( !line.startsWith("#") && line.trim().length() > 0) { FusionRecord record = fusionUtil.parseRecord(line); // process case id String barCode = record.getTumorSampleID(); String caseId = ExtendedMutationUtil.getCaseId(barCode); if (!DaoCaseProfile.caseExistsInGeneticProfile(caseId, geneticProfileId)) { DaoCaseProfile.addCaseProfile(caseId, geneticProfileId); } // Assume we are dealing with Entrez Gene Ids (this is the best / most stable option) String geneSymbol = record.getHugoGeneSymbol(); long entrezGeneId = record.getEntrezGeneId(); CanonicalGene gene = null; if (entrezGeneId != TabDelimitedFileUtil.NA_LONG) { gene = daoGene.getGene(entrezGeneId); } if (gene == null) { // If Entrez Gene ID Fails, try Symbol. gene = daoGene.getNonAmbiguousGene(geneSymbol); } if(gene == null) { pMonitor.logWarning("Gene not found: " + geneSymbol + " [" + entrezGeneId + "]. Ignoring it " + "and all fusion data associated with it!"); } else { // create a mutation instance with default values ExtendedMutation mutation = ExtendedMutationUtil.newMutation(); mutation.setGeneticProfileId(geneticProfileId); mutation.setCaseId(caseId); mutation.setGene(gene); mutation.setSequencingCenter(record.getCenter()); // TODO this may not be safe... mutation.setMutationType("Fusion"); mutation.setProteinChange(record.getFusion()); // add mutation (but add mutation event only once since it is a dummy event) DaoMutation.addMutation(mutation, addEvent); addEvent = false; } } } buf.close(); if( MySQLbulkLoader.isBulkLoad()) { MySQLbulkLoader.flushAll(); } } }
minor improvement for fusion data importer
core/src/main/java/org/mskcc/cbio/cgds/scripts/ImportFusionData.java
minor improvement for fusion data importer
<ide><path>ore/src/main/java/org/mskcc/cbio/cgds/scripts/ImportFusionData.java <ide> /** <ide> * Imports a fusion file. <ide> * Columns may be in any order. <add> * Creates an ExtendedMutation instances for each row. <ide> * <ide> * @author Selcuk Onur Sumer <ide> */ <ide> public class ImportFusionData <ide> { <add> public static final String FUSION = "Fusion"; <add> <ide> private ProgressMonitor pMonitor; <ide> private File fusionFile; <ide> private int geneticProfileId; <ide> mutation.setCaseId(caseId); <ide> mutation.setGene(gene); <ide> mutation.setSequencingCenter(record.getCenter()); <add> mutation.setProteinChange(record.getFusion()); <ide> <del> // TODO this may not be safe... <del> mutation.setMutationType("Fusion"); <del> mutation.setProteinChange(record.getFusion()); <add> // TODO we may need get mutation type from the file <add> // instead of defining a constant <add> mutation.setMutationType(FUSION); <ide> <ide> // add mutation (but add mutation event only once since it is a dummy event) <ide> DaoMutation.addMutation(mutation, addEvent);
Java
mit
f345ef589b8753df6591d5df248507f02be1b758
0
typescript-exercise/rusk,typescript-exercise/rusk,typescript-exercise/rusk
package rusk.test.db; import jp.classmethod.testing.database.DbUnitTester; import jp.classmethod.testing.database.JdbcDatabaseConnectionManager; /** * Rusk 開発用の DbUnitTester */ public class RuskDBTester extends DbUnitTester { public RuskDBTester() { super(new RuskJdbcDatabaseConnectionManager()); } private static class RuskJdbcDatabaseConnectionManager extends JdbcDatabaseConnectionManager { RuskJdbcDatabaseConnectionManager() { super(TestDatabaseConfig.DRIVER, TestDatabaseConfig.URL); super.username = TestDatabaseConfig.USER; super.password = TestDatabaseConfig.PASS; } } }
src/test/java/rusk/test/db/RuskDBTester.java
package rusk.test.db; import jp.classmethod.testing.database.DbUnitTester; import jp.classmethod.testing.database.JdbcDatabaseConnectionManager; /** * Rusk 開発用の DbUnitTester */ public class RuskDBTester extends DbUnitTester { public RuskDBTester() { super(new RuskJdbcDatabaseConnectionManager()); } private static class RuskJdbcDatabaseConnectionManager extends JdbcDatabaseConnectionManager { RuskJdbcDatabaseConnectionManager() { super("org.hsqldb.jdbcDriver", "jdbc:hsqldb:file:testdb/rusk;shutdown=true"); super.username = "SA"; super.password = ""; } } }
DB 接続設定共通化漏れ
src/test/java/rusk/test/db/RuskDBTester.java
DB 接続設定共通化漏れ
<ide><path>rc/test/java/rusk/test/db/RuskDBTester.java <ide> <ide> private static class RuskJdbcDatabaseConnectionManager extends JdbcDatabaseConnectionManager { <ide> RuskJdbcDatabaseConnectionManager() { <del> super("org.hsqldb.jdbcDriver", "jdbc:hsqldb:file:testdb/rusk;shutdown=true"); <del> super.username = "SA"; <del> super.password = ""; <add> super(TestDatabaseConfig.DRIVER, TestDatabaseConfig.URL); <add> super.username = TestDatabaseConfig.USER; <add> super.password = TestDatabaseConfig.PASS; <ide> } <ide> } <ide> }
JavaScript
mit
618c3e48aca5b1e606a6e93b03d7011946eb4679
0
overtrue/validator.js,overtrue/validator.js
/** * mod-validator * * @author Carlos <[email protected]> * @link https://github.com/overtrue/mod-validator * @version 0.0.7 * @license MIT */ /** * mod-validator * * @return {Void} */ (function() { // numeric rules var _numericRules = ['Numeric', 'Integer']; // messages var _messages = { accepted : "The :attribute must be accepted.", alpha : "The :attribute may only contain letters.", alpha_dash : "The :attribute may only contain letters, numbers, and dashes.", alpha_num : "The :attribute may only contain letters and numbers.", array : "The :attribute must be an array.", object : "The :attribute must be an object.", between : { numeric : "The :attribute must be between :min and :max.", string : "The :attribute must be between :min and :max characters.", array : "The :attribute must have between :min and :max items.", }, confirmed : "The :attribute confirmation does not match.", different : "The :attribute and :other must be different.", digits : "The :attribute must be :digits digits.", digits_between : "The :attribute must be between :min and :max digits.", email : "The :attribute format is invalid.", "in" : "The selected :attribute is invalid.", integer : "The :attribute must be an integer.", ip : "The :attribute must be a valid IP address.", max : { numeric : "The :attribute may not be greater than :max.", string : "The :attribute may not be greater than :max characters.", array : "The :attribute may not have more than :max items.", }, mimes : "The :attribute must be a file of type: :values.", min : { numeric : "The :attribute must be at least :min.", string : "The :attribute must be at least :min characters.", array : "The :attribute must have at least :min items.", }, not_in : "The selected :attribute is invalid.", numeric : "The :attribute must be a number.", regex : "The :attribute format is invalid.", required : "The :attribute field is required.", required_if : "The :attribute field is required when :other is :value.", required_with : "The :attribute field is required when :values is present.", required_without : "The :attribute field is required when :values is not present.", same : "The :attribute and :other must match.", size : { numeric : "The :attribute must be :size.", string : "The :attribute must be :size characters.", array : "The :attribute must contain :size items.", }, url : "The :attribute format is invalid.", def : 'The :attribute attribute has errors.', }; // attribute alias var _attributes = {}; // attribute value alias var _values = {}; // input data var _input = {}; // validation rules var _rules = {}; // failed rules var _failedRules = {}; // errors var _errors = {}; // attribute replacers var _replacers = {}; // translator var _translator = { trans: function(key){ return key; } }; // Based on jquery's extend function function extend() { var src, copy, name, options, clone; var target = arguments[0] || {}; var i = 1; var length = arguments.length; for ( ; i < length; i++ ) { // Only deal with non-null/undefined values if ( (options = arguments[ i ]) != null ) { // Extend the base object for ( name in options ) { src = target[ name ]; copy = options[ name ]; // Prevent never-ending loop if ( target === copy ) { continue; } // Recurse if we're merging plain objects or arrays if ( copy && typeof copy === "object" ) { clone = src && typeof src === "object" ? src : {}; // Never move original objects, clone them target[ name ] = extend( clone, copy ); // Don't bring in undefined values } else if ( copy !== undefined ) { target[ name ] = copy; } } } } // Return the modified object return target; } //php function:in_array function in_array(needle, haystack, argStrict) { var key = '', strict = !! argStrict; for (key in haystack) { if (strict ? (haystack[key] === needle) : haystack[key] == needle) { return true; } } return false; } /** * determine needle is a object * * @param {Mixed} needle * * @return {Boolean} */ function is_object(needle) { return (typeof needle === 'object'); } /** * determine object is a empty object * * @param {Object} obj * * @return {Boolean} */ function isEmptyObject(obj){ for(var n in obj){return false} return true; } /** * determine needle is a array * * @param {Mixed} needle * * @return {Boolean} */ function is_array(arr) { return typeof arr === 'object' && typeof arr.length === 'number' && !(arr.propertyIsEnumerable('length')) && typeof arr.splice === 'function'; } /** * determine needle is a function * * @param {Mixed} needle * * @return {Boolean} */ function is_function(needle) { return (typeof needle === 'function'); } /** * determine needle is a object * * @param {Mixed} needle * * @return {Boolean} */ function is_string(needle) { return (typeof needle === 'string'); } /** * explode the rules into an array of rules. * * @return {Void} */ function _explodeRules(rules) { for (var i in rules) { if (is_string(rules[i])) { rules[i] = rules[i].split('|'); } } return rules; } /** * parse the rule * * @param {Array} rule * * @return {Object} */ function _parseRule(rule) { var parameters = []; // The format for specifying validation rules and parameters follows an // easy {rule}:{parameters} formatting convention. For instance the // rule "Max:3" states that the value may only be three letters. if (rule.indexOf(':')) { var ruleInfo = rule.split(':'); parameters = _parseParameters(ruleInfo[0], ruleInfo[1]); } return { parameters: parameters, rule: ruleInfo[0]}; } /** * parse parameters of rule * * @param {String} rule * @param {String} parameter * * @return {Array} */ function _parseParameters(rule, parameter) { if (rule.toLowerCase() == 'regex') return [parameter]; if (is_string(parameter)) { return parameter.split(','); }; return []; } /** * add a failure rule * * @param {String} attribute * @param {String} rule * @param {Array} parameters * * @return {Void} */ function _addFailure(attribute, rule, parameters) { _addError(attribute, rule, parameters); if (! _failedRules[attribute]) { _failedRules[attribute] = {}; } _failedRules[attribute][rule] = parameters; } /** * add a error message * * @param {String} attribute * @param {String} rule * @param {Array} parameters * * @return {Void} */ function _addError(attribute, rule, parameters) { if (_errors[attribute]) { return; }; _errors[attribute] = _doReplacements(_getMessage(attribute, rule) || '', attribute, rule, parameters); } /** * get value of arrtibute * * @param {String} attribute * * @return {Mixed} */ function _getValue(attribute) { return _input[attribute] || null; } /** * get attribute message * * @param {String} attribute * @param {String} rule * * @return {String} */ function _getMessage(attribute, rule) { var message = _messages[rule]; if (is_object(message)) { var value = _getValue(attribute); if (is_array(value) && message['array']) { return message['array']; } else if (_resolvers.numeric(value) && message['numeric']) { return message['numeric']; } else if (is_string(value) && message['string']){ return message['string']; } }; return message; } /** * replace attributes in mesage * * @param {String} message * @param {String} attribute * @param {String} rule * @param {Array} parameters * * @return {String} */ function _doReplacements(message, attribute, rule, parameters) { message = message.replace(':attribute', _getAttribute(attribute)) if (typeof _replacers[rule] === 'function') { message = _replacers[rule](message, attribute, rule, parameters); } return message; } /** * get attribute name * * @param {String} attribute * * @return {String} */ function _getAttribute(attribute) { if (is_string(_attributes[attribute])) { return _attributes[attribute]; } if ((line = _translator.trans(attribute)) !== attribute) { return line; } else { return attribute.replace('_', ' '); } } /** * determine if the given attribute has a rule in the given set. * * @param {String} attribute * @param {String|array} rules * * @return {Boolean} */ function _hasRule(attribute, rules) { return ! _getRule(attribute, rules) == null; } /** * get rule and parameters of a rules * * @param {String} attribute * @param {String|array} rules * * @return {Array|null} */ function _getRule(attribute, rules) { rules = rules || []; if ( ! rules[attribute]) { return; } for(var i in rules[attribute]) { var value = rules[attribute][i]; parsedRule = _parseRule(rule); if (in_array(parsedRule.rule, rules)) return [parsedRule.rule, parsedRule.parameters]; } } /** * get attribute size * * @param {String} attribute * @param {Mixed} value * * @return {Number} */ function _getSize(attribute, value) { hasNumeric = _hasRule(attribute, _numericRules); // This method will determine if the attribute is a number, string, or file and // return the proper size accordingly. If it is a number, then number itself // is the size. If it is a file, we take kilobytes, and for a string the // entire length of the string will be considered the attribute size. if (/^[0-9]+$/.test(value) && hasNumeric) { return getValue(attribute); } else if (value && is_string(value) || is_array(value)) { return value.length; } return 0; } /** * check parameters count * * @param {Number} count * @param {Array} parameters * @param {String} rule * * @return {Void} */ function _requireParameterCount(count, parameters, rule) { if (parameters.length < count) { throw Error('Validation rule"' + rule + '" requires at least ' + count + ' parameters.'); } } /** * all failing check * * @param {Array} attributes * * @return {Boolean} */ function _allFailingRequired(attributes) { for (var i in attributes) { var akey = attributes[i]; if (resolvers.validateRequired(key, self._getValue(key))) { return false; } } return true; } /** * determine if any of the given attributes fail the required test. * * @param array $attributes * @return bool */ function _anyFailingRequired(attributes) { for (var i in attributes) { var key = attributes[i]; if ( ! _resolvers.validateRequired(key, self.date[key])) { return true; } } return false; } var _resolvers = { accepted: function(attribute, value) { var acceptable = ['yes', 'on', '1', 1, true, 'true']; is_string(value) && (value = value.toLowerCase()); return (this.required(attribute, value) && in_array(value, acceptable, true)); }, alpha: function(attribute, value) { if (!value) { return false;}; return ((new RegExp('^[a-z]+$', 'i')).test(value)); }, alpha_dash: function(attribute, value) { return ((new RegExp('^[a-z0-9\-_]+$', 'i')).test(value)); }, alpha_num: function(attribute, value) { return ((new RegExp('^[a-z0-9]+$', 'i')).test(value)); }, array: function(attribute, value) { return is_array(value); }, object: function(attribute, value) { return is_object(value); }, between: function(attribute, value, parameters) { _requireParameterCount(2, parameters, 'between'); var size = _getSize(attribute, value); return size >= parameters[0] && size <= parameters[1]; }, confirmed: function(attribute, value, parameters) { return this.same(attribute, value, [attribute + '_confirmation']); }, same: function(attribute, value, parameters) { _requireParameterCount(1, parameters, 'same'); var other = _getValue(parameters[0]); return (other && value == other); }, different: function(attribute, value, parameters) { return ! this.same(attribute, value, parameters); }, digits: function(attribute, value, parameters) { _requireParameterCount(1, parameters, 'digits'); return (new RegExp('^\d{' + Math.abs(parameters[0]) + '}$')).test(value); }, digits_between: function(attribute, value, parameters) { _requireParameterCount(2, parameters, 'digits_between'); return ((new RegExp('^\d{' + Math.abs(parameters[0]) + '}$')).test(value) && value > parameters[0] && value < parameters[1]); }, email: function(attribute, value) { var regex = /^((([a-z]|\d|[!#\$%&'\*\+\-\/=\?\^_`{\|}~]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])+(\.([a-z]|\d|[!#\$%&'\*\+\-\/=\?\^_`{\|}~]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])+)*)|((\x22)((((\x20|\x09)*(\x0d\x0a))?(\x20|\x09)+)?(([\x01-\x08\x0b\x0c\x0e-\x1f\x7f]|\x21|[\x23-\x5b]|[\x5d-\x7e]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(\\([\x01-\x09\x0b\x0c\x0d-\x7f]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF]))))*(((\x20|\x09)*(\x0d\x0a))?(\x20|\x09)+)?(\x22)))@((([a-z]|\d|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(([a-z]|\d|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])([a-z]|\d|-|\.|_|~|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])*([a-z]|\d|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])))\.)+(([a-z]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(([a-z]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])([a-z]|\d|-|\.|_|~|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])*([a-z]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])))\.?$/i; return regex.test(value); }, "in": function(attribute, value, parameters) { return in_array(value || '', parameters); }, not_in: function(attribute, value, parameters) { return !in_array(value || '', parameters); }, integer: function(attribute, value) { return /^(?:-?(?:0|[1-9][0-9]*))$/.test(value); }, ip: function(attribute, value) { var ipv4Maybe = /^(\d?\d?\d)\.(\d?\d?\d)\.(\d?\d?\d)\.(\d?\d?\d)$/ , ipv6 = /^::|^::1|^([a-fA-F0-9]{1,4}::?){1,7}([a-fA-F0-9]{1,4})$/; return ipv4Maybe.test(value) || ipv6.test(value); }, max: function(attribute, value, parameters) { _requireParameterCount(1, parameters, 'max'); return _getSize(attribute, value) <= parameters[0]; }, min: function(attribute, value, parameters) { _requireParameterCount(1, parameters, 'min'); return _getSize(attribute, value) >= parameters[0]; }, numeric: function(attribute, value) { return /^[0-9]+$/.test(value); }, regex: function(attribute, value, parameters) { _requireParameterCount(1, parameters, 'regex'); return (new RegExp(parameters[0])).test(value); }, required: function(attribute, value) { if (!value || undefined === value) { return false; } else if ((is_string(value) || is_array(value) || is_object(value)) && !value.length) { return false; } return true; }, required_if: function(attribute, value, parameters) { _requireParameterCount(2, parameters, 'required_if'); var _input = getValue(parameters[0]); var values = parameters.splice(1); if (in_array(data, values)) { return resolvers.required(attribute, value); } return true; }, required_with: function(attribute, value, parameters) { if ( ! self._allFailingRequired(parameters)) { return resolvers.required(attribute, value); } return true; }, required_without: function(attribute, value, parameters) { if (self._anyFailingRequired(parameters)) { return resolvers.required(attribute, value); } return true; }, size: function(attribute, value, parameters) { _requireParameterCount(1, parameters, 'size'); return _getSize(attribute, value) == parameters[0]; }, url: function(attribute, value) { var strRegex = "^((https|http|ftp|rtsp|mms)?://)" + "?(([0-9a-z_!~*'().&=+$%-]+: )?[0-9a-z_!~*'().&=+$%-]+@)?" //ftp user@ + "(([0-9]{1,3}/.){3}[0-9]{1,3}" // IP- 199.194.52.184 + "|" // ip or domain + "([0-9a-z_!~*'()-]+/.)*" // domain- www. + "([0-9a-z][0-9a-z-]{0,61})?[0-9a-z]/." // sub domain + "[a-z]{2,6})" // first level domain- .com or .museum + "(:[0-9]{1,4})?" // port- :80 + "((/?)|" // a slash isn't required if there is no file name + "(/[0-9a-z_!~*'().;?:@&=+$,%#-]+)+/?)$"; var regex = new RegExp(strRegex); return regex.test(str_url); } }; var Validator = function(input, rules, customMessages) { if (undefined === input || undefined === rules) { throw Error('Validator constructor requires at least 2 parameters.'); }; // reset data expect _messages,_atteibutes, _values _input = input; _rules = rules; _failedRules = {}; _errors = {}; _messages = extend({}, _messages, customMessages || {}); }; Validator.prototype = { name: 'Validator', constructor: Validator, // error messages // {username: xxxx, password: xxxx} messages: function() { return _errors; }, errors: function(){ return _errors; }, // faildRules faildRules: _failedRules, // set translator setTranslator: function(translator){ _translator = translator || _translator; }, /** * exec validate * * @return {Boolean} */ passes: function() { rulesArray = _explodeRules(_rules); for (var attribute in rulesArray) { var rules = rulesArray[attribute]; for (var i in rules) { if (_errors[attribute]) { continue; }; var ruleString = rules[i]; var parsedRule = _parseRule(ruleString); var rule = parsedRule.rule; var parameters = parsedRule.parameters; var value = _input[attribute] || null; var validatable = is_function(_resolvers[rule]); if (validatable && ! _resolvers[rule](attribute, value, parameters)) { _addFailure(attribute, rule, parameters); } } } return isEmptyObject(_errors); }, /** * return the validate value * * @return {Boolean} */ fails: function() { return ! this.passes(); }, /** * add custom messages * * @param {String/Object} rule * @param {String} message * * @return {Void} */ mergeMessage: function(rule, message) { if (is_object(rule)) { _messages = extend({}, _messages, rule); } else if (is_string(rule)) { _messages[rule] = message; } }, /** * add attributes alias * * @param {String/Object} attribute * @param {String} alias * * @return {Void} */ mergeAttribute: function(attribute, alias) { if (is_object(attribute)) { _attributes = extend({}, _attributes, attribute); } else if (is_string(attribute)) { _attributes[attribute] = alias; } }, /** * add values alias * * @param {String/Object} attribute * @param {String} alias * * @return {Void} */ mergeValue: function(value, alias) { if (is_object(value)) { _values = extend({}, _values, value); } else if (is_string(rule)) { _values[value] = alias; } }, /** * add message replacers * * @param {String/Object} rule * @param {Function} fn * * @return {Void} */ mergeReplacers: function(rule, fn) { if (is_object(rule)) { _replacers = extend({}, _replacers, rule); } else if (is_string(rule)) { _replacers[rule] = fn; } } }; /** * register a user custom rule * * @param {String} rule * @param {Function} fn * @param {Object} errMsg * * @return {Void} */ Validator.register = function(rule, fn, errMsg) { _resolvers[rule] = fn; _messages[rule] = (is_string(errMsg)) ? errMsg : _messages['def']; }; /** * make a Validator instance * * @param {Object} data * @param {Object} rule * @param {Object} messages * * @return {Object} */ Validator.make = function(data, rule, messages){ return new Validator(data, rule, messages); }; if (typeof module !== 'undefined' && typeof require !== 'undefined') { module.exports = Validator; } else { window.validator = Validator; } }());
lib/validator.js
/** * mod-validator * * @author Carlos <[email protected]> * @link https://github.com/overtrue/mod-validator * @version 0.0.7 * @license MIT */ /** * mod-validator * * @return {Void} */ (function() { // numeric rules var _numericRules = ['Numeric', 'Integer']; // messages var _messages = { accepted : "The :attribute must be accepted.", alpha : "The :attribute may only contain letters.", alpha_dash : "The :attribute may only contain letters, numbers, and dashes.", alpha_num : "The :attribute may only contain letters and numbers.", array : "The :attribute must be an array.", between : { numeric : "The :attribute must be between :min and :max.", string : "The :attribute must be between :min and :max characters.", array : "The :attribute must have between :min and :max items.", }, confirmed : "The :attribute confirmation does not match.", different : "The :attribute and :other must be different.", digits : "The :attribute must be :digits digits.", digits_between : "The :attribute must be between :min and :max digits.", email : "The :attribute format is invalid.", "in" : "The selected :attribute is invalid.", integer : "The :attribute must be an integer.", ip : "The :attribute must be a valid IP address.", max : { numeric : "The :attribute may not be greater than :max.", string : "The :attribute may not be greater than :max characters.", array : "The :attribute may not have more than :max items.", }, mimes : "The :attribute must be a file of type: :values.", min : { numeric : "The :attribute must be at least :min.", string : "The :attribute must be at least :min characters.", array : "The :attribute must have at least :min items.", }, not_in : "The selected :attribute is invalid.", numeric : "The :attribute must be a number.", regex : "The :attribute format is invalid.", required : "The :attribute field is required.", required_if : "The :attribute field is required when :other is :value.", required_with : "The :attribute field is required when :values is present.", required_without : "The :attribute field is required when :values is not present.", same : "The :attribute and :other must match.", size : { numeric : "The :attribute must be :size.", string : "The :attribute must be :size characters.", array : "The :attribute must contain :size items.", }, url : "The :attribute format is invalid.", def : 'The :attribute attribute has errors.', }; // attribute alias var _attributes = {}; // attribute value alias var _values = {}; // input data var _input = {}; // validation rules var _rules = {}; // failed rules var _failedRules = {}; // errors var _errors = {}; // attribute replacers var _replacers = {}; // translator var _translator = { trans: function(key){ return key; } }; // Based on jquery's extend function function extend() { var src, copy, name, options, clone; var target = arguments[0] || {}; var i = 1; var length = arguments.length; for ( ; i < length; i++ ) { // Only deal with non-null/undefined values if ( (options = arguments[ i ]) != null ) { // Extend the base object for ( name in options ) { src = target[ name ]; copy = options[ name ]; // Prevent never-ending loop if ( target === copy ) { continue; } // Recurse if we're merging plain objects or arrays if ( copy && typeof copy === "object" ) { clone = src && typeof src === "object" ? src : {}; // Never move original objects, clone them target[ name ] = extend( clone, copy ); // Don't bring in undefined values } else if ( copy !== undefined ) { target[ name ] = copy; } } } } // Return the modified object return target; } //php function:in_array function in_array(needle, haystack, argStrict) { var key = '', strict = !! argStrict; for (key in haystack) { if (strict ? (haystack[key] === needle) : haystack[key] == needle) { return true; } } return false; } /** * determine needle is a object * * @param {Mixed} needle * * @return {Boolean} */ function is_object(needle) { return (typeof needle === 'object'); } /** * determine object is a empty object * * @param {Object} obj * * @return {Boolean} */ function isEmptyObject(obj){ for(var n in obj){return false} return true; } /** * determine needle is a array * * @param {Mixed} needle * * @return {Boolean} */ function is_array(arr) { return typeof arr === 'object' && typeof arr.length === 'number' && !(arr.propertyIsEnumerable('length')) && typeof arr.splice === 'function'; } /** * determine needle is a function * * @param {Mixed} needle * * @return {Boolean} */ function is_function(needle) { return (typeof needle === 'function'); } /** * determine needle is a object * * @param {Mixed} needle * * @return {Boolean} */ function is_string(needle) { return (typeof needle === 'string'); } /** * explode the rules into an array of rules. * * @return {Void} */ function _explodeRules(rules) { for (var i in rules) { if (is_string(rules[i])) { rules[i] = rules[i].split('|'); } } return rules; } /** * parse the rule * * @param {Array} rule * * @return {Object} */ function _parseRule(rule) { var parameters = []; // The format for specifying validation rules and parameters follows an // easy {rule}:{parameters} formatting convention. For instance the // rule "Max:3" states that the value may only be three letters. if (rule.indexOf(':')) { var ruleInfo = rule.split(':'); parameters = _parseParameters(ruleInfo[0], ruleInfo[1]); } return { parameters: parameters, rule: ruleInfo[0]}; } /** * parse parameters of rule * * @param {String} rule * @param {String} parameter * * @return {Array} */ function _parseParameters(rule, parameter) { if (rule.toLowerCase() == 'regex') return [parameter]; if (is_string(parameter)) { return parameter.split(','); }; return []; } /** * add a failure rule * * @param {String} attribute * @param {String} rule * @param {Array} parameters * * @return {Void} */ function _addFailure(attribute, rule, parameters) { _addError(attribute, rule, parameters); if (! _failedRules[attribute]) { _failedRules[attribute] = {}; } _failedRules[attribute][rule] = parameters; } /** * add a error message * * @param {String} attribute * @param {String} rule * @param {Array} parameters * * @return {Void} */ function _addError(attribute, rule, parameters) { if (_errors[attribute]) { return; }; _errors[attribute] = _doReplacements(_getMessage(attribute, rule) || '', attribute, rule, parameters); } /** * get value of arrtibute * * @param {String} attribute * * @return {Mixed} */ function _getValue(attribute) { return _input[attribute] || null; } /** * get attribute message * * @param {String} attribute * @param {String} rule * * @return {String} */ function _getMessage(attribute, rule) { var message = _messages[rule]; if (is_object(message)) { var value = _getValue(attribute); if (is_array(value) && message['array']) { return message['array']; } else if (_resolvers.numeric(value) && message['numeric']) { return message['numeric']; } else if (is_string(value) && message['string']){ return message['string']; } }; return message; } /** * replace attributes in mesage * * @param {String} message * @param {String} attribute * @param {String} rule * @param {Array} parameters * * @return {String} */ function _doReplacements(message, attribute, rule, parameters) { message = message.replace(':attribute', _getAttribute(attribute)) if (typeof _replacers[rule] === 'function') { message = _replacers[rule](message, attribute, rule, parameters); } return message; } /** * get attribute name * * @param {String} attribute * * @return {String} */ function _getAttribute(attribute) { if (is_string(_attributes[attribute])) { return _attributes[attribute]; } if ((line = _translator.trans(attribute)) !== attribute) { return line; } else { return attribute.replace('_', ' '); } } /** * determine if the given attribute has a rule in the given set. * * @param {String} attribute * @param {String|array} rules * * @return {Boolean} */ function _hasRule(attribute, rules) { return ! _getRule(attribute, rules) == null; } /** * get rule and parameters of a rules * * @param {String} attribute * @param {String|array} rules * * @return {Array|null} */ function _getRule(attribute, rules) { rules = rules || []; if ( ! rules[attribute]) { return; } for(var i in rules[attribute]) { var value = rules[attribute][i]; parsedRule = _parseRule(rule); if (in_array(parsedRule.rule, rules)) return [parsedRule.rule, parsedRule.parameters]; } } /** * get attribute size * * @param {String} attribute * @param {Mixed} value * * @return {Number} */ function _getSize(attribute, value) { hasNumeric = _hasRule(attribute, _numericRules); // This method will determine if the attribute is a number, string, or file and // return the proper size accordingly. If it is a number, then number itself // is the size. If it is a file, we take kilobytes, and for a string the // entire length of the string will be considered the attribute size. if (/^[0-9]+$/.test(value) && hasNumeric) { return getValue(attribute); } else if (value && is_string(value) || is_array(value)) { return value.length; } return 0; } /** * check parameters count * * @param {Number} count * @param {Array} parameters * @param {String} rule * * @return {Void} */ function _requireParameterCount(count, parameters, rule) { if (parameters.length < count) { throw Error('Validation rule"' + rule + '" requires at least ' + count + ' parameters.'); } } /** * all failing check * * @param {Array} attributes * * @return {Boolean} */ function _allFailingRequired(attributes) { for (var i in attributes) { var akey = attributes[i]; if (resolvers.validateRequired(key, self._getValue(key))) { return false; } } return true; } /** * determine if any of the given attributes fail the required test. * * @param array $attributes * @return bool */ function _anyFailingRequired(attributes) { for (var i in attributes) { var key = attributes[i]; if ( ! _resolvers.validateRequired(key, self.date[key])) { return true; } } return false; } var _resolvers = { accepted: function(attribute, value) { var acceptable = ['yes', 'on', '1', 1, true, 'true']; is_string(value) && (value = value.toLowerCase()); return (this.required(attribute, value) && in_array(value, acceptable, true)); }, alpha: function(attribute, value) { if (!value) { return false;}; return ((new RegExp('^[a-z]+$', 'i')).test(value)); }, alpha_dash: function(attribute, value) { return ((new RegExp('^[a-z0-9\-_]+$', 'i')).test(value)); }, alpha_num: function(attribute, value) { return ((new RegExp('^[a-z0-9]+$', 'i')).test(value)); }, array: function(attribute, value) { return is_array(value); }, between: function(attribute, value, parameters) { _requireParameterCount(2, parameters, 'between'); var size = _getSize(attribute, value); return size >= parameters[0] && size <= parameters[1]; }, confirmed: function(attribute, value, parameters) { return this.same(attribute, value, [attribute + '_confirmation']); }, same: function(attribute, value, parameters) { _requireParameterCount(1, parameters, 'same'); var other = _getValue(parameters[0]); return (other && value == other); }, different: function(attribute, value, parameters) { return ! this.same(attribute, value, parameters); }, digits: function(attribute, value, parameters) { _requireParameterCount(1, parameters, 'digits'); return (new RegExp('^\d{' + Math.abs(parameters[0]) + '}$')).test(value); }, digits_between: function(attribute, value, parameters) { _requireParameterCount(2, parameters, 'digits_between'); return ((new RegExp('^\d{' + Math.abs(parameters[0]) + '}$')).test(value) && value > parameters[0] && value < parameters[1]); }, email: function(attribute, value) { var regex = /^((([a-z]|\d|[!#\$%&'\*\+\-\/=\?\^_`{\|}~]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])+(\.([a-z]|\d|[!#\$%&'\*\+\-\/=\?\^_`{\|}~]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])+)*)|((\x22)((((\x20|\x09)*(\x0d\x0a))?(\x20|\x09)+)?(([\x01-\x08\x0b\x0c\x0e-\x1f\x7f]|\x21|[\x23-\x5b]|[\x5d-\x7e]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(\\([\x01-\x09\x0b\x0c\x0d-\x7f]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF]))))*(((\x20|\x09)*(\x0d\x0a))?(\x20|\x09)+)?(\x22)))@((([a-z]|\d|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(([a-z]|\d|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])([a-z]|\d|-|\.|_|~|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])*([a-z]|\d|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])))\.)+(([a-z]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(([a-z]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])([a-z]|\d|-|\.|_|~|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])*([a-z]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])))\.?$/i; return regex.test(value); }, "in": function(attribute, value, parameters) { return in_array(value || '', parameters); }, not_in: function(attribute, value, parameters) { return !in_array(value || '', parameters); }, integer: function(attribute, value) { return /^(?:-?(?:0|[1-9][0-9]*))$/.test(value); }, ip: function(attribute, value) { var ipv4Maybe = /^(\d?\d?\d)\.(\d?\d?\d)\.(\d?\d?\d)\.(\d?\d?\d)$/ , ipv6 = /^::|^::1|^([a-fA-F0-9]{1,4}::?){1,7}([a-fA-F0-9]{1,4})$/; return ipv4Maybe.test(value) || ipv6.test(value); }, max: function(attribute, value, parameters) { _requireParameterCount(1, parameters, 'max'); return _getSize(attribute, value) <= parameters[0]; }, min: function(attribute, value, parameters) { _requireParameterCount(1, parameters, 'min'); return _getSize(attribute, value) >= parameters[0]; }, numeric: function(attribute, value) { return /^[0-9]+$/.test(value); }, regex: function(attribute, value, parameters) { _requireParameterCount(1, parameters, 'regex'); return (new RegExp(parameters[0])).test(value); }, required: function(attribute, value) { if (!value || undefined === value) { return false; } else if ((is_string(value) || is_array(value) || is_object(value)) && !value.length) { return false; } return true; }, required_if: function(attribute, value, parameters) { _requireParameterCount(2, parameters, 'required_if'); var _input = getValue(parameters[0]); var values = parameters.splice(1); if (in_array(data, values)) { return resolvers.required(attribute, value); } return true; }, required_with: function(attribute, value, parameters) { if ( ! self._allFailingRequired(parameters)) { return resolvers.required(attribute, value); } return true; }, required_without: function(attribute, value, parameters) { if (self._anyFailingRequired(parameters)) { return resolvers.required(attribute, value); } return true; }, size: function(attribute, value, parameters) { _requireParameterCount(1, parameters, 'size'); return _getSize(attribute, value) == parameters[0]; }, url: function(attribute, value) { var strRegex = "^((https|http|ftp|rtsp|mms)?://)" + "?(([0-9a-z_!~*'().&=+$%-]+: )?[0-9a-z_!~*'().&=+$%-]+@)?" //ftp user@ + "(([0-9]{1,3}/.){3}[0-9]{1,3}" // IP- 199.194.52.184 + "|" // ip or domain + "([0-9a-z_!~*'()-]+/.)*" // domain- www. + "([0-9a-z][0-9a-z-]{0,61})?[0-9a-z]/." // sub domain + "[a-z]{2,6})" // first level domain- .com or .museum + "(:[0-9]{1,4})?" // port- :80 + "((/?)|" // a slash isn't required if there is no file name + "(/[0-9a-z_!~*'().;?:@&=+$,%#-]+)+/?)$"; var regex = new RegExp(strRegex); return regex.test(str_url); } }; var Validator = function(input, rules, customMessages) { if (undefined === input || undefined === rules) { throw Error('Validator constructor requires at least 2 parameters.'); }; // reset data expect _messages,_atteibutes, _values _input = input; _rules = rules; _failedRules = {}; _errors = {}; _messages = extend({}, _messages, customMessages || {}); }; Validator.prototype = { name: 'Validator', constructor: Validator, // error messages // {username: xxxx, password: xxxx} messages: function() { return _errors; }, errors: function(){ return _errors; }, // faildRules faildRules: _failedRules, // set translator setTranslator: function(translator){ _translator = translator || _translator; }, /** * exec validate * * @return {Boolean} */ passes: function() { rulesArray = _explodeRules(_rules); for (var attribute in rulesArray) { var rules = rulesArray[attribute]; for (var i in rules) { if (_errors[attribute]) { continue; }; var ruleString = rules[i]; var parsedRule = _parseRule(ruleString); var rule = parsedRule.rule; var parameters = parsedRule.parameters; var value = _input[attribute] || null; var validatable = is_function(_resolvers[rule]); if (validatable && ! _resolvers[rule](attribute, value, parameters)) { _addFailure(attribute, rule, parameters); } } } return isEmptyObject(_errors); }, /** * return the validate value * * @return {Boolean} */ fails: function() { return ! this.passes(); }, /** * add custom messages * * @param {String/Object} rule * @param {String} message * * @return {Void} */ mergeMessage: function(rule, message) { if (is_object(rule)) { _messages = extend({}, _messages, rule); } else if (is_string(rule)) { _messages[rule] = message; } }, /** * add attributes alias * * @param {String/Object} attribute * @param {String} alias * * @return {Void} */ mergeAttribute: function(attribute, alias) { if (is_object(attribute)) { _attributes = extend({}, _attributes, attribute); } else if (is_string(attribute)) { _attributes[attribute] = alias; } }, /** * add values alias * * @param {String/Object} attribute * @param {String} alias * * @return {Void} */ mergeValue: function(value, alias) { if (is_object(value)) { _values = extend({}, _values, value); } else if (is_string(rule)) { _values[value] = alias; } }, /** * add message replacers * * @param {String/Object} rule * @param {Function} fn * * @return {Void} */ mergeReplacers: function(rule, fn) { if (is_object(rule)) { _replacers = extend({}, _replacers, rule); } else if (is_string(rule)) { _replacers[rule] = fn; } } }; /** * register a user custom rule * * @param {String} rule * @param {Function} fn * @param {Object} errMsg * * @return {Void} */ Validator.register = function(rule, fn, errMsg) { _resolvers[rule] = fn; _messages[rule] = (is_string(errMsg)) ? errMsg : _messages['def']; }; /** * make a Validator instance * * @param {Object} data * @param {Object} rule * @param {Object} messages * * @return {Object} */ Validator.make = function(data, rule, messages){ return new Validator(data, rule, messages); }; if (typeof module !== 'undefined' && typeof require !== 'undefined') { module.exports = Validator; } else { window.validator = Validator; } }());
添加object规则
lib/validator.js
添加object规则
<ide><path>ib/validator.js <ide> alpha_dash : "The :attribute may only contain letters, numbers, and dashes.", <ide> alpha_num : "The :attribute may only contain letters and numbers.", <ide> array : "The :attribute must be an array.", <add> object : "The :attribute must be an object.", <ide> between : { <ide> numeric : "The :attribute must be between :min and :max.", <ide> string : "The :attribute must be between :min and :max characters.", <ide> array: function(attribute, value) { <ide> return is_array(value); <ide> }, <add> <add> object: function(attribute, value) { <add> return is_object(value); <add> }, <ide> <ide> between: function(attribute, value, parameters) { <ide> _requireParameterCount(2, parameters, 'between');
Java
apache-2.0
2b992e7218ee573c79a2c2a6c0970631a6d04e0a
0
samaitra/jena,CesarPantoja/jena,CesarPantoja/jena,jianglili007/jena,samaitra/jena,kamir/jena,atsolakid/jena,tr3vr/jena,CesarPantoja/jena,atsolakid/jena,samaitra/jena,jianglili007/jena,jianglili007/jena,adrapereira/jena,CesarPantoja/jena,apache/jena,atsolakid/jena,apache/jena,samaitra/jena,tr3vr/jena,tr3vr/jena,adrapereira/jena,kamir/jena,apache/jena,samaitra/jena,CesarPantoja/jena,apache/jena,kidaa/jena,apache/jena,atsolakid/jena,apache/jena,jianglili007/jena,kidaa/jena,kamir/jena,adrapereira/jena,atsolakid/jena,samaitra/jena,tr3vr/jena,kamir/jena,kamir/jena,CesarPantoja/jena,jianglili007/jena,kamir/jena,tr3vr/jena,jianglili007/jena,adrapereira/jena,kidaa/jena,kidaa/jena,tr3vr/jena,adrapereira/jena,atsolakid/jena,adrapereira/jena,kidaa/jena,samaitra/jena,atsolakid/jena,apache/jena,CesarPantoja/jena,tr3vr/jena,apache/jena,kamir/jena,kidaa/jena,adrapereira/jena,jianglili007/jena,kidaa/jena
/* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.hp.hpl.jena.sparql.expr; import static com.hp.hpl.jena.datatypes.xsd.XSDDatatype.* ; import static com.hp.hpl.jena.sparql.expr.ValueSpaceClassification.* ; import static javax.xml.datatype.DatatypeConstants.* ; import java.io.File ; import java.io.FileInputStream ; import java.io.IOException ; import java.io.InputStream ; import java.math.BigDecimal ; import java.math.BigInteger ; import java.util.Calendar ; import java.util.Iterator ; import java.util.Properties ; import java.util.ServiceLoader ; import javax.xml.datatype.DatatypeConfigurationException ; import javax.xml.datatype.DatatypeFactory ; import javax.xml.datatype.Duration ; import javax.xml.datatype.XMLGregorianCalendar ; import org.apache.jena.atlas.lib.StrUtils ; import org.apache.jena.atlas.logging.Log ; import org.slf4j.Logger ; import org.slf4j.LoggerFactory ; import com.hp.hpl.jena.datatypes.DatatypeFormatException ; import com.hp.hpl.jena.datatypes.RDFDatatype ; import com.hp.hpl.jena.datatypes.TypeMapper ; import com.hp.hpl.jena.datatypes.xsd.XSDDatatype ; import com.hp.hpl.jena.datatypes.xsd.XSDDateTime ; import com.hp.hpl.jena.graph.Node ; import com.hp.hpl.jena.graph.impl.LiteralLabel ; import com.hp.hpl.jena.query.ARQ ; import com.hp.hpl.jena.rdf.model.AnonId ; import com.hp.hpl.jena.sparql.ARQInternalErrorException ; import com.hp.hpl.jena.sparql.engine.ExecutionContext ; import com.hp.hpl.jena.sparql.engine.binding.Binding ; import com.hp.hpl.jena.sparql.expr.nodevalue.* ; import com.hp.hpl.jena.sparql.function.FunctionEnv ; import com.hp.hpl.jena.sparql.graph.NodeConst ; import com.hp.hpl.jena.sparql.graph.NodeTransform ; import com.hp.hpl.jena.sparql.serializer.SerializationContext ; import com.hp.hpl.jena.sparql.util.* ; public abstract class NodeValue extends ExprNode { // Maybe:: NodeValueStringLang - strings with language tag /* Naming: * getXXX => plain accessor * asXXX => force to the required thing if necessary. * * Implementation notes: * * 1. There is little point delaying turning a node into its value * because it has to be verified anyway (e.g. illegal literals). * Because a NodeValue is being created, it is reasonably likely it * is going to be used for it's value, so processing the datatype * can be done at creation time where it is clearer. * * 2. Conversely, delaying turning a value into a graph node is * valuable because intermediates, like the result of 2+3, will not * be needed as nodes unless assignment (and there is no assignment * in SPARQL even if there is for ARQ). * Node level operations like str() don't need a full node. * * 3. nodevalue.NodeFunctions contains the SPARQL builtin implementations. * nodevalue.XSDFuncOp contains the implementation of the XQuery/Xpath * functions and operations. * See also NodeUtils. * * 4. Note that SPARQL "=" is "known to be sameValueAs". Similarly "!=" is * known to be different. * * 5. To add a new number type: * Add sub type into nodevalue.NodeValueXXX * Must implement .hashCode() and .equals() based on value. * Add Functions.add/subtract/etc code and compareNumeric * Add to compare code * Fix TestExprNumeric * Write lots of tests. * Library code Maths1 and Maths2 for maths functions */ /* * Effective boolean value rules. * boolean: value of the boolean * string: length(string) > 0 is true * numeric: number != Nan && number != 0 is true * ref: http://www.w3.org/TR/xquery/#dt-ebv * */ private static Logger log = LoggerFactory.getLogger(NodeValue.class) ; // ---- Constants and initializers / public public static boolean VerboseWarnings = true ; public static boolean VerboseExceptions = false ; private static boolean VALUE_EXTENSIONS = ARQ.getContext().isTrueOrUndef(ARQ.extensionValueTypes) ; private static boolean sameValueAsString = VALUE_EXTENSIONS ; private static RefBoolean enableRomanNumerals = new RefBoolean(ARQ.enableRomanNumerals, false) ; //private static RefBoolean strictSPARQL = new RefBoolean(ARQ.strictSPARQL, false) ; public static final BigInteger IntegerZERO = BigInteger.ZERO ; public static final BigDecimal DecimalZERO = BigDecimal.ZERO ; public static final NodeValue TRUE = NodeValue.makeNode("true", XSDboolean) ; public static final NodeValue FALSE = NodeValue.makeNode("false", XSDboolean) ; public static final NodeValue nvZERO = NodeValue.makeNode(NodeConst.nodeZero) ; public static final NodeValue nvONE = NodeValue.makeNode(NodeConst.nodeOne) ; public static final NodeValue nvNaN = NodeValue.makeNode("NaN", XSDdouble) ; public static final NodeValue nvINF = NodeValue.makeNode("INF", XSDdouble) ; public static final NodeValue nvNegINF = NodeValue.makeNode("-INF",XSDdouble) ; public static final NodeValue nvEmptyString = NodeValue.makeString("") ; // Use "==" for equality. private static final String strForUnNode = "node value nothing" ; public static final NodeValue nvNothing = NodeValue.makeNode(com.hp.hpl.jena.graph.NodeFactory.createAnon(new AnonId("node value nothing"))) ; public static final String xsdNamespace = XSD+"#" ; public static DatatypeFactory xmlDatatypeFactory = null ; static { try { xmlDatatypeFactory = getDatatypeFactory() ; } catch (DatatypeConfigurationException ex) { throw new ARQInternalErrorException("Can't create a javax.xml DatatypeFactory", ex) ; } } /** * Get a datatype factory using the correct classloader * * See JENA-328. DatatypeFactory.newInstance() clashes with OSGi * This is clearly crazy, but DatatypeFactory is missing a very obvious * method newInstance(Classloader). The method that was added is very * hard to use correctly, as we shall see... */ private static DatatypeFactory getDatatypeFactory() throws DatatypeConfigurationException { ClassLoader cl = NodeValue.class.getClassLoader(); File jaxpPropFile = new File( System.getProperty("java.home") + File.pathSeparator + "lib" + File.pathSeparator + "jaxp.properties"); // Step 1. Try the system property String dtfClass = System.getProperty(DatatypeFactory.DATATYPEFACTORY_PROPERTY); try { // Step 2. Otherwise, try property in jaxp.properties if (dtfClass == null && jaxpPropFile.exists() && jaxpPropFile.canRead()) { Properties jaxp = new Properties(); InputStream in = null; try { in = new FileInputStream(jaxpPropFile); jaxp.load(in); dtfClass = jaxp.getProperty(DatatypeFactory.DATATYPEFACTORY_PROPERTY); } catch (Exception e) { log.warn("Issue loading jaxp.properties", e); } finally { if (in != null) { try { in.close(); } catch (IOException ex) { log.warn("Issue closing jaxp.properties ", ex); } } } } } // File.exists and File.canRead may throw SecurityException (probably AccessControlException) catch (SecurityException ex) { log.warn("Security exception try to get jaxp.properties: "+ex.getMessage()) ; } // Step 3. Otherwise try the service approach if (dtfClass == null) { Iterator<DatatypeFactory> factoryIterator = ServiceLoader.load(DatatypeFactory.class, cl).iterator(); if (factoryIterator.hasNext()) return factoryIterator.next(); } // Step 4. Use the default if (dtfClass == null) dtfClass = DatatypeFactory.DATATYPEFACTORY_IMPLEMENTATION_CLASS; return DatatypeFactory.newInstance(dtfClass, NodeValue.class.getClassLoader()) ; } private Node node = null ; // Null used when a value has not be turned into a Node. // Don't create direct - the static builders manage the value/node relationship protected NodeValue() { super() ; } protected NodeValue(Node n) { super() ; node = n ; } // protected makeNodeValue(NodeValue nv) // { // if ( v.isNode() ) { ... } // if ( v.isBoolean() ) { ... } // if ( v.isInteger() ) { ... } // if ( v.isDouble() ) { ... } // if ( v.isDecimal() ) { ... } // if ( v.isString() ) { ... } // if ( v.isDate() ) { ... } // } // ---------------------------------------------------------------- // ---- Construct NodeValue without a graph node. /** Convenience operation - parse a string to produce a NodeValue - common namespaces like xsd: are built-in */ public static NodeValue parse(String string) { return makeNode(NodeFactoryExtra.parseNode(string)) ; } public static NodeValue makeInteger(long i) { return new NodeValueInteger(BigInteger.valueOf(i)) ; } public static NodeValue makeInteger(BigInteger i) { return new NodeValueInteger(i) ; } public static NodeValue makeInteger(String lexicalForm) { return new NodeValueInteger(new BigInteger(lexicalForm)) ; } public static NodeValue makeFloat(float f) { return new NodeValueFloat(f) ; } public static NodeValue makeDouble(double d) { return new NodeValueDouble(d) ; } public static NodeValue makeString(String s) { return new NodeValueString(s) ; } public static NodeValue makeDecimal(BigDecimal d) { return new NodeValueDecimal(d) ; } public static NodeValue makeDecimal(long i) { return new NodeValueDecimal(BigDecimal.valueOf(i)) ; } public static NodeValue makeDecimal(double d) { return new NodeValueDecimal(BigDecimal.valueOf(d)) ; } public static NodeValue makeDecimal(String lexicalForm) { return NodeValue.makeNode(lexicalForm, XSDdecimal) ; } public static NodeValue makeDateTime(String lexicalForm) { return NodeValue.makeNode(lexicalForm, XSDdateTime) ; } public static NodeValue makeDate(String lexicalForm) { return NodeValue.makeNode(lexicalForm, XSDdate) ; } public static NodeValue makeDateTime(Calendar cal) { String lex = Utils.calendarToXSDDateTimeString(cal) ; return NodeValue.makeNode(lex, XSDdateTime) ; } public static NodeValue makeDateTime(XMLGregorianCalendar cal) { String lex = cal.toXMLFormat() ; Node node = com.hp.hpl.jena.graph.NodeFactory.createLiteral(lex, XSDdateTime) ; return new NodeValueDT(lex, node) ; } public static NodeValue makeDate(Calendar cal) { String lex = Utils.calendarToXSDDateString(cal) ; return NodeValue.makeNode(lex, XSDdate) ; } public static NodeValue makeDate(XMLGregorianCalendar cal) { String lex = cal.toXMLFormat() ; Node node = com.hp.hpl.jena.graph.NodeFactory.createLiteral(lex, XSDdate) ; return new NodeValueDT(lex, node) ; } public static NodeValue makeDuration(String lexicalForm) { return NodeValue.makeNode(lexicalForm, XSDduration) ; } public static NodeValue makeDuration(Duration duration) { return new NodeValueDuration(duration); } public static NodeValue makeNodeDuration(Duration duration, Node node) { return new NodeValueDuration(duration, node); } public static NodeValue makeBoolean(boolean b) { return b ? NodeValue.TRUE : NodeValue.FALSE ; } public static NodeValue booleanReturn(boolean b) { return b ? NodeValue.TRUE : NodeValue.FALSE ; } // ---------------------------------------------------------------- // ---- Construct NodeValue from graph nodes public static NodeValue makeNode(Node n) { NodeValue nv = nodeToNodeValue(n) ; return nv ; } public static NodeValue makeNode(String lexicalForm, XSDDatatype dtype) { Node n = com.hp.hpl.jena.graph.NodeFactory.createLiteral(lexicalForm, null, dtype) ; NodeValue nv = NodeValue.makeNode(n) ; return nv ; } // Convenience - knows that lang tags aren't allowed with datatypes. public static NodeValue makeNode(String lexicalForm, String langTag, Node datatype) { String uri = (datatype==null) ? null : datatype.getURI() ; return makeNode(lexicalForm, langTag, uri) ; } public static NodeValue makeNode(String lexicalForm, String langTag, String datatype) { if ( datatype != null && datatype.equals("") ) datatype = null ; if ( langTag != null && datatype != null ) // raise?? Log.warn(NodeValue.class, "Both lang tag and datatype defined (lexcial form '"+lexicalForm+"')") ; Node n = null ; if ( datatype != null) { RDFDatatype dType = TypeMapper.getInstance().getSafeTypeByName(datatype) ; n = com.hp.hpl.jena.graph.NodeFactory.createLiteral(lexicalForm, null, dType) ; } else n = com.hp.hpl.jena.graph.NodeFactory.createLiteral(lexicalForm, langTag, null) ; return NodeValue.makeNode(n) ; } // ---------------------------------------------------------------- // ---- Construct NodeValue with graph node and value. public static NodeValue makeNodeBoolean(boolean b) { return b ? NodeValue.TRUE : NodeValue.FALSE ; } public static NodeValue makeNodeBoolean(String lexicalForm) { NodeValue nv = makeNode(lexicalForm, null, XSDboolean.getURI()) ; return nv ; } public static NodeValue makeNodeInteger(long v) { NodeValue nv = makeNode(Long.toString(v), null, XSDinteger.getURI()) ; return nv ; } public static NodeValue makeNodeInteger(String lexicalForm) { NodeValue nv = makeNode(lexicalForm, null, XSDinteger.getURI()) ; return nv ; } public static NodeValue makeNodeFloat(float f) { NodeValue nv = makeNode(Utils.stringForm(f), null, XSDfloat.getURI()) ; return nv ; } public static NodeValue makeNodeFloat(String lexicalForm) { NodeValue nv = makeNode(lexicalForm, null, XSDdouble.getURI()) ; return nv ; } public static NodeValue makeNodeDouble(double v) { NodeValue nv = makeNode(Utils.stringForm(v), null, XSDdouble.getURI()) ; return nv ; } public static NodeValue makeNodeDouble(String lexicalForm) { NodeValue nv = makeNode(lexicalForm, null, XSDdouble.getURI()) ; return nv ; } public static NodeValue makeNodeDecimal(BigDecimal decimal) { NodeValue nv = makeNode(Utils.stringForm(decimal), null, XSDdecimal.getURI()) ; return nv ; } public static NodeValue makeNodeDecimal(String lexicalForm) { NodeValue nv = makeNode(lexicalForm, null, XSDdecimal.getURI()) ; return nv ; } public static NodeValue makeNodeString(String string) { NodeValue nv = makeNode(string, null, (String)null) ; return nv ; } public static NodeValue makeNodeDateTime(Calendar date) { String lex = Utils.calendarToXSDDateTimeString(date) ; NodeValue nv = makeNode(lex, XSDdateTime) ; return nv ; } public static NodeValue makeNodeDateTime(String lexicalForm) { NodeValue nv = makeNode(lexicalForm, XSDdateTime) ; return nv ; } public static NodeValue makeNodeDate(Calendar date) { String lex = Utils.calendarToXSDDateString(date) ; NodeValue nv = makeNode(lex, XSDdate) ; return nv ; } public static NodeValue makeNodeDate(String lexicalForm) { NodeValue nv = makeNode(lexicalForm, XSDdate) ; return nv ; } // ---------------------------------------------------------------- // ---- Expr interface @Override public NodeValue eval(Binding binding, FunctionEnv env) { return this ; } // NodeValues are immutable so no need to duplicate. @Override public Expr copySubstitute(Binding binding, boolean foldConstants) { // return this ; Node n = asNode() ; return makeNode(n) ; } @Override public Expr applyNodeTransform(NodeTransform transform) { Node n = asNode() ; n = transform.convert(n) ; return makeNode(n) ; } public Node evalNode(Binding binding, ExecutionContext execCxt) { return asNode() ; } @Override public boolean isConstant() { return true ; } @Override public NodeValue getConstant() { return this ; } public boolean isIRI() { if ( node == null ) return false ; forceToNode() ; return node.isURI() ; } public boolean isBlank() { if ( node == null ) return false ; forceToNode() ; return node.isBlank() ; } // ---------------------------------------------------------------- // ---- sameValueAs // Disjoint value spaces : dateTime and dates are not comparable // Every langtag implies another value space as well. /** Return true if the two NodeValues are known to be the same value * return false if known to be different values, * throw ExprEvalException otherwise */ public static boolean sameAs(NodeValue nv1, NodeValue nv2) { if ( nv1 == null || nv2 == null ) throw new ARQInternalErrorException("Attempt to sameValueAs on a null") ; ValueSpaceClassification compType = classifyValueOp(nv1, nv2) ; // Special case - date/dateTime comparison is affected by timezones and may be // interdeterminate based on the value of the dateTime/date. switch (compType) { case VSPACE_NUM: return XSDFuncOp.compareNumeric(nv1, nv2) == Expr.CMP_EQUAL ; case VSPACE_DATETIME: case VSPACE_DATE: case VSPACE_TIME: case VSPACE_G_YEAR : case VSPACE_G_YEARMONTH : case VSPACE_G_MONTH : case VSPACE_G_MONTHDAY : case VSPACE_G_DAY : { int x = XSDFuncOp.compareDateTime(nv1, nv2) ; if ( x == Expr.CMP_INDETERMINATE ) throw new ExprNotComparableException("Indeterminate dateTime comparison") ; return x == Expr.CMP_EQUAL ; } case VSPACE_DURATION: { int x = XSDFuncOp.compareDuration(nv1, nv2) ; if ( x == Expr.CMP_INDETERMINATE ) throw new ExprNotComparableException("Indeterminate duration comparison") ; return x == Expr.CMP_EQUAL ; } case VSPACE_STRING: return XSDFuncOp.compareString(nv1, nv2) == Expr.CMP_EQUAL ; case VSPACE_BOOLEAN: return XSDFuncOp.compareBoolean(nv1, nv2) == Expr.CMP_EQUAL ; case VSPACE_LANG: { // two literals, both with a language tag Node node1 = nv1.asNode() ; Node node2 = nv2.asNode() ; return node1.getLiteralLexicalForm().equals(node2.getLiteralLexicalForm()) && node1.getLiteralLanguage().equalsIgnoreCase(node2.getLiteralLanguage()) ; } case VSPACE_NODE: // Two non-literals return NodeFunctions.sameTerm(nv1.getNode(), nv2.getNode()) ; case VSPACE_UNKNOWN: { // One or two unknown value spaces, or one has a lang tag (but not both). Node node1 = nv1.getNode() ; Node node2 = nv2.getNode() ; if ( ! VALUE_EXTENSIONS ) // No value extensions => raw rdfTermEquals return NodeFunctions.rdfTermEquals(node1, node2) ; // Some "value spaces" are know to be not equal (no overlap). // Like one literal with a language tag, and one without can't be sameAs. if ( ! node1.isLiteral() || ! node2.isLiteral() ) // One or other not a literal => not sameAs return false ; // Two literals at this point. if ( NodeFunctions.sameTerm(node1, node2) ) return true ; if ( ! node1.getLiteralLanguage().equals("") || ! node2.getLiteralLanguage().equals("") ) // One had lang tags but weren't sameNode => not equals return false ; raise(new ExprEvalException("Unknown equality test: "+nv1+" and "+nv2)) ; throw new ARQInternalErrorException("raise returned (sameValueAs)") ; } case VSPACE_DIFFERENT: // Known to be incompatible. if ( ! VALUE_EXTENSIONS && ( nv1.isLiteral() && nv2.isLiteral() ) ) raise(new ExprEvalException("Incompatible: "+nv1+" and "+nv2)) ; return false ; } throw new ARQInternalErrorException("sameValueAs failure "+nv1+" and "+nv2) ; } /** Return true if the two Nodes are known to be different, * return false if the two Nodes are known to be the same, * else throw ExprEvalException */ public static boolean notSameAs(Node n1, Node n2) { return notSameAs(NodeValue.makeNode(n1), NodeValue.makeNode(n2)) ; } /** Return true if the two NodeValues are known to be different, * return false if the two NodeValues are known to be the same, * else throw ExprEvalException */ public static boolean notSameAs(NodeValue nv1, NodeValue nv2) { return ! sameAs(nv1, nv2) ; } // ---------------------------------------------------------------- // compare // Compare by value code is here // NodeUtils.compareRDFTerms for syntactic comparison /** Compare by value if possible else compare by kind/type/lexical form * Only use when you want an ordering regardless of form of NodeValue, * for example in ORDER BY * * @param nv1 * @param nv2 * @return negative, 0, or postive for less than, equal, greater than. */ public static int compareAlways(NodeValue nv1, NodeValue nv2) { // ***** Only called from a test. Sort out with NodeUtils. try { int x = compare(nv1, nv2, true) ; // Same? if ( x != Expr.CMP_EQUAL ) return x ; } catch (ExprNotComparableException ex) { /* Drop through */ } return NodeUtils.compareRDFTerms(nv1.asNode(), nv2.asNode()) ; } /** Compare by value (and only value) if possible. * Supports <, <=, >, >= but not = nor != (which are sameValueAs and notSameValueAs) * @param nv1 * @param nv2 * @return negative, 0 , or positive for not possible, less than, equal, greater than. * @throws ExprNotComparableException */ public static int compare(NodeValue nv1, NodeValue nv2) { // Called from E_LessThat etc // and NodeUtils.comparLiteralsByValue if ( nv1 == null || nv2 == null ) //raise(new ExprEvalException("Attempt to notSameValueAs on null") ; throw new ARQInternalErrorException("Attempt to compare on null") ; int x = compare(nv1, nv2, false) ; return x ; } // E_GreaterThan/E_LessThan/E_GreaterThanOrEqual/E_LessThanOrEqual // ==> compare(nv1, nv2) => compare (nv1, nv2, false) // BindingComparator => compareAlways(nv1, nv2) => compare (nv1, nv2, true) // E_Equals calls NodeValue.sameAs() ==> // sortOrderingCompare means that the comparison should do something with normally unlike things, // and split plain strings from xsd:strings. private static int compare(NodeValue nv1, NodeValue nv2, boolean sortOrderingCompare) { if ( nv1 == null && nv2 == null ) return Expr.CMP_EQUAL ; if ( nv1 == null ) return Expr.CMP_LESS ; if ( nv2 == null ) return Expr.CMP_GREATER ; ValueSpaceClassification compType = classifyValueOp(nv1, nv2) ; // Special case - date/dateTime comparison is affected by timezones and may be // interdeterminate based on the value of the dateTime/date. // Do this first, switch (compType) { case VSPACE_DATETIME: case VSPACE_DATE: case VSPACE_TIME: case VSPACE_G_DAY : case VSPACE_G_MONTH : case VSPACE_G_MONTHDAY : case VSPACE_G_YEAR : case VSPACE_G_YEARMONTH : { int x = XSDFuncOp.compareDateTime(nv1, nv2) ; if ( x != Expr.CMP_INDETERMINATE ) return x ; // Indeterminate => can't compare as strict values. compType = ValueSpaceClassification.VSPACE_DIFFERENT ; break ; } case VSPACE_DURATION: { int x = XSDFuncOp.compareDuration(nv1, nv2) ; if ( x != Expr.CMP_INDETERMINATE ) return x ; // Indeterminate => can't compare as strict values. compType = ValueSpaceClassification.VSPACE_DIFFERENT ; break ; } //default: case VSPACE_BOOLEAN : case VSPACE_DIFFERENT : case VSPACE_LANG : case VSPACE_NODE : case VSPACE_NUM : case VSPACE_STRING : case VSPACE_UNKNOWN : // Drop through. } switch (compType) { case VSPACE_DATETIME: case VSPACE_DATE: case VSPACE_TIME: case VSPACE_G_DAY : case VSPACE_G_MONTH : case VSPACE_G_MONTHDAY : case VSPACE_G_YEAR : case VSPACE_G_YEARMONTH : case VSPACE_DURATION: throw new ARQInternalErrorException("Still seeing date/dateTime/time/duration compare type") ; case VSPACE_NUM: return XSDFuncOp.compareNumeric(nv1, nv2) ; case VSPACE_STRING: { int cmp = XSDFuncOp.compareString(nv1, nv2) ; // Split plain literals and xsd:strings for sorting purposes. if ( ! sortOrderingCompare ) return cmp ; if ( cmp != Expr.CMP_EQUAL ) return cmp ; // Same by string value. String dt1 = nv1.asNode().getLiteralDatatypeURI() ; String dt2 = nv2.asNode().getLiteralDatatypeURI() ; if ( dt1 == null && dt2 != null ) return Expr.CMP_LESS ; if ( dt2 == null && dt1 != null ) return Expr.CMP_GREATER ; return Expr.CMP_EQUAL; // Both plain or both xsd:string. } case VSPACE_BOOLEAN: return XSDFuncOp.compareBoolean(nv1, nv2) ; case VSPACE_LANG: { // Two literals, both with language tags. Node node1 = nv1.asNode() ; Node node2 = nv2.asNode() ; int x = StrUtils.strCompareIgnoreCase(node1.getLiteralLanguage(), node2.getLiteralLanguage()) ; if ( x != Expr.CMP_EQUAL ) { // Different lang tags if ( ! sortOrderingCompare ) raise(new ExprNotComparableException("Can't compare (different languages) "+nv1+" and "+nv2)) ; // Different lang tags - sorting return x ; } // same lang tag (case insensitive) x = StrUtils.strCompare(node1.getLiteralLexicalForm(), node2.getLiteralLexicalForm()) ; if ( x != Expr.CMP_EQUAL ) return x ; // Same lexcial forms, same lang tag by value // Try to split by syntactic lang tags. x = StrUtils.strCompare(node1.getLiteralLanguage(), node2.getLiteralLanguage()) ; // Maybe they are the same after all! // Should be node.equals by now. if ( x == Expr.CMP_EQUAL && ! NodeFunctions.sameTerm(node1, node2) ) throw new ARQInternalErrorException("Look the same (lang tags) but no node equals") ; return x ; } case VSPACE_NODE: // Two non-literals don't compare except for sorting. if ( sortOrderingCompare ) return NodeUtils.compareRDFTerms(nv1.asNode(), nv2.asNode()) ; else { raise(new ExprNotComparableException("Can't compare (nodes) "+nv1+" and "+nv2)) ; throw new ARQInternalErrorException("NodeValue.raise returned") ; } case VSPACE_UNKNOWN: { // One or two unknown value spaces. Node node1 = nv1.asNode() ; Node node2 = nv2.asNode() ; // Two unknown literals can be equal. if ( NodeFunctions.sameTerm(node1, node2) ) return Expr.CMP_EQUAL ; if ( sortOrderingCompare ) return NodeUtils.compareRDFTerms(node1, node2) ; raise(new ExprNotComparableException("Can't compare "+nv1+" and "+nv2)) ; throw new ARQInternalErrorException("NodeValue.raise returned") ; } case VSPACE_DIFFERENT: // Two literals, from different known value spaces if ( sortOrderingCompare ) return NodeUtils.compareRDFTerms(nv1.asNode(), nv2.asNode()) ; raise(new ExprNotComparableException("Can't compare (incompatible value spaces)"+nv1+" and "+nv2)) ; throw new ARQInternalErrorException("NodeValue.raise returned") ; } throw new ARQInternalErrorException("Compare failure "+nv1+" and "+nv2) ; } public static ValueSpaceClassification classifyValueOp(NodeValue nv1, NodeValue nv2) { ValueSpaceClassification c1 = nv1.getValueSpace() ; ValueSpaceClassification c2 = nv2.getValueSpace() ; if ( c1 == c2 ) return c1 ; if ( c1 == VSPACE_UNKNOWN || c2 == VSPACE_UNKNOWN ) return VSPACE_UNKNOWN ; // Known values spaces but incompatible return VSPACE_DIFFERENT ; } public ValueSpaceClassification getValueSpace() { return classifyValueSpace(this) ; } private static ValueSpaceClassification classifyValueSpace(NodeValue nv) { if ( nv.isNumber() ) return VSPACE_NUM ; if ( nv.isDateTime() ) return VSPACE_DATETIME ; if ( nv.isDate() ) return VSPACE_DATE ; if ( nv.isTime() ) return VSPACE_TIME ; if ( nv.isDuration() ) return VSPACE_DURATION ; if ( nv.isGYear() ) return VSPACE_G_YEAR ; if ( nv.isGYearMonth() ) return VSPACE_G_YEARMONTH ; if ( nv.isGMonth() ) return VSPACE_G_MONTH ; if ( nv.isGMonthDay() ) return VSPACE_G_MONTHDAY ; if ( nv.isGDay() ) return VSPACE_G_DAY ; if ( VALUE_EXTENSIONS && nv.isDate() ) return VSPACE_DATE ; if ( nv.isString()) return VSPACE_STRING ; if ( nv.isBoolean()) return VSPACE_BOOLEAN ; if ( ! nv.isLiteral() ) return VSPACE_NODE ; if ( VALUE_EXTENSIONS && nv.getNode() != null && nv.getNode().isLiteral() && ! nv.getNode().getLiteralLanguage().equals("") ) return VSPACE_LANG ; return VSPACE_UNKNOWN ; } // ---------------------------------------------------------------- // ---- Node operations public static Node toNode(NodeValue nv) { if ( nv == null ) return null ; return nv.asNode() ; } public final Node asNode() { if ( node == null ) node = makeNode() ; return node ; } protected abstract Node makeNode() ; /** getNode - return the node form - may be null (use .asNode() to force to a node) */ public Node getNode() { return node ; } public String getDatatypeURI() { return asNode().getLiteralDatatypeURI() ; } public boolean hasNode() { return node != null ; } // ---------------------------------------------------------------- // ---- Subclass operations public boolean isBoolean() { return false ; } public boolean isString() { return false ; } public boolean isNumber() { return false ; } public boolean isInteger() { return false ; } public boolean isDecimal() { return false ; } public boolean isFloat() { return false ; } public boolean isDouble() { return false ; } public boolean hasDateTime() { return isDateTime() || isDate() || isTime() || isGYear() || isGYearMonth() || isGMonth() || isGMonthDay() || isGDay() ; } public boolean isDateTime() { return false ; } public boolean isDate() { return false ; } public boolean isLiteral() { return getNode() == null || getNode().isLiteral() ; } public boolean isTime() { return false ; } public boolean isDuration() { return false ; } public boolean isYearMonth() { if ( ! isDuration() ) return false ; Duration dur = getDuration() ; return ( dur.isSet(YEARS) || dur.isSet(MONTHS) ) && ! dur.isSet(DAYS) && ! dur.isSet(HOURS) && ! dur.isSet(MINUTES) && ! dur.isSet(SECONDS) ; } boolean isDayTime() { if ( ! isDuration() ) return false ; Duration dur = getDuration() ; return !dur.isSet(YEARS) && ! dur.isSet(MONTHS) && ( dur.isSet(DAYS) || dur.isSet(HOURS) || dur.isSet(MINUTES) || dur.isSet(SECONDS) ); } public boolean isGYear() { return false ; } public boolean isGYearMonth() { return false ; } public boolean isGMonth() { return false ; } public boolean isGMonthDay() { return false ; } public boolean isGDay() { return false ; } public boolean getBoolean() { raise(new ExprEvalTypeException("Not a boolean: "+this)) ; return false ; } public String getString() { raise(new ExprEvalTypeException("Not a string: "+this)) ; return null ; } public BigInteger getInteger() { raise(new ExprEvalTypeException("Not an integer: "+this)) ; return null ; } public BigDecimal getDecimal() { raise(new ExprEvalTypeException("Not a decimal: "+this)) ; return null ; } public float getFloat() { raise(new ExprEvalTypeException("Not a float: "+this)) ; return Float.NaN ; } public double getDouble() { raise(new ExprEvalTypeException("Not a double: "+this)) ; return Double.NaN ; } // Value representation for all date and time values. public XMLGregorianCalendar getDateTime() { raise(new ExprEvalTypeException("No DateTime value: "+this)) ; return null ; } public Duration getDuration() { raise(new ExprEvalTypeException("Not a duration: "+this)) ; return null ; } // ---------------------------------------------------------------- // ---- Setting : used when a node is used to make a NodeValue private static NodeValue nodeToNodeValue(Node node) { if ( node.isVariable() ) Log.warn(NodeValue.class, "Variable passed to NodeValue.nodeToNodeValue") ; if ( ! node.isLiteral() ) // Not a literal - no value to extract return new NodeValueNode(node) ; boolean hasLangTag = ( node.getLiteralLanguage() != null && ! node.getLiteralLanguage().equals("")) ; boolean isPlainLiteral = ( node.getLiteralDatatypeURI() == null && ! hasLangTag ) ; if ( isPlainLiteral ) return new NodeValueString(node.getLiteralLexicalForm(), node) ; if ( hasLangTag ) { if ( node.getLiteralDatatypeURI() != null ) { if ( NodeValue.VerboseWarnings ) Log.warn(NodeValue.class, "Lang tag and datatype (datatype ignored)") ; } return new NodeValueNode(node) ; } // Typed literal LiteralLabel lit = node.getLiteral() ; // This includes type testing //if ( ! lit.getDatatype().isValidLiteral(lit) ) // Use this - already calculated when the node is formed. if ( !node.getLiteral().isWellFormed() ) { if ( NodeValue.VerboseWarnings ) { String tmp = FmtUtils.stringForNode(node) ; Log.warn(NodeValue.class, "Datatype format exception: "+tmp) ; } // Invalid lexical form. return new NodeValueNode(node) ; } NodeValue nv = _setByValue(node) ; if ( nv != null ) return nv ; return new NodeValueNode(node) ; //raise(new ExprException("NodeValue.nodeToNodeValue: Unknown Node type: "+n)) ; } // Jena code does not have these types (yet) private static final String dtXSDdateTimeStamp = XSD+"#dateTimeStamp" ; private static final String dtXSDdayTimeDuration = XSD+"#dayTimeDuration" ; private static final String dtXSDyearMonthDuration = XSD+"#yearMonthDuration" ; private static final String dtXSDprecisionDecimal = XSD+"#precisionDecimal" ; // Returns null for unrecognized literal. private static NodeValue _setByValue(Node node) { if ( NodeUtils.hasLang(node) ) // Check for RDF 1.1! return null ; LiteralLabel lit = node.getLiteral() ; String lex = lit.getLexicalForm() ; RDFDatatype datatype = lit.getDatatype() ; // Quick check. // Only XSD supported. // And (for testing) roman numerals. String datatypeURI = datatype.getURI() ; if ( ! datatypeURI.startsWith(xsdNamespace) && ! enableRomanNumerals.getValue() ) { // Not XSD. return null ; } try { // DatatypeFormatException - should not happen if ( sameValueAsString && XSDstring.isValidLiteral(lit) ) // String - plain or xsd:string return new NodeValueString(lit.getLexicalForm(), node) ; // Otherwise xsd:string is like any other unknown datatype. // Ditto literals with language tags (which are handled by nodeToNodeValue) // isValidLiteral is a value test - not a syntactic test. // This makes a difference in that "1"^^xsd:decimal" is a // valid literal for xsd:integer (all other cases are subtypes of xsd:integer) // which we want to become integer anyway). // Order here is promotion order integer-decimal-float-double if ( ! datatype.equals(XSDdecimal) ) { // XSD integer and derived types if ( XSDinteger.isValidLiteral(lit) ) { String s = node.getLiteralLexicalForm() ; if ( s.startsWith("+") ) // BigInteger does not accept leading "+" s = s.substring(1) ; // Includes subtypes (int, byte, postiveInteger etc). // NB Known to be valid for type by now BigInteger integer = new BigInteger(s) ; return new NodeValueInteger(integer, node) ; } } if ( datatype.equals(XSDdecimal) && XSDdecimal.isValidLiteral(lit) ) { BigDecimal decimal = new BigDecimal(lit.getLexicalForm()) ; return new NodeValueDecimal(decimal, node) ; } if ( datatype.equals(XSDfloat) && XSDfloat.isValidLiteral(lit) ) { // NB If needed, call to floatValue, then assign to double. // Gets 1.3f != 1.3d right float f = ((Number)lit.getValue()).floatValue() ; return new NodeValueFloat(f, node) ; } if ( datatype.equals(XSDdouble) && XSDdouble.isValidLiteral(lit) ) { double d = ((Number)lit.getValue()).doubleValue() ; return new NodeValueDouble(d, node) ; } // XXX Pending Jena update ... if ( ( datatype.equals(XSDdateTime) || dtXSDdateTimeStamp.equals(datatypeURI) ) && XSDdateTime.isValid(lex) ) { XSDDateTime dateTime = (XSDDateTime)lit.getValue() ; return new NodeValueDT(lex, node) ; } if ( datatype.equals(XSDdate) && XSDdate.isValidLiteral(lit) ) { // Jena datatype support works on masked dataTimes. XSDDateTime dateTime = (XSDDateTime)lit.getValue() ; return new NodeValueDT(lex, node) ; } if ( datatype.equals(XSDtime) && XSDtime.isValidLiteral(lit) ) { // Jena datatype support works on masked dataTimes. XSDDateTime time = (XSDDateTime)lit.getValue() ; return new NodeValueDT(lex, node) ; } if ( datatype.equals(XSDgYear) && XSDgYear.isValidLiteral(lit) ) { XSDDateTime time = (XSDDateTime)lit.getValue() ; return new NodeValueDT(lex, node) ; } if ( datatype.equals(XSDgYearMonth) && XSDgYearMonth.isValidLiteral(lit) ) { XSDDateTime time = (XSDDateTime)lit.getValue() ; return new NodeValueDT(lex, node) ; } if ( datatype.equals(XSDgMonth) && XSDgMonth.isValidLiteral(lit) ) { XSDDateTime time = (XSDDateTime)lit.getValue() ; return new NodeValueDT(lex, node) ; } if ( datatype.equals(XSDgMonthDay) && XSDgMonthDay.isValidLiteral(lit) ) { XSDDateTime time = (XSDDateTime)lit.getValue() ; return new NodeValueDT(lex, node) ; } if ( datatype.equals(XSDgDay) && XSDgDay.isValidLiteral(lit) ) { XSDDateTime time = (XSDDateTime)lit.getValue() ; return new NodeValueDT(lex, node) ; } // XXX Pending Jena update ... if ( ( datatype.equals(XSDduration) || dtXSDdayTimeDuration.equals(datatypeURI) || dtXSDyearMonthDuration.equals(datatypeURI) ) && XSDduration.isValid(lex) ) // use lex { Duration duration = xmlDatatypeFactory.newDuration(lex) ; if ( dtXSDdayTimeDuration.equals(datatypeURI) && ! XSDFuncOp.isDayTime(duration) ) return null ; if ( dtXSDyearMonthDuration.equals(datatypeURI) && ! XSDFuncOp.isYearMonth(duration) ) return null ; return new NodeValueDuration(duration, node) ; } if ( datatype.equals(XSDboolean) && XSDboolean.isValidLiteral(lit) ) { boolean b = ((Boolean)lit.getValue()).booleanValue() ; return new NodeValueBoolean(b, node) ; } // If wired into the TypeMapper via RomanNumeralDatatype.enableAsFirstClassDatatype // if ( RomanNumeralDatatype.get().isValidLiteral(lit) ) // { // int i = ((RomanNumeral)lit.getValue()).intValue() ; // return new NodeValueInteger(i) ; // } // Not wired in if ( enableRomanNumerals.getValue() ) { if ( lit.getDatatypeURI().equals(RomanNumeralDatatype.get().getURI()) ) { Object obj = RomanNumeralDatatype.get().parse(lit.getLexicalForm()) ; if ( obj instanceof Integer ) return new NodeValueInteger(((Integer)obj).longValue()) ; if ( obj instanceof RomanNumeral ) return new NodeValueInteger( ((RomanNumeral)obj).intValue() ) ; throw new ARQInternalErrorException("DatatypeFormatException: Roman numeral is unknown class") ; } } } catch (DatatypeFormatException ex) { // Should have been caught earlier by special test in nodeToNodeValue throw new ARQInternalErrorException("DatatypeFormatException: "+lit, ex) ; } return null ; } // ---------------------------------------------------------------- // Point to catch all exceptions. public static void raise(ExprException ex) { throw ex ; } @Override public void visit(ExprVisitor visitor) { visitor.visit(this) ; } private void forceToNode() { if ( node == null ) node = asNode() ; if ( node == null ) raise(new ExprEvalException("Not a node: "+this)) ; } // ---- Formatting (suitable for SPARQL syntax). // Usually done by being a Node and formatting that. // In desperation, will try toString() (no quoting) public final String asUnquotedString() { return asString() ; } public final String asQuotedString() { return asQuotedString(new SerializationContext()) ; } public final String asQuotedString(SerializationContext context) { // If possible, make a node and use that as the formatted output. if ( node == null ) node = asNode() ; if ( node != null ) return FmtUtils.stringForNode(node, context) ; return toString() ; } // Convert to a string - usually overridden. public String asString() { // Do not call .toString() forceToNode() ; return NodeFunctions.str(node) ; } @Override public int hashCode() { return asNode().hashCode() ; } @Override public boolean equals(Object other) { // This is the equality condition Jena uses - lang tags are different by case. if ( this == other ) return true ; if ( ! ( other instanceof NodeValue ) ) return false ; NodeValue nv = (NodeValue)other ; return asNode().equals(nv.asNode()) ; // Not NodeFunctions.sameTerm (which smooshes language tags by case) } public abstract void visit(NodeValueVisitor visitor) ; public Expr apply(ExprTransform transform) { return transform.transform(this) ; } @Override public String toString() { return asQuotedString() ; } }
jena-arq/src/main/java/com/hp/hpl/jena/sparql/expr/NodeValue.java
/* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.hp.hpl.jena.sparql.expr; import static com.hp.hpl.jena.datatypes.xsd.XSDDatatype.XSD ; import static com.hp.hpl.jena.datatypes.xsd.XSDDatatype.XSDboolean ; import static com.hp.hpl.jena.datatypes.xsd.XSDDatatype.XSDdate ; import static com.hp.hpl.jena.datatypes.xsd.XSDDatatype.XSDdateTime ; import static com.hp.hpl.jena.datatypes.xsd.XSDDatatype.XSDdecimal ; import static com.hp.hpl.jena.datatypes.xsd.XSDDatatype.XSDdouble ; import static com.hp.hpl.jena.datatypes.xsd.XSDDatatype.XSDduration ; import static com.hp.hpl.jena.datatypes.xsd.XSDDatatype.XSDfloat ; import static com.hp.hpl.jena.datatypes.xsd.XSDDatatype.XSDgDay ; import static com.hp.hpl.jena.datatypes.xsd.XSDDatatype.XSDgMonth ; import static com.hp.hpl.jena.datatypes.xsd.XSDDatatype.XSDgMonthDay ; import static com.hp.hpl.jena.datatypes.xsd.XSDDatatype.XSDgYear ; import static com.hp.hpl.jena.datatypes.xsd.XSDDatatype.XSDgYearMonth ; import static com.hp.hpl.jena.datatypes.xsd.XSDDatatype.XSDinteger ; import static com.hp.hpl.jena.datatypes.xsd.XSDDatatype.XSDstring ; import static com.hp.hpl.jena.datatypes.xsd.XSDDatatype.XSDtime ; import static com.hp.hpl.jena.sparql.expr.ValueSpaceClassification.VSPACE_BOOLEAN ; import static com.hp.hpl.jena.sparql.expr.ValueSpaceClassification.VSPACE_DATE ; import static com.hp.hpl.jena.sparql.expr.ValueSpaceClassification.VSPACE_DATETIME ; import static com.hp.hpl.jena.sparql.expr.ValueSpaceClassification.VSPACE_DIFFERENT ; import static com.hp.hpl.jena.sparql.expr.ValueSpaceClassification.VSPACE_DURATION ; import static com.hp.hpl.jena.sparql.expr.ValueSpaceClassification.VSPACE_G_DAY ; import static com.hp.hpl.jena.sparql.expr.ValueSpaceClassification.VSPACE_G_MONTH ; import static com.hp.hpl.jena.sparql.expr.ValueSpaceClassification.VSPACE_G_MONTHDAY ; import static com.hp.hpl.jena.sparql.expr.ValueSpaceClassification.VSPACE_G_YEAR ; import static com.hp.hpl.jena.sparql.expr.ValueSpaceClassification.VSPACE_G_YEARMONTH ; import static com.hp.hpl.jena.sparql.expr.ValueSpaceClassification.VSPACE_LANG ; import static com.hp.hpl.jena.sparql.expr.ValueSpaceClassification.VSPACE_NODE ; import static com.hp.hpl.jena.sparql.expr.ValueSpaceClassification.VSPACE_NUM ; import static com.hp.hpl.jena.sparql.expr.ValueSpaceClassification.VSPACE_STRING ; import static com.hp.hpl.jena.sparql.expr.ValueSpaceClassification.VSPACE_TIME ; import static com.hp.hpl.jena.sparql.expr.ValueSpaceClassification.VSPACE_UNKNOWN ; import static javax.xml.datatype.DatatypeConstants.DAYS ; import static javax.xml.datatype.DatatypeConstants.HOURS ; import static javax.xml.datatype.DatatypeConstants.MINUTES ; import static javax.xml.datatype.DatatypeConstants.MONTHS ; import static javax.xml.datatype.DatatypeConstants.SECONDS ; import static javax.xml.datatype.DatatypeConstants.YEARS ; import java.io.File ; import java.io.FileInputStream ; import java.io.IOException ; import java.io.InputStream ; import java.math.BigDecimal ; import java.math.BigInteger ; import java.util.Calendar ; import java.util.Iterator ; import java.util.Properties ; import java.util.ServiceLoader ; import javax.xml.datatype.DatatypeConfigurationException ; import javax.xml.datatype.DatatypeFactory ; import javax.xml.datatype.Duration ; import javax.xml.datatype.XMLGregorianCalendar ; import org.apache.jena.atlas.lib.StrUtils ; import org.apache.jena.atlas.logging.Log ; import org.slf4j.Logger ; import org.slf4j.LoggerFactory ; import com.hp.hpl.jena.datatypes.DatatypeFormatException ; import com.hp.hpl.jena.datatypes.RDFDatatype ; import com.hp.hpl.jena.datatypes.TypeMapper ; import com.hp.hpl.jena.datatypes.xsd.XSDDatatype ; import com.hp.hpl.jena.datatypes.xsd.XSDDateTime ; import com.hp.hpl.jena.graph.Node ; import com.hp.hpl.jena.graph.impl.LiteralLabel ; import com.hp.hpl.jena.query.ARQ ; import com.hp.hpl.jena.rdf.model.AnonId ; import com.hp.hpl.jena.sparql.ARQInternalErrorException ; import com.hp.hpl.jena.sparql.engine.ExecutionContext ; import com.hp.hpl.jena.sparql.engine.binding.Binding ; import com.hp.hpl.jena.sparql.expr.nodevalue.* ; import com.hp.hpl.jena.sparql.function.FunctionEnv ; import com.hp.hpl.jena.sparql.graph.NodeConst ; import com.hp.hpl.jena.sparql.graph.NodeTransform ; import com.hp.hpl.jena.sparql.serializer.SerializationContext ; import com.hp.hpl.jena.sparql.util.* ; public abstract class NodeValue extends ExprNode { // Maybe:: NodeValueStringLang - strings with language tag /* Naming: * getXXX => plain accessor * asXXX => force to the required thing if necessary. * * Implementation notes: * * 1. There is little point delaying turning a node into its value * because it has to be verified anyway (e.g. illegal literals). * Because a NodeValue is being created, it is reasonably likely it * is going to be used for it's value, so processing the datatype * can be done at creation time where it is clearer. * * 2. Conversely, delaying turning a value into a graph node is * valuable because intermediates, like the result of 2+3, will not * be needed as nodes unless assignment (and there is no assignment * in SPARQL even if there is for ARQ). * Node level operations like str() don't need a full node. * * 3. nodevalue.NodeFunctions contains the SPARQL builtin implementations. * nodevalue.XSDFuncOp contains the implementation of the XQuery/Xpath * functions and operations. * See also NodeUtils. * * 4. Note that SPARQL "=" is "known to be sameValueAs". Similarly "!=" is * known to be different. * * 5. To add a new number type: * Add sub type into nodevalue.NodeValueXXX * Must implement .hashCode() and .equals() based on value. * Add Functions.add/subtract/etc code and compareNumeric * Add to compare code * Fix TestExprNumeric * Write lots of tests. * Library code Maths1 and Maths2 for maths functions */ /* * Effective boolean value rules. * boolean: value of the boolean * string: length(string) > 0 is true * numeric: number != Nan && number != 0 is true * ref: http://www.w3.org/TR/xquery/#dt-ebv * */ private static Logger log = LoggerFactory.getLogger(NodeValue.class) ; // ---- Constants and initializers / public public static boolean VerboseWarnings = true ; public static boolean VerboseExceptions = false ; private static boolean VALUE_EXTENSIONS = ARQ.getContext().isTrueOrUndef(ARQ.extensionValueTypes) ; private static boolean sameValueAsString = VALUE_EXTENSIONS ; private static RefBoolean enableRomanNumerals = new RefBoolean(ARQ.enableRomanNumerals, false) ; //private static RefBoolean strictSPARQL = new RefBoolean(ARQ.strictSPARQL, false) ; public static final BigInteger IntegerZERO = BigInteger.ZERO ; public static final BigDecimal DecimalZERO = BigDecimal.ZERO ; public static final NodeValue TRUE = NodeValue.makeNode("true", XSDboolean) ; public static final NodeValue FALSE = NodeValue.makeNode("false", XSDboolean) ; public static final NodeValue nvZERO = NodeValue.makeNode(NodeConst.nodeZero) ; public static final NodeValue nvONE = NodeValue.makeNode(NodeConst.nodeOne) ; public static final NodeValue nvNaN = NodeValue.makeNode("NaN", XSDdouble) ; public static final NodeValue nvINF = NodeValue.makeNode("INF", XSDdouble) ; public static final NodeValue nvNegINF = NodeValue.makeNode("-INF",XSDdouble) ; public static final NodeValue nvEmptyString = NodeValue.makeString("") ; // Use "==" for equality. private static final String strForUnNode = "node value nothing" ; public static final NodeValue nvNothing = NodeValue.makeNode(com.hp.hpl.jena.graph.NodeFactory.createAnon(new AnonId("node value nothing"))) ; public static final String xsdNamespace = XSD+"#" ; public static DatatypeFactory xmlDatatypeFactory = null ; static { try { xmlDatatypeFactory = getDatatypeFactory() ; } catch (DatatypeConfigurationException ex) { throw new ARQInternalErrorException("Can't create a javax.xml DatatypeFactory", ex) ; } } /** * Get a datatype factory using the correct classloader * * See JENA-328. DatatypeFactory.newInstance() clashes with OSGi * This is clearly crazy, but DatatypeFactory is missing a very obvious * method newInstance(Classloader). The method that was added is very * hard to use correctly, as we shall see... */ private static DatatypeFactory getDatatypeFactory() throws DatatypeConfigurationException { ClassLoader cl = NodeValue.class.getClassLoader(); File jaxpPropFile = new File( System.getProperty("java.home") + File.pathSeparator + "lib" + File.pathSeparator + "jaxp.properties"); // Step 1. Try the system property String dtfClass = System.getProperty(DatatypeFactory.DATATYPEFACTORY_PROPERTY); // Step 2. Otherwise, try property in jaxp.properties if (dtfClass == null && jaxpPropFile.exists() && jaxpPropFile.canRead()) { Properties jaxp = new Properties(); InputStream in = null; try { in = new FileInputStream(jaxpPropFile); jaxp.load(in); dtfClass = jaxp.getProperty(DatatypeFactory.DATATYPEFACTORY_PROPERTY); } catch (Exception e) { log.warn("Issue loading jaxp.properties", e); } finally { if (in != null) { try { in.close(); } catch (IOException ex) { log.warn("Issue closing jaxp.properties ", ex); } } } } // Step 3. Otherwise try the service approach if (dtfClass == null) { Iterator<DatatypeFactory> factoryIterator = ServiceLoader.load(DatatypeFactory.class, cl).iterator(); if (factoryIterator.hasNext()) return factoryIterator.next(); } // Step 4. Use the default if (dtfClass == null) dtfClass = DatatypeFactory.DATATYPEFACTORY_IMPLEMENTATION_CLASS; return DatatypeFactory.newInstance(dtfClass, NodeValue.class.getClassLoader()) ; } private Node node = null ; // Null used when a value has not be turned into a Node. // Don't create direct - the static builders manage the value/node relationship protected NodeValue() { super() ; } protected NodeValue(Node n) { super() ; node = n ; } // protected makeNodeValue(NodeValue nv) // { // if ( v.isNode() ) { ... } // if ( v.isBoolean() ) { ... } // if ( v.isInteger() ) { ... } // if ( v.isDouble() ) { ... } // if ( v.isDecimal() ) { ... } // if ( v.isString() ) { ... } // if ( v.isDate() ) { ... } // } // ---------------------------------------------------------------- // ---- Construct NodeValue without a graph node. /** Convenience operation - parse a string to produce a NodeValue - common namespaces like xsd: are built-in */ public static NodeValue parse(String string) { return makeNode(NodeFactoryExtra.parseNode(string)) ; } public static NodeValue makeInteger(long i) { return new NodeValueInteger(BigInteger.valueOf(i)) ; } public static NodeValue makeInteger(BigInteger i) { return new NodeValueInteger(i) ; } public static NodeValue makeInteger(String lexicalForm) { return new NodeValueInteger(new BigInteger(lexicalForm)) ; } public static NodeValue makeFloat(float f) { return new NodeValueFloat(f) ; } public static NodeValue makeDouble(double d) { return new NodeValueDouble(d) ; } public static NodeValue makeString(String s) { return new NodeValueString(s) ; } public static NodeValue makeDecimal(BigDecimal d) { return new NodeValueDecimal(d) ; } public static NodeValue makeDecimal(long i) { return new NodeValueDecimal(BigDecimal.valueOf(i)) ; } public static NodeValue makeDecimal(double d) { return new NodeValueDecimal(BigDecimal.valueOf(d)) ; } public static NodeValue makeDecimal(String lexicalForm) { return NodeValue.makeNode(lexicalForm, XSDdecimal) ; } public static NodeValue makeDateTime(String lexicalForm) { return NodeValue.makeNode(lexicalForm, XSDdateTime) ; } public static NodeValue makeDate(String lexicalForm) { return NodeValue.makeNode(lexicalForm, XSDdate) ; } public static NodeValue makeDateTime(Calendar cal) { String lex = Utils.calendarToXSDDateTimeString(cal) ; return NodeValue.makeNode(lex, XSDdateTime) ; } public static NodeValue makeDateTime(XMLGregorianCalendar cal) { String lex = cal.toXMLFormat() ; Node node = com.hp.hpl.jena.graph.NodeFactory.createLiteral(lex, XSDdateTime) ; return new NodeValueDT(lex, node) ; } public static NodeValue makeDate(Calendar cal) { String lex = Utils.calendarToXSDDateString(cal) ; return NodeValue.makeNode(lex, XSDdate) ; } public static NodeValue makeDate(XMLGregorianCalendar cal) { String lex = cal.toXMLFormat() ; Node node = com.hp.hpl.jena.graph.NodeFactory.createLiteral(lex, XSDdate) ; return new NodeValueDT(lex, node) ; } public static NodeValue makeDuration(String lexicalForm) { return NodeValue.makeNode(lexicalForm, XSDduration) ; } public static NodeValue makeDuration(Duration duration) { return new NodeValueDuration(duration); } public static NodeValue makeNodeDuration(Duration duration, Node node) { return new NodeValueDuration(duration, node); } public static NodeValue makeBoolean(boolean b) { return b ? NodeValue.TRUE : NodeValue.FALSE ; } public static NodeValue booleanReturn(boolean b) { return b ? NodeValue.TRUE : NodeValue.FALSE ; } // ---------------------------------------------------------------- // ---- Construct NodeValue from graph nodes public static NodeValue makeNode(Node n) { NodeValue nv = nodeToNodeValue(n) ; return nv ; } public static NodeValue makeNode(String lexicalForm, XSDDatatype dtype) { Node n = com.hp.hpl.jena.graph.NodeFactory.createLiteral(lexicalForm, null, dtype) ; NodeValue nv = NodeValue.makeNode(n) ; return nv ; } // Convenience - knows that lang tags aren't allowed with datatypes. public static NodeValue makeNode(String lexicalForm, String langTag, Node datatype) { String uri = (datatype==null) ? null : datatype.getURI() ; return makeNode(lexicalForm, langTag, uri) ; } public static NodeValue makeNode(String lexicalForm, String langTag, String datatype) { if ( datatype != null && datatype.equals("") ) datatype = null ; if ( langTag != null && datatype != null ) // raise?? Log.warn(NodeValue.class, "Both lang tag and datatype defined (lexcial form '"+lexicalForm+"')") ; Node n = null ; if ( datatype != null) { RDFDatatype dType = TypeMapper.getInstance().getSafeTypeByName(datatype) ; n = com.hp.hpl.jena.graph.NodeFactory.createLiteral(lexicalForm, null, dType) ; } else n = com.hp.hpl.jena.graph.NodeFactory.createLiteral(lexicalForm, langTag, null) ; return NodeValue.makeNode(n) ; } // ---------------------------------------------------------------- // ---- Construct NodeValue with graph node and value. public static NodeValue makeNodeBoolean(boolean b) { return b ? NodeValue.TRUE : NodeValue.FALSE ; } public static NodeValue makeNodeBoolean(String lexicalForm) { NodeValue nv = makeNode(lexicalForm, null, XSDboolean.getURI()) ; return nv ; } public static NodeValue makeNodeInteger(long v) { NodeValue nv = makeNode(Long.toString(v), null, XSDinteger.getURI()) ; return nv ; } public static NodeValue makeNodeInteger(String lexicalForm) { NodeValue nv = makeNode(lexicalForm, null, XSDinteger.getURI()) ; return nv ; } public static NodeValue makeNodeFloat(float f) { NodeValue nv = makeNode(Utils.stringForm(f), null, XSDfloat.getURI()) ; return nv ; } public static NodeValue makeNodeFloat(String lexicalForm) { NodeValue nv = makeNode(lexicalForm, null, XSDdouble.getURI()) ; return nv ; } public static NodeValue makeNodeDouble(double v) { NodeValue nv = makeNode(Utils.stringForm(v), null, XSDdouble.getURI()) ; return nv ; } public static NodeValue makeNodeDouble(String lexicalForm) { NodeValue nv = makeNode(lexicalForm, null, XSDdouble.getURI()) ; return nv ; } public static NodeValue makeNodeDecimal(BigDecimal decimal) { NodeValue nv = makeNode(Utils.stringForm(decimal), null, XSDdecimal.getURI()) ; return nv ; } public static NodeValue makeNodeDecimal(String lexicalForm) { NodeValue nv = makeNode(lexicalForm, null, XSDdecimal.getURI()) ; return nv ; } public static NodeValue makeNodeString(String string) { NodeValue nv = makeNode(string, null, (String)null) ; return nv ; } public static NodeValue makeNodeDateTime(Calendar date) { String lex = Utils.calendarToXSDDateTimeString(date) ; NodeValue nv = makeNode(lex, XSDdateTime) ; return nv ; } public static NodeValue makeNodeDateTime(String lexicalForm) { NodeValue nv = makeNode(lexicalForm, XSDdateTime) ; return nv ; } public static NodeValue makeNodeDate(Calendar date) { String lex = Utils.calendarToXSDDateString(date) ; NodeValue nv = makeNode(lex, XSDdate) ; return nv ; } public static NodeValue makeNodeDate(String lexicalForm) { NodeValue nv = makeNode(lexicalForm, XSDdate) ; return nv ; } // ---------------------------------------------------------------- // ---- Expr interface @Override public NodeValue eval(Binding binding, FunctionEnv env) { return this ; } // NodeValues are immutable so no need to duplicate. @Override public Expr copySubstitute(Binding binding, boolean foldConstants) { // return this ; Node n = asNode() ; return makeNode(n) ; } @Override public Expr applyNodeTransform(NodeTransform transform) { Node n = asNode() ; n = transform.convert(n) ; return makeNode(n) ; } public Node evalNode(Binding binding, ExecutionContext execCxt) { return asNode() ; } @Override public boolean isConstant() { return true ; } @Override public NodeValue getConstant() { return this ; } public boolean isIRI() { if ( node == null ) return false ; forceToNode() ; return node.isURI() ; } public boolean isBlank() { if ( node == null ) return false ; forceToNode() ; return node.isBlank() ; } // ---------------------------------------------------------------- // ---- sameValueAs // Disjoint value spaces : dateTime and dates are not comparable // Every langtag implies another value space as well. /** Return true if the two NodeValues are known to be the same value * return false if known to be different values, * throw ExprEvalException otherwise */ public static boolean sameAs(NodeValue nv1, NodeValue nv2) { if ( nv1 == null || nv2 == null ) throw new ARQInternalErrorException("Attempt to sameValueAs on a null") ; ValueSpaceClassification compType = classifyValueOp(nv1, nv2) ; // Special case - date/dateTime comparison is affected by timezones and may be // interdeterminate based on the value of the dateTime/date. switch (compType) { case VSPACE_NUM: return XSDFuncOp.compareNumeric(nv1, nv2) == Expr.CMP_EQUAL ; case VSPACE_DATETIME: case VSPACE_DATE: case VSPACE_TIME: case VSPACE_G_YEAR : case VSPACE_G_YEARMONTH : case VSPACE_G_MONTH : case VSPACE_G_MONTHDAY : case VSPACE_G_DAY : { int x = XSDFuncOp.compareDateTime(nv1, nv2) ; if ( x == Expr.CMP_INDETERMINATE ) throw new ExprNotComparableException("Indeterminate dateTime comparison") ; return x == Expr.CMP_EQUAL ; } case VSPACE_DURATION: { int x = XSDFuncOp.compareDuration(nv1, nv2) ; if ( x == Expr.CMP_INDETERMINATE ) throw new ExprNotComparableException("Indeterminate duration comparison") ; return x == Expr.CMP_EQUAL ; } case VSPACE_STRING: return XSDFuncOp.compareString(nv1, nv2) == Expr.CMP_EQUAL ; case VSPACE_BOOLEAN: return XSDFuncOp.compareBoolean(nv1, nv2) == Expr.CMP_EQUAL ; case VSPACE_LANG: { // two literals, both with a language tag Node node1 = nv1.asNode() ; Node node2 = nv2.asNode() ; return node1.getLiteralLexicalForm().equals(node2.getLiteralLexicalForm()) && node1.getLiteralLanguage().equalsIgnoreCase(node2.getLiteralLanguage()) ; } case VSPACE_NODE: // Two non-literals return NodeFunctions.sameTerm(nv1.getNode(), nv2.getNode()) ; case VSPACE_UNKNOWN: { // One or two unknown value spaces, or one has a lang tag (but not both). Node node1 = nv1.getNode() ; Node node2 = nv2.getNode() ; if ( ! VALUE_EXTENSIONS ) // No value extensions => raw rdfTermEquals return NodeFunctions.rdfTermEquals(node1, node2) ; // Some "value spaces" are know to be not equal (no overlap). // Like one literal with a language tag, and one without can't be sameAs. if ( ! node1.isLiteral() || ! node2.isLiteral() ) // One or other not a literal => not sameAs return false ; // Two literals at this point. if ( NodeFunctions.sameTerm(node1, node2) ) return true ; if ( ! node1.getLiteralLanguage().equals("") || ! node2.getLiteralLanguage().equals("") ) // One had lang tags but weren't sameNode => not equals return false ; raise(new ExprEvalException("Unknown equality test: "+nv1+" and "+nv2)) ; throw new ARQInternalErrorException("raise returned (sameValueAs)") ; } case VSPACE_DIFFERENT: // Known to be incompatible. if ( ! VALUE_EXTENSIONS && ( nv1.isLiteral() && nv2.isLiteral() ) ) raise(new ExprEvalException("Incompatible: "+nv1+" and "+nv2)) ; return false ; } throw new ARQInternalErrorException("sameValueAs failure "+nv1+" and "+nv2) ; } /** Return true if the two Nodes are known to be different, * return false if the two Nodes are known to be the same, * else throw ExprEvalException */ public static boolean notSameAs(Node n1, Node n2) { return notSameAs(NodeValue.makeNode(n1), NodeValue.makeNode(n2)) ; } /** Return true if the two NodeValues are known to be different, * return false if the two NodeValues are known to be the same, * else throw ExprEvalException */ public static boolean notSameAs(NodeValue nv1, NodeValue nv2) { return ! sameAs(nv1, nv2) ; } // ---------------------------------------------------------------- // compare // Compare by value code is here // NodeUtils.compareRDFTerms for syntactic comparison /** Compare by value if possible else compare by kind/type/lexical form * Only use when you want an ordering regardless of form of NodeValue, * for example in ORDER BY * * @param nv1 * @param nv2 * @return negative, 0, or postive for less than, equal, greater than. */ public static int compareAlways(NodeValue nv1, NodeValue nv2) { // ***** Only called from a test. Sort out with NodeUtils. try { int x = compare(nv1, nv2, true) ; // Same? if ( x != Expr.CMP_EQUAL ) return x ; } catch (ExprNotComparableException ex) { /* Drop through */ } return NodeUtils.compareRDFTerms(nv1.asNode(), nv2.asNode()) ; } /** Compare by value (and only value) if possible. * Supports <, <=, >, >= but not = nor != (which are sameValueAs and notSameValueAs) * @param nv1 * @param nv2 * @return negative, 0 , or positive for not possible, less than, equal, greater than. * @throws ExprNotComparableException */ public static int compare(NodeValue nv1, NodeValue nv2) { // Called from E_LessThat etc // and NodeUtils.comparLiteralsByValue if ( nv1 == null || nv2 == null ) //raise(new ExprEvalException("Attempt to notSameValueAs on null") ; throw new ARQInternalErrorException("Attempt to compare on null") ; int x = compare(nv1, nv2, false) ; return x ; } // E_GreaterThan/E_LessThan/E_GreaterThanOrEqual/E_LessThanOrEqual // ==> compare(nv1, nv2) => compare (nv1, nv2, false) // BindingComparator => compareAlways(nv1, nv2) => compare (nv1, nv2, true) // E_Equals calls NodeValue.sameAs() ==> // sortOrderingCompare means that the comparison should do something with normally unlike things, // and split plain strings from xsd:strings. private static int compare(NodeValue nv1, NodeValue nv2, boolean sortOrderingCompare) { if ( nv1 == null && nv2 == null ) return Expr.CMP_EQUAL ; if ( nv1 == null ) return Expr.CMP_LESS ; if ( nv2 == null ) return Expr.CMP_GREATER ; ValueSpaceClassification compType = classifyValueOp(nv1, nv2) ; // Special case - date/dateTime comparison is affected by timezones and may be // interdeterminate based on the value of the dateTime/date. // Do this first, switch (compType) { case VSPACE_DATETIME: case VSPACE_DATE: case VSPACE_TIME: case VSPACE_G_DAY : case VSPACE_G_MONTH : case VSPACE_G_MONTHDAY : case VSPACE_G_YEAR : case VSPACE_G_YEARMONTH : { int x = XSDFuncOp.compareDateTime(nv1, nv2) ; if ( x != Expr.CMP_INDETERMINATE ) return x ; // Indeterminate => can't compare as strict values. compType = ValueSpaceClassification.VSPACE_DIFFERENT ; break ; } case VSPACE_DURATION: { int x = XSDFuncOp.compareDuration(nv1, nv2) ; if ( x != Expr.CMP_INDETERMINATE ) return x ; // Indeterminate => can't compare as strict values. compType = ValueSpaceClassification.VSPACE_DIFFERENT ; break ; } //default: case VSPACE_BOOLEAN : case VSPACE_DIFFERENT : case VSPACE_LANG : case VSPACE_NODE : case VSPACE_NUM : case VSPACE_STRING : case VSPACE_UNKNOWN : // Drop through. } switch (compType) { case VSPACE_DATETIME: case VSPACE_DATE: case VSPACE_TIME: case VSPACE_G_DAY : case VSPACE_G_MONTH : case VSPACE_G_MONTHDAY : case VSPACE_G_YEAR : case VSPACE_G_YEARMONTH : case VSPACE_DURATION: throw new ARQInternalErrorException("Still seeing date/dateTime/time/duration compare type") ; case VSPACE_NUM: return XSDFuncOp.compareNumeric(nv1, nv2) ; case VSPACE_STRING: { int cmp = XSDFuncOp.compareString(nv1, nv2) ; // Split plain literals and xsd:strings for sorting purposes. if ( ! sortOrderingCompare ) return cmp ; if ( cmp != Expr.CMP_EQUAL ) return cmp ; // Same by string value. String dt1 = nv1.asNode().getLiteralDatatypeURI() ; String dt2 = nv2.asNode().getLiteralDatatypeURI() ; if ( dt1 == null && dt2 != null ) return Expr.CMP_LESS ; if ( dt2 == null && dt1 != null ) return Expr.CMP_GREATER ; return Expr.CMP_EQUAL; // Both plain or both xsd:string. } case VSPACE_BOOLEAN: return XSDFuncOp.compareBoolean(nv1, nv2) ; case VSPACE_LANG: { // Two literals, both with language tags. Node node1 = nv1.asNode() ; Node node2 = nv2.asNode() ; int x = StrUtils.strCompareIgnoreCase(node1.getLiteralLanguage(), node2.getLiteralLanguage()) ; if ( x != Expr.CMP_EQUAL ) { // Different lang tags if ( ! sortOrderingCompare ) raise(new ExprNotComparableException("Can't compare (different languages) "+nv1+" and "+nv2)) ; // Different lang tags - sorting return x ; } // same lang tag (case insensitive) x = StrUtils.strCompare(node1.getLiteralLexicalForm(), node2.getLiteralLexicalForm()) ; if ( x != Expr.CMP_EQUAL ) return x ; // Same lexcial forms, same lang tag by value // Try to split by syntactic lang tags. x = StrUtils.strCompare(node1.getLiteralLanguage(), node2.getLiteralLanguage()) ; // Maybe they are the same after all! // Should be node.equals by now. if ( x == Expr.CMP_EQUAL && ! NodeFunctions.sameTerm(node1, node2) ) throw new ARQInternalErrorException("Look the same (lang tags) but no node equals") ; return x ; } case VSPACE_NODE: // Two non-literals don't compare except for sorting. if ( sortOrderingCompare ) return NodeUtils.compareRDFTerms(nv1.asNode(), nv2.asNode()) ; else { raise(new ExprNotComparableException("Can't compare (nodes) "+nv1+" and "+nv2)) ; throw new ARQInternalErrorException("NodeValue.raise returned") ; } case VSPACE_UNKNOWN: { // One or two unknown value spaces. Node node1 = nv1.asNode() ; Node node2 = nv2.asNode() ; // Two unknown literals can be equal. if ( NodeFunctions.sameTerm(node1, node2) ) return Expr.CMP_EQUAL ; if ( sortOrderingCompare ) return NodeUtils.compareRDFTerms(node1, node2) ; raise(new ExprNotComparableException("Can't compare "+nv1+" and "+nv2)) ; throw new ARQInternalErrorException("NodeValue.raise returned") ; } case VSPACE_DIFFERENT: // Two literals, from different known value spaces if ( sortOrderingCompare ) return NodeUtils.compareRDFTerms(nv1.asNode(), nv2.asNode()) ; raise(new ExprNotComparableException("Can't compare (incompatible value spaces)"+nv1+" and "+nv2)) ; throw new ARQInternalErrorException("NodeValue.raise returned") ; } throw new ARQInternalErrorException("Compare failure "+nv1+" and "+nv2) ; } public static ValueSpaceClassification classifyValueOp(NodeValue nv1, NodeValue nv2) { ValueSpaceClassification c1 = nv1.getValueSpace() ; ValueSpaceClassification c2 = nv2.getValueSpace() ; if ( c1 == c2 ) return c1 ; if ( c1 == VSPACE_UNKNOWN || c2 == VSPACE_UNKNOWN ) return VSPACE_UNKNOWN ; // Known values spaces but incompatible return VSPACE_DIFFERENT ; } public ValueSpaceClassification getValueSpace() { return classifyValueSpace(this) ; } private static ValueSpaceClassification classifyValueSpace(NodeValue nv) { if ( nv.isNumber() ) return VSPACE_NUM ; if ( nv.isDateTime() ) return VSPACE_DATETIME ; if ( nv.isDate() ) return VSPACE_DATE ; if ( nv.isTime() ) return VSPACE_TIME ; if ( nv.isDuration() ) return VSPACE_DURATION ; if ( nv.isGYear() ) return VSPACE_G_YEAR ; if ( nv.isGYearMonth() ) return VSPACE_G_YEARMONTH ; if ( nv.isGMonth() ) return VSPACE_G_MONTH ; if ( nv.isGMonthDay() ) return VSPACE_G_MONTHDAY ; if ( nv.isGDay() ) return VSPACE_G_DAY ; if ( VALUE_EXTENSIONS && nv.isDate() ) return VSPACE_DATE ; if ( nv.isString()) return VSPACE_STRING ; if ( nv.isBoolean()) return VSPACE_BOOLEAN ; if ( ! nv.isLiteral() ) return VSPACE_NODE ; if ( VALUE_EXTENSIONS && nv.getNode() != null && nv.getNode().isLiteral() && ! nv.getNode().getLiteralLanguage().equals("") ) return VSPACE_LANG ; return VSPACE_UNKNOWN ; } // ---------------------------------------------------------------- // ---- Node operations public static Node toNode(NodeValue nv) { if ( nv == null ) return null ; return nv.asNode() ; } public final Node asNode() { if ( node == null ) node = makeNode() ; return node ; } protected abstract Node makeNode() ; /** getNode - return the node form - may be null (use .asNode() to force to a node) */ public Node getNode() { return node ; } public String getDatatypeURI() { return asNode().getLiteralDatatypeURI() ; } public boolean hasNode() { return node != null ; } // ---------------------------------------------------------------- // ---- Subclass operations public boolean isBoolean() { return false ; } public boolean isString() { return false ; } public boolean isNumber() { return false ; } public boolean isInteger() { return false ; } public boolean isDecimal() { return false ; } public boolean isFloat() { return false ; } public boolean isDouble() { return false ; } public boolean hasDateTime() { return isDateTime() || isDate() || isTime() || isGYear() || isGYearMonth() || isGMonth() || isGMonthDay() || isGDay() ; } public boolean isDateTime() { return false ; } public boolean isDate() { return false ; } public boolean isLiteral() { return getNode() == null || getNode().isLiteral() ; } public boolean isTime() { return false ; } public boolean isDuration() { return false ; } public boolean isYearMonth() { if ( ! isDuration() ) return false ; Duration dur = getDuration() ; return ( dur.isSet(YEARS) || dur.isSet(MONTHS) ) && ! dur.isSet(DAYS) && ! dur.isSet(HOURS) && ! dur.isSet(MINUTES) && ! dur.isSet(SECONDS) ; } boolean isDayTime() { if ( ! isDuration() ) return false ; Duration dur = getDuration() ; return !dur.isSet(YEARS) && ! dur.isSet(MONTHS) && ( dur.isSet(DAYS) || dur.isSet(HOURS) || dur.isSet(MINUTES) || dur.isSet(SECONDS) ); } public boolean isGYear() { return false ; } public boolean isGYearMonth() { return false ; } public boolean isGMonth() { return false ; } public boolean isGMonthDay() { return false ; } public boolean isGDay() { return false ; } public boolean getBoolean() { raise(new ExprEvalTypeException("Not a boolean: "+this)) ; return false ; } public String getString() { raise(new ExprEvalTypeException("Not a string: "+this)) ; return null ; } public BigInteger getInteger() { raise(new ExprEvalTypeException("Not an integer: "+this)) ; return null ; } public BigDecimal getDecimal() { raise(new ExprEvalTypeException("Not a decimal: "+this)) ; return null ; } public float getFloat() { raise(new ExprEvalTypeException("Not a float: "+this)) ; return Float.NaN ; } public double getDouble() { raise(new ExprEvalTypeException("Not a double: "+this)) ; return Double.NaN ; } // Value representation for all date and time values. public XMLGregorianCalendar getDateTime() { raise(new ExprEvalTypeException("No DateTime value: "+this)) ; return null ; } public Duration getDuration() { raise(new ExprEvalTypeException("Not a duration: "+this)) ; return null ; } // ---------------------------------------------------------------- // ---- Setting : used when a node is used to make a NodeValue private static NodeValue nodeToNodeValue(Node node) { if ( node.isVariable() ) Log.warn(NodeValue.class, "Variable passed to NodeValue.nodeToNodeValue") ; if ( ! node.isLiteral() ) // Not a literal - no value to extract return new NodeValueNode(node) ; boolean hasLangTag = ( node.getLiteralLanguage() != null && ! node.getLiteralLanguage().equals("")) ; boolean isPlainLiteral = ( node.getLiteralDatatypeURI() == null && ! hasLangTag ) ; if ( isPlainLiteral ) return new NodeValueString(node.getLiteralLexicalForm(), node) ; if ( hasLangTag ) { if ( node.getLiteralDatatypeURI() != null ) { if ( NodeValue.VerboseWarnings ) Log.warn(NodeValue.class, "Lang tag and datatype (datatype ignored)") ; } return new NodeValueNode(node) ; } // Typed literal LiteralLabel lit = node.getLiteral() ; // This includes type testing //if ( ! lit.getDatatype().isValidLiteral(lit) ) // Use this - already calculated when the node is formed. if ( !node.getLiteral().isWellFormed() ) { if ( NodeValue.VerboseWarnings ) { String tmp = FmtUtils.stringForNode(node) ; Log.warn(NodeValue.class, "Datatype format exception: "+tmp) ; } // Invalid lexical form. return new NodeValueNode(node) ; } NodeValue nv = _setByValue(node) ; if ( nv != null ) return nv ; return new NodeValueNode(node) ; //raise(new ExprException("NodeValue.nodeToNodeValue: Unknown Node type: "+n)) ; } // Jena code does not have these types (yet) private static final String dtXSDdateTimeStamp = XSD+"#dateTimeStamp" ; private static final String dtXSDdayTimeDuration = XSD+"#dayTimeDuration" ; private static final String dtXSDyearMonthDuration = XSD+"#yearMonthDuration" ; private static final String dtXSDprecisionDecimal = XSD+"#precisionDecimal" ; // Returns null for unrecognized literal. private static NodeValue _setByValue(Node node) { if ( NodeUtils.hasLang(node) ) // Check for RDF 1.1! return null ; LiteralLabel lit = node.getLiteral() ; String lex = lit.getLexicalForm() ; RDFDatatype datatype = lit.getDatatype() ; // Quick check. // Only XSD supported. // And (for testing) roman numerals. String datatypeURI = datatype.getURI() ; if ( ! datatypeURI.startsWith(xsdNamespace) && ! enableRomanNumerals.getValue() ) { // Not XSD. return null ; } try { // DatatypeFormatException - should not happen if ( sameValueAsString && XSDstring.isValidLiteral(lit) ) // String - plain or xsd:string return new NodeValueString(lit.getLexicalForm(), node) ; // Otherwise xsd:string is like any other unknown datatype. // Ditto literals with language tags (which are handled by nodeToNodeValue) // isValidLiteral is a value test - not a syntactic test. // This makes a difference in that "1"^^xsd:decimal" is a // valid literal for xsd:integer (all other cases are subtypes of xsd:integer) // which we want to become integer anyway). // Order here is promotion order integer-decimal-float-double if ( ! datatype.equals(XSDdecimal) ) { // XSD integer and derived types if ( XSDinteger.isValidLiteral(lit) ) { String s = node.getLiteralLexicalForm() ; if ( s.startsWith("+") ) // BigInteger does not accept leading "+" s = s.substring(1) ; // Includes subtypes (int, byte, postiveInteger etc). // NB Known to be valid for type by now BigInteger integer = new BigInteger(s) ; return new NodeValueInteger(integer, node) ; } } if ( datatype.equals(XSDdecimal) && XSDdecimal.isValidLiteral(lit) ) { BigDecimal decimal = new BigDecimal(lit.getLexicalForm()) ; return new NodeValueDecimal(decimal, node) ; } if ( datatype.equals(XSDfloat) && XSDfloat.isValidLiteral(lit) ) { // NB If needed, call to floatValue, then assign to double. // Gets 1.3f != 1.3d right float f = ((Number)lit.getValue()).floatValue() ; return new NodeValueFloat(f, node) ; } if ( datatype.equals(XSDdouble) && XSDdouble.isValidLiteral(lit) ) { double d = ((Number)lit.getValue()).doubleValue() ; return new NodeValueDouble(d, node) ; } // XXX Pending Jena update ... if ( ( datatype.equals(XSDdateTime) || dtXSDdateTimeStamp.equals(datatypeURI) ) && XSDdateTime.isValid(lex) ) { XSDDateTime dateTime = (XSDDateTime)lit.getValue() ; return new NodeValueDT(lex, node) ; } if ( datatype.equals(XSDdate) && XSDdate.isValidLiteral(lit) ) { // Jena datatype support works on masked dataTimes. XSDDateTime dateTime = (XSDDateTime)lit.getValue() ; return new NodeValueDT(lex, node) ; } if ( datatype.equals(XSDtime) && XSDtime.isValidLiteral(lit) ) { // Jena datatype support works on masked dataTimes. XSDDateTime time = (XSDDateTime)lit.getValue() ; return new NodeValueDT(lex, node) ; } if ( datatype.equals(XSDgYear) && XSDgYear.isValidLiteral(lit) ) { XSDDateTime time = (XSDDateTime)lit.getValue() ; return new NodeValueDT(lex, node) ; } if ( datatype.equals(XSDgYearMonth) && XSDgYearMonth.isValidLiteral(lit) ) { XSDDateTime time = (XSDDateTime)lit.getValue() ; return new NodeValueDT(lex, node) ; } if ( datatype.equals(XSDgMonth) && XSDgMonth.isValidLiteral(lit) ) { XSDDateTime time = (XSDDateTime)lit.getValue() ; return new NodeValueDT(lex, node) ; } if ( datatype.equals(XSDgMonthDay) && XSDgMonthDay.isValidLiteral(lit) ) { XSDDateTime time = (XSDDateTime)lit.getValue() ; return new NodeValueDT(lex, node) ; } if ( datatype.equals(XSDgDay) && XSDgDay.isValidLiteral(lit) ) { XSDDateTime time = (XSDDateTime)lit.getValue() ; return new NodeValueDT(lex, node) ; } // XXX Pending Jena update ... if ( ( datatype.equals(XSDduration) || dtXSDdayTimeDuration.equals(datatypeURI) || dtXSDyearMonthDuration.equals(datatypeURI) ) && XSDduration.isValid(lex) ) // use lex { Duration duration = xmlDatatypeFactory.newDuration(lex) ; if ( dtXSDdayTimeDuration.equals(datatypeURI) && ! XSDFuncOp.isDayTime(duration) ) return null ; if ( dtXSDyearMonthDuration.equals(datatypeURI) && ! XSDFuncOp.isYearMonth(duration) ) return null ; return new NodeValueDuration(duration, node) ; } if ( datatype.equals(XSDboolean) && XSDboolean.isValidLiteral(lit) ) { boolean b = ((Boolean)lit.getValue()).booleanValue() ; return new NodeValueBoolean(b, node) ; } // If wired into the TypeMapper via RomanNumeralDatatype.enableAsFirstClassDatatype // if ( RomanNumeralDatatype.get().isValidLiteral(lit) ) // { // int i = ((RomanNumeral)lit.getValue()).intValue() ; // return new NodeValueInteger(i) ; // } // Not wired in if ( enableRomanNumerals.getValue() ) { if ( lit.getDatatypeURI().equals(RomanNumeralDatatype.get().getURI()) ) { Object obj = RomanNumeralDatatype.get().parse(lit.getLexicalForm()) ; if ( obj instanceof Integer ) return new NodeValueInteger(((Integer)obj).longValue()) ; if ( obj instanceof RomanNumeral ) return new NodeValueInteger( ((RomanNumeral)obj).intValue() ) ; throw new ARQInternalErrorException("DatatypeFormatException: Roman numeral is unknown class") ; } } } catch (DatatypeFormatException ex) { // Should have been caught earlier by special test in nodeToNodeValue throw new ARQInternalErrorException("DatatypeFormatException: "+lit, ex) ; } return null ; } // ---------------------------------------------------------------- // Point to catch all exceptions. public static void raise(ExprException ex) { throw ex ; } @Override public void visit(ExprVisitor visitor) { visitor.visit(this) ; } private void forceToNode() { if ( node == null ) node = asNode() ; if ( node == null ) raise(new ExprEvalException("Not a node: "+this)) ; } // ---- Formatting (suitable for SPARQL syntax). // Usually done by being a Node and formatting that. // In desperation, will try toString() (no quoting) public final String asUnquotedString() { return asString() ; } public final String asQuotedString() { return asQuotedString(new SerializationContext()) ; } public final String asQuotedString(SerializationContext context) { // If possible, make a node and use that as the formatted output. if ( node == null ) node = asNode() ; if ( node != null ) return FmtUtils.stringForNode(node, context) ; return toString() ; } // Convert to a string - usually overridden. public String asString() { // Do not call .toString() forceToNode() ; return NodeFunctions.str(node) ; } @Override public int hashCode() { return asNode().hashCode() ; } @Override public boolean equals(Object other) { // This is the equality condition Jena uses - lang tags are different by case. if ( this == other ) return true ; if ( ! ( other instanceof NodeValue ) ) return false ; NodeValue nv = (NodeValue)other ; return asNode().equals(nv.asNode()) ; // Not NodeFunctions.sameTerm (which smooshes language tags by case) } public abstract void visit(NodeValueVisitor visitor) ; public Expr apply(ExprTransform transform) { return transform.transform(this) ; } @Override public String toString() { return asQuotedString() ; } }
JENA-328 : Armour the file access code against SecurityExceptions. git-svn-id: bc509ec38c1227b3e85ea1246fda136342965d36@1551647 13f79535-47bb-0310-9956-ffa450edef68
jena-arq/src/main/java/com/hp/hpl/jena/sparql/expr/NodeValue.java
JENA-328 : Armour the file access code against SecurityExceptions.
<ide><path>ena-arq/src/main/java/com/hp/hpl/jena/sparql/expr/NodeValue.java <ide> <ide> package com.hp.hpl.jena.sparql.expr; <ide> <del>import static com.hp.hpl.jena.datatypes.xsd.XSDDatatype.XSD ; <del>import static com.hp.hpl.jena.datatypes.xsd.XSDDatatype.XSDboolean ; <del>import static com.hp.hpl.jena.datatypes.xsd.XSDDatatype.XSDdate ; <del>import static com.hp.hpl.jena.datatypes.xsd.XSDDatatype.XSDdateTime ; <del>import static com.hp.hpl.jena.datatypes.xsd.XSDDatatype.XSDdecimal ; <del>import static com.hp.hpl.jena.datatypes.xsd.XSDDatatype.XSDdouble ; <del>import static com.hp.hpl.jena.datatypes.xsd.XSDDatatype.XSDduration ; <del>import static com.hp.hpl.jena.datatypes.xsd.XSDDatatype.XSDfloat ; <del>import static com.hp.hpl.jena.datatypes.xsd.XSDDatatype.XSDgDay ; <del>import static com.hp.hpl.jena.datatypes.xsd.XSDDatatype.XSDgMonth ; <del>import static com.hp.hpl.jena.datatypes.xsd.XSDDatatype.XSDgMonthDay ; <del>import static com.hp.hpl.jena.datatypes.xsd.XSDDatatype.XSDgYear ; <del>import static com.hp.hpl.jena.datatypes.xsd.XSDDatatype.XSDgYearMonth ; <del>import static com.hp.hpl.jena.datatypes.xsd.XSDDatatype.XSDinteger ; <del>import static com.hp.hpl.jena.datatypes.xsd.XSDDatatype.XSDstring ; <del>import static com.hp.hpl.jena.datatypes.xsd.XSDDatatype.XSDtime ; <del>import static com.hp.hpl.jena.sparql.expr.ValueSpaceClassification.VSPACE_BOOLEAN ; <del>import static com.hp.hpl.jena.sparql.expr.ValueSpaceClassification.VSPACE_DATE ; <del>import static com.hp.hpl.jena.sparql.expr.ValueSpaceClassification.VSPACE_DATETIME ; <del>import static com.hp.hpl.jena.sparql.expr.ValueSpaceClassification.VSPACE_DIFFERENT ; <del>import static com.hp.hpl.jena.sparql.expr.ValueSpaceClassification.VSPACE_DURATION ; <del>import static com.hp.hpl.jena.sparql.expr.ValueSpaceClassification.VSPACE_G_DAY ; <del>import static com.hp.hpl.jena.sparql.expr.ValueSpaceClassification.VSPACE_G_MONTH ; <del>import static com.hp.hpl.jena.sparql.expr.ValueSpaceClassification.VSPACE_G_MONTHDAY ; <del>import static com.hp.hpl.jena.sparql.expr.ValueSpaceClassification.VSPACE_G_YEAR ; <del>import static com.hp.hpl.jena.sparql.expr.ValueSpaceClassification.VSPACE_G_YEARMONTH ; <del>import static com.hp.hpl.jena.sparql.expr.ValueSpaceClassification.VSPACE_LANG ; <del>import static com.hp.hpl.jena.sparql.expr.ValueSpaceClassification.VSPACE_NODE ; <del>import static com.hp.hpl.jena.sparql.expr.ValueSpaceClassification.VSPACE_NUM ; <del>import static com.hp.hpl.jena.sparql.expr.ValueSpaceClassification.VSPACE_STRING ; <del>import static com.hp.hpl.jena.sparql.expr.ValueSpaceClassification.VSPACE_TIME ; <del>import static com.hp.hpl.jena.sparql.expr.ValueSpaceClassification.VSPACE_UNKNOWN ; <del>import static javax.xml.datatype.DatatypeConstants.DAYS ; <del>import static javax.xml.datatype.DatatypeConstants.HOURS ; <del>import static javax.xml.datatype.DatatypeConstants.MINUTES ; <del>import static javax.xml.datatype.DatatypeConstants.MONTHS ; <del>import static javax.xml.datatype.DatatypeConstants.SECONDS ; <del>import static javax.xml.datatype.DatatypeConstants.YEARS ; <add>import static com.hp.hpl.jena.datatypes.xsd.XSDDatatype.* ; <add>import static com.hp.hpl.jena.sparql.expr.ValueSpaceClassification.* ; <add>import static javax.xml.datatype.DatatypeConstants.* ; <ide> <ide> import java.io.File ; <ide> import java.io.FileInputStream ; <ide> // Step 1. Try the system property <ide> String dtfClass = System.getProperty(DatatypeFactory.DATATYPEFACTORY_PROPERTY); <ide> <del> // Step 2. Otherwise, try property in jaxp.properties <del> if (dtfClass == null && jaxpPropFile.exists() && jaxpPropFile.canRead()) { <del> Properties jaxp = new Properties(); <del> InputStream in = null; <del> try { <del> in = new FileInputStream(jaxpPropFile); <del> jaxp.load(in); <del> dtfClass = jaxp.getProperty(DatatypeFactory.DATATYPEFACTORY_PROPERTY); <del> } catch (Exception e) { <del> log.warn("Issue loading jaxp.properties", e); <del> } finally { <del> if (in != null) { <del> try { <del> in.close(); <del> } catch (IOException ex) { <del> log.warn("Issue closing jaxp.properties ", ex); <add> try { <add> // Step 2. Otherwise, try property in jaxp.properties <add> if (dtfClass == null && jaxpPropFile.exists() && jaxpPropFile.canRead()) { <add> Properties jaxp = new Properties(); <add> InputStream in = null; <add> try { <add> in = new FileInputStream(jaxpPropFile); <add> jaxp.load(in); <add> dtfClass = jaxp.getProperty(DatatypeFactory.DATATYPEFACTORY_PROPERTY); <add> } catch (Exception e) { <add> log.warn("Issue loading jaxp.properties", e); <add> } finally { <add> if (in != null) { <add> try { <add> in.close(); <add> } catch (IOException ex) { <add> log.warn("Issue closing jaxp.properties ", ex); <add> } <ide> } <ide> } <ide> } <add> } <add> // File.exists and File.canRead may throw SecurityException (probably AccessControlException) <add> catch (SecurityException ex) { <add> log.warn("Security exception try to get jaxp.properties: "+ex.getMessage()) ; <ide> } <ide> <ide> // Step 3. Otherwise try the service approach
Java
apache-2.0
cd04a6829a3f70265c057ef985ccce7b81f9f5a3
0
budgefeeney/twitter-tools,budgefeeney/twitter-tools,budgefeeney/twitter-tools
package cc.twittertools.download; import java.io.BufferedReader; import java.io.File; import java.io.FileInputStream; import java.io.FileOutputStream; import java.io.IOException; import java.io.InputStreamReader; import java.io.OutputStreamWriter; import java.util.Map; import java.util.Timer; import java.util.TimerTask; import java.util.concurrent.ConcurrentSkipListMap; import java.util.concurrent.atomic.AtomicInteger; import java.util.zip.GZIPOutputStream; import org.apache.commons.cli.CommandLine; import org.apache.commons.cli.CommandLineParser; import org.apache.commons.cli.GnuParser; import org.apache.commons.cli.HelpFormatter; import org.apache.commons.cli.OptionBuilder; import org.apache.commons.cli.Options; import org.apache.commons.cli.ParseException; import org.apache.commons.lang.StringEscapeUtils; import org.apache.log4j.Logger; import cc.twittertools.corpus.data.Status; import com.google.common.base.Preconditions; import com.google.gson.Gson; import com.google.gson.JsonObject; import com.google.gson.JsonParser; import com.google.gson.JsonSyntaxException; import com.ning.http.client.AsyncCompletionHandler; import com.ning.http.client.AsyncHttpClient; import com.ning.http.client.AsyncHttpClientConfig; import com.ning.http.client.HttpResponseHeaders; import com.ning.http.client.HttpResponseStatus; import com.ning.http.client.Response; import com.ning.http.client.extra.ThrottleRequestFilter; public class AsyncEmbeddedJsonStatusBlockCrawler { private static final Logger LOG = Logger.getLogger(AsyncEmbeddedJsonStatusBlockCrawler.class); public static final String JSON_START = "<input type=\"hidden\" id=\"init-data\" class=\"json-data\" value=\""; public static final String JSON_END = "\">"; private static final int TWEET_BLOCK_SIZE = 500; private static final int MAX_CONNECTIONS = 100; private static final int CONNECTION_TIMEOUT = 10000; private static final int IDLE_CONNECTION_TIMEOUT = 10000; private static final int REQUEST_TIMEOUT = 10000; private static final int MAX_RETRY_ATTEMPTS = 2; private static final int WAIT_BEFORE_RETRY = 1000; private static final Timer timer = new Timer(true); private static final JsonParser JSON_PARSER = new JsonParser(); private static final Gson GSON = new Gson(); private final File file; private final File output; private final File repair; private final AsyncHttpClient asyncHttpClient; private final boolean noFollow; // key = statud id, value = tweet JSON private final ConcurrentSkipListMap<Long, String> crawl = new ConcurrentSkipListMap<Long, String>(); // key = statud id, value = data line private final ConcurrentSkipListMap<Long, String> crawl_repair = new ConcurrentSkipListMap<Long, String>(); private final AtomicInteger connections = new AtomicInteger(0); public AsyncEmbeddedJsonStatusBlockCrawler(File file, String output, String repair, boolean noFollow) throws IOException { this.file = Preconditions.checkNotNull(file); this.noFollow = noFollow; if (!file.exists()) { throw new IOException(file + " does not exist!"); } // check existence of output's parent directory this.output = new File(Preconditions.checkNotNull(output)); File parent = this.output.getParentFile(); if (parent != null && !parent.exists()) { throw new IOException(output + "'s parent directory does not exist!"); } // check existence of repair's parent directory (or set to null if no // repair file specified) if (repair != null) { this.repair = new File(repair); parent = this.repair.getParentFile(); if (parent != null && !parent.exists()) { throw new IOException(repair + "'s parent directory does not exist!"); } } else { this.repair = null; } AsyncHttpClientConfig config = new AsyncHttpClientConfig.Builder() .addRequestFilter(new ThrottleRequestFilter(MAX_CONNECTIONS)) .setConnectionTimeoutInMs(CONNECTION_TIMEOUT) .setIdleConnectionInPoolTimeoutInMs(IDLE_CONNECTION_TIMEOUT) .setRequestTimeoutInMs(REQUEST_TIMEOUT).setMaxRequestRetry(0).build(); this.asyncHttpClient = new AsyncHttpClient(config); } public static String getUrl(long id, String username) { Preconditions.checkNotNull(username); return String.format("http://api.twitter.com/1/statuses/oembed.json?id=%d&&omit_script=true", id); } public void fetch() throws IOException { long start = System.currentTimeMillis(); LOG.info("Processing " + file); int cnt = 0; BufferedReader data = null; try { data = new BufferedReader(new InputStreamReader(new FileInputStream(file))); String line; while ((line = data.readLine()) != null) { try { String[] arr = line.split("\t"); long id = Long.parseLong(arr[0]); String username = (arr.length > 1) ? arr[1] : "a"; String url = getUrl(id, username); connections.incrementAndGet(); crawlURL(url, new TweetFetcherHandler(id, username, url, 0, !this.noFollow, line)); cnt++; if (cnt % TWEET_BLOCK_SIZE == 0) { LOG.info(cnt + " requests submitted"); } } catch (NumberFormatException e) { // parseLong continue; } } } catch (IOException e) { e.printStackTrace(); } finally { data.close(); } // Wait for the last requests to complete. LOG.info("Waiting for remaining requests (" + connections.get() + ") to finish!"); for (int i = 0; i < 10; i++) { if (connections.get() == 0) { break; } try { Thread.sleep(1000); } catch (Exception e) { e.printStackTrace(); } } asyncHttpClient.close(); long end = System.currentTimeMillis(); long duration = end - start; LOG.info("Total request submitted: " + cnt); LOG.info(crawl.size() + " tweets fetched in " + duration + "ms"); LOG.info("Writing tweets..."); int written = 0; OutputStreamWriter out = new OutputStreamWriter(new GZIPOutputStream( new FileOutputStream(output)), "UTF-8"); for (Map.Entry<Long, String> entry : crawl.entrySet()) { written++; out.write(entry.getValue() + "\n"); } out.close(); LOG.info(written + " statuses written."); if (this.repair != null) { LOG.info("Writing repair data file..."); written = 0; out = new OutputStreamWriter(new FileOutputStream(repair), "UTF-8"); for (Map.Entry<Long, String> entry : crawl_repair.entrySet()) { written++; out.write(entry.getValue() + "\n"); } out.close(); LOG.info(written + " statuses need repair."); } LOG.info("Done!"); } private class TweetFetcherHandler extends AsyncCompletionHandler<Response> { private final long id; private final String username; private final String url; private final int numRetries; private final boolean followRedirects; private final String line; private int httpStatus = -1; public TweetFetcherHandler(long id, String username, String url, int numRetries, boolean followRedirects, String line) { this.id = id; this.username = username; this.url = url; this.numRetries = numRetries; this.followRedirects = followRedirects; this.line = line; } public long getId() { return id; } public String getLine() { return line; } @Override public STATE onStatusReceived(HttpResponseStatus responseStatus) throws Exception { this.httpStatus = responseStatus.getStatusCode(); switch (this.httpStatus) { case 404: LOG.warn("Abandoning missing page: " + url); connections.decrementAndGet(); return STATE.ABORT; case 500: retry(); return STATE.ABORT; } return super.onStatusReceived(responseStatus); } @Override public STATE onHeadersReceived(HttpResponseHeaders headers) throws Exception { switch (this.httpStatus) { case 301: case 302: String redirect = headers.getHeaders().getFirstValue("Location"); if (redirect.contains("protected_redirect=true")) { LOG.warn("Abandoning protected account: " + url); connections.decrementAndGet(); } else if (redirect.contains("account/suspended")) { LOG.warn("Abandoning suspended account: " + url); connections.decrementAndGet(); } else if (redirect.contains("//status") || redirect.contains("login?redirect_after_login")) { LOG.warn("Abandoning deleted account: " + url); connections.decrementAndGet(); } else if (followRedirects) { crawlURL(redirect, new TweetFetcherHandler(id, username, redirect, numRetries, followRedirects, line)); } else { LOG.warn("Abandoning redirect: " + url); connections.decrementAndGet(); } return STATE.ABORT; } return super.onHeadersReceived(headers); } @Override public Response onCompleted(Response response) { switch (this.httpStatus) { case -1: case 301: case 302: case 404: case 500: return response; } // extract embedded JSON try { String json = response.getResponseBody("UTF-8"); JsonObject status = (JsonObject) JSON_PARSER.parse(json); if (!status.isJsonObject()) { LOG.warn("Unable to find embedded JSON: " + url); retry(); return response; } // save the requested id status.addProperty("requested_id", new Long(id)); crawl.put(id, GSON.toJson(status)); connections.decrementAndGet(); return response; } catch (IOException e) { LOG.warn("Error (" + e + "): " + url); retry(); return response; } catch (JsonSyntaxException e) { LOG.warn("Unable to parse embedded JSON: " + url); retry(); return response; } catch (NullPointerException e) { LOG.warn("Unexpected format for embedded JSON: " + url); retry(); return response; } } @Override public void onThrowable(Throwable t) { retry(); } private void retry() { if (this.numRetries >= MAX_RETRY_ATTEMPTS) { LOG.warn("Abandoning after max retry attempts: " + url); crawl_repair.put(id, line); connections.decrementAndGet(); return; } timer.schedule(new RetryTask(id, username, url, numRetries + 1, followRedirects), WAIT_BEFORE_RETRY); } private class RetryTask extends TimerTask { private final long id; private final String username; private final String url; private final int numRetries; private final boolean followRedirects; public RetryTask(long id, String username, String url, int numRetries, boolean followRedirects) { this.id = id; this.username = username; this.url = url; this.numRetries = numRetries; this.followRedirects = followRedirects; } public void run() { crawlURL(url, new TweetFetcherHandler(id, username, url, numRetries, followRedirects, line)); } } } private void crawlURL(String url, TweetFetcherHandler handler) { try { asyncHttpClient.prepareGet(url).addHeader("Accept-Charset", "utf-8") .addHeader("Accept-Language", "en-US").execute(handler); } catch (IOException e) { LOG.warn("Abandoning due to error (" + e + "): " + url); crawl_repair.put(handler.getId(), handler.getLine()); connections.decrementAndGet(); } } private static final String DATA_OPTION = "data"; private static final String OUTPUT_OPTION = "output"; private static final String REPAIR_OPTION = "repair"; private static final String NOFOLLOW_OPTION = "noFollow"; @SuppressWarnings("static-access") public static void main(String[] args) throws Exception { Options options = new Options(); options.addOption(OptionBuilder.withArgName("path").hasArg() .withDescription("data file with tweet ids").create(DATA_OPTION)); options.addOption(OptionBuilder.withArgName("path").hasArg() .withDescription("output file (*.gz)").create(OUTPUT_OPTION)); options.addOption(OptionBuilder.withArgName("path").hasArg() .withDescription("output repair file (can be used later as a data file)") .create(REPAIR_OPTION)); options.addOption(NOFOLLOW_OPTION, NOFOLLOW_OPTION, false, "don't follow 301 redirects"); CommandLine cmdline = null; CommandLineParser parser = new GnuParser(); try { cmdline = parser.parse(options, args); } catch (ParseException exp) { System.err.println("Error parsing command line: " + exp.getMessage()); System.exit(-1); } if (!cmdline.hasOption(DATA_OPTION) || !cmdline.hasOption(OUTPUT_OPTION)) { HelpFormatter formatter = new HelpFormatter(); formatter.printHelp(AsyncEmbeddedJsonStatusBlockCrawler.class.getName(), options); System.exit(-1); } String data = cmdline.getOptionValue(DATA_OPTION); String output = cmdline.getOptionValue(OUTPUT_OPTION); String repair = cmdline.getOptionValue(REPAIR_OPTION); boolean noFollow = cmdline.hasOption(NOFOLLOW_OPTION); new AsyncEmbeddedJsonStatusBlockCrawler(new File(data), output, repair, noFollow).fetch(); } }
src/main/java/cc/twittertools/download/AsyncEmbeddedJsonStatusBlockCrawler.java
package cc.twittertools.download; import java.io.BufferedReader; import java.io.File; import java.io.FileInputStream; import java.io.FileOutputStream; import java.io.IOException; import java.io.InputStreamReader; import java.io.OutputStreamWriter; import java.util.Map; import java.util.Timer; import java.util.TimerTask; import java.util.concurrent.ConcurrentSkipListMap; import java.util.concurrent.atomic.AtomicInteger; import java.util.zip.GZIPOutputStream; import org.apache.commons.cli.CommandLine; import org.apache.commons.cli.CommandLineParser; import org.apache.commons.cli.GnuParser; import org.apache.commons.cli.HelpFormatter; import org.apache.commons.cli.OptionBuilder; import org.apache.commons.cli.Options; import org.apache.commons.cli.ParseException; import org.apache.commons.lang.StringEscapeUtils; import org.apache.log4j.Logger; import com.google.common.base.Preconditions; import com.google.gson.Gson; import com.google.gson.JsonObject; import com.google.gson.JsonParser; import com.google.gson.JsonSyntaxException; import com.ning.http.client.AsyncCompletionHandler; import com.ning.http.client.AsyncHttpClient; import com.ning.http.client.AsyncHttpClientConfig; import com.ning.http.client.HttpResponseHeaders; import com.ning.http.client.HttpResponseStatus; import com.ning.http.client.Response; import com.ning.http.client.extra.ThrottleRequestFilter; public class AsyncEmbeddedJsonStatusBlockCrawler { private static final Logger LOG = Logger.getLogger(AsyncEmbeddedJsonStatusBlockCrawler.class); public static final String JSON_START = "<input type=\"hidden\" id=\"init-data\" class=\"json-data\" value=\""; public static final String JSON_END = "\">"; private static final int TWEET_BLOCK_SIZE = 500; private static final int MAX_CONNECTIONS = 100; private static final int CONNECTION_TIMEOUT = 10000; private static final int IDLE_CONNECTION_TIMEOUT = 10000; private static final int REQUEST_TIMEOUT = 10000; private static final int MAX_RETRY_ATTEMPTS = 2; private static final int WAIT_BEFORE_RETRY = 1000; private static final Timer timer = new Timer(true); private static final JsonParser JSON_PARSER = new JsonParser(); private static final Gson GSON = new Gson(); private final File file; private final File output; private final File repair; private final AsyncHttpClient asyncHttpClient; private final boolean noFollow; // key = statud id, value = tweet JSON private final ConcurrentSkipListMap<Long, String> crawl = new ConcurrentSkipListMap<Long, String>(); // key = statud id, value = data line private final ConcurrentSkipListMap<Long, String> crawl_repair = new ConcurrentSkipListMap<Long, String>(); private final AtomicInteger connections = new AtomicInteger(0); public AsyncEmbeddedJsonStatusBlockCrawler(File file, String output, String repair, boolean noFollow) throws IOException { this.file = Preconditions.checkNotNull(file); this.noFollow = noFollow; if (!file.exists()) { throw new IOException(file + " does not exist!"); } // check existence of output's parent directory this.output = new File(Preconditions.checkNotNull(output)); File parent = this.output.getParentFile(); if (parent != null && !parent.exists()) { throw new IOException(output + "'s parent directory does not exist!"); } // check existence of repair's parent directory (or set to null if no // repair file specified) if (repair != null) { this.repair = new File(repair); parent = this.repair.getParentFile(); if (parent != null && !parent.exists()) { throw new IOException(repair + "'s parent directory does not exist!"); } } else { this.repair = null; } AsyncHttpClientConfig config = new AsyncHttpClientConfig.Builder() .addRequestFilter(new ThrottleRequestFilter(MAX_CONNECTIONS)) .setConnectionTimeoutInMs(CONNECTION_TIMEOUT) .setIdleConnectionInPoolTimeoutInMs(IDLE_CONNECTION_TIMEOUT) .setRequestTimeoutInMs(REQUEST_TIMEOUT).setMaxRequestRetry(0).build(); this.asyncHttpClient = new AsyncHttpClient(config); } public static String getUrl(long id, String username) { Preconditions.checkNotNull(username); return String.format("http://api.twitter.com/1/statuses/oembed.json?id=%d&&omit_script=true", id); } public void fetch() throws IOException { long start = System.currentTimeMillis(); LOG.info("Processing " + file); int cnt = 0; BufferedReader data = null; try { data = new BufferedReader(new InputStreamReader(new FileInputStream(file))); String line; while ((line = data.readLine()) != null) { try { String[] arr = line.split("\t"); long id = Long.parseLong(arr[0]); String username = (arr.length > 1) ? arr[1] : "a"; String url = getUrl(id, username); connections.incrementAndGet(); crawlURL(url, new TweetFetcherHandler(id, username, url, 0, !this.noFollow, line)); cnt++; if (cnt % TWEET_BLOCK_SIZE == 0) { LOG.info(cnt + " requests submitted"); } } catch (NumberFormatException e) { // parseLong continue; } } } catch (IOException e) { e.printStackTrace(); } finally { data.close(); } // Wait for the last requests to complete. LOG.info("Waiting for remaining requests (" + connections.get() + ") to finish!"); for (int i = 0; i < 10; i++) { if (connections.get() == 0) { break; } try { Thread.sleep(1000); } catch (Exception e) { e.printStackTrace(); } } asyncHttpClient.close(); long end = System.currentTimeMillis(); long duration = end - start; LOG.info("Total request submitted: " + cnt); LOG.info(crawl.size() + " tweets fetched in " + duration + "ms"); LOG.info("Writing tweets..."); int written = 0; OutputStreamWriter out = new OutputStreamWriter(new GZIPOutputStream( new FileOutputStream(output)), "UTF-8"); for (Map.Entry<Long, String> entry : crawl.entrySet()) { written++; out.write(entry.getValue() + "\n"); } out.close(); LOG.info(written + " statuses written."); if (this.repair != null) { LOG.info("Writing repair data file..."); written = 0; out = new OutputStreamWriter(new FileOutputStream(repair), "UTF-8"); for (Map.Entry<Long, String> entry : crawl_repair.entrySet()) { written++; out.write(entry.getValue() + "\n"); } out.close(); LOG.info(written + " statuses need repair."); } LOG.info("Done!"); } private class TweetFetcherHandler extends AsyncCompletionHandler<Response> { private final long id; private final String username; private final String url; private final int numRetries; private final boolean followRedirects; private final String line; private int httpStatus = -1; public TweetFetcherHandler(long id, String username, String url, int numRetries, boolean followRedirects, String line) { this.id = id; this.username = username; this.url = url; this.numRetries = numRetries; this.followRedirects = followRedirects; this.line = line; } public long getId() { return id; } public String getLine() { return line; } @Override public STATE onStatusReceived(HttpResponseStatus responseStatus) throws Exception { this.httpStatus = responseStatus.getStatusCode(); switch (this.httpStatus) { case 404: LOG.warn("Abandoning missing page: " + url); connections.decrementAndGet(); return STATE.ABORT; case 500: retry(); return STATE.ABORT; } return super.onStatusReceived(responseStatus); } @Override public STATE onHeadersReceived(HttpResponseHeaders headers) throws Exception { switch (this.httpStatus) { case 301: case 302: String redirect = headers.getHeaders().getFirstValue("Location"); if (redirect.contains("protected_redirect=true")) { LOG.warn("Abandoning protected account: " + url); connections.decrementAndGet(); } else if (redirect.contains("account/suspended")) { LOG.warn("Abandoning suspended account: " + url); connections.decrementAndGet(); } else if (redirect.contains("//status") || redirect.contains("login?redirect_after_login")) { LOG.warn("Abandoning deleted account: " + url); connections.decrementAndGet(); } else if (followRedirects) { crawlURL(redirect, new TweetFetcherHandler(id, username, redirect, numRetries, followRedirects, line)); } else { LOG.warn("Abandoning redirect: " + url); connections.decrementAndGet(); } return STATE.ABORT; } return super.onHeadersReceived(headers); } @Override public Response onCompleted(Response response) { switch (this.httpStatus) { case -1: case 301: case 302: case 404: case 500: return response; } // extract embedded JSON try { String html = response.getResponseBody("UTF-8"); int jsonStart = html.indexOf(JSON_START); int jsonEnd = html.indexOf(JSON_END, jsonStart + JSON_START.length()); if (jsonStart < 0 || jsonEnd < 0) { LOG.warn("Unable to find embedded JSON: " + url); retry(); return response; } String json = html.substring(jsonStart + JSON_START.length(), jsonEnd); json = StringEscapeUtils.unescapeHtml(json); JsonObject page = (JsonObject) JSON_PARSER.parse(json); JsonObject status = page.getAsJsonObject("embedData").getAsJsonObject("status"); // save the requested id status.addProperty("requested_id", new Long(id)); crawl.put(id, GSON.toJson(status)); connections.decrementAndGet(); return response; } catch (IOException e) { LOG.warn("Error (" + e + "): " + url); retry(); return response; } catch (JsonSyntaxException e) { LOG.warn("Unable to parse embedded JSON: " + url); retry(); return response; } catch (NullPointerException e) { LOG.warn("Unexpected format for embedded JSON: " + url); retry(); return response; } } @Override public void onThrowable(Throwable t) { retry(); } private void retry() { if (this.numRetries >= MAX_RETRY_ATTEMPTS) { LOG.warn("Abandoning after max retry attempts: " + url); crawl_repair.put(id, line); connections.decrementAndGet(); return; } timer.schedule(new RetryTask(id, username, url, numRetries + 1, followRedirects), WAIT_BEFORE_RETRY); } private class RetryTask extends TimerTask { private final long id; private final String username; private final String url; private final int numRetries; private final boolean followRedirects; public RetryTask(long id, String username, String url, int numRetries, boolean followRedirects) { this.id = id; this.username = username; this.url = url; this.numRetries = numRetries; this.followRedirects = followRedirects; } public void run() { crawlURL(url, new TweetFetcherHandler(id, username, url, numRetries, followRedirects, line)); } } } private void crawlURL(String url, TweetFetcherHandler handler) { try { asyncHttpClient.prepareGet(url).addHeader("Accept-Charset", "utf-8") .addHeader("Accept-Language", "en-US").execute(handler); } catch (IOException e) { LOG.warn("Abandoning due to error (" + e + "): " + url); crawl_repair.put(handler.getId(), handler.getLine()); connections.decrementAndGet(); } } private static final String DATA_OPTION = "data"; private static final String OUTPUT_OPTION = "output"; private static final String REPAIR_OPTION = "repair"; private static final String NOFOLLOW_OPTION = "noFollow"; @SuppressWarnings("static-access") public static void main(String[] args) throws Exception { Options options = new Options(); options.addOption(OptionBuilder.withArgName("path").hasArg() .withDescription("data file with tweet ids").create(DATA_OPTION)); options.addOption(OptionBuilder.withArgName("path").hasArg() .withDescription("output file (*.gz)").create(OUTPUT_OPTION)); options.addOption(OptionBuilder.withArgName("path").hasArg() .withDescription("output repair file (can be used later as a data file)") .create(REPAIR_OPTION)); options.addOption(NOFOLLOW_OPTION, NOFOLLOW_OPTION, false, "don't follow 301 redirects"); CommandLine cmdline = null; CommandLineParser parser = new GnuParser(); try { cmdline = parser.parse(options, args); } catch (ParseException exp) { System.err.println("Error parsing command line: " + exp.getMessage()); System.exit(-1); } if (!cmdline.hasOption(DATA_OPTION) || !cmdline.hasOption(OUTPUT_OPTION)) { HelpFormatter formatter = new HelpFormatter(); formatter.printHelp(AsyncEmbeddedJsonStatusBlockCrawler.class.getName(), options); System.exit(-1); } String data = cmdline.getOptionValue(DATA_OPTION); String output = cmdline.getOptionValue(OUTPUT_OPTION); String repair = cmdline.getOptionValue(REPAIR_OPTION); boolean noFollow = cmdline.hasOption(NOFOLLOW_OPTION); new AsyncEmbeddedJsonStatusBlockCrawler(new File(data), output, repair, noFollow).fetch(); } }
Update code to use new api
src/main/java/cc/twittertools/download/AsyncEmbeddedJsonStatusBlockCrawler.java
Update code to use new api
<ide><path>rc/main/java/cc/twittertools/download/AsyncEmbeddedJsonStatusBlockCrawler.java <ide> import org.apache.commons.cli.ParseException; <ide> import org.apache.commons.lang.StringEscapeUtils; <ide> import org.apache.log4j.Logger; <add> <add>import cc.twittertools.corpus.data.Status; <ide> <ide> import com.google.common.base.Preconditions; <ide> import com.google.gson.Gson; <ide> <ide> // extract embedded JSON <ide> try { <del> String html = response.getResponseBody("UTF-8"); <del> int jsonStart = html.indexOf(JSON_START); <del> int jsonEnd = html.indexOf(JSON_END, jsonStart + JSON_START.length()); <del> <del> if (jsonStart < 0 || jsonEnd < 0) { <add> String json = response.getResponseBody("UTF-8"); <add> <add> JsonObject status = (JsonObject) JSON_PARSER.parse(json); <add> <add> if (!status.isJsonObject()) { <ide> LOG.warn("Unable to find embedded JSON: " + url); <ide> retry(); <ide> return response; <ide> } <del> <del> String json = html.substring(jsonStart + JSON_START.length(), jsonEnd); <del> json = StringEscapeUtils.unescapeHtml(json); <del> JsonObject page = (JsonObject) JSON_PARSER.parse(json); <del> <del> JsonObject status = page.getAsJsonObject("embedData").getAsJsonObject("status"); <del> <ide> // save the requested id <ide> status.addProperty("requested_id", new Long(id)); <ide>
JavaScript
mit
15ec7a0161b2c7070187bb904193de0ea2061199
0
dtulibrary/ddf,dtulibrary/ddf,dtulibrary/ddf
dataset = [ {"value":"dja","hits":367796,"label":"Journal article"}, {"value":"dba","hits":88849,"label":"Book chapter"}, {"value":"dcp","hits":85135,"label":"Conference paper"}, {"value":"dca","hits":49126,"label":"Conference abstract"}, {"value":"db","hits":37094,"label":"Book"}, {"value":"dr","hits":33567,"label":"Report"}, {"value":"dna","hits":20720,"label":"Newspaper article"}, {"value":"dco","hits":20005,"label":"Conference poster"}, {"value":"do","hits":17755,"label":"Other"}, {"value":"dtp","hits":16809,"label":"Thesis PhD"}, {"value":"dw","hits":12919,"label":"Working paper"}, {"value":"djb","hits":10198,"label":"Journal book review"}, {"value":"dra","hits":9340,"label":"Report chapter"}, {"value":"dbp","hits":8311,"label":"Book preface"}, {"value":"djr","hits":5978,"label":"Journal review article"}, {"value":"dln","hits":2586,"label":"Lecture notes"}, {"value":"djc","hits":2462,"label":"Journal comment"}, {"value":"dp","hits":1487,"label":"Patent"}, {"value":"dtd","hits":748,"label":"Thesis Doctoral"}, {"value":"dd","hits":719,"label":"Data set"}, {"value":"dso","hits":173,"label":"Software"} ]; function draw(dataset) { var width = 720; var height = 720; var radius = Math.min(width, height) / 2; var donutWidth = 75; var legendRectSize = 18; var legendSpacing = 6.5; var color = d3.scale.category20c(); var svg = d3.select('#chart') .append('svg') .attr('width', width) .attr('height', height) .append('g') .attr('transform', 'translate(' + (width / 2) +',' + (height / 2) + ')'); var arc = d3.svg.arc() .innerRadius(radius - donutWidth) .outerRadius(radius); var pie = d3.layout.pie() .value(function(d) { return d.hits; }) .sort(null); var tooltip = d3.select('#chart') .append('div') .attr('class', 'tooltip'); tooltip.append('div') .attr('class', 'label'); tooltip.append('div') .attr('class', 'hits'); tooltip.append('div') .attr('class', 'percent'); // The rest of the code below is wrapped inside this callback: // d3.csv('weekdays.csv', function(error, dataset) { // dataset.forEach(function(d) { // d.count = +d.count; // }); // HERE. // }); // INSIDE CALLBACK START var path = svg.selectAll('path') .data(pie(dataset)) .enter() .append('path') .attr('d', arc) .attr('fill', function(d, i) { return color(d.data.label); }); path.on('mouseover', function(d) { var total = d3.sum(dataset.map(function(d) { return d.hits; // alert(d.hits); doesn't get triggered })); var percent = Math.round(1000 * d.data.hits / total) / 10; tooltip.select('.label').html(d.data.label); tooltip.select('.hits').html(d.data.hits); tooltip.select('.percent').html(percent + '%'); tooltip.style('display', 'block'); }); path.on('mouseout', function() { tooltip.style('display', 'none'); }); // OPTIONAL // path.on('mousemove', function(d) { // tooltip.style('top', (d3.event.pageY + 10) + 'px') // .style('left', (d3.event.pageX + 10) + 'px'); // }); var legend = svg.selectAll('.legend') .data(color.domain()) .enter() .append('g') .attr('class', 'legend') .attr('transform', function(d, i) { var height = legendRectSize + legendSpacing; var offset = height * color.domain().length / 2; var horz = -2 * legendRectSize; var vert = i * height - offset; return 'translate(' + horz + ',' + vert + ')'; }); legend.append('rect') .attr('width', legendRectSize) .attr('height', legendRectSize) .style('fill', color) .style('stroke', color); legend.append('text') .attr('x', legendRectSize + legendSpacing) .attr('y', 15) .text(function(d) { return d; }); // INSIDE CALLBACK END } $(document).ready(function() { draw(dataset); });
app/assets/javascripts/visualizations.js
dataset = [ {"value":"dja","hits":367796,"label":"Journal article"}, {"value":"dba","hits":88849,"label":"Book chapter"}, {"value":"dcp","hits":85135,"label":"Conference paper"}, {"value":"dca","hits":49126,"label":"Conference abstract"}, {"value":"db","hits":37094,"label":"Book"}, {"value":"dr","hits":33567,"label":"Report"}, {"value":"dna","hits":20720,"label":"Newspaper article"}, {"value":"dco","hits":20005,"label":"Conference poster"}, {"value":"do","hits":17755,"label":"Other"}, {"value":"dtp","hits":16809,"label":"Thesis PhD"}, {"value":"dw","hits":12919,"label":"Working paper"}, {"value":"djb","hits":10198,"label":"Journal book review"}, {"value":"dra","hits":9340,"label":"Report chapter"}, {"value":"dbp","hits":8311,"label":"Book preface"}, {"value":"djr","hits":5978,"label":"Journal review article"}, {"value":"dln","hits":2586,"label":"Lecture notes"}, {"value":"djc","hits":2462,"label":"Journal comment"}, {"value":"dp","hits":1487,"label":"Patent"}, {"value":"dtd","hits":748,"label":"Thesis Doctoral"}, {"value":"dd","hits":719,"label":"Data set"}, {"value":"dso","hits":173,"label":"Software"} ]; function draw(dataset) { var width = 720; var height = 720; var radius = Math.min(width, height) / 2; var donutWidth = 75; var legendRectSize = 18; var legendSpacing = 6.5; var color = d3.scale.category20c(); var svg = d3.select('#chart') .append('svg') .attr('width', width) .attr('height', height) .append('g') .attr('transform', 'translate(' + (width / 2) +',' + (height / 2) + ')'); var arc = d3.svg.arc() .innerRadius(radius - donutWidth) .outerRadius(radius); var pie = d3.layout.pie() .value(function(d) { return d.hits; }) .sort(null); var tooltip = d3.select('#chart') .append('div') .attr('class', 'tooltip'); tooltip.append('div') .attr('class', 'label'); tooltip.append('div') .attr('class', 'hits'); tooltip.append('div') .attr('class', 'percent'); // The rest of the code below is wrapped inside this callback: // d3.csv('weekdays.csv', function(error, dataset) { // dataset.forEach(function(d) { // d.count = +d.count; // }); // HERE. // }); // INSIDE CALLBACK START var path = svg.selectAll('path') .data(pie(dataset)) .enter() .append('path') .attr('d', arc) .attr('fill', function(d, i) { return color(d.data.label); }); path.on('mouseover', function(d) { var total = d3.sum(dataset.map(function(d) { return d.hits; // alert(d.hits); doesn't get triggered })); var percent = Math.round(1000 * d.data.hits / total) / 10; tooltip.select('.label').html(d.data.label); tooltip.select('.hits').html(d.data.hits); tooltip.select('.percent').html(percent + '%'); tooltip.style('display', 'block'); }); path.on('mouseout', function() { tooltip.style('display', 'none'); }); // OPTIONAL // path.on('mousemove', function(d) { // tooltip.style('top', (d3.event.pageY + 10) + 'px') // .style('left', (d3.event.pageX + 10) + 'px'); // }); var legend = svg.selectAll('.legend') .data(color.domain()) .enter() .append('g') .attr('class', 'legend') .attr('transform', function(d, i) { var height = legendRectSize + legendSpacing; var offset = height * color.domain().length / 2; var horz = -2 * legendRectSize; var vert = i * height - offset; return 'translate(' + horz + ',' + vert + ')'; }); legend.append('rect') .attr('width', legendRectSize) .attr('height', legendRectSize) .style('fill', color) .style('stroke', color); legend.append('text') .attr('x', legendRectSize + legendSpacing) .attr('y', 15) .text(function(d) { return d; }); // INSIDE CALLBACK END } //$(document).ready(function() { draw(dataset); });
asset compilation test
app/assets/javascripts/visualizations.js
asset compilation test
<ide><path>pp/assets/javascripts/visualizations.js <ide> // INSIDE CALLBACK END <ide> } <ide> <del>//$(document).ready(function() { draw(dataset); }); <add>$(document).ready(function() { draw(dataset); }); <ide>
JavaScript
mit
7550cba7fd4f4159f9ce3da3e8d2e5d031e5f40f
0
nuintun/gulp-cmd
/** * Created by nuintun on 2015/4/27. */ 'use strict'; var is = require('is'); var path = require('path'); var join = path.join; var extname = path.extname; var dirname = path.dirname; var basename = path.basename; var relative = path.relative; var util = require('util'); var colors = require('colors/safe'); var debug = require('debug')('gulp-cmd'); // variable declaration var cwd = process.cwd(); var OUTBOUNDRE = /(?:^[\\\/]?)\.\.(?:[\\\/]|$)/; var PATHSRE = /^([^/:]+)(\/.+)$/; var VARSRE = /{([^{]+)}/g; // set debug color use 6 debug.color = 6; /** * parse package form vinyl * @param vinyl * @param wwwroot * @returns {object} */ function parsePackage(vinyl, wwwroot){ var relative = vinyl.relative; // vinyl not in base dir, user wwwroot if (OUTBOUNDRE.test(relative)) { relative = path.relative(wwwroot, vinyl.path); // vinyl not in wwwroot, throw error if (OUTBOUNDRE.test(relative)) { throwError('file: %s is out of bound of wwwroot: %s.', normalize(vinyl.path), normalize(wwwroot)); } // reset relative relative = path.join('/', relative); } var dir = normalize(dirname(relative)); var filename = basename(relative); var SPLITRE = /\/((?:\d+\.){2}\d+)(?:\/|$)/; var match = dir.split(SPLITRE); return { name: match[0] || '', version: match[1] || '', file: match[2] ? match[2] + '/' + filename : filename } } /** * simple template * @param format * @param data * @returns {string} * ``` * var tpl = '{{name}}/{{version}}'; * util.template(tpl, {name:'base', version: '1.0.0'}); * ``` */ function template(format, data){ if (!is.string(format)) return ''; return format.replace(/{{([a-z]*)}}/gi, function (all, match){ return data[match] || ''; }); } /** * create a plugin * @param name * @param transport * @returns {Function} */ function plugin(name, transport){ return function (vinyl, options){ // debug debug('load plugin: %s', colors.green(name)); // debug debug('read file: %s', colors.magenta(pathFromCwd(vinyl.path))); vinyl = transport(vinyl, options); // normalize package if (!vinyl.package) { vinyl.package = {}; } return vinyl; }; } /** * parse alias * @param id * @param alias * @returns {String} */ function parseAlias(id, alias){ alias = alias || {}; return alias && is.string(alias[id]) ? alias[id] : id; } /** * parse paths * @param id * @param paths * @returns {String} */ function parsePaths(id, paths){ var match; paths = paths || {}; if (paths && (match = id.match(PATHSRE)) && is.string(paths[match[1]])) { id = paths[match[1]] + match[2]; } return id; } /** * parse vars * @param id * @param vars * @returns {String} */ function parseVars(id, vars){ vars = vars || {}; if (vars && id.indexOf('{') !== -1) { id = id.replace(VARSRE, function (match, key){ return is.string(vars[key]) ? vars[key] : match; }); } return id; } /** * parse map * @param id * @param map * @returns {String} */ function parseMap(id, map){ var ret = id; if (Array.isArray(map)) { for (var i = 0, len = map.length; i < len; i++) { var rule = map[i]; // parse map if (is.fn(rule)) { ret = rule(id); } else if (Array.isArray(rule)) { ret = id.replace(rule[0], rule[1]); } // must be string if (!ret || !is.string(ret)) { ret = id; } // only apply the first matched rule if (ret !== id) break; } } return ret; } /** * normalize path * @param path * @returns {string} */ function normalize(path){ path = path.replace(/\\+/g, '/'); path = path.replace(/([^:/])\/+\//g, '$1/'); path = path.replace(/(:)?\/{2,}/, '$1//'); return path; } /** * resolve a `relative` path base on `base` path * @param relative * @param vinyl * @param wwwroot * @returns {string} */ function resolve(relative, vinyl, wwwroot){ var base; var absolute; // debug debug('resolve path: %s', colors.magenta(normalize(relative))); // resolve if (isRelative(relative)) { base = dirname(vinyl.path); absolute = join(base, relative); // out of base, use wwwroot if (isOutBound(absolute, wwwroot)) { throwError('file: %s is out of bound of wwwroot: %s.', normalize(absolute), normalize(wwwroot)); } } else if (isAbsolute(relative)) { base = wwwroot; absolute = join(base, relative.substring(1)); } else { base = join(vinyl.cwd, vinyl.base); absolute = join(base, relative); } // debug debug('of base path: %s', colors.magenta(pathFromCwd(base))); debug('to: %s', colors.magenta(pathFromCwd(absolute))); return absolute; } /** * add .js if not exists * @param path * @returns {*} */ function addExt(path){ return extname(path) === '.js' ? path : (path + '.js'); } /** * hide .js if exists * @param path * @returns {*} */ function hideExt(path){ return extname(path) === '.js' ? path.replace(/\.js$/, '') : path; } /** * test path is relative path or not * @param path * @returns {boolean} */ function isRelative(path){ return /^\.{1,2}[\\/]/.test(path); } /** * test path is absolute path or not * @param path * @returns {boolean} */ function isAbsolute(path){ return /^[\\/](?:[^\\/]|$)/.test(path); } /** * test path is local path or not * @param path * @returns {boolean} */ function isLocal(path){ return !/^\w*?:\/\/|^\/\//.test(path) && !/^data:\w+?\/\w+?[,;]/i.test(path); } /** * test path is out of bound of base * @param path * @param base * @returns {boolean} */ function isOutBound(path, base){ return OUTBOUNDRE.test(relative(base, path)); } /** * Get relative path from cwd * @param path * @returns {string} */ function pathFromCwd(path){ return normalize(relative(cwd, path)) || './'; } /** * plugin error */ function throwError(){ var slice = [].slice; var message = util.format .apply(null, slice.call(arguments)); throw new Error(message); } /** * node extend * Copyright 2011, John Resig * Dual licensed under the MIT or GPL Version 2 licenses. * http://jquery.org/license * * @fileoverview * Port of jQuery.extend that actually works on node.js */ function extend(){ var target = arguments[0] || {}; var i = 1; var length = arguments.length; var deep = false; var options, name, src, copy, copyIsArray, clone; // handle a deep copy situation if (is.bool(target)) { deep = target; target = arguments[1] || {}; // skip the boolean and the target i = 2; } // handle case when target is a string or something (possible in deep copy) if ((typeof target !== 'object' && !is.fn(target)) || target === null) { target = {}; } for (; i < length; i++) { // only deal with non-null/undefined values options = arguments[i]; if (options !== null) { // extend the base object for (name in options) { if (options.hasOwnProperty(name)) { src = target[name]; copy = options[name]; // prevent never-ending loop if (target === copy) { continue; } // recurse if we're merging plain objects or arrays if (deep && copy && (is.hash(copy) || (copyIsArray = Array.isArray(copy)))) { if (copyIsArray) { copyIsArray = false; clone = src && Array.isArray(src) ? src : []; } else { clone = src && is.hash(src) ? src : {}; } // never move original objects, clone them target[name] = extend(deep, clone, copy); // don't bring in undefined values } else if (typeof copy !== 'undefined') { target[name] = copy; } } } } } // return the modified object return target; } /** * wrap module * @param id * @param deps * @param code * @returns {string} */ function wrapModule(id, deps, code){ // header and footer template string var headerTpl = 'define({{id}}, {{deps}}, function(require, exports, module){'; var footerTpl = '});\n'; if (Buffer.isBuffer(code)) code = code.toString(); // debug debug('compile module: %s', colors.magenta(id)); id = JSON.stringify(id); deps = JSON.stringify(deps); return template(headerTpl, { id: id, deps: deps }) + '\n' + code + '\n' + footerTpl; } /** * print message */ function print(){ var slice = [].slice; var message = util.format .apply(null, slice.call(arguments)); process.stdout.write(colors.cyan.bold(' gulp-cmd ') + message + '\n'); } /** * exports module. */ module.exports.cwd = cwd; module.exports.colors = colors; module.exports.debug = debug; module.exports.parsePackage = parsePackage; module.exports.template = template; module.exports.plugin = plugin; module.exports.parseAlias = parseAlias; module.exports.parsePaths = parsePaths; module.exports.parseVars = parseVars; module.exports.parseMap = parseMap; module.exports.normalize = normalize; module.exports.resolve = resolve; module.exports.addExt = addExt; module.exports.hideExt = hideExt; module.exports.isRelative = isRelative; module.exports.isAbsolute = isAbsolute; module.exports.isLocal = isLocal; module.exports.isOutBound = isOutBound; module.exports.pathFromCwd = pathFromCwd; module.exports.throwError = throwError; module.exports.extend = extend; module.exports.wrapModule = wrapModule; module.exports.print = print;
lib/util.js
/** * Created by nuintun on 2015/4/27. */ 'use strict'; var is = require('is'); var path = require('path'); var join = path.join; var extname = path.extname; var dirname = path.dirname; var basename = path.basename; var relative = path.relative; var util = require('util'); var colors = require('colors/safe'); var debug = require('debug')('gulp-cmd'); // variable declaration var cwd = process.cwd(); var OUTBOUNDRE = /(?:^[\\\/]?)\.\.(?:[\\\/]|$)/; var PATHSRE = /^([^/:]+)(\/.+)$/; var VARSRE = /{([^{]+)}/g; // set debug color use 6 debug.color = 6; /** * parse package form vinyl * @param vinyl * @param wwwroot * @returns {object} */ function parsePackage(vinyl, wwwroot){ var relative = vinyl.relative; // vinyl not in base dir, user wwwroot if (OUTBOUNDRE.test(relative)) { relative = path.relative(wwwroot, vinyl.path); // vinyl not in wwwroot, throw error if (OUTBOUNDRE.test(relative)) { throwError('file: %s is out of bound of wwwroot: %s.', normalize(vinyl.path), normalize(wwwroot)); } // reset relative relative = path.join('/', relative); } var dir = normalize(dirname(relative)); var filename = basename(relative); var SPLITRE = /\/((?:\d+\.){2}\d+)(?:\/|$)/; var match = dir.split(SPLITRE); return { name: match[0] || '', version: match[1] || '', file: match[2] ? match[2] + '/' + filename : filename } } /** * simple template * @param format * @param data * @returns {string} * ``` * var tpl = '{{name}}/{{version}}'; * util.template(tpl, {name:'base', version: '1.0.0'}); * ``` */ function template(format, data){ if (!is.string(format)) return ''; return format.replace(/{{([a-z]*)}}/gi, function (all, match){ return data[match] || ''; }); } /** * create a plugin * @param name * @param transport * @returns {Function} */ function plugin(name, transport){ return function (vinyl, options){ // debug debug('load plugin: %s', colors.green(name)); // debug debug('read file: %s', colors.magenta(pathFromCwd(vinyl.path))); vinyl = transport(vinyl, options); // normalize package if (!vinyl.package) { vinyl.package = {}; } return vinyl; }; } /** * parse alias * @param id * @param alias * @returns {String} */ function parseAlias(id, alias){ alias = alias || {}; return alias && is.string(alias[id]) ? alias[id] : id; } /** * parse paths * @param id * @param paths * @returns {String} */ function parsePaths(id, paths){ var match; paths = paths || {}; if (paths && (match = id.match(PATHSRE)) && is.string(paths[match[1]])) { id = paths[match[1]] + match[2]; } return id; } /** * parse vars * @param id * @param vars * @returns {String} */ function parseVars(id, vars){ vars = vars || {}; if (vars && id.indexOf('{') > -1) { id = id.replace(VARSRE, function (match, key){ return is.string(vars[key]) ? vars[key] : match; }); } return id; } /** * parse map * @param id * @param map * @returns {String} */ function parseMap(id, map){ var ret = id; if (Array.isArray(map)) { for (var i = 0, len = map.length; i < len; i++) { var rule = map[i]; // parse map if (is.fn(rule)) { ret = rule(id); } else if (Array.isArray(rule)) { ret = id.replace(rule[0], rule[1]); } // must be string if (!ret || !is.string(ret)) { ret = id; } // only apply the first matched rule if (ret !== id) break; } } return ret; } /** * normalize path * @param path * @returns {string} */ function normalize(path){ path = path.replace(/\\+/g, '/'); path = path.replace(/([^:/])\/+\//g, '$1/'); path = path.replace(/(:)?\/{2,}/, '$1//'); return path; } /** * resolve a `relative` path base on `base` path * @param relative * @param vinyl * @param wwwroot * @returns {string} */ function resolve(relative, vinyl, wwwroot){ var base; var absolute; // debug debug('resolve path: %s', colors.magenta(normalize(relative))); // resolve if (isRelative(relative)) { base = dirname(vinyl.path); absolute = join(base, relative); // out of base, use wwwroot if (isOutBound(absolute, wwwroot)) { throwError('file: %s is out of bound of wwwroot: %s.', normalize(absolute), normalize(wwwroot)); } } else if (isAbsolute(relative)) { base = wwwroot; absolute = join(base, relative.substring(1)); } else { base = join(vinyl.cwd, vinyl.base); absolute = join(base, relative); } // debug debug('of base path: %s', colors.magenta(pathFromCwd(base))); debug('to: %s', colors.magenta(pathFromCwd(absolute))); return absolute; } /** * add .js if not exists * @param path * @returns {*} */ function addExt(path){ return extname(path) === '.js' ? path : (path + '.js'); } /** * hide .js if exists * @param path * @returns {*} */ function hideExt(path){ return extname(path) === '.js' ? path.replace(/\.js$/, '') : path; } /** * test path is relative path or not * @param path * @returns {boolean} */ function isRelative(path){ return /^\.{1,2}[\\/]/.test(path); } /** * test path is absolute path or not * @param path * @returns {boolean} */ function isAbsolute(path){ return /^[\\/](?:[^\\/]|$)/.test(path); } /** * test path is local path or not * @param path * @returns {boolean} */ function isLocal(path){ return !/^\w*?:\/\/|^\/\//.test(path) && !/^data:\w+?\/\w+?[,;]/i.test(path); } /** * test path is out of bound of base * @param path * @param base * @returns {boolean} */ function isOutBound(path, base){ return OUTBOUNDRE.test(relative(base, path)); } /** * Get relative path from cwd * @param path * @returns {string} */ function pathFromCwd(path){ return normalize(relative(cwd, path)) || './'; } /** * plugin error */ function throwError(){ var slice = [].slice; var message = util.format .apply(null, slice.call(arguments)); throw new Error(message); } /** * node extend * Copyright 2011, John Resig * Dual licensed under the MIT or GPL Version 2 licenses. * http://jquery.org/license * * @fileoverview * Port of jQuery.extend that actually works on node.js */ function extend(){ var target = arguments[0] || {}; var i = 1; var length = arguments.length; var deep = false; var options, name, src, copy, copyIsArray, clone; // handle a deep copy situation if (is.bool(target)) { deep = target; target = arguments[1] || {}; // skip the boolean and the target i = 2; } // handle case when target is a string or something (possible in deep copy) if ((typeof target !== 'object' && !is.fn(target)) || target === null) { target = {}; } for (; i < length; i++) { // only deal with non-null/undefined values options = arguments[i]; if (options !== null) { // extend the base object for (name in options) { if (options.hasOwnProperty(name)) { src = target[name]; copy = options[name]; // prevent never-ending loop if (target === copy) { continue; } // recurse if we're merging plain objects or arrays if (deep && copy && (is.hash(copy) || (copyIsArray = Array.isArray(copy)))) { if (copyIsArray) { copyIsArray = false; clone = src && Array.isArray(src) ? src : []; } else { clone = src && is.hash(src) ? src : {}; } // never move original objects, clone them target[name] = extend(deep, clone, copy); // don't bring in undefined values } else if (typeof copy !== 'undefined') { target[name] = copy; } } } } } // return the modified object return target; } /** * wrap module * @param id * @param deps * @param code * @returns {string} */ function wrapModule(id, deps, code){ // header and footer template string var headerTpl = 'define({{id}}, {{deps}}, function(require, exports, module){'; var footerTpl = '});\n'; if (Buffer.isBuffer(code)) code = code.toString(); // debug debug('compile module: %s', colors.magenta(id)); id = JSON.stringify(id); deps = JSON.stringify(deps); return template(headerTpl, { id: id, deps: deps }) + '\n' + code + '\n' + footerTpl; } /** * print message */ function print(){ var slice = [].slice; var message = util.format .apply(null, slice.call(arguments)); process.stdout.write(colors.cyan.bold(' gulp-cmd ') + message + '\n'); } /** * exports module. */ module.exports.cwd = cwd; module.exports.colors = colors; module.exports.debug = debug; module.exports.parsePackage = parsePackage; module.exports.template = template; module.exports.plugin = plugin; module.exports.parseAlias = parseAlias; module.exports.parsePaths = parsePaths; module.exports.parseVars = parseVars; module.exports.parseMap = parseMap; module.exports.normalize = normalize; module.exports.resolve = resolve; module.exports.addExt = addExt; module.exports.hideExt = hideExt; module.exports.isRelative = isRelative; module.exports.isAbsolute = isAbsolute; module.exports.isLocal = isLocal; module.exports.isOutBound = isOutBound; module.exports.pathFromCwd = pathFromCwd; module.exports.throwError = throwError; module.exports.extend = extend; module.exports.wrapModule = wrapModule; module.exports.print = print;
update files
lib/util.js
update files
<ide><path>ib/util.js <ide> function parseVars(id, vars){ <ide> vars = vars || {}; <ide> <del> if (vars && id.indexOf('{') > -1) { <add> if (vars && id.indexOf('{') !== -1) { <ide> id = id.replace(VARSRE, function (match, key){ <ide> return is.string(vars[key]) ? vars[key] : match; <ide> });
JavaScript
bsd-3-clause
ffe516f3bf57a13e123411a9ca76b48915a00acb
0
acdlite/react,terminatorheart/react,acdlite/react,tomocchino/react,acdlite/react,billfeller/react,terminatorheart/react,cpojer/react,trueadm/react,camsong/react,mosoft521/react,billfeller/react,tomocchino/react,trueadm/react,cpojer/react,billfeller/react,facebook/react,tomocchino/react,facebook/react,camsong/react,trueadm/react,camsong/react,cpojer/react,mosoft521/react,cpojer/react,facebook/react,cpojer/react,yungsters/react,ArunTesco/react,tomocchino/react,yungsters/react,tomocchino/react,yungsters/react,mosoft521/react,yungsters/react,trueadm/react,terminatorheart/react,mosoft521/react,yungsters/react,trueadm/react,facebook/react,mosoft521/react,trueadm/react,yungsters/react,terminatorheart/react,billfeller/react,tomocchino/react,billfeller/react,mosoft521/react,facebook/react,terminatorheart/react,terminatorheart/react,billfeller/react,camsong/react,camsong/react,trueadm/react,acdlite/react,acdlite/react,ArunTesco/react,camsong/react,yungsters/react,billfeller/react,acdlite/react,cpojer/react,camsong/react,mosoft521/react,cpojer/react,acdlite/react,tomocchino/react,ArunTesco/react,facebook/react,facebook/react
/** * Copyright (c) Facebook, Inc. and its affiliates. * * This source code is licensed under the MIT license found in the * LICENSE file in the root directory of this source tree. * * @flow */ import type {FiberRoot, ReactPriorityLevel} from './ReactInternalTypes'; export opaque type LanePriority = | 0 | 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | 9 | 10 | 11 | 12 | 13 | 14 | 15 | 16; export opaque type Lanes = number; export opaque type Lane = number; export opaque type LaneMap<T> = Array<T>; import invariant from 'shared/invariant'; import { ImmediatePriority as ImmediateSchedulerPriority, UserBlockingPriority as UserBlockingSchedulerPriority, NormalPriority as NormalSchedulerPriority, LowPriority as LowSchedulerPriority, IdlePriority as IdleSchedulerPriority, NoPriority as NoSchedulerPriority, } from './SchedulerWithReactIntegration.new'; export const SyncLanePriority: LanePriority = 16; const SyncBatchedLanePriority: LanePriority = 15; const InputDiscreteHydrationLanePriority: LanePriority = 14; export const InputDiscreteLanePriority: LanePriority = 13; const InputContinuousHydrationLanePriority: LanePriority = 12; const InputContinuousLanePriority: LanePriority = 11; const DefaultHydrationLanePriority: LanePriority = 10; const DefaultLanePriority: LanePriority = 9; const TransitionShortHydrationLanePriority: LanePriority = 8; export const TransitionShortLanePriority: LanePriority = 7; const TransitionLongHydrationLanePriority: LanePriority = 6; export const TransitionLongLanePriority: LanePriority = 5; const SelectiveHydrationLanePriority: LanePriority = 4; const IdleHydrationLanePriority: LanePriority = 3; const IdleLanePriority: LanePriority = 2; const OffscreenLanePriority: LanePriority = 1; export const NoLanePriority: LanePriority = 0; const TotalLanes = 31; export const NoLanes: Lanes = /* */ 0b0000000000000000000000000000000; export const NoLane: Lane = /* */ 0b0000000000000000000000000000000; export const SyncLane: Lane = /* */ 0b0000000000000000000000000000001; const SyncUpdateRangeEnd = 1; export const SyncBatchedLane: Lane = /* */ 0b0000000000000000000000000000010; const SyncBatchedUpdateRangeEnd = 2; export const InputDiscreteHydrationLane: Lane = /* */ 0b0000000000000000000000000000100; const InputDiscreteLanes: Lanes = /* */ 0b0000000000000000000000000011100; const InputDiscreteUpdateRangeStart = 3; const InputDiscreteUpdateRangeEnd = 5; const InputContinuousHydrationLane: Lane = /* */ 0b0000000000000000000000000100000; const InputContinuousLanes: Lanes = /* */ 0b0000000000000000000000011100000; const InputContinuousUpdateRangeStart = 6; const InputContinuousUpdateRangeEnd = 8; export const DefaultHydrationLane: Lane = /* */ 0b0000000000000000000000100000000; const DefaultLanes: Lanes = /* */ 0b0000000000000000011111100000000; const DefaultUpdateRangeStart = 9; const DefaultUpdateRangeEnd = 14; const TransitionShortHydrationLane: Lane = /* */ 0b0000000000000000100000000000000; const TransitionShortLanes: Lanes = /* */ 0b0000000000011111100000000000000; const TransitionShortUpdateRangeStart = 15; const TransitionShortUpdateRangeEnd = 20; const TransitionLongHydrationLane: Lane = /* */ 0b0000000000100000000000000000000; const TransitionLongLanes: Lanes = /* */ 0b0000011111100000000000000000000; const TransitionLongUpdateRangeStart = 21; const TransitionLongUpdateRangeEnd = 26; export const SelectiveHydrationLane: Lane = /* */ 0b0000110000000000000000000000000; const SelectiveHydrationRangeEnd = 27; // Includes all non-Idle updates const UpdateRangeEnd = 27; const NonIdleLanes = /* */ 0b0000111111111111111111111111111; export const IdleHydrationLane: Lane = /* */ 0b0001000000000000000000000000000; const IdleLanes: Lanes = /* */ 0b0111000000000000000000000000000; const IdleUpdateRangeStart = 28; const IdleUpdateRangeEnd = 30; export const OffscreenLane: Lane = /* */ 0b1000000000000000000000000000000; export const NoTimestamp = -1; // "Registers" used to "return" multiple values // Used by getHighestPriorityLanes and getNextLanes: let return_highestLanePriority: LanePriority = DefaultLanePriority; let return_updateRangeEnd: number = -1; function getHighestPriorityLanes(lanes: Lanes | Lane): Lanes { if ((SyncLane & lanes) !== NoLanes) { return_highestLanePriority = SyncLanePriority; return_updateRangeEnd = SyncUpdateRangeEnd; return SyncLane; } if ((SyncBatchedLane & lanes) !== NoLanes) { return_highestLanePriority = SyncBatchedLanePriority; return_updateRangeEnd = SyncBatchedUpdateRangeEnd; return SyncBatchedLane; } const inputDiscreteLanes = InputDiscreteLanes & lanes; if (inputDiscreteLanes !== NoLanes) { if (inputDiscreteLanes & InputDiscreteHydrationLane) { return_highestLanePriority = InputDiscreteHydrationLanePriority; return_updateRangeEnd = InputDiscreteUpdateRangeStart; return InputDiscreteHydrationLane; } else { return_highestLanePriority = InputDiscreteLanePriority; return_updateRangeEnd = InputDiscreteUpdateRangeEnd; return inputDiscreteLanes; } } const inputContinuousLanes = InputContinuousLanes & lanes; if (inputContinuousLanes !== NoLanes) { if (inputContinuousLanes & InputContinuousHydrationLane) { return_highestLanePriority = InputContinuousHydrationLanePriority; return_updateRangeEnd = InputContinuousUpdateRangeStart; return InputContinuousHydrationLane; } else { return_highestLanePriority = InputContinuousLanePriority; return_updateRangeEnd = InputContinuousUpdateRangeEnd; return inputContinuousLanes; } } const defaultLanes = DefaultLanes & lanes; if (defaultLanes !== NoLanes) { if (defaultLanes & DefaultHydrationLane) { return_highestLanePriority = DefaultHydrationLanePriority; return_updateRangeEnd = DefaultUpdateRangeStart; return DefaultHydrationLane; } else { return_highestLanePriority = DefaultLanePriority; return_updateRangeEnd = DefaultUpdateRangeEnd; return defaultLanes; } } const transitionShortLanes = TransitionShortLanes & lanes; if (transitionShortLanes !== NoLanes) { if (transitionShortLanes & TransitionShortHydrationLane) { return_highestLanePriority = TransitionShortHydrationLanePriority; return_updateRangeEnd = TransitionShortUpdateRangeStart; return TransitionShortHydrationLane; } else { return_highestLanePriority = TransitionShortLanePriority; return_updateRangeEnd = TransitionShortUpdateRangeEnd; return transitionShortLanes; } } const transitionLongLanes = TransitionLongLanes & lanes; if (transitionLongLanes !== NoLanes) { if (transitionLongLanes & TransitionLongHydrationLane) { return_highestLanePriority = TransitionLongHydrationLanePriority; return_updateRangeEnd = TransitionLongUpdateRangeStart; return TransitionLongHydrationLane; } else { return_highestLanePriority = TransitionLongLanePriority; return_updateRangeEnd = TransitionLongUpdateRangeEnd; return transitionLongLanes; } } if (lanes & SelectiveHydrationLane) { return_highestLanePriority = SelectiveHydrationLanePriority; return_updateRangeEnd = SelectiveHydrationRangeEnd; return SelectiveHydrationLane; } const idleLanes = IdleLanes & lanes; if (idleLanes !== NoLanes) { if (idleLanes & IdleHydrationLane) { return_highestLanePriority = IdleHydrationLanePriority; return_updateRangeEnd = IdleUpdateRangeStart; return IdleHydrationLane; } else { return_highestLanePriority = IdleLanePriority; return_updateRangeEnd = IdleUpdateRangeEnd; return idleLanes; } } if ((OffscreenLane & lanes) !== NoLanes) { return_highestLanePriority = OffscreenLanePriority; return_updateRangeEnd = TotalLanes; return OffscreenLane; } if (__DEV__) { console.error('Should have found matching lanes. This is a bug in React.'); } // This shouldn't be reachable, but as a fallback, return the entire bitmask. return_highestLanePriority = DefaultLanePriority; return_updateRangeEnd = DefaultUpdateRangeEnd; return lanes; } export function schedulerPriorityToLanePriority( schedulerPriorityLevel: ReactPriorityLevel, ): LanePriority { switch (schedulerPriorityLevel) { case ImmediateSchedulerPriority: return SyncLanePriority; case UserBlockingSchedulerPriority: return InputContinuousLanePriority; case NormalSchedulerPriority: case LowSchedulerPriority: // TODO: Handle LowSchedulerPriority, somehow. Maybe the same lane as hydration. return DefaultLanePriority; case IdleSchedulerPriority: return IdleLanePriority; default: return NoLanePriority; } } export function lanePriorityToSchedulerPriority( lanePriority: LanePriority, ): ReactPriorityLevel { switch (lanePriority) { case SyncLanePriority: case SyncBatchedLanePriority: return ImmediateSchedulerPriority; case InputDiscreteHydrationLanePriority: case InputDiscreteLanePriority: case InputContinuousHydrationLanePriority: case InputContinuousLanePriority: return UserBlockingSchedulerPriority; case DefaultHydrationLanePriority: case DefaultLanePriority: case TransitionShortHydrationLanePriority: case TransitionShortLanePriority: case TransitionLongHydrationLanePriority: case TransitionLongLanePriority: case SelectiveHydrationLanePriority: return NormalSchedulerPriority; case IdleHydrationLanePriority: case IdleLanePriority: case OffscreenLanePriority: return IdleSchedulerPriority; case NoLanePriority: return NoSchedulerPriority; default: invariant( false, 'Invalid update priority: %s. This is a bug in React.', lanePriority, ); } } export function getNextLanes(root: FiberRoot, wipLanes: Lanes): Lanes { // Early bailout if there's no pending work left. const pendingLanes = root.pendingLanes; if (pendingLanes === NoLanes) { return_highestLanePriority = NoLanePriority; return NoLanes; } let nextLanes = NoLanes; let nextLanePriority = NoLanePriority; let equalOrHigherPriorityLanes = NoLanes; const expiredLanes = root.expiredLanes; const suspendedLanes = root.suspendedLanes; const pingedLanes = root.pingedLanes; // Check if any work has expired. if (expiredLanes !== NoLanes) { nextLanes = expiredLanes; nextLanePriority = return_highestLanePriority = SyncLanePriority; equalOrHigherPriorityLanes = (getLowestPriorityLane(nextLanes) << 1) - 1; } else { // Do not work on any idle work until all the non-idle work has finished, // even if the work is suspended. const nonIdlePendingLanes = pendingLanes & NonIdleLanes; if (nonIdlePendingLanes !== NoLanes) { const nonIdleUnblockedLanes = nonIdlePendingLanes & ~suspendedLanes; if (nonIdleUnblockedLanes !== NoLanes) { nextLanes = getHighestPriorityLanes(nonIdleUnblockedLanes); nextLanePriority = return_highestLanePriority; equalOrHigherPriorityLanes = (1 << return_updateRangeEnd) - 1; } else { const nonIdlePingedLanes = nonIdlePendingLanes & pingedLanes; if (nonIdlePingedLanes !== NoLanes) { nextLanes = getHighestPriorityLanes(nonIdlePingedLanes); nextLanePriority = return_highestLanePriority; equalOrHigherPriorityLanes = (1 << return_updateRangeEnd) - 1; } } } else { // The only remaining work is Idle. const unblockedLanes = pendingLanes & ~suspendedLanes; if (unblockedLanes !== NoLanes) { nextLanes = getHighestPriorityLanes(unblockedLanes); nextLanePriority = return_highestLanePriority; equalOrHigherPriorityLanes = (1 << return_updateRangeEnd) - 1; } else { if (pingedLanes !== NoLanes) { nextLanes = getHighestPriorityLanes(pingedLanes); nextLanePriority = return_highestLanePriority; equalOrHigherPriorityLanes = (1 << return_updateRangeEnd) - 1; } } } } if (nextLanes === NoLanes) { // This should only be reachable if we're suspended // TODO: Consider warning in this path if a fallback timer is not scheduled. return NoLanes; } // If there are higher priority lanes, we'll include them even if they // are suspended. nextLanes = pendingLanes & equalOrHigherPriorityLanes; // If we're already in the middle of a render, switching lanes will interrupt // it and we'll lose our progress. We should only do this if the new lanes are // higher priority. if ( wipLanes !== NoLanes && wipLanes !== nextLanes && // If we already suspended with a delay, then interrupting is fine. Don't // bother waiting until the root is complete. (wipLanes & suspendedLanes) === NoLanes ) { getHighestPriorityLanes(wipLanes); const wipLanePriority = return_highestLanePriority; if (nextLanePriority <= wipLanePriority) { return wipLanes; } else { return_highestLanePriority = nextLanePriority; } } // Check for entangled lanes and add them to the batch. // // A lane is said to be entangled with another when it's not allowed to render // in a batch that does not also include the other lane. Typically we do this // when multiple updates have the same source, and we only want to respond to // the most recent event from that source. // // Note that we apply entanglements *after* checking for partial work above. // This means that if a lane is entangled during an interleaved event while // it's already rendering, we won't interrupt it. This is intentional, since // entanglement is usually "best effort": we'll try our best to render the // lanes in the same batch, but it's not worth throwing out partially // completed work in order to do it. // // For those exceptions where entanglement is semantically important, like // useMutableSource, we should ensure that there is no partial work at the // time we apply the entanglement. const entangledLanes = root.entangledLanes; if (entangledLanes !== NoLanes) { const entanglements = root.entanglements; let lanes = nextLanes & entangledLanes; while (lanes > 0) { const index = pickArbitraryLaneIndex(lanes); const lane = 1 << index; nextLanes |= entanglements[index]; lanes &= ~lane; } } return nextLanes; } function computeExpirationTime(lane: Lane, currentTime: number) { // TODO: Expiration heuristic is constant per lane, so could use a map. getHighestPriorityLanes(lane); const priority = return_highestLanePriority; if (priority >= InputContinuousLanePriority) { // User interactions should expire slightly more quickly. return currentTime + 1000; } else if (priority >= TransitionLongLanePriority) { return currentTime + 5000; } else { // Anything idle priority or lower should never expire. return NoTimestamp; } } export function markStarvedLanesAsExpired( root: FiberRoot, currentTime: number, ): void { // TODO: This gets called every time we yield. We can optimize by storing // the earliest expiration time on the root. Then use that to quickly bail out // of this function. const pendingLanes = root.pendingLanes; const suspendedLanes = root.suspendedLanes; const pingedLanes = root.pingedLanes; const expirationTimes = root.expirationTimes; // Iterate through the pending lanes and check if we've reached their // expiration time. If so, we'll assume the update is being starved and mark // it as expired to force it to finish. let lanes = pendingLanes; while (lanes > 0) { const index = pickArbitraryLaneIndex(lanes); const lane = 1 << index; const expirationTime = expirationTimes[index]; if (expirationTime === NoTimestamp) { // Found a pending lane with no expiration time. If it's not suspended, or // if it's pinged, assume it's CPU-bound. Compute a new expiration time // using the current time. if ( (lane & suspendedLanes) === NoLanes || (lane & pingedLanes) !== NoLanes ) { // Assumes timestamps are monotonically increasing. expirationTimes[index] = computeExpirationTime(lane, currentTime); } } else if (expirationTime <= currentTime) { // This lane expired root.expiredLanes |= lane; } lanes &= ~lane; } } // This returns the highest priority pending lanes regardless of whether they // are suspended. export function getHighestPriorityPendingLanes(root: FiberRoot) { return getHighestPriorityLanes(root.pendingLanes); } export function getLanesToRetrySynchronouslyOnError(root: FiberRoot): Lanes { const everythingButOffscreen = root.pendingLanes & ~OffscreenLane; if (everythingButOffscreen !== NoLanes) { return everythingButOffscreen; } if (everythingButOffscreen & OffscreenLane) { return OffscreenLane; } return NoLanes; } export function returnNextLanesPriority() { return return_highestLanePriority; } export function hasUpdatePriority(lanes: Lanes) { return (lanes & NonIdleLanes) !== NoLanes; } // To ensure consistency across multiple updates in the same event, this should // be a pure function, so that it always returns the same lane for given inputs. export function findUpdateLane( lanePriority: LanePriority, wipLanes: Lanes, ): Lane { switch (lanePriority) { case NoLanePriority: break; case SyncLanePriority: return SyncLane; case SyncBatchedLanePriority: return SyncBatchedLane; case InputDiscreteLanePriority: { let lane = findLane( InputDiscreteUpdateRangeStart, UpdateRangeEnd, wipLanes, ); if (lane === NoLane) { lane = InputDiscreteHydrationLane; } return lane; } case InputContinuousLanePriority: { let lane = findLane( InputContinuousUpdateRangeStart, UpdateRangeEnd, wipLanes, ); if (lane === NoLane) { lane = InputContinuousHydrationLane; } return lane; } case DefaultLanePriority: { let lane = findLane(DefaultUpdateRangeStart, UpdateRangeEnd, wipLanes); if (lane === NoLane) { lane = DefaultHydrationLane; } return lane; } case TransitionShortLanePriority: case TransitionLongLanePriority: // Should be handled by findTransitionLane instead break; case IdleLanePriority: let lane = findLane(IdleUpdateRangeStart, IdleUpdateRangeEnd, wipLanes); if (lane === NoLane) { lane = IdleHydrationLane; } return lane; default: // The remaining priorities are not valid for updates break; } invariant( false, 'Invalid update priority: %s. This is a bug in React.', lanePriority, ); } // To ensure consistency across multiple updates in the same event, this should // be pure function, so that it always returns the same lane for given inputs. export function findTransitionLane( lanePriority: LanePriority, wipLanes: Lanes, pendingLanes: Lanes, ): Lane { if (lanePriority === TransitionShortLanePriority) { let lane = findLane( TransitionShortUpdateRangeStart, TransitionShortUpdateRangeEnd, wipLanes | pendingLanes, ); if (lane === NoLane) { lane = findLane( TransitionShortUpdateRangeStart, TransitionShortUpdateRangeEnd, wipLanes, ); if (lane === NoLane) { lane = TransitionShortHydrationLane; } } return lane; } if (lanePriority === TransitionLongLanePriority) { let lane = findLane( TransitionLongUpdateRangeStart, TransitionLongUpdateRangeEnd, wipLanes | pendingLanes, ); if (lane === NoLane) { lane = findLane( TransitionLongUpdateRangeStart, TransitionLongUpdateRangeEnd, wipLanes, ); if (lane === NoLane) { lane = TransitionLongHydrationLane; } } return lane; } invariant( false, 'Invalid transition priority: %s. This is a bug in React.', lanePriority, ); } function findLane(start, end, skipLanes) { // This finds the first bit between the `start` and `end` positions that isn't // in `skipLanes`. // TODO: This will always favor the rightmost bits. That's usually fine // because any bit that's pending will be part of `skipLanes`, so we'll do our // best to avoid accidental entanglement. However, lanes that are pending // inside an Offscreen tree aren't considered "pending" at the root level. So // they aren't included in `skipLanes`. So we should try not to favor any // particular part of the range, perhaps by incrementing an offset for each // distinct event. Must be the same within a single event, though. const bitsInRange = ((1 << (end - start)) - 1) << start; const possibleBits = bitsInRange & ~skipLanes; const leastSignificantBit = possibleBits & -possibleBits; return leastSignificantBit; } function getLowestPriorityLane(lanes: Lanes): Lane { // This finds the most significant non-zero bit. const index = 31 - clz32(lanes); return index < 0 ? NoLanes : 1 << index; } export function pickArbitraryLane(lanes: Lanes): Lane { return getLowestPriorityLane(lanes); } function pickArbitraryLaneIndex(lanes: Lane | Lanes) { return 31 - clz32(lanes); } export function includesSomeLane(a: Lanes | Lane, b: Lanes | Lane) { return (a & b) !== NoLanes; } export function isSubsetOfLanes(set: Lanes, subset: Lanes | Lane) { return (set & subset) === subset; } export function mergeLanes(a: Lanes | Lane, b: Lanes | Lane): Lanes { return a | b; } export function removeLanes(set: Lanes, subset: Lanes | Lane): Lanes { return set & ~subset; } // Seems redundant, but it changes the type from a single lane (used for // updates) to a group of lanes (used for flushing work). export function laneToLanes(lane: Lane): Lanes { return lane; } export function higherPriorityLane(a: Lane, b: Lane) { // This works because the bit ranges decrease in priority as you go left. return a !== NoLane && a < b ? a : b; } export function createLaneMap<T>(initial: T): LaneMap<T> { return new Array(TotalLanes).fill(initial); } export function markRootUpdated(root: FiberRoot, updateLane: Lane) { root.pendingLanes |= updateLane; // TODO: Theoretically, any update to any lane can unblock any other lane. But // it's not practical to try every single possible combination. We need a // heuristic to decide which lanes to attempt to render, and in which batches. // For now, we use the same heuristic as in the old ExpirationTimes model: // retry any lane at equal or lower priority, but don't try updates at higher // priority without also including the lower priority updates. This works well // when considering updates across different priority levels, but isn't // sufficient for updates within the same priority, since we want to treat // those updates as parallel. // Unsuspend any update at equal or lower priority. const higherPriorityLanes = updateLane - 1; // Turns 0b1000 into 0b0111 root.suspendedLanes &= higherPriorityLanes; root.pingedLanes &= higherPriorityLanes; } export function markRootSuspended(root: FiberRoot, suspendedLanes: Lanes) { root.suspendedLanes |= suspendedLanes; root.pingedLanes &= ~suspendedLanes; // The suspended lanes are no longer CPU-bound. Clear their expiration times. const expirationTimes = root.expirationTimes; let lanes = suspendedLanes; while (lanes > 0) { const index = pickArbitraryLaneIndex(lanes); const lane = 1 << index; expirationTimes[index] = NoTimestamp; lanes &= ~lane; } } export function markRootPinged( root: FiberRoot, pingedLanes: Lanes, eventTime: number, ) { root.pingedLanes |= root.suspendedLanes & pingedLanes; } export function markRootExpired(root: FiberRoot, expiredLanes: Lanes) { root.expiredLanes |= expiredLanes & root.pendingLanes; } export function markDiscreteUpdatesExpired(root: FiberRoot) { root.expiredLanes |= InputDiscreteLanes & root.pendingLanes; } export function hasDiscreteLanes(lanes: Lanes) { return (lanes & InputDiscreteLanes) !== NoLanes; } export function markRootMutableRead(root: FiberRoot, updateLane: Lane) { root.mutableReadLanes |= updateLane & root.pendingLanes; } export function markRootFinished(root: FiberRoot, remainingLanes: Lanes) { const noLongerPendingLanes = root.pendingLanes & ~remainingLanes; root.pendingLanes = remainingLanes; // Let's try everything again root.suspendedLanes = 0; root.pingedLanes = 0; root.expiredLanes &= remainingLanes; root.mutableReadLanes &= remainingLanes; root.entangledLanes &= remainingLanes; const expirationTimes = root.expirationTimes; let lanes = noLongerPendingLanes; while (lanes > 0) { const index = pickArbitraryLaneIndex(lanes); const lane = 1 << index; // Clear the expiration time expirationTimes[index] = NoTimestamp; lanes &= ~lane; } } export function markRootEntangled(root: FiberRoot, entangledLanes: Lanes) { root.entangledLanes |= entangledLanes; const entanglements = root.entanglements; let lanes = entangledLanes; while (lanes > 0) { const index = pickArbitraryLaneIndex(lanes); const lane = 1 << index; entanglements[index] |= entangledLanes; lanes &= ~lane; } } export function getBumpedLaneForHydration( root: FiberRoot, renderLanes: Lanes, ): Lane { getHighestPriorityLanes(renderLanes); const highestLanePriority = return_highestLanePriority; let lane; switch (highestLanePriority) { case SyncLanePriority: case SyncBatchedLanePriority: lane = NoLane; break; case InputDiscreteHydrationLanePriority: case InputDiscreteLanePriority: lane = InputDiscreteHydrationLane; break; case InputContinuousHydrationLanePriority: case InputContinuousLanePriority: lane = InputContinuousHydrationLane; break; case DefaultHydrationLanePriority: case DefaultLanePriority: lane = DefaultHydrationLane; break; case TransitionShortHydrationLanePriority: case TransitionShortLanePriority: lane = TransitionShortHydrationLane; break; case TransitionLongHydrationLanePriority: case TransitionLongLanePriority: lane = TransitionLongHydrationLane; break; case SelectiveHydrationLanePriority: lane = SelectiveHydrationLane; break; case IdleHydrationLanePriority: case IdleLanePriority: lane = IdleHydrationLane; break; case OffscreenLanePriority: case NoLanePriority: lane = NoLane; break; default: invariant(false, 'Invalid lane: %s. This is a bug in React.', lane); } // Check if the lane we chose is suspended. If so, that indicates that we // already attempted and failed to hydrate at that level. Also check if we're // already rendering that lane, which is rare but could happen. if ((lane & (root.suspendedLanes | renderLanes)) !== NoLane) { // Give up trying to hydrate and fall back to client render. return NoLane; } return lane; } const clz32 = Math.clz32 ? Math.clz32 : clz32Fallback; // Count leading zeros. Only used on lanes, so assume input is an integer. // Based on: // https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Math/clz32 const log = Math.log; const LN2 = Math.LN2; function clz32Fallback(lanes: Lanes | Lane) { if (lanes === 0) { return 32; } return (31 - ((log(lanes) / LN2) | 0)) | 0; }
packages/react-reconciler/src/ReactFiberLane.js
/** * Copyright (c) Facebook, Inc. and its affiliates. * * This source code is licensed under the MIT license found in the * LICENSE file in the root directory of this source tree. * * @flow */ import type {FiberRoot, ReactPriorityLevel} from './ReactInternalTypes'; export opaque type LanePriority = | 0 | 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | 9 | 10 | 11 | 12 | 13 | 14 | 15 | 16; export opaque type Lanes = number; export opaque type Lane = number; export opaque type LaneMap<T> = Array<T>; import invariant from 'shared/invariant'; import { ImmediatePriority as ImmediateSchedulerPriority, UserBlockingPriority as UserBlockingSchedulerPriority, NormalPriority as NormalSchedulerPriority, LowPriority as LowSchedulerPriority, IdlePriority as IdleSchedulerPriority, NoPriority as NoSchedulerPriority, } from './SchedulerWithReactIntegration.new'; export const SyncLanePriority: LanePriority = 16; const SyncBatchedLanePriority: LanePriority = 15; const InputDiscreteHydrationLanePriority: LanePriority = 14; export const InputDiscreteLanePriority: LanePriority = 13; const InputContinuousHydrationLanePriority: LanePriority = 12; const InputContinuousLanePriority: LanePriority = 11; const DefaultHydrationLanePriority: LanePriority = 10; const DefaultLanePriority: LanePriority = 9; const TransitionShortHydrationLanePriority: LanePriority = 8; export const TransitionShortLanePriority: LanePriority = 7; const TransitionLongHydrationLanePriority: LanePriority = 6; export const TransitionLongLanePriority: LanePriority = 5; const SelectiveHydrationLanePriority: LanePriority = 4; const IdleHydrationLanePriority: LanePriority = 3; const IdleLanePriority: LanePriority = 2; const OffscreenLanePriority: LanePriority = 1; export const NoLanePriority: LanePriority = 0; const TotalLanes = 31; export const NoLanes: Lanes = /* */ 0b0000000000000000000000000000000; export const NoLane: Lane = /* */ 0b0000000000000000000000000000000; export const SyncLane: Lane = /* */ 0b0000000000000000000000000000001; const SyncUpdateRangeEnd = 1; export const SyncBatchedLane: Lane = /* */ 0b0000000000000000000000000000010; const SyncBatchedUpdateRangeEnd = 2; export const InputDiscreteHydrationLane: Lane = /* */ 0b0000000000000000000000000000100; const InputDiscreteLanes: Lanes = /* */ 0b0000000000000000000000000011100; const InputDiscreteUpdateRangeStart = 3; const InputDiscreteUpdateRangeEnd = 5; const InputContinuousHydrationLane: Lane = /* */ 0b0000000000000000000000000100000; const InputContinuousLanes: Lanes = /* */ 0b0000000000000000000000011100000; const InputContinuousUpdateRangeStart = 6; const InputContinuousUpdateRangeEnd = 8; export const DefaultHydrationLane: Lane = /* */ 0b0000000000000000000000100000000; const DefaultLanes: Lanes = /* */ 0b0000000000000000011111100000000; const DefaultUpdateRangeStart = 9; const DefaultUpdateRangeEnd = 14; const TransitionShortHydrationLane: Lane = /* */ 0b0000000000000000100000000000000; const TransitionShortLanes: Lanes = /* */ 0b0000000000011111100000000000000; const TransitionShortUpdateRangeStart = 15; const TransitionShortUpdateRangeEnd = 20; const TransitionLongHydrationLane: Lane = /* */ 0b0000000000100000000000000000000; const TransitionLongLanes: Lanes = /* */ 0b0000011111100000000000000000000; const TransitionLongUpdateRangeStart = 21; const TransitionLongUpdateRangeEnd = 26; export const SelectiveHydrationLane: Lane = /* */ 0b0000110000000000000000000000000; const SelectiveHydrationRangeEnd = 27; // Includes all non-Idle updates const UpdateRangeEnd = 27; const NonIdleLanes = /* */ 0b0000111111111111111111111111111; export const IdleHydrationLane: Lane = /* */ 0b0001000000000000000000000000000; const IdleLanes: Lanes = /* */ 0b0111000000000000000000000000000; const IdleUpdateRangeStart = 28; const IdleUpdateRangeEnd = 30; export const OffscreenLane: Lane = /* */ 0b1000000000000000000000000000000; export const NoTimestamp = -1; // "Registers" used to "return" multiple values // Used by getHighestPriorityLanes and getNextLanes: let return_highestLanePriority: LanePriority = DefaultLanePriority; let return_updateRangeEnd: number = -1; function getHighestPriorityLanes(lanes: Lanes | Lane): Lanes { if ((SyncLane & lanes) !== NoLanes) { return_highestLanePriority = SyncLanePriority; return_updateRangeEnd = SyncUpdateRangeEnd; return SyncLane; } if ((SyncBatchedLane & lanes) !== NoLanes) { return_highestLanePriority = SyncBatchedLanePriority; return_updateRangeEnd = SyncBatchedUpdateRangeEnd; return SyncBatchedLane; } const inputDiscreteLanes = InputDiscreteLanes & lanes; if (inputDiscreteLanes !== NoLanes) { if (inputDiscreteLanes & InputDiscreteHydrationLane) { return_highestLanePriority = InputDiscreteHydrationLanePriority; return_updateRangeEnd = InputDiscreteUpdateRangeStart; return InputDiscreteHydrationLane; } else { return_highestLanePriority = InputDiscreteLanePriority; return_updateRangeEnd = InputDiscreteUpdateRangeEnd; return inputDiscreteLanes; } } const inputContinuousLanes = InputContinuousLanes & lanes; if (inputContinuousLanes !== NoLanes) { if (inputContinuousLanes & InputContinuousHydrationLane) { return_highestLanePriority = InputContinuousHydrationLanePriority; return_updateRangeEnd = InputContinuousUpdateRangeStart; return InputContinuousHydrationLane; } else { return_highestLanePriority = InputContinuousLanePriority; return_updateRangeEnd = InputContinuousUpdateRangeEnd; return inputContinuousLanes; } } const defaultLanes = DefaultLanes & lanes; if (defaultLanes !== NoLanes) { if (defaultLanes & DefaultHydrationLane) { return_highestLanePriority = DefaultHydrationLanePriority; return_updateRangeEnd = DefaultUpdateRangeStart; return DefaultHydrationLane; } else { return_highestLanePriority = DefaultLanePriority; return_updateRangeEnd = DefaultUpdateRangeEnd; return defaultLanes; } } const transitionShortLanes = TransitionShortLanes & lanes; if (transitionShortLanes !== NoLanes) { if (transitionShortLanes & TransitionShortHydrationLane) { return_highestLanePriority = TransitionShortHydrationLanePriority; return_updateRangeEnd = TransitionShortUpdateRangeStart; return TransitionShortHydrationLane; } else { return_highestLanePriority = TransitionShortLanePriority; return_updateRangeEnd = TransitionShortUpdateRangeEnd; return transitionShortLanes; } } const transitionLongLanes = TransitionLongLanes & lanes; if (transitionLongLanes !== NoLanes) { if (transitionLongLanes & TransitionLongHydrationLane) { return_highestLanePriority = TransitionLongHydrationLanePriority; return_updateRangeEnd = TransitionLongUpdateRangeStart; return TransitionLongHydrationLane; } else { return_highestLanePriority = TransitionLongLanePriority; return_updateRangeEnd = TransitionLongUpdateRangeEnd; return transitionLongLanes; } } if (lanes & SelectiveHydrationLane) { return_highestLanePriority = SelectiveHydrationLanePriority; return_updateRangeEnd = SelectiveHydrationRangeEnd; return SelectiveHydrationLane; } const idleLanes = IdleLanes & lanes; if (idleLanes !== NoLanes) { if (idleLanes & IdleHydrationLane) { return_highestLanePriority = IdleHydrationLanePriority; return_updateRangeEnd = IdleUpdateRangeStart; return IdleHydrationLane; } else { return_highestLanePriority = IdleLanePriority; return_updateRangeEnd = IdleUpdateRangeEnd; return idleLanes; } } if ((OffscreenLane & lanes) !== NoLanes) { return_highestLanePriority = OffscreenLanePriority; return_updateRangeEnd = TotalLanes; return OffscreenLane; } if (__DEV__) { console.error('Should have found matching lanes. This is a bug in React.'); } // This shouldn't be reachable, but as a fallback, return the entire bitmask. return_highestLanePriority = DefaultLanePriority; return_updateRangeEnd = DefaultUpdateRangeEnd; return lanes; } export function schedulerPriorityToLanePriority( schedulerPriorityLevel: ReactPriorityLevel, ): LanePriority { switch (schedulerPriorityLevel) { case ImmediateSchedulerPriority: return SyncLanePriority; case UserBlockingSchedulerPriority: return InputContinuousLanePriority; case NormalSchedulerPriority: case LowSchedulerPriority: // TODO: Handle LowSchedulerPriority, somehow. Maybe the same lane as hydration. return DefaultLanePriority; case IdleSchedulerPriority: return IdleLanePriority; default: return NoLanePriority; } } export function lanePriorityToSchedulerPriority( lanePriority: LanePriority, ): ReactPriorityLevel { switch (lanePriority) { case SyncLanePriority: case SyncBatchedLanePriority: return ImmediateSchedulerPriority; case InputDiscreteHydrationLanePriority: case InputDiscreteLanePriority: case InputContinuousHydrationLanePriority: case InputContinuousLanePriority: return UserBlockingSchedulerPriority; case DefaultHydrationLanePriority: case DefaultLanePriority: case TransitionShortHydrationLanePriority: case TransitionShortLanePriority: case TransitionLongHydrationLanePriority: case TransitionLongLanePriority: case SelectiveHydrationLanePriority: return NormalSchedulerPriority; case IdleHydrationLanePriority: case IdleLanePriority: case OffscreenLanePriority: return IdleSchedulerPriority; case NoLanePriority: return NoSchedulerPriority; default: invariant( false, 'Invalid update priority: %s. This is a bug in React.', lanePriority, ); } } export function getNextLanes(root: FiberRoot, wipLanes: Lanes): Lanes { // Early bailout if there's no pending work left. const pendingLanes = root.pendingLanes; if (pendingLanes === NoLanes) { return_highestLanePriority = NoLanePriority; return NoLanes; } let nextLanes = NoLanes; let nextLanePriority = NoLanePriority; let equalOrHigherPriorityLanes = NoLanes; const expiredLanes = root.expiredLanes; const suspendedLanes = root.suspendedLanes; const pingedLanes = root.pingedLanes; // Check if any work has expired. if (expiredLanes !== NoLanes) { nextLanes = expiredLanes; nextLanePriority = return_highestLanePriority = SyncLanePriority; equalOrHigherPriorityLanes = (getLowestPriorityLane(nextLanes) << 1) - 1; } else { // Do not work on any idle work until all the non-idle work has finished, // even if the work is suspended. const nonIdlePendingLanes = pendingLanes & NonIdleLanes; if (nonIdlePendingLanes !== NoLanes) { const nonIdleUnblockedLanes = nonIdlePendingLanes & ~suspendedLanes; if (nonIdleUnblockedLanes !== NoLanes) { nextLanes = getHighestPriorityLanes(nonIdleUnblockedLanes); nextLanePriority = return_highestLanePriority; equalOrHigherPriorityLanes = (1 << return_updateRangeEnd) - 1; } else { const nonIdlePingedLanes = nonIdlePendingLanes & pingedLanes; if (nonIdlePingedLanes !== NoLanes) { nextLanes = getHighestPriorityLanes(nonIdlePingedLanes); nextLanePriority = return_highestLanePriority; equalOrHigherPriorityLanes = (1 << return_updateRangeEnd) - 1; } } } else { // The only remaining work is Idle. const unblockedLanes = pendingLanes & ~suspendedLanes; if (unblockedLanes !== NoLanes) { nextLanes = getHighestPriorityLanes(unblockedLanes); nextLanePriority = return_highestLanePriority; equalOrHigherPriorityLanes = (1 << return_updateRangeEnd) - 1; } else { if (pingedLanes !== NoLanes) { nextLanes = getHighestPriorityLanes(pingedLanes); nextLanePriority = return_highestLanePriority; equalOrHigherPriorityLanes = (1 << return_updateRangeEnd) - 1; } } } } if (nextLanes === NoLanes) { // This should only be reachable if we're suspended // TODO: Consider warning in this path if a fallback timer is not scheduled. return NoLanes; } // If there are higher priority lanes, we'll include them even if they // are suspended. nextLanes = pendingLanes & equalOrHigherPriorityLanes; // If we're already in the middle of a render, switching lanes will interrupt // it and we'll lose our progress. We should only do this if the new lanes are // higher priority. if ( wipLanes !== NoLanes && wipLanes !== nextLanes && // If we already suspended with a delay, then interrupting is fine. Don't // bother waiting until the root is complete. (wipLanes & suspendedLanes) === NoLanes ) { getHighestPriorityLanes(wipLanes); const wipLanePriority = return_highestLanePriority; if (nextLanePriority <= wipLanePriority) { return wipLanes; } else { return_highestLanePriority = nextLanePriority; } } // Check for entangled lanes and add them to the batch. // // A lane is said to be entangled with another when it's not allowed to render // in a batch that does not also include the other lane. Typically we do this // when multiple updates have the same source, and we only want to respond to // the most recent event from that source. // // Note that we apply entanglements *after* checking for partial work above. // This means that if a lane is entangled during an interleaved event while // it's already rendering, we won't interrupt it. This is intentional, since // entanglement is usually "best effort": we'll try our best to render the // lanes in the same batch, but it's not worth throwing out partially // completed work in order to do it. // // For those exceptions where entanglement is semantically important, like // useMutableSource, we should ensure that there is no partial work at the // time we apply the entanglement. const entangledLanes = root.entangledLanes; if (entangledLanes !== NoLanes) { const entanglements = root.entanglements; let lanes = nextLanes & entangledLanes; while (lanes > 0) { const index = pickArbitraryLaneIndex(lanes); const lane = 1 << index; nextLanes |= entanglements[index]; lanes &= ~lane; } } return nextLanes; } function computeExpirationTime(lane: Lane, currentTime: number) { // TODO: Expiration heuristic is constant per lane, so could use a map. getHighestPriorityLanes(lane); const priority = return_highestLanePriority; if (priority >= InputContinuousLanePriority) { // User interactions should expire slightly more quickly. return currentTime + 1000; } else if (priority >= TransitionLongLanePriority) { return currentTime + 5000; } else { // Anything idle priority or lower should never expire. return NoTimestamp; } } export function markStarvedLanesAsExpired( root: FiberRoot, currentTime: number, ): void { // TODO: This gets called every time we yield. We can optimize by storing // the earliest expiration time on the root. Then use that to quickly bail out // of this function. const pendingLanes = root.pendingLanes; const suspendedLanes = root.suspendedLanes; const pingedLanes = root.pingedLanes; const expirationTimes = root.expirationTimes; // Iterate through the pending lanes and check if we've reached their // expiration time. If so, we'll assume the update is being starved and mark // it as expired to force it to finish. let lanes = pendingLanes; while (lanes > 0) { const index = pickArbitraryLaneIndex(lanes); const lane = 1 << index; const expirationTime = expirationTimes[index]; if (expirationTime === NoTimestamp) { // Found a pending lane with no expiration time. If it's not suspended, or // if it's pinged, assume it's CPU-bound. Compute a new expiration time // using the current time. if ( (lane & suspendedLanes) === NoLanes || (lane & pingedLanes) !== NoLanes ) { // Assumes timestamps are monotonically increasing. expirationTimes[index] = computeExpirationTime(lane, currentTime); } } else if (expirationTime <= currentTime) { // This lane expired root.expiredLanes |= lane; } lanes &= ~lane; } } // This returns the highest priority pending lanes regardless of whether they // are suspended. export function getHighestPriorityPendingLanes(root: FiberRoot) { return getHighestPriorityLanes(root.pendingLanes); } export function getLanesToRetrySynchronouslyOnError(root: FiberRoot): Lanes { const everythingButOffscreen = root.pendingLanes & ~OffscreenLane; if (everythingButOffscreen !== NoLanes) { return everythingButOffscreen; } if (everythingButOffscreen & OffscreenLane) { return OffscreenLane; } return NoLanes; } export function returnNextLanesPriority() { return return_highestLanePriority; } export function hasUpdatePriority(lanes: Lanes) { return (lanes & NonIdleLanes) !== NoLanes; } // To ensure consistency across multiple updates in the same event, this should // be a pure function, so that it always returns the same lane for given inputs. export function findUpdateLane( lanePriority: LanePriority, wipLanes: Lanes, ): Lane { switch (lanePriority) { case NoLanePriority: break; case SyncLanePriority: return SyncLane; case SyncBatchedLanePriority: return SyncBatchedLane; case InputDiscreteLanePriority: { let lane = findLane( InputDiscreteUpdateRangeStart, UpdateRangeEnd, wipLanes, ); if (lane === NoLane) { lane = InputDiscreteHydrationLane; } return lane; } case InputContinuousLanePriority: { let lane = findLane( InputContinuousUpdateRangeStart, UpdateRangeEnd, wipLanes, ); if (lane === NoLane) { lane = InputContinuousHydrationLane; } return lane; } case DefaultLanePriority: { let lane = findLane(DefaultUpdateRangeStart, UpdateRangeEnd, wipLanes); if (lane === NoLane) { lane = DefaultHydrationLane; } return lane; } case TransitionShortLanePriority: case TransitionLongLanePriority: // Should be handled by findTransitionLane instead break; case IdleLanePriority: let lane = findLane(IdleUpdateRangeStart, IdleUpdateRangeEnd, wipLanes); if (lane === NoLane) { lane = IdleHydrationLane; } return lane; default: // The remaining priorities are not valid for updates break; } invariant( false, 'Invalid update priority: %s. This is a bug in React.', lanePriority, ); } // To ensure consistency across multiple updates in the same event, this should // be pure function, so that it always returns the same lane for given inputs. export function findTransitionLane( lanePriority: LanePriority, wipLanes: Lanes, pendingLanes: Lanes, ): Lane { if (lanePriority === TransitionShortLanePriority) { let lane = findLane( TransitionShortUpdateRangeStart, TransitionShortUpdateRangeEnd, wipLanes | pendingLanes, ); if (lane === NoLane) { lane = findLane( TransitionShortUpdateRangeStart, TransitionShortUpdateRangeEnd, wipLanes, ); if (lane === NoLane) { lane = TransitionShortHydrationLane; } } return lane; } if (lanePriority === TransitionLongLanePriority) { let lane = findLane( TransitionLongUpdateRangeStart, TransitionLongUpdateRangeEnd, wipLanes | pendingLanes, ); if (lane === NoLane) { lane = findLane( TransitionLongUpdateRangeStart, TransitionLongUpdateRangeEnd, wipLanes, ); if (lane === NoLane) { lane = TransitionLongHydrationLane; } } return lane; } invariant( false, 'Invalid transition priority: %s. This is a bug in React.', lanePriority, ); } function findLane(start, end, skipLanes) { // This finds the first bit between the `start` and `end` positions that isn't // in `skipLanes`. // TODO: This will always favor the rightmost bits. That's usually fine // because any bit that's pending will be part of `skipLanes`, so we'll do our // best to avoid accidental entanglement. However, lanes that are pending // inside an Offscreen tree aren't considered "pending" at the root level. So // they aren't included in `skipLanes`. So we should try not to favor any // particular part of the range, perhaps by incrementing an offset for each // distinct event. Must be the same within a single event, though. const bitsInRange = ((1 << (end - start)) - 1) << start; const possibleBits = bitsInRange & ~skipLanes; const leastSignificantBit = possibleBits & -possibleBits; return leastSignificantBit; } function getLowestPriorityLane(lanes: Lanes): Lane { // This finds the most significant non-zero bit. const index = 31 - clz32(lanes); return index < 0 ? NoLanes : 1 << index; } export function pickArbitraryLane(lanes: Lanes): Lane { return getLowestPriorityLane(lanes); } function pickArbitraryLaneIndex(lanes: Lane | Lanes) { return 31 - clz32(lanes); } export function includesSomeLane(a: Lanes | Lane, b: Lanes | Lane) { return (a & b) !== NoLanes; } export function isSubsetOfLanes(set: Lanes, subset: Lanes | Lane) { return (set & subset) === subset; } export function mergeLanes(a: Lanes | Lane, b: Lanes | Lane): Lanes { return a | b; } export function removeLanes(set: Lanes, subset: Lanes | Lane): Lanes { return set & ~subset; } // Seems redundant, but it changes the type from a single lane (used for // updates) to a group of lanes (used for flushing work). export function laneToLanes(lane: Lane): Lanes { return lane; } export function higherPriorityLane(a: Lane, b: Lane) { // This works because the bit ranges decrease in priority as you go left. return a !== NoLane && a < b ? a : b; } export function createLaneMap<T>(initial: T): LaneMap<T> { return new Array(TotalLanes).fill(initial); } export function markRootUpdated(root: FiberRoot, updateLane: Lane) { root.pendingLanes |= updateLane; // TODO: Theoretically, any update to any lane can unblock any other lane. But // it's not practical to try every single possible combination. We need a // heuristic to decide which lanes to attempt to render, and in which batches. // For now, we use the same heuristic as in the old ExpirationTimes model: // retry any lane at equal or lower priority, but don't try updates at higher // priority without also including the lower priority updates. This works well // when considering updates across different priority levels, but isn't // sufficient for updates within the same priority, since we want to treat // those updates as parallel. // Unsuspend any update at equal or lower priority. const higherPriorityLanes = updateLane - 1; // Turns 0b1000 into 0b0111 root.suspendedLanes &= higherPriorityLanes; root.pingedLanes &= higherPriorityLanes; } export function markRootSuspended(root: FiberRoot, suspendedLanes: Lanes) { root.suspendedLanes |= suspendedLanes; root.pingedLanes &= ~suspendedLanes; // The suspended lanes are no longer CPU-bound. Clear their expiration times. const expirationTimes = root.expirationTimes; let lanes = suspendedLanes; while (lanes > 0) { const index = pickArbitraryLaneIndex(lanes); const lane = 1 << index; expirationTimes[index] = NoTimestamp; lanes &= ~lane; } } export function markRootPinged( root: FiberRoot, pingedLanes: Lanes, eventTime: number, ) { root.pingedLanes |= root.suspendedLanes & pingedLanes; } export function markRootExpired(root: FiberRoot, expiredLanes: Lanes) { root.expiredLanes |= expiredLanes & root.pendingLanes; } export function markDiscreteUpdatesExpired(root: FiberRoot) { root.expiredLanes |= InputDiscreteLanes & root.pendingLanes; } export function hasDiscreteLanes(lanes: Lanes) { return (lanes & InputDiscreteLanes) !== NoLanes; } export function markRootMutableRead(root: FiberRoot, updateLane: Lane) { root.mutableReadLanes |= updateLane & root.pendingLanes; } export function markRootFinished(root: FiberRoot, remainingLanes: Lanes) { const noLongerPendingLanes = root.pendingLanes & ~remainingLanes; root.pendingLanes = remainingLanes; // Let's try everything again root.suspendedLanes = 0; root.pingedLanes = 0; root.expiredLanes &= remainingLanes; root.mutableReadLanes &= remainingLanes; root.entangledLanes &= remainingLanes; const expirationTimes = root.expirationTimes; let lanes = noLongerPendingLanes; while (lanes > 0) { const index = pickArbitraryLaneIndex(lanes); const lane = 1 << index; // Clear the expiration time expirationTimes[index] = -1; lanes &= ~lane; } } export function markRootEntangled(root: FiberRoot, entangledLanes: Lanes) { root.entangledLanes |= entangledLanes; const entanglements = root.entanglements; let lanes = entangledLanes; while (lanes > 0) { const index = pickArbitraryLaneIndex(lanes); const lane = 1 << index; entanglements[index] |= entangledLanes; lanes &= ~lane; } } export function getBumpedLaneForHydration( root: FiberRoot, renderLanes: Lanes, ): Lane { getHighestPriorityLanes(renderLanes); const highestLanePriority = return_highestLanePriority; let lane; switch (highestLanePriority) { case SyncLanePriority: case SyncBatchedLanePriority: lane = NoLane; break; case InputDiscreteHydrationLanePriority: case InputDiscreteLanePriority: lane = InputDiscreteHydrationLane; break; case InputContinuousHydrationLanePriority: case InputContinuousLanePriority: lane = InputContinuousHydrationLane; break; case DefaultHydrationLanePriority: case DefaultLanePriority: lane = DefaultHydrationLane; break; case TransitionShortHydrationLanePriority: case TransitionShortLanePriority: lane = TransitionShortHydrationLane; break; case TransitionLongHydrationLanePriority: case TransitionLongLanePriority: lane = TransitionLongHydrationLane; break; case SelectiveHydrationLanePriority: lane = SelectiveHydrationLane; break; case IdleHydrationLanePriority: case IdleLanePriority: lane = IdleHydrationLane; break; case OffscreenLanePriority: case NoLanePriority: lane = NoLane; break; default: invariant(false, 'Invalid lane: %s. This is a bug in React.', lane); } // Check if the lane we chose is suspended. If so, that indicates that we // already attempted and failed to hydrate at that level. Also check if we're // already rendering that lane, which is rare but could happen. if ((lane & (root.suspendedLanes | renderLanes)) !== NoLane) { // Give up trying to hydrate and fall back to client render. return NoLane; } return lane; } const clz32 = Math.clz32 ? Math.clz32 : clz32Fallback; // Count leading zeros. Only used on lanes, so assume input is an integer. // Based on: // https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Math/clz32 const log = Math.log; const LN2 = Math.LN2; function clz32Fallback(lanes: Lanes | Lane) { if (lanes === 0) { return 32; } return (31 - ((log(lanes) / LN2) | 0)) | 0; }
use NoTimestamp instead of -1 (#19182)
packages/react-reconciler/src/ReactFiberLane.js
use NoTimestamp instead of -1 (#19182)
<ide><path>ackages/react-reconciler/src/ReactFiberLane.js <ide> const lane = 1 << index; <ide> <ide> // Clear the expiration time <del> expirationTimes[index] = -1; <add> expirationTimes[index] = NoTimestamp; <ide> <ide> lanes &= ~lane; <ide> }
Java
apache-2.0
3b7bca90f2338cf3bffcce1ba2132c9e30f4511d
0
jack-luj/flyway,Muni10/flyway,jack-luj/flyway,chrsoo/flyway,nathanvick/flyway,flyway/flyway,IAops/flyway,CristianUrbainski/flyway,mpage23/flyway,fdefalco/flyway,livingobjects/flyway,michaelyaakoby/flyway,nathanvick/flyway,IAops/flyway,wuschi/flyway,FulcrumTechnologies/flyway,togusafish/lnial-_-flyway,murdos/flyway,jmahonin/flyway,ysobj/flyway,wuschi/flyway,nathanvick/flyway,pauxus/flyway,brennan-collins/flyway,kevinc0825/flyway,Muni10/flyway,kevinc0825/flyway,chrsoo/flyway,mpage23/flyway,krishofmans/flyway,brennan-collins/flyway,pauxus/flyway,FulcrumTechnologies/flyway,kevinc0825/flyway,livingobjects/flyway,togusafish/lnial-_-flyway,cdedie/flyway,pauxus/flyway,jmahonin/flyway,livingobjects/flyway,super132/flyway,mpage23/flyway,jack-luj/flyway,IAops/flyway,fdefalco/flyway,super132/flyway,michaelyaakoby/flyway,murdos/flyway,CristianUrbainski/flyway,wuschi/flyway,CristianUrbainski/flyway,cdedie/flyway,krishofmans/flyway,Muni10/flyway,krishofmans/flyway,murdos/flyway,chrsoo/flyway,flyway/flyway,Dispader/flyway,Dispader/flyway,FulcrumTechnologies/flyway,ysobj/flyway,togusafish/lnial-_-flyway,Dispader/flyway,fdefalco/flyway,super132/flyway,ysobj/flyway,pauxus/flyway,cdedie/flyway,brennan-collins/flyway,Muni10/flyway
/** * Copyright 2010-2013 Axel Fontaine and the many contributors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.googlecode.flyway.maven; import org.codehaus.classworlds.ClassRealm; import org.codehaus.plexus.component.configurator.AbstractComponentConfigurator; import org.codehaus.plexus.component.configurator.ComponentConfigurationException; import org.codehaus.plexus.component.configurator.ConfigurationListener; import org.codehaus.plexus.component.configurator.converters.composite.ObjectWithFieldsConverter; import org.codehaus.plexus.component.configurator.converters.special.ClassRealmConverter; import org.codehaus.plexus.component.configurator.expression.ExpressionEvaluationException; import org.codehaus.plexus.component.configurator.expression.ExpressionEvaluator; import org.codehaus.plexus.configuration.PlexusConfiguration; import java.io.File; import java.net.MalformedURLException; import java.net.URL; import java.util.ArrayList; import java.util.List; /** * A custom ComponentConfigurator which adds the project's runtime classpath elements to the plugin's classpath. * * @plexus.component role="org.codehaus.plexus.component.configurator.ComponentConfigurator" * role-hint="include-project-dependencies" * @plexus.requirement role="org.codehaus.plexus.component.configurator.converters.lookup.ConverterLookup" * role-hint="default" */ @SuppressWarnings({"JavaDoc", "UnusedDeclaration"}) public class IncludeProjectDependenciesComponentConfigurator extends AbstractComponentConfigurator { public void configureComponent(Object component, PlexusConfiguration configuration, ExpressionEvaluator expressionEvaluator, ClassRealm containerRealm, ConfigurationListener listener) throws ComponentConfigurationException { addProjectDependenciesToClassRealm(expressionEvaluator, containerRealm); ObjectWithFieldsConverter converter = new ObjectWithFieldsConverter(); converter.processConfiguration(converterLookup, component, containerRealm.getClassLoader(), configuration, expressionEvaluator, listener); } @SuppressWarnings({"unchecked"}) private void addProjectDependenciesToClassRealm(ExpressionEvaluator expressionEvaluator, ClassRealm containerRealm) throws ComponentConfigurationException { List<String> classpathElements; try { classpathElements = (List<String>) expressionEvaluator.evaluate("${project.testClasspathElements}"); } catch (ExpressionEvaluationException e) { throw new ComponentConfigurationException("There was a problem evaluating: ${project.testClasspathElements}", e); } // Add the project dependencies to the ClassRealm final URL[] urls = buildURLs(classpathElements); for (URL url : urls) { containerRealm.addConstituent(url); } } private URL[] buildURLs(List<String> classpathElements) throws ComponentConfigurationException { // Add the projects classes and dependencies List<URL> urls = new ArrayList<URL>(classpathElements.size()); for (String element : classpathElements) { try { final URL url = new File(element).toURI().toURL(); urls.add(url); } catch (MalformedURLException e) { throw new ComponentConfigurationException("Unable to access project dependency: " + element, e); } } // Add the plugin's dependencies (so Trove stuff works if Trove isn't on return urls.toArray(new URL[urls.size()]); } }
flyway-maven-plugin/src/main/java/com/googlecode/flyway/maven/IncludeProjectDependenciesComponentConfigurator.java
/** * Copyright 2010-2013 Axel Fontaine and the many contributors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.googlecode.flyway.maven; import org.codehaus.classworlds.ClassRealm; import org.codehaus.plexus.component.configurator.AbstractComponentConfigurator; import org.codehaus.plexus.component.configurator.ComponentConfigurationException; import org.codehaus.plexus.component.configurator.ConfigurationListener; import org.codehaus.plexus.component.configurator.converters.composite.ObjectWithFieldsConverter; import org.codehaus.plexus.component.configurator.converters.special.ClassRealmConverter; import org.codehaus.plexus.component.configurator.expression.ExpressionEvaluationException; import org.codehaus.plexus.component.configurator.expression.ExpressionEvaluator; import org.codehaus.plexus.configuration.PlexusConfiguration; import java.io.File; import java.net.MalformedURLException; import java.net.URL; import java.util.ArrayList; import java.util.List; /** * A custom ComponentConfigurator which adds the project's runtime classpath elements to the * * @plexus.component role="org.codehaus.plexus.component.configurator.ComponentConfigurator" * role-hint="include-project-dependencies" * @plexus.requirement role="org.codehaus.plexus.component.configurator.converters.lookup.ConverterLookup" * role-hint="default" */ @SuppressWarnings({"JavaDoc", "UnusedDeclaration"}) public class IncludeProjectDependenciesComponentConfigurator extends AbstractComponentConfigurator { public void configureComponent(Object component, PlexusConfiguration configuration, ExpressionEvaluator expressionEvaluator, ClassRealm containerRealm, ConfigurationListener listener) throws ComponentConfigurationException { addProjectDependenciesToClassRealm(expressionEvaluator, containerRealm); ObjectWithFieldsConverter converter = new ObjectWithFieldsConverter(); converter.processConfiguration(converterLookup, component, containerRealm.getClassLoader(), configuration, expressionEvaluator, listener); } @SuppressWarnings({"unchecked"}) private void addProjectDependenciesToClassRealm(ExpressionEvaluator expressionEvaluator, ClassRealm containerRealm) throws ComponentConfigurationException { List<String> classpathElements; try { classpathElements = (List<String>) expressionEvaluator.evaluate("${project.testClasspathElements}"); } catch (ExpressionEvaluationException e) { throw new ComponentConfigurationException("There was a problem evaluating: ${project.testClasspathElements}", e); } // Add the project dependencies to the ClassRealm final URL[] urls = buildURLs(classpathElements); for (URL url : urls) { containerRealm.addConstituent(url); } } private URL[] buildURLs(List<String> classpathElements) throws ComponentConfigurationException { // Add the projects classes and dependencies List<URL> urls = new ArrayList<URL>(classpathElements.size()); for (String element : classpathElements) { try { final URL url = new File(element).toURI().toURL(); urls.add(url); } catch (MalformedURLException e) { throw new ComponentConfigurationException("Unable to access project dependency: " + element, e); } } // Add the plugin's dependencies (so Trove stuff works if Trove isn't on return urls.toArray(new URL[urls.size()]); } }
Fixed missing Javadoc
flyway-maven-plugin/src/main/java/com/googlecode/flyway/maven/IncludeProjectDependenciesComponentConfigurator.java
Fixed missing Javadoc
<ide><path>lyway-maven-plugin/src/main/java/com/googlecode/flyway/maven/IncludeProjectDependenciesComponentConfigurator.java <ide> import java.util.List; <ide> <ide> /** <del> * A custom ComponentConfigurator which adds the project's runtime classpath elements to the <add> * A custom ComponentConfigurator which adds the project's runtime classpath elements to the plugin's classpath. <ide> * <ide> * @plexus.component role="org.codehaus.plexus.component.configurator.ComponentConfigurator" <ide> * role-hint="include-project-dependencies"