code
stringlengths
1
2.01M
repo_name
stringlengths
3
62
path
stringlengths
1
267
language
stringclasses
231 values
license
stringclasses
13 values
size
int64
1
2.01M
// Sage Android Client. // Connect to a Sage server, remotely execute commands and display results. // // Copyright (C) 2010, Harald Schilly <harald.schilly@gmail.com> // // This program is free software: you can redistribute it and/or modify // it under the terms of the GNU General Public License as published by // the Free Software Foundation, either version 3 of the License, or // (at your option) any later version. // // This program is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // // You should have received a copy of the GNU General Public License // along with this program. If not, see <http://www.gnu.org/licenses/>. package org.sagemath.android; import org.apache.http.Header; import org.apache.http.HttpEntity; import org.apache.http.HttpResponse; import org.apache.http.NameValuePair; import org.apache.http.client.HttpClient; import org.apache.http.client.entity.UrlEncodedFormEntity; import org.apache.http.client.methods.HttpGet; import org.apache.http.client.methods.HttpPost; import org.apache.http.impl.client.DefaultHttpClient; import org.apache.http.message.BasicNameValuePair; import org.json.JSONObject; import android.app.Notification; import android.app.NotificationManager; import android.app.PendingIntent; import android.app.Service; import android.content.Context; import android.content.Intent; import android.net.Uri; import android.os.IBinder; import android.os.RemoteException; import android.util.Log; import java.io.BufferedReader; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import java.util.ArrayList; import java.util.Iterator; import java.util.List; import java.util.Timer; import java.util.TimerTask; import java.util.concurrent.CountDownLatch; import java.util.concurrent.LinkedBlockingQueue; import java.util.concurrent.atomic.AtomicBoolean; import java.util.concurrent.atomic.AtomicReference; /** * This is our background service to keep a connection with a Sage server. It is * designed to connect to <b>one</b> server with given credentials, or if there * are non, does not connect. If keepAlive is true, it tries to reconnect if the * connection is broken. After a certain time of inactivity it assumes that it * is no longer needed and disconnects. * * @author Harald Schilly */ final public class SageConnection extends Service { final static String TAG = SageConnection.class.getSimpleName(); public final static int DISCONNECTED = 0, CONNECTING = 1, CONNECTED = 2; private int status = SageConnection.DISCONNECTED; private Timer timerCalc, timerConn; private boolean keepAlive = true; private boolean showNotification = false; private List<CalculationListener> calcListeners = new ArrayList<CalculationListener>(2); private ConnectionListener connListener = null; private CountDownLatch countdown = null; private boolean killMeIsScheduled = false; // connection credentials private Server server = null; // TODO once the api and interface is settled, we switch to a longer // queue where all commands are executed in given order. beware, all // interacts need to behave nicely and skip commands if a calculation // is currently running. /** * work queue, restricted to size 1 for now ... so there is only 0 or 1 * {@link Work} object in the queue. */ final private LinkedBlockingQueue<Calculation> work = new LinkedBlockingQueue<Calculation>(1); final private AtomicBoolean calcRunning = new AtomicBoolean(false); public SageConnection() { super(); startConnection(); } /** * This task is repeated by the timer and checks if the connection to the Sage * server is still alive. */ final private TimerTask checkConnectedTask = new TimerTask() { @Override final public void run() { // TODO this task should not take longer than 10 secs. try { Thread.sleep(1000); } catch (InterruptedException e) { Thread.currentThread().interrupt(); } status = (int) (Math.random() * 3); updateConnectonListener(status); } }; /** * This task is started once and runs forever until it is interrupted. It * blocks on the {@link work} queue and waits for new {@link Work} objects to * submit to the Sage server. TODO Some intelligence when there is no * connection. */ final private TimerTask calculationTask = new TimerTask() { private Calculation c; @Override final public void run() { while (true) { try { c = work.take(); } catch (InterruptedException e1) { Log.w(TAG, "Calculation Task interrupted!"); Thread.currentThread().interrupt(); return; } // blocking set calc flag to true before starting calculation calcRunning.set(true); // bogus calculation try { Thread.sleep(500 + (long) (Math.random() * 500.0)); } catch (InterruptedException e) { calcRunning.set(false); Thread.currentThread().interrupt(); return; } int i; try { i = 2 * Integer.parseInt(c.getCode()); } catch (NumberFormatException nfe) { i = 42; } c.setResult(Integer.toString(i)); // end bogus calculation // after calculation, set calc flag to false calcRunning.set(false); // if not null, killMe wants me to count down. if (countdown != null) { countdown.countDown(); } // notify listeners updateListenersResult(c); showNotification(c.getElapsed() + " " + c.getResult()); } } }; /** * This is called when the service is about to shut down or is not needed any * more. It checks if there is still some work to do and waits for it to * finish. */ final private TimerTask killMe = new TimerTask() { @Override final public void run() { killMeIsScheduled = true; // TODO wait for calculation to finish try { while (work.size() > 0 && calcRunning.get()) { // TODO that's not correct, because we will not get the remaining // calculations countdown = new CountDownLatch(1); countdown.await(); } } catch (InterruptedException ex) { Thread.currentThread().interrupt(); } finally { Log.i(TAG, "stopSelf called by killMe TimerTask"); stopSelf(); } } }; /** * used for reading the content of HTTP responses */ final private StringBuilder calcSb = new StringBuilder(); /** * This stores the session ID. If null, we do not have a session. */ final private AtomicReference<String> sessionID = new AtomicReference<String>(); /** * Communicate with the Sage server. This contains the HTTP communication and * parsing of the returned data. * * @throws CalculationException */ final private String doCalculation(String input) throws CalculationException { String answer = "<error>"; if (sessionID.equals(null)) { // we don't have a session sessionID.set(doEstablishSession()); } // HTTP GET String queryCalc = server + "/simple/compute?" + "session=" + sessionID.get() + "&code=" + Uri.encode(input); // for more read doEstablishSession() // HTTP POST Example HttpClient httpclient = new DefaultHttpClient(); try { HttpPost httpPost = new HttpPost(server + "/simple/compute"); // POST Payload List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(2); nameValuePairs.add(new BasicNameValuePair("session", sessionID.get())); nameValuePairs.add(new BasicNameValuePair("code", input)); httpPost.setEntity(new UrlEncodedFormEntity(nameValuePairs)); // Send to server HttpResponse response = httpclient.execute(httpPost); int status = response.getStatusLine().getStatusCode(); if (status != 200) { // 200 is HTTP OK } // headers, i.e. check if Sage actually did something, eventually retry to // fetch the calculation later, ... Header[] sageStatus = response.getHeaders("SAGE-STATUS"); String sageStatusValue = sageStatus[0].getValue(); // response content, here should be the actual answer answer = readContent(response); } catch (Exception ex) { // TODO: explain what has happened and properly handle exception throw new CalculationException("unable to do a calculation"); } finally { // TODO I think it should be possible to reuse the httpclient object ... httpclient.getConnectionManager().shutdown(); } return answer; } /** * Helper to read the HTTP content of a response and return it as a String * * @throws IOException */ private String readContent(HttpResponse response) throws IOException { HttpEntity entity = response.getEntity(); InputStream in = entity.getContent(); // The following just copies the content into the StringBuilder BufferedReader reader = new BufferedReader(new InputStreamReader(in)); calcSb.setLength(0); for (String line; (line = reader.readLine()) != null;) { calcSb.append(line + "\n"); // TODO get system specific newline } in.close(); return calcSb.toString(); } /** * Communicate with the Sage to establish a session. * * @return if true, a session has been established * @throws CalculationException */ final private String doEstablishSession() throws CalculationException { if (server == null) { throw new CalculationException("unable to establish a session"); } HttpClient httpclient = new DefaultHttpClient(); try { // HTTP GET String querySession = server + "/simple/login?username=" + server.username + "&password=" + server.password; HttpGet httpget = new HttpGet(querySession); HttpResponse response = httpclient.execute(httpget); String answer = readContent(response); String[] data = answer.split("___S_A_G_E___"); JSONObject json = new JSONObject(data[0]); return json.getString("session"); } catch (Exception ex) { // TODO: explain what has happened and properly handle exception throw new CalculationException("unable to establish a session"); } finally { // TODO I think it should be possible to reuse the httpclient object ... httpclient.getConnectionManager().shutdown(); } } /** * Defines a mapping of what to do when a client issues an action or requests * a calculation. */ final private CalculationAPI.Stub apiEndpoint = new CalculationAPI.Stub() { @Override final public void addCalcListener(CalculationListener listener) throws RemoteException { synchronized (calcListeners) { calcListeners.add(listener); } } @Override final public void removeCalcListener(CalculationListener listener) throws RemoteException { synchronized (calcListeners) { calcListeners.remove(listener); } } @Override final public void addConnListener(ConnectionListener l) throws RemoteException { connListener = l; } @Override final public void removeConnListener(ConnectionListener l) throws RemoteException { connListener = null; } @Override final public void stopService() throws RemoteException { killConnection(); stopSelf(); } @Override final public void killConnection() throws RemoteException { killConnection(); } @Override final public int getStatus() throws RemoteException { return status; } @Override final public void setServer(Server server) throws RemoteException { SageConnection.this.server = server; } @Override final public boolean getKeepAlive() throws RemoteException { return keepAlive; } @Override final public void setKeepAlive(boolean keepAlive) throws RemoteException { SageConnection.this.keepAlive = keepAlive; } /** * background service API hook to start and enqueue a new * {@link Calculation} * * @return the unique ID of the new Calculation */ @Override final public int calculate(String code) throws RemoteException { Calculation c = new Calculation(); c.setCode(code); c.setStartTime(System.currentTimeMillis()); boolean added = false; while (!added) { added = work.offer(c); if (!added) { work.clear(); } } return c.getId(); } @Override final public boolean isCalculationRunning() throws RemoteException { return calcRunning.get(); } @Override final public void clearQueue() throws RemoteException { work.clear(); } @Override final public int getQueueSize() throws RemoteException { return work.size(); } @Override final public void setShowNotification(boolean b) throws RemoteException { showNotification = b; } }; /** * Tell listeners about the connection * * @param b */ final private void updateConnectonListener(int s) { synchronized (connListener) { if (connListener != null) { try { connListener.handleConnectionState(s); } catch (RemoteException e) { Log.w(TAG, "Failed to notify listener about ConnectionState: " + s, e); // TODO I'm no longer needed, except there is a calculation running // make sure that it is only called once (we are synchronized in here) if (!killMeIsScheduled) { timerConn.schedule(killMe, 0); } } } } } /** * Tell listeners about a result, which is stored in the {@link Calculation} * object. * * @param c */ final private void updateListenersResult(Calculation c) { synchronized (calcListeners) { for (Iterator<CalculationListener> li = calcListeners.iterator(); li.hasNext();) { CalculationListener l = li.next(); try { if (l.handleCalculationResult(c)) { return; // true means calculation was consumed } } catch (RemoteException e) { Log.i(TAG, "Failed to notify listener " + l + " - removing", e); li.remove(); } } } } /** * Establish a new connection. * <ol> * <li>check if we have credentials (otherwise send something back to client * ... NYI)</li> * <li>get a session key and store it locally. each subsequent request needs * it</li> * <li>start a periodic async task to check if the connection is still alive</li> * <li>tell the calculation task that it can start doing work</li> * </ol> */ final private void startConnection() { // TODO start actual connection timerCalc = new Timer("Calculation"); timerCalc.schedule(calculationTask, 0); timerConn = new Timer("Connection"); // check connection every 10 secs, with a delay of 1 sec. // it is NOT fixed rate which means that the starting time does not // depend on the execution time. // TODO set this to 30 secs timerConn.schedule(checkConnectedTask, 1000, 1 * 1000); } /** * Kill connection, especially tell Sage goodbye and to kill its current * session and session key. */ final private void killConnection() { // if connection exists, kill it if (timerCalc != null) { calculationTask.cancel(); timerCalc.cancel(); timerCalc = null; } if (timerConn != null) { checkConnectedTask.cancel(); timerConn.cancel(); timerConn = null; } } /** * Server/Client binding mechanism, check if we are really called on the * correct intent. */ @Override final public IBinder onBind(Intent intent) { if (SageConnection.class.getName().equals(intent.getAction())) { return apiEndpoint; } else { return null; } } /** * */ @Override final public void onCreate() { super.onCreate(); // TODO some kind of reset? } /** * */ @Override final public void onDestroy() { super.onDestroy(); killConnection(); } /** * ID for the notification, unique in application service */ final private static int HELLO_ID = 10781; /** * the idea is to show a notification in androids main UI's * notification bar when the main app is currently closed. By clicking on the * notification the main UI is launched again and should show the result. */ final private void showNotification(String result) { if (!showNotification) { return; } // get system's notification manager String ns = Context.NOTIFICATION_SERVICE; NotificationManager mNotificationManager = (NotificationManager) getSystemService(ns); // what to show in the bar int icon = R.drawable.notification_icon; CharSequence tickerText = "Sage finished."; long when = System.currentTimeMillis(); Notification notification = new Notification(icon, tickerText, when); // cancel it after selecting notification.flags |= Notification.FLAG_AUTO_CANCEL; // notification content itself + intent for launching the main app Context context = getApplicationContext(); CharSequence contentTitle = "Sage Calculation finished."; String part = result.substring(0, Math.min(result.length(), 30)) + "..."; CharSequence contentText = "Result: " + part; Intent notificationIntent = new Intent(this, SageAndroid.class); // TODO somehow store an ID which interact should show the result. this // should probably be part of the original calculation. notificationIntent.putExtra("target", 0); PendingIntent contentIntent = PendingIntent.getActivity(this, 0, notificationIntent, 0); notification.setLatestEventInfo(context, contentTitle, contentText, contentIntent); // show it mNotificationManager.notify(HELLO_ID, notification); } } /** * A CalculationException describes the problem of a failed calculation. */ @SuppressWarnings("serial") final class CalculationException extends Exception { private Calculation c; public CalculationException(String msg) { super(msg); } /** * Creates a new CalculationException and attaches the {@link Calculation} c * to it. * * @param msg * @param c */ public CalculationException(String msg, Calculation c) { super(msg); this.c = c; } final Calculation getCalculation() { return c; } }
12085952-sageandroid
app-v1/src/org/sagemath/android/SageConnection.java
Java
gpl3
19,057
// Sage Android Client. // Connect to a Sage server, remotely execute commands and display results. // // Copyright (C) 2010, Harald Schilly <harald.schilly@gmail.com> // // This program is free software: you can redistribute it and/or modify // it under the terms of the GNU General Public License as published by // the Free Software Foundation, either version 3 of the License, or // (at your option) any later version. // // This program is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // // You should have received a copy of the GNU General Public License // along with this program. If not, see <http://www.gnu.org/licenses/>. package org.sagemath.android; import org.sagemath.android.interacts.AbstractInteract; import org.sagemath.android.interacts.ExecuteCommand; import org.sagemath.android.interacts.Plot; import org.sagemath.android.interacts.SliderTest2; import android.app.Activity; import android.app.AlertDialog; import android.app.ProgressDialog; import android.content.ComponentName; import android.content.Context; import android.content.DialogInterface; import android.content.Intent; import android.content.ServiceConnection; import android.graphics.Color; import android.os.Bundle; import android.os.Handler; import android.os.IBinder; import android.os.Message; import android.os.RemoteException; import android.util.Log; import android.view.GestureDetector; import android.view.LayoutInflater; import android.view.Menu; import android.view.MenuInflater; import android.view.MenuItem; import android.view.MotionEvent; import android.view.View; import android.view.Window; import android.view.GestureDetector.OnGestureListener; import android.view.View.OnClickListener; import android.view.animation.Animation; import android.view.animation.AnimationUtils; import android.widget.AdapterView; import android.widget.ArrayAdapter; import android.widget.Button; import android.widget.EditText; import android.widget.Spinner; import android.widget.TextView; import android.widget.Toast; import android.widget.ViewFlipper; import android.widget.AdapterView.OnItemSelectedListener; import java.util.ArrayList; import java.util.HashMap; import java.util.Map; /** * Main Activity of the Sage Android application. * * @author Harald Schilly */ final public class SageAndroid extends Activity implements OnGestureListener { private static final int UI_STATE = 0; private static final int UI_OUTPUT = 1; @SuppressWarnings("unused") private static final int[] CONN_COL = new int[] { Color.RED, Color.YELLOW, Color.GREEN }; private LayoutInflater layoutInflater = null; TextView output = null; // , status = null; ViewFlipper vf = null; Animation inLeft, inRight, outLeft, outRight, fadeIn, fadeOut; // we talk with the sage connection service through its API private CalculationAPI api = null; /** * returns the CalculationAPI for the service (could be null) * * @return */ final public CalculationAPI getCalculationAPI() { return api; } final public Context getContext() { return SageAndroid.this; } private GestureDetector gestureDetector; // TODO remove it, just for development mockup private int stored_i = -1; private EditText txtFx; private AbstractInteract currentInteract = null; /** * Starting point of the whole Application: * <ol> * <li>We define an instance of {@link Global} and inject dependencies.</li> * <li>Start a background Service to handle the connection with Sage, i.e. * poll to keep it alive and wait for results. Details will depend on Sage's * Server API. From the perspective of this application, everything is done * via calls to the {@link CalculationAPI} and callbacks via * {@link CalculationListener}. UI updates happen in the local Handler.</li> * <li>There is a collection of "Interacts" to query the server in a certain * way. This is still unclear ...</li> * </ol> */ @Override final public void onCreate(Bundle icicle) { super.onCreate(icicle); requestWindowFeature(Window.FEATURE_RIGHT_ICON); setContentView(R.layout.main); // store a reference to me globally, a bit hackish Global.setContext(this); // call the background service, we can call this as often as we want // the intent must match the intent-filter in the manifest Intent intent = new Intent(SageConnection.class.getName()); startService(intent); // the connection service does the wiring bindService(intent, sageConnnectionService, Context.BIND_AUTO_CREATE); // dynamic titlebar updateTitlebar(SageConnection.DISCONNECTED, ""); // locally store the ui objects output = (TextView) findViewById(R.id.output); // status = (TextView) findViewById(R.id.status); vf = (ViewFlipper) findViewById(R.id.MainVF); // load the animations inLeft = AnimationUtils.makeInAnimation(this, true); inRight = AnimationUtils.makeInAnimation(this, false); outLeft = AnimationUtils.makeOutAnimation(this, false); outRight = AnimationUtils.makeOutAnimation(this, true); fadeOut = AnimationUtils.loadAnimation(this, R.anim.fade_out); fadeOut = AnimationUtils.loadAnimation(this, R.anim.fade_in); // registers the gesture detector with this view and ourself since we also // listen gestureDetector = new GestureDetector(this, this); layoutInflater = LayoutInflater.from(SageAndroid.this); Button testing = (Button) findViewById(R.id.btnTest); testing.setOnClickListener(new OnClickListener() { @Override public void onClick(View v) { try { api.setServer(new Server("http://www.bogusserver.org/", "admin", "password")); stored_i++; api.calculate(Long.toString(stored_i)); } catch (RemoteException re) { output.setText("calculate remote exeception: \n" + re); } } }); txtFx = (EditText) findViewById(R.id.txtFxTest); Button btnFxTest = (Button) findViewById(R.id.btnFxTest); btnFxTest.setOnClickListener(new OnClickListener() { @Override public void onClick(View v) { Intent intent = new Intent(SageAndroid.this, org.sagemath.android.fx.FunctionEditor.class); intent.putExtra("func", txtFx.getText().toString()); intent.putExtra("start", txtFx.getSelectionStart()); intent.putExtra("end", txtFx.getSelectionEnd()); startActivityForResult(intent, Global.FUNC_EDIT); } }); } /** * Listen to results from a started FunctionEditor activity. */ @Override final protected void onActivityResult(int requestCode, int resultCode, Intent data) { // See which child activity is calling us back. switch (requestCode) { case Global.FUNC_EDIT: if (resultCode == RESULT_OK) { Bundle bundle = data.getBundleExtra("data"); String func = bundle.getString("func"); Log.d(Global.TAG, "func = " + func); txtFx.setText(func); txtFx.setSelection(bundle.getInt("start"), bundle.getInt("end")); txtFx.requestFocus(); } default: break; } } /** * Helper * * @see wireButton */ final private void registerInteracts() { wireButton(R.id.btnActCmd, ExecuteCommand.class); wireButton(R.id.btnSlider, SliderTest2.class); wireButton(R.id.btnPlotInteract, Plot.class); wireButton(R.id.btnSystem, org.sagemath.android.interacts.System.class); } final private Map<Class<? extends AbstractInteract>, AbstractInteract> interactCache = new HashMap<Class<? extends AbstractInteract>, AbstractInteract>(); /** * Helper to wire buttons with interact views. * * @param id * @param interactView */ final private void wireButton(final int id, final Class<? extends AbstractInteract> clsInteract) { // we only accept classes that extend the {@link AbstractInteract} abstract // class and when the button is pressed, we either use a cached object or // instantiate a new one. // this postpones the instantiation as long as possible and when opening the // same interact again the current state is preserved. ((Button) findViewById(id)).setOnClickListener(new OnClickListener() { @Override public void onClick(View v) { AbstractInteract interact = null; if (!interactCache.containsKey(clsInteract)) { try { interact = clsInteract.newInstance(); interactCache.put(clsInteract, interact); } catch (Exception ex) { Log.d(Global.TAG, ex.getLocalizedMessage(), ex); } } else { interact = interactCache.get(clsInteract); interact.reset(); } interact.addCalcListener(); showVF(interact); } }); } /** * Helper to update the Titlebar. */ final private void updateTitlebar(int status, String text) { // fyi, for more customization we need our own titlebar, that's possible setTitle(getString(R.string.app_name) + " " + text); // setTitleColor(CONN_COL[status]); switch (status) { case SageConnection.DISCONNECTED: setFeatureDrawableResource(Window.FEATURE_RIGHT_ICON, R.drawable.icon_conn_0); break; case SageConnection.CONNECTING: setFeatureDrawableResource(Window.FEATURE_RIGHT_ICON, R.drawable.icon_conn_1); break; case SageConnection.CONNECTED: setFeatureDrawableResource(Window.FEATURE_RIGHT_ICON, R.drawable.icon_conn_2); break; default: Toast.makeText(this, "Unknown State " + status, Toast.LENGTH_SHORT).show(); } } /** * for the button's onClick, to show the view * * @param v */ final private void showVF(AbstractInteract ai) { vf.setInAnimation(fadeIn); vf.setOutAnimation(fadeOut); if (currentInteract != null) { currentInteract.removeCalcListener(); } currentInteract = ai; // make sure that there is only the main view for (int cc; (cc = vf.getChildCount()) >= 2;) { // TODO unregister calculation listener vf.removeViewAt(cc - 1); } // add the interact and show it vf.addView(ai.getView()); vf.showNext(); } /** * called when application is restored - that's not persistence! */ @Override final protected void onRestoreInstanceState(Bundle icicle) { stored_i = icicle.getInt("i", 0); } /** * called when application should save it's current state - that's not * persistence! */ @Override final protected void onSaveInstanceState(Bundle icicle) { icicle.putInt("i", stored_i); } /** * Android lifecycle, we are back to front after a short break. */ @Override final protected void onResume() { super.onResume(); try { if (api != null) { // tell the service that we will see results on the screen api.setShowNotification(false); } } catch (RemoteException ex) { } } /** * Android lifecycle, we are currently hidden behind another window. */ @Override final protected void onPause() { super.onPause(); try { // tell the service to show notifications in the top bar if (api != null) { api.setShowNotification(true); } } catch (RemoteException ex) { } } /** * Android OS destroys us */ @Override final protected void onDestroy() { super.onDestroy(); try { if (api != null) { api.setShowNotification(true); api.removeCalcListener(calcListener); } unbindService(sageConnnectionService); } catch (Throwable t) { // catch any issues, typical for destroy routines // even if we failed to destroy something, we need to continue // destroying Log.w(Global.TAG, "Failed to unbind from the service", t); } Log.i(Global.TAG, "onDestroy()"); } /** * this is called when the service is connected or disconnected. * we create the api interface here which is used to communicate with * the service. */ final private ServiceConnection sageConnnectionService = new ServiceConnection() { @Override final public void onServiceConnected(ComponentName name, IBinder service) { // that's how we get the client side of the IPC connection api = CalculationAPI.Stub.asInterface(service); Global.setCalculationAPI(api); try { api.setShowNotification(false); api.addConnListener(connListener); api.addCalcListener(calcListener); // TODO remove this below // vf.removeViewAt(vf.getChildCount() - 1); // vf.addView(interacts.getSliderTest()); } catch (RemoteException e) { Log.e(Global.TAG, "Failed to add listener", e); } Log.i(Global.TAG, "Service connection established"); registerInteracts(); } @Override final public void onServiceDisconnected(ComponentName name) { Log.i(Global.TAG, "Service connection closed: " + name.toShortString()); api = null; Global.setCalculationAPI(null); } }; /** * our little helper to update the ui via messages when updates happen on * other threads. it is bound to this thread and used for callbacks from the * service to the main application. */ final private Handler handler = new Handler() { @Override public void handleMessage(Message msg) { msg.getData().getBoolean("status"); switch (msg.what) { case UI_STATE: updateTitlebar((Integer) msg.obj, ""); break; case UI_OUTPUT: output.setText("RECV: " + msg.obj); break; default: super.handleMessage(msg); } } }; /** * this is called by the remote service to tell us about the calculation * result by giving us back the {@link Calculation} object with hopefully * some content in the result field. */ final private CalculationListener.Stub calcListener = new CalculationListener.Stub() { @Override final public boolean handleCalculationResult(Calculation cr) throws RemoteException { handler.sendMessage(handler.obtainMessage(UI_OUTPUT, cr.getResult())); // false means that other listeners should also be informed about this return false; } }; /** * this is called by the remote service to tell us about the connection * state. */ final private ConnectionListener.Stub connListener = new ConnectionListener.Stub() { @Override final public void handleConnectionState(int i) throws RemoteException { handler.sendMessage(handler.obtainMessage(UI_STATE, i)); } }; /** * This is part of the App lifecycle. It is called when the OS wants to get * rid of us. Make the transient data persistent now! */ @Override final protected void onStop() { super.onStop(); Global.saveSettings(); } /** * This is called when the dedicated back button is pressed. */ @Override final public void onBackPressed() { flipViewFlipper(Global.FLIP); } /** * This either displays the last interact again (if there is a * current one) or just goes back to the main view in the view * flipper. */ final private void flipViewFlipper(final int dir) { // check if there is something to show if (currentInteract != null) { // child 0 is main view if (vf.getDisplayedChild() == 0) { if (dir == Global.FLIP || dir == Global.RIGHT) { vf.setInAnimation(inRight); vf.setOutAnimation(outLeft); vf.setDisplayedChild(1); } } else { // case when interact is currently displayed if (dir == Global.FLIP || dir == Global.LEFT) { vf.setInAnimation(inLeft); vf.setOutAnimation(outRight); vf.setDisplayedChild(0); } } } } /** * This is called when we press the menu button on the device. * * @see res/menu/main_menu.xml */ @Override final public boolean onCreateOptionsMenu(Menu menu) { MenuInflater inflater = getMenuInflater(); inflater.inflate(R.menu.main_menu, menu); return true; } /** * This is called a button in the options menu is pressed. * This works when showing the main menu and when showing * an interact. The "id" is used to identify the selection. */ @Override final public boolean onOptionsItemSelected(MenuItem item) { switch (item.getItemId()) { case R.id.MenuSettingsDialog: showSettingsDialog(); return true; case R.id.MenuQuit: this.finish(); return true; default: return super.onOptionsItemSelected(item); } } /** * called via the menu to show the settings dialog */ final private void showSettingsDialog() { // TODO encapsulate this in it's own class. final View textEntryView = layoutInflater.inflate(R.layout.settings_dialog, null); final AlertDialog dlg = new AlertDialog.Builder(SageAndroid.this) .setTitle("Server Credentials").setView(textEntryView) .setPositiveButton("Connect", new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int whichButton) { Toast.makeText(SageAndroid.this, "Connect ...", Toast.LENGTH_LONG).show(); AlertDialog d = (AlertDialog) dialog; EditText pe = (EditText) d.findViewById(R.id.PasswordEdit); EditText ue = (EditText) d.findViewById(R.id.UsernameEdit); EditText se = (EditText) d.findViewById(R.id.ServerEdit); Server s = new Server(se.getText().toString(), ue.getText().toString(), pe.getText() .toString()); Global.setServer(s); Global.saveSettings(); } }) .setNeutralButton("Test", new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int whichButton) { // dialog.dismiss(); ProgressDialog pd = new ProgressDialog(getContext(), ProgressDialog.STYLE_SPINNER); pd.setMessage("Connecting..."); pd.setButton(ProgressDialog.BUTTON_NEGATIVE, "Cancel", new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { dialog.dismiss(); } }); pd.show(); } }) .setNegativeButton("Delete", new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialogMain, int whichButton) { final AlertDialog confirmDelete = new AlertDialog.Builder(getContext()) // .setIcon(android.R.drawable.ic_dialog_alert) // .setTitle("Confirm Delete") // .setMessage("Really delete " + Global.getServer().server) // .setPositiveButton("Yes", new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { Global.servers.remove(Global.getServer()); } }) // .setNegativeButton("No", null).show(); } }).create(); dlg.show(); // ~~~ Set User/Password EditText ue = (EditText) dlg.findViewById(R.id.UsernameEdit); ue.setText(Global.getUser()); EditText pe = (EditText) dlg.findViewById(R.id.PasswordEdit); pe.setText(Global.getPassword()); // ~~~ start Server Spinner final Spinner serverSpinner = (Spinner) dlg.findViewById(R.id.ServerSpinner); final ArrayList<Server> serverList = new ArrayList<Server>(Global.servers); final ArrayAdapter<Server> adapter = new ArrayAdapter<Server>(this, android.R.layout.simple_spinner_item, serverList); adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item); serverSpinner.setAdapter(adapter); if (Global.getServer() != null) { int selidx = -1; for (int i = 0; i < adapter.getCount(); i++) { if (Global.getServer().equals(adapter.getItem(i))) { selidx = i; break; } } if (selidx < 0) { adapter.add(Global.getServer()); serverSpinner.setSelection(adapter.getCount()); } else { serverSpinner.setSelection(selidx); } } serverSpinner.setOnItemSelectedListener(new OnItemSelectedListener() { @Override final public void onItemSelected(AdapterView<?> arg0, View arg1, int position, long arg3) { final Server s = serverList.get(position); Global.setServer(s); EditText se = (EditText) dlg.findViewById(R.id.ServerEdit); se.setText(s.server); } @Override final public void onNothingSelected(AdapterView<?> arg0) { } }); // ~~~~ end Server Spinner } // ~~~~ Touch Event business for the OnGestureListener ~~~~ @Override final public boolean onTouchEvent(MotionEvent event) { return gestureDetector.onTouchEvent(event); } @Override final public boolean onDown(MotionEvent e) { return false; } @Override final public boolean onFling(MotionEvent arg0, MotionEvent arg1, float dx, float dy) { // info: dx/dy is measured in pixel/second. that's not a distance. // silly threshold if (Math.hypot(dx, dy) > 100) { if (dx > 200 && Math.abs(dy) < 50) { // right flipViewFlipper(Global.RIGHT); } if (dx < -200 && Math.abs(dy) < 50) { // left flipViewFlipper(Global.LEFT); } } return true; } @Override final public void onLongPress(MotionEvent arg0) { } @Override final public boolean onScroll(MotionEvent arg0, MotionEvent arg1, float arg2, float arg3) { return false; } @Override final public void onShowPress(MotionEvent arg0) { } @Override final public boolean onSingleTapUp(MotionEvent arg0) { return false; } }
12085952-sageandroid
app-v1/src/org/sagemath/android/SageAndroid.java
Java
gpl3
22,638
/** * Copyright (C) 2011, Karsten Priegnitz * * Permission to use, copy, modify, and distribute this piece of software * for any purpose with or without fee is hereby granted, provided that * the above copyright notice and this permission notice appear in the * source code of all copies. * * It would be appreciated if you mention the author in your change log, * contributors list or the like. * * @author: Karsten Priegnitz * @see: http://code.google.com/p/android-change-log/ */ package sheetrock.panda.changelog; import java.io.BufferedReader; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import android.app.AlertDialog; import android.content.Context; import android.content.DialogInterface; import android.content.SharedPreferences; import android.content.pm.PackageManager.NameNotFoundException; import android.os.Build; import android.preference.PreferenceManager; import android.util.Log; import android.webkit.WebView; import org.sagemath.droid.R; public class ChangeLog { private final Context context; private String lastVersion, thisVersion; // this is the key for storing the version name in SharedPreferences private static final String VERSION_KEY = "PREFS_VERSION_KEY"; /** * Constructor * * Retrieves the version names and stores the new version name in * SharedPreferences * * @param context */ public ChangeLog(Context context) { this(context, PreferenceManager.getDefaultSharedPreferences(context)); } /** * Constructor * * Retrieves the version names and stores the new version name in * SharedPreferences * * @param context * @param sp the shared preferences to store the last version name into */ public ChangeLog(Context context, SharedPreferences sp) { this.context = context; // get version numbers this.lastVersion = sp.getString(VERSION_KEY, ""); Log.d(TAG, "lastVersion: " + lastVersion); try { this.thisVersion = context.getPackageManager().getPackageInfo( context.getPackageName(), 0).versionName; } catch (NameNotFoundException e) { this.thisVersion = "?"; Log.e(TAG, "could not get version name from manifest!"); e.printStackTrace(); } Log.d(TAG, "appVersion: " + this.thisVersion); // save new version number to preferences SharedPreferences.Editor editor = sp.edit(); editor.putString(VERSION_KEY, this.thisVersion); editor.commit(); } /** * @return The version name of the last installation of this app (as * described in the former manifest). This will be the same as * returned by <code>getThisVersion()</code> the second time * this version of the app is launched (more precisely: the * second time ChangeLog is instantiated). * @see AndroidManifest.xml#android:versionName */ public String getLastVersion() { return this.lastVersion; } /** * @return The version name of this app as described in the manifest. * @see AndroidManifest.xml#android:versionName */ public String getThisVersion() { return this.thisVersion; } /** * @return <code>true</code> if this version of your app is started the * first time */ public boolean firstRun() { return ! this.lastVersion.equals(this.thisVersion); } /** * @return <code>true</code> if your app is started the first time ever. * Also <code>true</code> if your app was deinstalled and * installed again. */ public boolean firstRunEver() { return "".equals(this.lastVersion); } /** * @return an AlertDialog displaying the changes since the previous * installed version of your app (what's new). */ public AlertDialog getLogDialog() { return this.getDialog(false); } /** * @return an AlertDialog with a full change log displayed */ public AlertDialog getFullLogDialog() { return this.getDialog(true); } private AlertDialog getDialog(boolean full) { WebView wv = new WebView(this.context); wv.setBackgroundColor(0); // transparent // wv.getSettings().setDefaultTextEncodingName("utf-8"); wv.loadDataWithBaseURL(null, this.getLog(full), "text/html", "UTF-8", null); AlertDialog.Builder builder; if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB) builder = new AlertDialog.Builder(this.context, AlertDialog.THEME_HOLO_DARK); else builder = new AlertDialog.Builder(this.context); builder.setTitle(context.getResources().getString(full ? R.string.changelog_full_title : R.string.changelog_title)) .setView(wv) .setCancelable(false) .setPositiveButton( context.getResources().getString( R.string.changelog_ok_button), new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int id) { dialog.cancel(); } }); return builder.create(); } /** * @return HTML displaying the changes since the previous * installed version of your app (what's new) */ public String getLog() { return this.getLog(false); } /** * @return HTML which displays full change log */ public String getFullLog() { return this.getLog(true); } /** modes for HTML-Lists (bullet, numbered) */ private enum Listmode { NONE, ORDERED, UNORDERED, }; private Listmode listMode = Listmode.NONE; private StringBuffer sb = null; private static final String EOCL = "END_OF_CHANGE_LOG"; private String getLog(boolean full) { // read changelog.txt file sb = new StringBuffer(); try { InputStream ins = context.getResources().openRawResource(R.raw.changelog); BufferedReader br = new BufferedReader(new InputStreamReader(ins)); String line = null; boolean advanceToEOVS = false; // if true: ignore further version sections while ((line = br.readLine()) != null) { line = line.trim(); char marker = line.length() > 0 ? line.charAt(0) : 0; if (marker == '$') { // begin of a version section this.closeList(); String version = line.substring(1).trim(); // stop output? if (! full) { if (this.lastVersion.equals(version)) { advanceToEOVS = true; } else if (version.equals(EOCL)) { advanceToEOVS = false; } } } else if (! advanceToEOVS) { switch (marker) { case '%': // line contains version title this.closeList(); sb.append("<div class='title'>" + line.substring(1).trim() + "</div>\n"); break; case '_': // line contains version title this.closeList(); sb.append("<div class='subtitle'>" + line.substring(1).trim() + "</div>\n"); break; case '!': // line contains free text this.closeList(); sb.append("<div class='freetext'>" + line.substring(1).trim() + "</div>\n"); break; case '#': // line contains numbered list item this.openList(Listmode.ORDERED); sb.append("<li>" + line.substring(1).trim() + "</li>\n"); break; case '*': // line contains bullet list item this.openList(Listmode.UNORDERED); sb.append("<li>" + line.substring(1).trim() + "</li>\n"); break; default: // no special character: just use line as is this.closeList(); sb.append(line + "\n"); } } } this.closeList(); br.close(); } catch (IOException e) { e.printStackTrace(); } return sb.toString(); } private void openList(Listmode listMode) { if (this.listMode != listMode) { closeList(); if (listMode == Listmode.ORDERED) { sb.append("<div class='list'><ol>\n"); } else if (listMode == Listmode.UNORDERED) { sb.append("<div class='list'><ul>\n"); } this.listMode = listMode; } } private void closeList() { if (this.listMode == Listmode.ORDERED) { sb.append("</ol></div>\n"); } else if (this.listMode == Listmode.UNORDERED) { sb.append("</ul></div>\n"); } this.listMode = Listmode.NONE; } private static final String TAG = "ChangeLog"; /** * manually set the last version name - for testing purposes only * @param lastVersion */ void setLastVersion(String lastVersion) { this.lastVersion = lastVersion; } }
12085952-sageandroid
app-v2/src/sheetrock/panda/changelog/ChangeLog.java
Java
gpl3
9,829
package org.sagemath.singlecellserver; import java.io.BufferedReader; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import java.net.URISyntaxException; import java.text.DateFormat; import java.util.LinkedList; import java.util.ListIterator; import java.util.Timer; import java.util.UUID; import org.apache.http.HttpEntity; import org.apache.http.HttpResponse; import org.apache.http.HttpStatus; import org.apache.http.StatusLine; import org.apache.http.client.ClientProtocolException; import org.apache.http.client.methods.HttpPost; import org.apache.http.entity.mime.HttpMultipartMode; import org.apache.http.entity.mime.MultipartEntity; import org.json.JSONArray; import org.json.JSONException; import org.json.JSONObject; import org.sagemath.singlecellserver.SageSingleCell.SageInterruptedException; import android.text.format.Time; import android.util.Log; public class CommandRequest extends Command { private static final String TAG = "CommandRequest"; long time = System.currentTimeMillis(); private int SLEEP_BEFORE_TRY = 20; private boolean error = false; public CommandRequest() { super(); } public CommandRequest(UUID session) { super(session); } public JSONObject toJSON() throws JSONException { JSONObject header = new JSONObject(); header.put("session", session.toString()); header.put("msg_id", msg_id.toString()); JSONObject result = new JSONObject(); result.put("header", header); return result; } protected void sendRequest(SageSingleCell.ServerTask server) { CommandReply reply; try { HttpResponse httpResponse = server.postEval(toJSON()); processInitialReply(httpResponse); return; } catch (JSONException e) { reply = new HttpError(this, e.getLocalizedMessage()); } catch (ClientProtocolException e) { reply = new HttpError(this, e.getLocalizedMessage()); } catch (IOException e) { reply = new HttpError(this, e.getLocalizedMessage()); } catch (SageInterruptedException e) { reply = new HttpError(this, "Interrupted on user request"); } error = true; server.addReply(reply); } public StatusLine processInitialReply(HttpResponse response) throws IllegalStateException, IOException, JSONException { InputStream outputStream = response.getEntity().getContent(); String output = SageSingleCell.streamToString(outputStream); outputStream.close(); System.out.println("output = " + output); JSONObject outputJSON = new JSONObject(output); if (outputJSON.has("session_id")) session = UUID.fromString(outputJSON.getString("session_id")); return response.getStatusLine(); } public void receiveReply(SageSingleCell.ServerTask server) { sendRequest(server); if (error) return; long timeEnd = System.currentTimeMillis() + server.timeout(); int count = 0; while (System.currentTimeMillis() < timeEnd) { count++; LinkedList<CommandReply> result = pollResult(server); // System.out.println("Poll got "+ result.size()); ListIterator<CommandReply> iter = result.listIterator(); while (iter.hasNext()) { CommandReply reply = iter.next(); timeEnd += reply.extendTimeOut(); server.addReply(reply); } if (error) return; if (!result.isEmpty() && (result.getLast().terminateServerConnection())) return; try { Thread.sleep(count*SLEEP_BEFORE_TRY); } catch (InterruptedException e) {} } error = true; server.addReply(new HttpError(this, "Timeout")); } private LinkedList<CommandReply> pollResult(SageSingleCell.ServerTask server) { LinkedList<CommandReply> result = new LinkedList<CommandReply>(); try { int sequence = server.result.size(); result.addAll(pollResult(server, sequence)); return result; } catch (JSONException e) { CommandReply reply = new HttpError(this, e.getLocalizedMessage()); result.add(reply); } catch (ClientProtocolException e) { CommandReply reply = new HttpError(this, e.getLocalizedMessage()); result.add(reply); } catch (IOException e) { CommandReply reply = new HttpError(this, e.getLocalizedMessage()); result.add(reply); } catch (URISyntaxException e) { CommandReply reply = new HttpError(this, e.getLocalizedMessage()); result.add(reply); } catch (SageInterruptedException e) { CommandReply reply = new HttpError(this, "Interrupted on user request"); result.add(reply); } error = true; return result; } private LinkedList<CommandReply> pollResult(SageSingleCell.ServerTask server, int sequence) throws JSONException, IOException, URISyntaxException, SageInterruptedException { LinkedList<CommandReply> result = new LinkedList<CommandReply>(); try { Thread.sleep(SLEEP_BEFORE_TRY); } catch (InterruptedException e) { Log.e(TAG, e.getLocalizedMessage()); return result; } HttpResponse response = server.pollOutput(this, sequence); error = (response.getStatusLine().getStatusCode() != HttpStatus.SC_OK); HttpEntity entity = response.getEntity(); InputStream outputStream = entity.getContent(); String output = SageSingleCell.streamToString(outputStream); outputStream.close(); //output = output.substring(7, output.length()-2); // strip out "jQuery("...")" System.out.println("output = " + output); JSONObject outputJSON = new JSONObject(output); if (!outputJSON.has("content")) return result; JSONArray content = outputJSON.getJSONArray("content"); for (int i=0; i<content.length(); i++) { JSONObject obj = content.getJSONObject(i); CommandReply command = CommandReply.parse(obj); result.add(command); if (command instanceof DataFile) { DataFile file = (DataFile)command; file.downloadFile(server); } else if (command instanceof HtmlFiles) { HtmlFiles file = (HtmlFiles)command; file.downloadFile(server); } } return result; } public String toLongString() { JSONObject json; try { json = toJSON(); } catch (JSONException e) { return e.getLocalizedMessage(); } JSONWriter writer = new JSONWriter(); writer.write(json.toString()); //try { // json.write(writer); //} catch (JSONException e) { // return e.getLocalizedMessage(); //} StringBuffer str = writer.getBuffer(); return str.toString(); } }
12085952-sageandroid
app-v2/src/org/sagemath/singlecellserver/CommandRequest.java
Java
gpl3
6,409
package org.sagemath.singlecellserver; import org.json.JSONException; import org.json.JSONObject; /* * * jQuery({ * "content": [{ * "parent_header": { * "username": "", "msg_id": "749529bd-bcfe-43a7-b660-2cea20df3f32", * "session": "7af9a99a-2a0d-438f-8576-5e0bd853501a"}, * "msg_type": "extension", * "sequence": 0, * "output_block": null, * "content": { * "content": { * "interact_id": "8157151862156143292", * "layout": {"top_center": ["n"]}, * "update": {"n": ["n"]}, * "controls": { * "n": { * "ncols": null, * "control_type": "selector", * "raw": true, * "default": 0, * "label": null, * "nrows": null, * "subtype": "list", * "values": 10, "width": "", * "value_labels": ["0", "1", "2", "3", "4", "5", "6", "7", "8", "9"]}}}, * "msg_type": "interact_prepare"}, * "header": {"msg_id": "4744042977225053037"} * }, { * "parent_header": { * "username": "", * "msg_id": "749529bd-bcfe-43a7-b660-2cea20df3f32", * "session": "7af9a99a-2a0d-438f-8576-5e0bd853501a"}, * "msg_type": "stream", "sequence": 1, "output_block": "8157151862156143292", * "content": {"data": "0\n", "name": "stdout"}, "header": {"msg_id": "7423072463567901439"}}, {"parent_header": {"username": "", "msg_id": "749529bd-bcfe-43a7-b660-2cea20df3f32", "session": "7af9a99a-2a0d-438f-8576-5e0bd853501a"}, "msg_type": "execute_reply", "sequence": 2, "output_block": null, "content": {"status": "ok"}, "header": {"msg_id": "1900046197361249484"}}]}) * * */ public class Interact extends CommandOutput { private final static String TAG = "Interact"; private final String id; protected JSONObject controls, layout; protected Interact(JSONObject json) throws JSONException { super(json); JSONObject content = json.getJSONObject("content").getJSONObject("content"); id = content.getString("interact_id"); controls = content.getJSONObject("controls"); layout = content.getJSONObject("layout"); } public long extendTimeOut() { return 60 * 1000; } public boolean isInteract() { return true; } public String getID() { return id; } public String toString() { return "Prepare interact id=" + getID(); } public JSONObject getControls() { return controls; } public JSONObject getLayout() { return layout; } } /* HTTP/1.1 200 OK Server: nginx/1.0.11 Date: Tue, 10 Jan 2012 21:03:24 GMT Content-Type: text/javascript; charset=utf-8 Connection: keep-alive Content-Length: 1225 jQuery150664064213167876_1326208736019({"content": [{ "parent_header": {"username": "", "msg_id": "f0826b78-7aaf-4eea-a5ce-0b10d24c5888", "session": "184c2fb0-1a8d-4c07-aee6-df85183d9ac2"}, "msg_type": "extension", "sequence": 0, "output_block": null, "content": {"content": {"interact_id": "5455242645056671226", "layout": {"top_center": ["n"]}, "update": {"n": ["n"]}, "controls": {"n": {"control_type": "slider", "raw": true, "default": 0.0, "step": 0.40000000000000002, "label": null, "subtype": "continuous", "range": [0.0, 100.0], "display_value": true}}}, "msg_type": "interact_prepare"}, "header": {"msg_id": "8880643058896313398"}}, { "parent_header": {"username": "", "msg_id": "f0826b78-7aaf-4eea-a5ce-0b10d24c5888", "session": "184c2fb0-1a8d-4c07-aee6-df85183d9ac2"}, "msg_type": "stream", "sequence": 1, "output_block": "5455242645056671226", "content": {"data": "0\n", "name": "stdout"}, "header": {"msg_id": "8823336185428654730"}}, {"parent_header": {"username": "", "msg_id": "f0826b78-7aaf-4eea-a5ce-0b10d24c5888", "session": "184c2fb0-1a8d-4c07-aee6-df85183d9ac2"}, "msg_type": "execute_reply", "sequence": 2, "output_block": null, "content": {"status": "ok"}, "header": {"msg_id": "1224514542068124881"}}]}) POST /eval?callback=jQuery150664064213167876_1326208736022 HTTP/1.1 Host: sagemath.org:5467 Connection: keep-alive Content-Length: 368 Origin: http://sagemath.org:5467 x-requested-with: XMLHttpRequest User-Agent: Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/535.7 (KHTML, like Gecko) Chrome/16.0.912.63 Safari/535.7 content-type: application/x-www-form-urlencoded accept: text/javascript, application/javascript, q=0.01 Referer: http://sagemath.org:5467/ Accept-Encoding: gzip,deflate,sdch Accept-Language: en-US,en;q=0.8,fr;q=0.6,de;q=0.4,ja;q=0.2 Accept-Charset: ISO-8859-1,utf-8;q=0.7,;q=0.3 Cookie: __utma=1.260350506.1306546516.1306612711.1306855420.3; HstCfa1579950=1313082432530; HstCmu1579950=1313082432530; c_ref_1579950=http:%2F%2Fboxen.math.washington.edu%2F; HstCla1579950=1314023965352; HstPn1579950=4; HstPt1579950=6; HstCnv1579950=2; HstCns1579950=2; __utma=138969649.2037720324.1307556884.1314205520.1326143310.11; __utmz=138969649.1314205520.10.6.utmcsr=en.wikipedia.org|utmccn=(referral)|utmcmd=referral|utmcct=/wiki/Sage_(mathematics_software) message={"parent_header":{},"header":{"msg_id":"45724d5f-01f8-4d9c-9eb0-d877a8880db8","session":"184c2fb0-1a8d-4c07-aee6-df85183d9ac2"},"msg_type":"execute_request","content":{"code":"_update_interact('5455242645056671226',control_vals=dict(n=23.6,))","sage_mode":true}} GET /output_poll?callback=jQuery150664064213167876_1326208736025&computation_id=184c2fb0-1a8d-4c07-aee6-df85183d9ac2&sequence=3&_=1326229408735 HTTP/1.1 Host: sagemath.org:5467 Connection: keep-alive x-requested-with: XMLHttpRequest User-Agent: Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/535.7 (KHTML, like Gecko) Chrome/16.0.912.63 Safari/535.7 accept: text/javascript, application/javascript,; q=0.01 Referer: http://sagemath.org:5467/ Accept-Encoding: gzip,deflate,sdch Accept-Language: en-US,en;q=0.8,fr;q=0.6,de;q=0.4,ja;q=0.2 Accept-Charset: ISO-8859-1,utf-8;q=0.7,*;q=0.3 Cookie: __utma=1.260350506.1306546516.1306612711.1306855420.3; HstCfa1579950=1313082432530; HstCmu1579950=1313082432530; c_ref_1579950=http%3A%2F%2Fboxen.math.washington.edu%2F; HstCla1579950=1314023965352; HstPn1579950=4; HstPt1579950=6; HstCnv1579950=2; HstCns1579950=2; __utma=138969649.2037720324.1307556884.1314205520.1326143310.11; __utmz=138969649.1314205520.10.6.utmcsr=en.wikipedia.org|utmccn=(referral)|utmcmd=referral|utmcct=/wiki/Sage_(mathematics_software) HTTP/1.1 200 OK Server: nginx/1.0.11 Date: Tue, 10 Jan 2012 21:03:29 GMT Content-Type: text/javascript; charset=utf-8 Connection: keep-alive Content-Length: 618 jQuery150664064213167876_1326208736025({"content": [{"parent_header": {"session": "184c2fb0-1a8d-4c07-aee6-df85183d9ac2", "msg_id": "45724d5f-01f8-4d9c-9eb0-d877a8880db8"}, "msg_type": "stream", "sequence": 3, "output_block": "5455242645056671226", "content": {"data": "23.6000000000000\n", "name": "stdout"}, "header": {"msg_id": "514409474887099253"}}, {"parent_header": {"session": "184c2fb0-1a8d-4c07-aee6-df85183d9ac2", "msg_id": "45724d5f-01f8-4d9c-9eb0-d877a8880db8"}, "msg_type": "execute_reply", "sequence": 4, "output_block": null, "content": {"status": "ok"}, "header": {"msg_id": "7283788905623826736"}}]}) */
12085952-sageandroid
app-v2/src/org/sagemath/singlecellserver/Interact.java
Java
gpl3
7,079
package org.sagemath.singlecellserver; import java.util.UUID; import junit.framework.Assert; import org.json.JSONException; import org.json.JSONObject; import android.util.Log; /** * The base class for a server reply * * @author vbraun * */ public class CommandReply extends Command { private final static String TAG = "CommandReply"; private JSONObject json; protected CommandReply(JSONObject json) throws JSONException { this.json = json; JSONObject parent_header = json.getJSONObject("parent_header"); session = UUID.fromString(parent_header.getString("session")); msg_id = UUID.fromString(parent_header.getString("msg_id")); } protected CommandReply(CommandRequest request) { session = request.session; msg_id = request.msg_id; } public String toString() { return "Command reply base class"; } public void prettyPrint() { prettyPrint(json); } /** * Extend the HTTP timetout receive timeout. This is for interacts to extend the timeout. * @return milliseconds */ public long extendTimeOut() { return 0; } public boolean isInteract() { return false; } /** * Whether to keep polling for more results after receiving this message * @return */ public boolean terminateServerConnection() { return false; } /** * Turn a received JSONObject into the corresponding Command object * * @return a new CommandReply or derived class */ protected static CommandReply parse(JSONObject json) throws JSONException { String msg_type = json.getString("msg_type"); JSONObject content = json.getJSONObject("content"); Log.d(TAG, "content = "+content.toString()); // prettyPrint(json); if (msg_type.equals("pyout")) return new PythonOutput(json); else if (msg_type.equals("display_data")) { JSONObject data = json.getJSONObject("content").getJSONObject("data"); if (data.has("text/filename")) return new DataFile(json); else return new DisplayData(json); } else if (msg_type.equals("stream")) return new ResultStream(json); else if (msg_type.equals("execute_reply")) { if (content.has("traceback")) return new Traceback(json); else return new ExecuteReply(json); } else if (msg_type.equals("extension")) { String ext_msg_type = content.getString("msg_type"); if (ext_msg_type.equals("session_end")) return new SessionEnd(json); if (ext_msg_type.equals("files")) return new HtmlFiles(json); if (ext_msg_type.equals("interact_prepare")) return new Interact(json); } throw new JSONException("Unknown msg_type"); } public String toLongString() { if (json == null) return "null"; JSONWriter writer = new JSONWriter(); writer.write(json.toString()); // try { // does not work on Android // json.write(writer); // } catch (JSONException e) { // return e.getLocalizedMessage(); // } StringBuffer str = writer.getBuffer(); return str.toString(); } /** * Whether the reply is a reply to the given request * @param request * @return boolean */ public boolean isReplyTo(CommandRequest request) { return (request != null) && session.equals(request.session); } }
12085952-sageandroid
app-v2/src/org/sagemath/singlecellserver/CommandReply.java
Java
gpl3
3,160
package org.sagemath.singlecellserver; import java.util.UUID; import junit.framework.Assert; import org.json.JSONException; import org.json.JSONObject; import android.util.Log; /** * The base class for server communication. All derived classes should * derive from CommandRequest and CommandReply, but not from Command * directly. * * @author vbraun * */ public class Command { private final static String TAG = "Command"; protected UUID session; protected UUID msg_id; protected Command() { this.session = UUID.randomUUID(); msg_id = UUID.randomUUID(); } protected Command(UUID session) { if (session == null) this.session = UUID.randomUUID(); else this.session = session; msg_id = UUID.randomUUID(); } public String toShortString() { return toString(); } public String toLongString() { return toString(); } public String toString() { return "Command base class @" + Integer.toHexString(System.identityHashCode(this)); } /** * Whether or not the command contains data that is supposed to be shown to the user * @return boolean */ public boolean containsOutput() { return false; } protected static void prettyPrint(JSONObject json) { if (json == null) { System.out.println("null"); return; } JSONWriter writer = new JSONWriter(); writer.write(json.toString()); // try { // json.write(writer); // } catch (JSONException e) { // e.printStackTrace(); // } StringBuffer str = writer.getBuffer(); System.out.println(str); } }
12085952-sageandroid
app-v2/src/org/sagemath/singlecellserver/Command.java
Java
gpl3
1,530
package org.sagemath.singlecellserver; import org.json.JSONException; import org.json.JSONObject; public class ExecuteReply extends CommandOutput { private final static String TAG = "ExecuteReply"; private String status; protected ExecuteReply(JSONObject json) throws JSONException { super(json); JSONObject content = json.getJSONObject("content"); status = content.getString("status"); } public String toString() { return "Execute reply status = "+status; } public String getStatus() { return status; } }
12085952-sageandroid
app-v2/src/org/sagemath/singlecellserver/ExecuteReply.java
Java
gpl3
534
package org.sagemath.singlecellserver; import java.io.IOException; import java.net.URI; import java.net.URISyntaxException; import java.util.LinkedList; import org.json.JSONArray; import org.json.JSONException; import org.json.JSONObject; public class HtmlFiles extends CommandOutput { private final static String TAG = "HtmlFiles"; protected JSONArray files; protected LinkedList<URI> uriList = new LinkedList<URI>(); protected HtmlFiles(JSONObject json) throws JSONException { super(json); files = json.getJSONObject("content").getJSONObject("content").getJSONArray("files"); } public String toString() { if (uriList.isEmpty()) return "Html files (empty list)"; else return "Html files, number = "+uriList.size()+" first = "+getFirstURI().toString(); } public URI getFirstURI() { return uriList.getFirst(); } public void downloadFile(SageSingleCell.ServerTask server) throws IOException, URISyntaxException, JSONException { for (int i=0; i<files.length(); i++) { URI uri = server.downloadFileURI(this, files.get(i).toString()); uriList.add(uri); } } }
12085952-sageandroid
app-v2/src/org/sagemath/singlecellserver/HtmlFiles.java
Java
gpl3
1,111
package org.sagemath.singlecellserver; import org.json.JSONException; import org.json.JSONObject; /** * Roughly, a CommandOutput is any JSON object that has a "output_block" field. These are intended * to be displayed on the screen. * * @author vbraun * */ public class CommandOutput extends CommandReply { private final static String TAG = "CommandOutput"; private String output_block; protected CommandOutput(JSONObject json) throws JSONException { super(json); output_block = json.get("output_block").toString(); // prettyPrint(); // System.out.println("block = " + output_block); } public boolean containsOutput() { return true; } public String outputBlock() { return output_block; } }
12085952-sageandroid
app-v2/src/org/sagemath/singlecellserver/CommandOutput.java
Java
gpl3
729
package org.sagemath.singlecellserver; import junit.framework.Assert; import org.json.JSONException; import org.json.JSONObject; public class DisplayData extends CommandOutput { private final static String TAG = "DisplayData"; private JSONObject data; protected String value, mime; protected DisplayData(JSONObject json) throws JSONException { super(json); data = json.getJSONObject("content").getJSONObject("data"); mime = data.keys().next().toString(); value = data.getString(mime); // prettyPrint(json); } public String toString() { return "Display data "+value; } public String getData() { return value; } public String getMime() { return mime; } public String toHTML() { if (mime.equals("text/html")) return value; if (mime.equals("text/plain")) return "<pre>"+value+"</pre>"; return null; } }
12085952-sageandroid
app-v2/src/org/sagemath/singlecellserver/DisplayData.java
Java
gpl3
853
package org.sagemath.singlecellserver; import java.io.BufferedInputStream; import java.io.ByteArrayOutputStream; import java.io.DataInputStream; import java.io.IOException; import java.io.InputStream; import java.net.URI; import java.net.URISyntaxException; import java.nio.Buffer; import org.apache.http.HttpEntity; import org.apache.http.HttpResponse; import org.apache.http.HttpStatus; import org.json.JSONException; import org.json.JSONObject; import org.sagemath.singlecellserver.SageSingleCell.SageInterruptedException; public class DataFile extends DisplayData { private final static String TAG = "DataFile"; protected DataFile(JSONObject json) throws JSONException { super(json); } public String toString() { if (data == null) return "Data file "+uri.toString(); else return "Data file "+value+" ("+data.length+" bytes)"; } public String mime() { String name = value.toLowerCase(); if (name.endsWith(".png")) return "image/png"; if (name.endsWith(".jpg")) return "image/png"; if (name.endsWith(".jpeg")) return "image/png"; if (name.endsWith(".svg")) return "image/svg"; return null; } protected byte[] data; protected URI uri; public URI getURI() { return uri; } public void downloadFile(SageSingleCell.ServerTask server) throws IOException, URISyntaxException, SageInterruptedException { uri = server.downloadFileURI(this, this.value); if (server.downloadDataFiles()) download(server, uri); } private void download(SageSingleCell.ServerTask server, URI uri) throws IOException, SageInterruptedException { HttpResponse response = server.downloadFile(uri); boolean error = (response.getStatusLine().getStatusCode() != HttpStatus.SC_OK); HttpEntity entity = response.getEntity(); InputStream stream = entity.getContent(); byte[] buffer = new byte[4096]; ByteArrayOutputStream buf = new ByteArrayOutputStream(); try { for (int n; (n = stream.read(buffer)) != -1; ) buf.write(buffer, 0, n); } finally { stream.close(); buf.close(); } data = buf.toByteArray(); } }
12085952-sageandroid
app-v2/src/org/sagemath/singlecellserver/DataFile.java
Java
gpl3
2,176
package org.sagemath.singlecellserver; import org.json.JSONException; import org.json.JSONObject; /** * <h1>Streams (stdout, stderr, etc)</h1> * <p> * <pre><code> * Message type: ``stream``:: * content = { * # The name of the stream is one of 'stdin', 'stdout', 'stderr' * 'name' : str, * * # The data is an arbitrary string to be written to that stream * 'data' : str, * } * </code></pre> * When a kernel receives a raw_input call, it should also broadcast it on the pub * socket with the names 'stdin' and 'stdin_reply'. This will allow other clients * to monitor/display kernel interactions and possibly replay them to their user * or otherwise expose them. * * @author vbraun * */ public class ResultStream extends CommandOutput { private final static String TAG = "ResultStream"; protected JSONObject content; protected String data; protected ResultStream(JSONObject json) throws JSONException { super(json); content = json.getJSONObject("content"); data = content.getString("data"); } public String toString() { return "Result: stream = >>>"+data+"<<<"; } public String toShortString() { return "Stream output"; } public String get() { return data; } }
12085952-sageandroid
app-v2/src/org/sagemath/singlecellserver/ResultStream.java
Java
gpl3
1,255
package org.sagemath.singlecellserver; public class HttpError extends CommandReply { private final static String TAG = "HttpError"; protected String message; protected HttpError(CommandRequest request, String message) { super(request); this.message = message; } public String toString() { return "HTTP error "+message; } @Override public boolean terminateServerConnection() { return true; } }
12085952-sageandroid
app-v2/src/org/sagemath/singlecellserver/HttpError.java
Java
gpl3
424
package org.sagemath.singlecellserver; import java.util.LinkedList; import java.util.UUID; import org.json.JSONArray; import org.json.JSONException; import org.json.JSONObject; public class ExecuteRequest extends CommandRequest { private final static String TAG = "ExecuteRequest"; String input; boolean sage; public ExecuteRequest(String input, boolean sage, UUID session) { super(session); this.input = input; this.sage = sage; } public ExecuteRequest(String input) { super(); this.input = input; sage = true; } public String toString() { return "Request to execute >"+input+"<"; } public String toShortString() { return "Request to execute"; } public JSONObject toJSON() throws JSONException { JSONObject result = super.toJSON(); result.put("parent_header", new JSONArray()); result.put("msg_type", "execute_request"); JSONObject content = new JSONObject(); content.put("code", input); content.put("sage_mode", sage); result.put("content", content); return result; } // {"parent_header":{}, // "header":{ // "msg_id":"1ec1b4b4-722e-42c7-997d-e4a9605f5056", // "session":"c11a0761-910e-4c8c-b94e-803a13e5859a"}, // "msg_type":"execute_request", // "content":{"code":"code to execute", // "sage_mode":true}} }
12085952-sageandroid
app-v2/src/org/sagemath/singlecellserver/ExecuteRequest.java
Java
gpl3
1,336
package org.sagemath.singlecellserver; import java.io.BufferedReader; import java.io.File; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import java.net.URI; import java.net.URISyntaxException; import java.util.LinkedList; import java.util.ListIterator; import java.util.UUID; import javax.net.ssl.HandshakeCompletedListener; import junit.framework.Assert; import org.apache.http.HttpEntity; import org.apache.http.HttpResponse; import org.apache.http.HttpStatus; import org.apache.http.HttpVersion; import org.apache.http.StatusLine; import org.apache.http.client.ClientProtocolException; import org.apache.http.client.ResponseHandler; import org.apache.http.client.methods.HttpGet; import org.apache.http.client.methods.HttpPost; import org.apache.http.entity.mime.HttpMultipartMode; import org.apache.http.entity.mime.MultipartEntity; import org.apache.http.entity.mime.content.StringBody; import org.apache.http.impl.client.DefaultHttpClient; import org.apache.http.params.BasicHttpParams; import org.apache.http.params.CoreProtocolPNames; import org.apache.http.params.HttpParams; import org.apache.http.util.EntityUtils; import org.json.JSONArray; import org.json.JSONException; import org.json.JSONObject; import android.util.Log; import android.text.format.Time; /** * Interface with the Sage single cell server * * @author vbraun * */ public class SageSingleCell { private final static String TAG = "SageSingleCell"; private long timeout = 30*1000; // private String server = "http://localhost:8001"; private String server = "http://sagemath.org:5467"; private String server_path_eval = "/eval"; private String server_path_output_poll = "/output_poll"; private String server_path_files = "/files"; protected boolean downloadDataFiles = true; /** * Whether to immediately download data files or only save their URI * * @param value Download immediately if true */ public void setDownloadDataFiles(boolean value) { downloadDataFiles = value; } /** * Set the server * * @param server The server, for example "http://sagemath.org:5467" * @param eval The path on the server for the eval post, for example "/eval" * @param poll The path on the server for the output polling, for example "/output_poll" */ public void setServer(String server, String eval, String poll, String files) { this.server = server; this.server_path_eval = eval; this.server_path_output_poll = poll; this.server_path_files = files; } public interface OnSageListener { /** * Output in a new block or an existing block where all current entries are supposed to be erased * @param output */ public void onSageOutputListener(CommandOutput output); /** * Output to add to an existing output block * @param output */ public void onSageAdditionalOutputListener(CommandOutput output); /** * Callback for an interact_prepare message * @param interact The interact */ public void onSageInteractListener(Interact interact); /** * The Sage session has been closed * @param reason A SessionEnd message or a HttpError */ public void onSageFinishedListener(CommandReply reason); } private OnSageListener listener; /** * Set the result callback, see {@link #query(String)} * * @param listener */ public void setOnSageListener(OnSageListener listener) { this.listener = listener; } public SageSingleCell() { logging(); } public void logging() { // You also have to // adb shell setprop log.tag.httpclient.wire.header VERBOSE // adb shell setprop log.tag.httpclient.wire.content VERBOSE java.util.logging.Logger apacheWireLog = java.util.logging.Logger.getLogger("org.apache.http.wire"); apacheWireLog.setLevel(java.util.logging.Level.FINEST); } protected static String streamToString(InputStream is) { BufferedReader reader = new BufferedReader(new InputStreamReader(is)); StringBuilder sb = new StringBuilder(); String line = null; try { while ((line = reader.readLine()) != null) { sb.append(line + "\n"); } } catch (IOException e) { e.printStackTrace(); } finally { try { is.close(); } catch (IOException e) { e.printStackTrace(); } } return sb.toString(); } public static class SageInterruptedException extends Exception { private static final long serialVersionUID = -5638564842011063160L; } LinkedList<ServerTask> threads = new LinkedList<ServerTask>(); private void addThread(ServerTask thread) { synchronized (threads) { threads.add(thread); } } private void removeThread(ServerTask thread) { synchronized (threads) { threads.remove(thread); } } public enum LogLevel { NONE, BRIEF, VERBOSE }; private LogLevel logLevel = LogLevel.NONE; public void setLogLevel(LogLevel logLevel) { this.logLevel = logLevel; } public class ServerTask extends Thread { private final static String TAG = "ServerTask"; private final UUID session; private final String sageInput; private boolean sendOnly = false; private final boolean sageMode = true; private boolean interrupt = false; private DefaultHttpClient httpClient; private Interact interact; private CommandRequest request, currentRequest; private LinkedList<String> outputBlocks = new LinkedList<String>(); private long initialTime = System.currentTimeMillis(); protected LinkedList<CommandReply> result = new LinkedList<CommandReply>(); protected void log(Command command) { if (logLevel.equals(LogLevel.NONE)) return; String s; if (command instanceof CommandReply) s = ">> "; else if (command instanceof CommandRequest) s = "<< "; else s = "== "; long t = System.currentTimeMillis() - initialTime; s += "(" + String.valueOf(t) + "ms) "; s += command.toShortString(); if (logLevel.equals(LogLevel.VERBOSE)) { s += " "; s += command.toLongString(); s += "\n"; } System.out.println(s); System.out.flush(); } /** * Whether to only send or also receive the replies * @param sendOnly */ protected void setSendOnly(boolean sendOnly) { this.sendOnly = sendOnly; } protected void addReply(CommandReply reply) { log(reply); result.add(reply); if (reply.isInteract()) { interact = (Interact) reply; listener.onSageInteractListener(interact); } else if (reply.containsOutput() && reply.isReplyTo(currentRequest)) { CommandOutput output = (CommandOutput) reply; if (outputBlocks.contains(output.outputBlock())) listener.onSageAdditionalOutputListener(output); else { outputBlocks.add(output.outputBlock()); listener.onSageOutputListener(output); } } } /** * The timeout for the http request * @return timeout in milliseconds */ public long timeout() { return timeout; } private void init() { HttpParams params = new BasicHttpParams(); params.setParameter(CoreProtocolPNames.PROTOCOL_VERSION, HttpVersion.HTTP_1_1); httpClient = new DefaultHttpClient(params); addThread(this); currentRequest = request = new ExecuteRequest(sageInput, sageMode, session); } public ServerTask() { this.sageInput = null; this.session = null; init(); } public ServerTask(String sageInput) { this.sageInput = sageInput; this.session = null; init(); } public ServerTask(String sageInput, UUID session) { this.sageInput = sageInput; this.session = session; init(); } public void interrupt() { interrupt = true; } public boolean isInterrupted() { return interrupt; } protected HttpResponse postEval(JSONObject request) throws ClientProtocolException, IOException, SageInterruptedException, JSONException { if (interrupt) throw new SageInterruptedException(); HttpPost httpPost = new HttpPost(server + server_path_eval); MultipartEntity multipartEntity = new MultipartEntity(HttpMultipartMode.BROWSER_COMPATIBLE); if (request.has("content")) multipartEntity.addPart("message", new StringBody(request.toString())); else { JSONObject content = request.getJSONObject("content"); JSONObject header = request.getJSONObject("header"); multipartEntity.addPart("commands", new StringBody(JSONObject.quote(content.getString("code")))); multipartEntity.addPart("msg_id", new StringBody(header.getString("msg_id"))); multipartEntity.addPart("sage_mode", new StringBody("on")); } httpPost.setEntity(multipartEntity); HttpResponse httpResponse = httpClient.execute(httpPost); return httpResponse; } protected HttpResponse pollOutput(CommandRequest request, int sequence) throws ClientProtocolException, IOException, SageInterruptedException { if (interrupt) throw new SageInterruptedException(); Time time = new Time(); StringBuilder query = new StringBuilder(); time.setToNow(); // query.append("?callback=jQuery"); query.append("?computation_id=" + request.session.toString()); query.append("&sequence=" + sequence); query.append("&rand=" + time.toMillis(true)); HttpGet httpGet = new HttpGet(server + server_path_output_poll + query); return httpClient.execute(httpGet); } // protected void callSageOutputListener(CommandOutput output) { // listener.onSageOutputListener(output); // } // // protected void callSageReplaceOutputListener(CommandOutput output) { // listener.onSageReplaceOutputListener(output); // } // // protected void callSageInteractListener(Interact interact) { // listener.onSageInteractListener(interact); // } protected URI downloadFileURI(CommandReply reply, String filename) throws URISyntaxException { StringBuilder query = new StringBuilder(); query.append("/"+reply.session.toString()); query.append("/"+filename); return new URI(server + server_path_files + query); } protected HttpResponse downloadFile(URI uri) throws ClientProtocolException, IOException, SageInterruptedException { if (interrupt) throw new SageInterruptedException(); HttpGet httpGet = new HttpGet(uri); return httpClient.execute(httpGet); } protected boolean downloadDataFiles() { return SageSingleCell.this.downloadDataFiles; } @Override public void run() { super.run(); log(request); if (sendOnly) { request.sendRequest(this); removeThread(this); return; } request.receiveReply(this); removeThread(this); listener.onSageFinishedListener(result.getLast()); } } /** * Start an asynchronous query on the Sage server * The result will be handled by the callback set by {@link #setOnSageListener(OnSageListener)} * @param sageInput */ public void query(String sageInput) { ServerTask task = new ServerTask(sageInput); task.start(); } /** * Update an interactive element * @param interact The interact_prepare message we got from the server as we set up the interact * @param name The name of the variable in the interact function declaration * @param value The new value */ public void interact(Interact interact, String name, Object value) { String sageInput = "_update_interact('" + interact.getID() + "',control_vals=dict(" + name + "=" + value.toString() + ",))"; ServerTask task = new ServerTask(sageInput, interact.session); synchronized (threads) { for (ServerTask thread: threads) if (thread.interact == interact) { thread.currentRequest = task.request; thread.outputBlocks.clear(); } } task.setSendOnly(true); task.start(); } /** * Interrupt all pending Sage server transactions */ public void interrupt() { synchronized (threads) { for (ServerTask thread: threads) thread.interrupt(); } } /** * Whether a computation is currently running * * @return */ public boolean isRunning() { synchronized (threads) { for (ServerTask thread: threads) if (!thread.isInterrupted()) return true; } return false; } } /* === Send request === POST /eval HTTP/1.1 Host: localhost:8001 Connection: keep-alive Content-Length: 506 Cache-Control: max-age=0 Origin: http://localhost:8001 User-Agent: Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/535.2 (KHTML, like Gecko) Chrome/15.0.874.121 Safari/535.2 Content-Type: multipart/form-data; boundary=----WebKitFormBoundaryh9NcFTBy2FksKYpN Accept: text/html,application/xhtml+xml,application/xml;q=0.9,* / *;q=0.8 Referer: http://localhost:8001/ Accept-Encoding: gzip,deflate,sdch Accept-Language: en-US,en;q=0.8,de;q=0.6,ja;q=0.4,fr-FR;q=0.2,he;q=0.2,ga;q=0.2,ko;q=0.2 Accept-Charset: ISO-8859-1,utf-8;q=0.7,*;q=0.3 Cookie: DWd8c32a438995fbf98bd158172221d77e=dmJyYXVu%7C1%7CWHhzTnc5M0NXZDZyekQzcjlVL1lNZz09; DOKU_PREFS=sizeCtl%23679px ------WebKitFormBoundaryh9NcFTBy2FksKYpN Content-Disposition: form-data; name="commands" "1+1" ------WebKitFormBoundaryh9NcFTBy2FksKYpN Content-Disposition: form-data; name="session_id" 87013257-7c34-4c83-b7ed-2ec7e7480935 ------WebKitFormBoundaryh9NcFTBy2FksKYpN Content-Disposition: form-data; name="msg_id" 489696dc-ed8d-4cb6-a140-4282a43eda95 ------WebKitFormBoundaryh9NcFTBy2FksKYpN Content-Disposition: form-data; name="sage_mode" True ------WebKitFormBoundaryh9NcFTBy2FksKYpN-- HTTP/1.1 200 OK Server: nginx/1.0.4 Date: Mon, 12 Dec 2011 19:12:14 GMT Content-Type: text/html; charset=utf-8 Connection: keep-alive Content-Length: 0 === Poll for reply (unsuccessfully, try again) === GET /output_poll?callback=jQuery15015045171417295933_1323715011672&computation_id=25508880-6a6a-4353-9439-689468ec679e&sequence=0&_=1323718075839 HTTP/1.1 Host: localhost:8001 Connection: keep-alive x-requested-with: XMLHttpRequest User-Agent: Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/535.2 (KHTML, like Gecko) Chrome/15.0.874.121 Safari/535.2 accept: text/javascript, application/javascript, * / *; q=0.01 Referer: http://localhost:8001/ Accept-Encoding: gzip,deflate,sdch Accept-Language: en-US,en;q=0.8,de;q=0.6,ja;q=0.4,fr-FR;q=0.2,he;q=0.2,ga;q=0.2,ko;q=0.2 Accept-Charset: ISO-8859-1,utf-8;q=0.7,*;q=0.3 Cookie: DWd8c32a438995fbf98bd158172221d77e=dmJyYXVu%7C1%7CWHhzTnc5M0NXZDZyekQzcjlVL1lNZz09; DOKU_PREFS=sizeCtl%23679px HTTP/1.1 200 OK Server: nginx/1.0.4 Date: Mon, 12 Dec 2011 19:27:55 GMT Content-Type: text/javascript; charset=utf-8 Connection: keep-alive Content-Length: 44 jQuery15015045171417295933_1323715011672({}) === Poll for reply (success) === GET /output_poll?callback=jQuery15015045171417295933_1323715011662&computation_id=87013257-7c34-4c83-b7ed-2ec7e7480935&sequence=0&_=1323717134406 HTTP/1.1 Host: localhost:8001 Connection: keep-alive x-requested-with: XMLHttpRequest User-Agent: Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/535.2 (KHTML, like Gecko) Chrome/15.0.874.121 Safari/535.2 accept: text/javascript, application/javascript, * / *; q=0.01 Referer: http://localhost:8001/ Accept-Encoding: gzip,deflate,sdch Accept-Language: en-US,en;q=0.8,de;q=0.6,ja;q=0.4,fr-FR;q=0.2,he;q=0.2,ga;q=0.2,ko;q=0.2 Accept-Charset: ISO-8859-1,utf-8;q=0.7,*;q=0.3 Cookie: DWd8c32a438995fbf98bd158172221d77e=dmJyYXVu%7C1%7CWHhzTnc5M0NXZDZyekQzcjlVL1lNZz09; DOKU_PREFS=sizeCtl%23679px === Reply with result from server === HTTP/1.1 200 OK Server: nginx/1.0.4 Date: Mon, 12 Dec 2011 19:12:14 GMT Content-Type: text/javascript; charset=utf-8 Connection: keep-alive Content-Length: 830 jQuery15015045171417295933_1323715011662( {"content": [{ "parent_header": { "username": "", "msg_id": "489696dc-ed8d-4cb6-a140-4282a43eda95", "session": "87013257-7c34-4c83-b7ed-2ec7e7480935"}, "msg_type": "pyout", "sequence": 0, "output_block": null, "content": { "data": {"text/plain": "2"}}, "header": {"msg_id": "1620524024608841996"}}, { "parent_header": { "username": "", "msg_id": "489696dc-ed8d-4cb6-a140-4282a43eda95", "session": "87013257-7c34-4c83-b7ed-2ec7e7480935"}, "msg_type": "execute_reply", "sequence": 1, "output_block": null, "content": {"status": "ok"}, "header": {"msg_id": "1501182239947896697"}}, { "parent_header": {"session": "87013257-7c34-4c83-b7ed-2ec7e7480935"}, "msg_type": "extension", "sequence": 2, "content": {"msg_type": "session_end"}, "header": {"msg_id": "1e6db71f-61a0-47f9-9607-f2054243bb67"} }]}) === Reply with Syntax Erorr === GET /output_poll?callback=jQuery15015045171417295933_1323715011664&computation_id=9b3ed6bb-01e8-4a6e-9076-14c71324daf6&sequence=0&_=1323717902557 HTTP/1.1 Host: localhost:8001 Connection: keep-alive x-requested-with: XMLHttpRequest User-Agent: Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/535.2 (KHTML, like Gecko) Chrome/15.0.874.121 Safari/535.2 accept: text/javascript, application/javascript, * / *; q=0.01 Referer: http://localhost:8001/ Accept-Encoding: gzip,deflate,sdch Accept-Language: en-US,en;q=0.8,de;q=0.6,ja;q=0.4,fr-FR;q=0.2,he;q=0.2,ga;q=0.2,ko;q=0.2 Accept-Charset: ISO-8859-1,utf-8;q=0.7,*;q=0.3 Cookie: DWd8c32a438995fbf98bd158172221d77e=dmJyYXVu%7C1%7CWHhzTnc5M0NXZDZyekQzcjlVL1lNZz09; DOKU_PREFS=sizeCtl%23679px HTTP/1.1 200 OK Server: nginx/1.0.4 Date: Mon, 12 Dec 2011 19:25:02 GMT Content-Type: text/javascript; charset=utf-8 Connection: keep-alive Content-Length: 673 jQuery15015045171417295933_1323715011664({"content": [{"parent_header": {"username": "", "msg_id": "df56f48a-d47f-4267-b228-77f051d7d834", "session": "9b3ed6bb-01e8-4a6e-9076-14c71324daf6"}, "msg_type": "execute_reply", "sequence": 0, "output_block": null, "content": {"status": "error", "ename": "SyntaxError", "evalue": "invalid syntax", "traceback": ["\u001b[1;31m---------------------------------------------------------------------------\u001b[0m\n\u001b[1;31mSyntaxError\u001b[0m Traceback (most recent call last)", "\u001b[1;31mSyntaxError\u001b[0m: invalid syntax (<string>, line 39)"]}, "header": {"msg_id": "2853508955959610959"}}]})GET /output_poll?callback=jQuery15015045171417295933_1323715011665&computation_id=9b3ed6bb-01e8-4a6e-9076-14c71324daf6&sequence=1&_=1323717904769 HTTP/1.1 Host: localhost:8001 Connection: keep-alive x-requested-with: XMLHttpRequest User-Agent: Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/535.2 (KHTML, like Gecko) Chrome/15.0.874.121 Safari/535.2 accept: text/javascript, application/javascript, * / *; q=0.01 Referer: http://localhost:8001/ Accept-Encoding: gzip,deflate,sdch Accept-Language: en-US,en;q=0.8,de;q=0.6,ja;q=0.4,fr-FR;q=0.2,he;q=0.2,ga;q=0.2,ko;q=0.2 Accept-Charset: ISO-8859-1,utf-8;q=0.7,*;q=0.3 Cookie: DWd8c32a438995fbf98bd158172221d77e=dmJyYXVu%7C1%7CWHhzTnc5M0NXZDZyekQzcjlVL1lNZz09; DOKU_PREFS=sizeCtl%23679px HTTP/1.1 200 OK Server: nginx/1.0.4 Date: Mon, 12 Dec 2011 19:25:04 GMT Content-Type: text/javascript; charset=utf-8 Connection: keep-alive Content-Length: 269 jQuery15015045171417295933_1323715011665({"content": [{"parent_header": {"session": "9b3ed6bb-01e8-4a6e-9076-14c71324daf6"}, "msg_type": "extension", "sequence": 1, "content": {"msg_type": "session_end"}, "header": {"msg_id": "e01180d4-934c-4f12-858c-72d52e0330cd"}}]}) */
12085952-sageandroid
app-v2/src/org/sagemath/singlecellserver/SageSingleCell.java
Java
gpl3
19,442
package org.sagemath.singlecellserver; import org.json.JSONException; import org.json.JSONObject; public class SessionEnd extends CommandReply { public final static String TAG = "SessionEnd"; protected SessionEnd(JSONObject json) throws JSONException { super(json); } public String toString() { return "End of Sage session marker"; } @Override public boolean terminateServerConnection() { return true; } }
12085952-sageandroid
app-v2/src/org/sagemath/singlecellserver/SessionEnd.java
Java
gpl3
429
package org.sagemath.singlecellserver; import java.io.StringWriter; /** * * @author Elad Tabak * @since 28-Nov-2011 * @version 0.1 * */ public class JSONWriter extends StringWriter { private int indent = 0; @Override public void write(int c) { if (((char)c) == '[' || ((char)c) == '{') { super.write(c); super.write('\n'); indent++; writeIndentation(); } else if (((char)c) == ',') { super.write(c); super.write('\n'); writeIndentation(); } else if (((char)c) == ']' || ((char)c) == '}') { super.write('\n'); indent--; writeIndentation(); super.write(c); } else { super.write(c); } } private void writeIndentation() { for (int i = 0; i < indent; i++) { super.write(" "); } } }
12085952-sageandroid
app-v2/src/org/sagemath/singlecellserver/JSONWriter.java
Java
gpl3
921
package org.sagemath.singlecellserver; import java.util.Iterator; import org.json.JSONException; import org.json.JSONObject; /** * <h1>Python output</h1> * <p> * When Python produces output from code that has been compiled in with the * 'single' flag to :func:`compile`, any expression that produces a value (such as * ``1+1``) is passed to ``sys.displayhook``, which is a callable that can do with * this value whatever it wants. The default behavior of ``sys.displayhook`` in * the Python interactive prompt is to print to ``sys.stdout`` the :func:`repr` of * the value as long as it is not ``None`` (which isn't printed at all). In our * case, the kernel instantiates as ``sys.displayhook`` an object which has * similar behavior, but which instead of printing to stdout, broadcasts these * values as ``pyout`` messages for clients to display appropriately. * <p> * IPython's displayhook can handle multiple simultaneous formats depending on its * configuration. The default pretty-printed repr text is always given with the * ``data`` entry in this message. Any other formats are provided in the * ``extra_formats`` list. Frontends are free to display any or all of these * according to its capabilities. ``extra_formats`` list contains 3-tuples of an ID * string, a type string, and the data. The ID is unique to the formatter * implementation that created the data. Frontends will typically ignore the ID * unless if it has requested a particular formatter. The type string tells the * frontend how to interpret the data. It is often, but not always a MIME type. * Frontends should ignore types that it does not understand. The data itself is * any JSON object and depends on the format. It is often, but not always a string. * <p> * Message type: ``pyout``:: * <p> * <pre><code> * content = { * # The counter for this execution is also provided so that clients can * # display it, since IPython automatically creates variables called _N * # (for prompt N). * 'execution_count' : int, * * # The data dict contains key/value pairs, where the kids are MIME * # types and the values are the raw data of the representation in that * # format. The data dict must minimally contain the ``text/plain`` * # MIME type which is used as a backup representation. * 'data' : dict, * } * </code></pre> * * @author vbraun */ public class PythonOutput extends CommandOutput { private final static String TAG = "PythonOutput"; protected JSONObject content, data; protected String text; protected PythonOutput(JSONObject json) throws JSONException { super(json); content = json.getJSONObject("content"); data = content.getJSONObject("data"); text = data.getString("text/plain"); } public String toString() { return "Python output: "+text; } public String toShortString() { return "Python output"; } /** * Get an iterator for the possible encodings. * * @return */ public Iterator<?> getEncodings() { return data.keys(); } /** * Get the output * * @param encoding Which of possibly multiple representations to return * @return The output in the chosen representation * @throws JSONException */ public String get(String encoding) throws JSONException { return data.getString(encoding); } /** * Return a textual representation of the output * * @return Text representation of the output; */ public String get() { return text; } }
12085952-sageandroid
app-v2/src/org/sagemath/singlecellserver/PythonOutput.java
Java
gpl3
3,522
package org.sagemath.singlecellserver; import java.util.LinkedList; import java.util.ListIterator; public class Transaction { protected final SageSingleCell server; protected final CommandRequest request; protected final LinkedList<CommandReply> reply; public static class Factory { public Transaction newTransaction(SageSingleCell server, CommandRequest request, LinkedList<CommandReply> reply) { return new Transaction(server, request, reply); } } protected Transaction(SageSingleCell server, CommandRequest request, LinkedList<CommandReply> reply) { this.server = server; this.request = request; this.reply = reply; } public DataFile getDataFile() { for (CommandReply r: reply) if (r instanceof DataFile) return (DataFile)r; return null; } public HtmlFiles getHtmlFiles() { for (CommandReply r: reply) if (r instanceof HtmlFiles) return (HtmlFiles)r; return null; } public DisplayData getDisplayData() { for (CommandReply r: reply) if (r instanceof DisplayData) return (DisplayData)r; return null; } public ResultStream getResultStream() { for (CommandReply r: reply) if (r instanceof ResultStream) return (ResultStream)r; return null; } public PythonOutput getPythonOutput() { for (CommandReply r: reply) if (r instanceof PythonOutput) return (PythonOutput)r; return null; } public Traceback getTraceback() { for (CommandReply r: reply) if (r instanceof Traceback) return (Traceback)r; return null; } public HttpError getHttpError() { for (CommandReply r: reply) if (r instanceof HttpError) return (HttpError)r; return null; } public ExecuteReply getExecuteReply() { for (CommandReply r: reply) if (r instanceof ExecuteReply) return (ExecuteReply)r; return null; } public String toString() { StringBuilder s = new StringBuilder(); s.append(request); if (reply.isEmpty()) s.append("no reply"); else s.append("\n"); ListIterator<CommandReply> iter = reply.listIterator(); while (iter.hasNext()) { s.append(iter.next()); if (iter.hasNext()) s.append("\n"); } return s.toString(); } }
12085952-sageandroid
app-v2/src/org/sagemath/singlecellserver/Transaction.java
Java
gpl3
2,152
package org.sagemath.droid; import sheetrock.panda.changelog.ChangeLog; import com.example.android.actionbarcompat.ActionBarActivity; import android.content.Context; import android.content.Intent; import android.net.Uri; import android.os.Bundle; import android.util.Log; import android.view.Menu; import android.view.MenuInflater; import android.view.MenuItem; import android.view.View; import android.view.inputmethod.InputMethodManager; import android.widget.AdapterView; import android.widget.AdapterView.OnItemClickListener; import android.widget.AdapterView.OnItemSelectedListener; import android.widget.Button; import android.widget.EditText; import android.widget.Spinner; import android.widget.Toast; import org.sagemath.singlecellserver.Interact; import org.sagemath.singlecellserver.SageSingleCell; /** * The main activity of the Sage app * * @author vbraun * */ public class SageActivity extends ActionBarActivity implements Button.OnClickListener, OutputView.onSageListener, OnItemSelectedListener { private final static String TAG = "SageActivity"; private ChangeLog changeLog; private EditText input; private Button roundBracket, squareBracket, curlyBracket; private Button runButton; private Spinner insertSpinner; private OutputView outputView; private static SageSingleCell server = new SageSingleCell(); private CellData cell; @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); CellCollection.initialize(getApplicationContext()); cell = CellCollection.getInstance().getCurrentCell(); server.setServer("http://aleph.sagemath.org", "/eval", "/output_poll", "/files"); setContentView(R.layout.main); changeLog = new ChangeLog(this); if (changeLog.firstRun()) changeLog.getLogDialog().show(); input = (EditText) findViewById(R.id.sage_input); roundBracket = (Button) findViewById(R.id.bracket_round); squareBracket = (Button) findViewById(R.id.bracket_square); curlyBracket = (Button) findViewById(R.id.bracket_curly); runButton = (Button) findViewById(R.id.button_run); outputView = (OutputView) findViewById(R.id.sage_output); insertSpinner = (Spinner) findViewById(R.id.insert_text); server.setOnSageListener(outputView); outputView.setOnSageListener(this); insertSpinner.setOnItemSelectedListener(this); roundBracket.setOnClickListener(this); squareBracket.setOnClickListener(this); curlyBracket.setOnClickListener(this); runButton.setOnClickListener(this); server.setDownloadDataFiles(false); setTitle(cell.getTitle()); if (server.isRunning()) getActionBarHelper().setRefreshActionItemState(true); input.setText(cell.getInput()); } @Override public boolean onCreateOptionsMenu(Menu menu) { MenuInflater menuInflater = getMenuInflater(); menuInflater.inflate(R.menu.main, menu); return super.onCreateOptionsMenu(menu); } @Override public boolean onOptionsItemSelected(MenuItem item) { Uri uri; Intent intent; switch (item.getItemId()) { case android.R.id.home: finish(); return true; case R.id.menu_refresh: runButton(); return true; case R.id.menu_search: Toast.makeText(this, "Tapped search", Toast.LENGTH_SHORT).show(); return true; case R.id.menu_share: Toast.makeText(this, "Tapped share", Toast.LENGTH_SHORT).show(); return true; case R.id.menu_changelog: changeLog.getFullLogDialog().show(); return true; case R.id.menu_about_sage: uri = Uri.parse("http://www.sagemath.org"); intent = new Intent(Intent.ACTION_VIEW, uri); startActivity(intent); return true; case R.id.menu_manual_user: uri = Uri.parse("http://www.sagemath.org/doc/tutorial/"); intent = new Intent(Intent.ACTION_VIEW, uri); startActivity(intent); return true; case R.id.menu_manual_dev: uri = Uri.parse("http://http://www.sagemath.org/doc/reference/"); intent = new Intent(Intent.ACTION_VIEW, uri); startActivity(intent); return true; } return super.onOptionsItemSelected(item); } // public void setTitle(String title) { // this.title.setText(title); // } // @Override public void onClick(View v) { int cursor = input.getSelectionStart(); switch (v.getId()) { case R.id.button_run: runButton(); break; case R.id.bracket_round: input.getText().insert(cursor, "( )"); input.setSelection(cursor + 2); break; case R.id.bracket_square: input.getText().insert(cursor, "[ ]"); input.setSelection(cursor + 2); break; case R.id.bracket_curly: input.getText().insert(cursor, "{ }"); input.setSelection(cursor + 2); break; } } private void runButton() { InputMethodManager imm = (InputMethodManager)getSystemService(Context.INPUT_METHOD_SERVICE); imm.hideSoftInputFromWindow(input.getWindowToken(), 0); server.interrupt(); outputView.clear(); server.query(input.getText().toString()); getActionBarHelper().setRefreshActionItemState(true); outputView.requestFocus(); } @Override public void onSageFinishedListener() { getActionBarHelper().setRefreshActionItemState(false); } @Override public void onSageInteractListener(Interact interact, String name, Object value) { Log.e(TAG, name + " = " + value); server.interact(interact, name, value); } @Override protected void onPause() { super.onPause(); } @Override protected void onResume() { super.onResume(); outputView.onResume(); } protected static final int INSERT_PROMPT = 0; protected static final int INSERT_FOR_LOOP = 1; protected static final int INSERT_LIST_COMPREHENSION = 2; @Override public void onItemSelected(AdapterView<?> parent, View view, int position, long arg3) { if (parent != insertSpinner) return; int cursor = input.getSelectionStart(); switch (position) { case INSERT_FOR_LOOP: input.getText().append("\nfor i in range(0,10):\n "); input.setSelection(input.getText().length()); break; case INSERT_LIST_COMPREHENSION: input.getText().insert(cursor, "[ i for i in range(0,10) ]"); input.setSelection(cursor+2, cursor+3); break; } parent.setSelection(0); } @Override public void onNothingSelected(AdapterView<?> arg0) { // TODO Auto-generated method stub } }
12085952-sageandroid
app-v2/src/org/sagemath/droid/SageActivity.java
Java
gpl3
6,803
package org.sagemath.droid; import java.util.LinkedList; import java.util.ListIterator; import junit.framework.Assert; import org.sagemath.singlecellserver.CommandOutput; import org.sagemath.singlecellserver.CommandReply; import org.sagemath.singlecellserver.Interact; import org.sagemath.singlecellserver.SageSingleCell; import org.sagemath.singlecellserver.SageSingleCell.ServerTask; import android.content.Context; import android.os.Handler; import android.util.AttributeSet; import android.util.Log; import android.webkit.WebSettings; import android.widget.LinearLayout; import android.widget.SeekBar; public class OutputView extends LinearLayout implements SageSingleCell.OnSageListener, InteractView.OnInteractListener { private final static String TAG = "OutputView"; interface onSageListener { public void onSageInteractListener(Interact interact, String name, Object value); public void onSageFinishedListener(); } private onSageListener listener; public void setOnSageListener(onSageListener listener) { this.listener = listener; } private LinkedList<OutputBlock> blocks = new LinkedList<OutputBlock>(); private Context context; private CellData cell; public OutputView(Context context, AttributeSet attrs) { super(context, attrs); this.context = context; setOrientation(VERTICAL); setFocusable(true); setFocusableInTouchMode(true); } @Override public void onSageOutputListener(CommandOutput output) { UpdateResult task = new UpdateResult(); task.output = output; handler.post(task); } @Override public void onSageAdditionalOutputListener(CommandOutput output) { UpdateResult task = new UpdateResult(); task.additionalOutput = output; handler.post(task); } @Override public void onSageInteractListener(Interact interact) { UpdateResult task = new UpdateResult(); task.interact = interact; handler.post(task); } @Override public void onSageFinishedListener(CommandReply reason) { UpdateResult task = new UpdateResult(); task.finished = reason; handler.post(task); } private Handler handler = new Handler(); /** * Retrieve the OutputBlock representing the output. Creates a new OutputBlock if necessary. * @param output * @return */ private OutputBlock getOutputBlock(CommandOutput output) { return getOutputBlock(output.outputBlock()); } private OutputBlock getOutputBlock(String output_block) { ListIterator<OutputBlock> iter = blocks.listIterator(); while (iter.hasNext()) { OutputBlock block = iter.next(); if (block.getOutputBlock().equals(output_block)) return block; } return newOutputBlock(); } private OutputBlock newOutputBlock() { OutputBlock block = new OutputBlock(context, cell); addView(block); blocks.add(block); return block; } private class UpdateResult implements Runnable { private CommandOutput output; private CommandOutput additionalOutput; private Interact interact; private CommandReply finished; @Override public void run() { if (output != null) { // Log.d(TAG, "set "+output.toShortString()); OutputBlock block = getOutputBlock(output); block.set(output); } if (additionalOutput != null ) { // Log.d(TAG, "add "+additionalOutput.toShortString()); OutputBlock block = getOutputBlock(additionalOutput); block.add(additionalOutput); } if (interact != null) { InteractView interactView = new InteractView(context); interactView.set(interact); interactView.setOnInteractListener(OutputView.this); addView(interactView); } if (finished != null) listener.onSageFinishedListener(); } } /** * Called during onResume. Reloads the embedded web views from cache. */ protected void onResume() { removeAllViews(); blocks.clear(); cell = CellCollection.getInstance().getCurrentCell(); Assert.assertNotNull(cell); for (String block : cell.getOutputBlocks()) { if (cell.hasCachedOutput(block)) { OutputBlock outputBlock = newOutputBlock(); outputBlock.set(block); } } //block.getSettings().setCacheMode(WebSettings.LOAD_CACHE_ELSE_NETWORK); // displayResult(); //block.getSettings().setCacheMode(WebSettings.LOAD_NORMAL); } public void clear() { removeAllViews(); blocks.clear(); cell.clearCache(); } @Override public void onInteractListener(Interact interact, String name, Object value) { listener.onSageInteractListener(interact, name, value); } }
12085952-sageandroid
app-v2/src/org/sagemath/droid/OutputView.java
Java
gpl3
4,481
package org.sagemath.droid; import java.util.LinkedList; import android.app.Activity; import android.graphics.Color; import android.graphics.PixelFormat; import android.os.Bundle; import android.support.v4.app.ListFragment; import android.util.Log; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.view.Window; import android.widget.AdapterView; import android.widget.AdapterView.OnItemClickListener; import android.widget.ArrayAdapter; import android.widget.ListView; public class CellGroupsFragment extends ListFragment { private static final String TAG = "CellGroupsFragment"; interface OnGroupSelectedListener { public void onGroupSelected(String group); } private OnGroupSelectedListener listener; public void setOnGroupSelected(OnGroupSelectedListener listener) { this.listener = listener; } @Override public void onListItemClick(ListView parent, View view, int position, long id) { adapter.setSelectedItem(position); String group = groups.get(position); listener.onGroupSelected(group); } protected LinkedList<String> groups; protected CellGroupsAdapter adapter; @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); groups = CellCollection.getInstance().groups(); adapter = new CellGroupsAdapter(getActivity().getApplicationContext(), groups); setListAdapter(adapter); } @Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { return inflater.inflate(R.layout.cell_groups_layout, container); } @Override public void onResume() { super.onResume(); } @Override public void onAttach(Activity activity) { super.onAttach(activity); Window window = activity.getWindow(); window.setFormat(PixelFormat.RGBA_8888); } }
12085952-sageandroid
app-v2/src/org/sagemath/droid/CellGroupsFragment.java
Java
gpl3
1,864
package org.sagemath.droid; import org.sagemath.droid.CellGroupsFragment.OnGroupSelectedListener; import sheetrock.panda.changelog.ChangeLog; import com.example.android.actionbarcompat.ActionBarActivity; import android.content.Intent; import android.os.Bundle; import android.support.v4.app.FragmentActivity; import android.util.Log; import android.view.Menu; import android.view.MenuItem; public class CellActivity extends ActionBarActivity implements OnGroupSelectedListener{ private final static String TAG = "CellActivity"; private ChangeLog changeLog; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); CellCollection.initialize(getApplicationContext()); setContentView(R.layout.cell_activity); changeLog = new ChangeLog(this); if (changeLog.firstRun()) changeLog.getLogDialog().show(); CellGroupsFragment groupsFragment = (CellGroupsFragment) getSupportFragmentManager().findFragmentById(R.id.cell_groups_fragment); groupsFragment.setOnGroupSelected(this); CellListFragment listFragment = (CellListFragment) getSupportFragmentManager().findFragmentById(R.id.cell_list_fragment); if (listFragment != null && listFragment.isInLayout()) listFragment.switchToGroup(null); } public static final String INTENT_SWITCH_GROUP = "intent_switch_group"; @Override public void onGroupSelected(String group) { CellListFragment listFragment = (CellListFragment) getSupportFragmentManager().findFragmentById(R.id.cell_list_fragment); if (listFragment == null || !listFragment.isInLayout()) { Intent i = new Intent(getApplicationContext(), CellListActivity.class); i.putExtra(INTENT_SWITCH_GROUP, group); startActivity(i); } else { listFragment.switchToGroup(group); } } @Override public boolean onOptionsItemSelected(MenuItem item) { switch (item.getItemId()) { case android.R.id.home: finish(); return true; } return super.onOptionsItemSelected(item); } }
12085952-sageandroid
app-v2/src/org/sagemath/droid/CellActivity.java
Java
gpl3
2,054
package org.sagemath.droid; import java.util.LinkedList; import java.util.ListIterator; import junit.framework.Assert; import org.sagemath.singlecellserver.CommandOutput; import org.sagemath.singlecellserver.DataFile; import org.sagemath.singlecellserver.DisplayData; import org.sagemath.singlecellserver.ExecuteReply; import org.sagemath.singlecellserver.HtmlFiles; import org.sagemath.singlecellserver.PythonOutput; import org.sagemath.singlecellserver.ResultStream; import org.sagemath.singlecellserver.Traceback; import android.content.Context; import android.text.TextUtils; import android.util.Log; import android.webkit.WebView; public class OutputBlock extends WebView { private final static String TAG = "OutputBlock"; private final CellData cell; public OutputBlock(Context context, CellData cell) { super(context); this.cell = cell; } // The output_block field of the JSON message protected String name; private static String htmlify(String str) { StringBuilder s = new StringBuilder(); s.append("<pre style=\"font-size:130%\">"); String[] lines = str.split("\n"); for (int i=0; i<lines.length; i++) { if (i>0) s.append("&#13;&#10;"); s.append(TextUtils.htmlEncode(lines[i])); } s.append("</pre>"); return s.toString(); } private LinkedList<String> divs = new LinkedList<String>(); public String getHtml() { StringBuilder s = new StringBuilder(); s.append("<html><body>"); ListIterator<String> iter = divs.listIterator(); while (iter.hasNext()) { s.append("<div>"); s.append(iter.next()); s.append("</div>"); } s.append("</body></html>"); return s.toString(); } private void addDiv(CommandOutput output) { if (output instanceof DataFile) addDivDataFile((DataFile) output); else if (output instanceof HtmlFiles) addDivHtmlFiles((HtmlFiles) output); else if (output instanceof DisplayData) addDivDisplayData((DisplayData) output); else if (output instanceof PythonOutput) addDivPythonOutput((PythonOutput) output); else if (output instanceof ResultStream) addDivResultStream((ResultStream) output); else if (output instanceof Traceback) addDivTraceback((Traceback) output); else if (output instanceof ExecuteReply) addDivExecuteReply((ExecuteReply) output); else divs.add("Unknown output: "+output.toShortString()); } private void addDivDataFile(DataFile dataFile) { String uri = dataFile.getURI().toString(); String div; String mime = dataFile.getMime(); if (dataFile.mime().equals("image/png") || dataFile.mime().equals("image/jpg")) div = "<img src=\"" + uri + "\" alt=\"plot output\"></img>"; else if (dataFile.mime().equals("image/svg")) div = "<object data\"" + uri + "\" type=\"image/svg+xml\"></object>"; else div = "Unknow MIME type "+dataFile.mime(); divs.add(div); } private void addDivHtmlFiles(HtmlFiles htmlFiles) { String div = "HTML"; divs.add(div); } private void addDivDisplayData(DisplayData displayData) { String div = displayData.toHTML(); divs.add(div); } private void addDivPythonOutput(PythonOutput pythonOutput) { String div = htmlify(pythonOutput.get()); divs.add(div); } private void addDivResultStream(ResultStream resultStream) { String div = htmlify(resultStream.get()); divs.add(div); } private void addDivTraceback(Traceback traceback) { String div = htmlify(traceback.toString()); divs.add(div); } private void addDivExecuteReply(ExecuteReply reply) { if (reply.getStatus().equals("ok")) divs.add("<font color=\"green\">ok</font>"); else divs.add(reply.toString()); } public void add(CommandOutput output) { if (name == null) { Log.e(TAG, "adding output without initially setting it"); return; } if (!name.equals(output.outputBlock())) Log.e(TAG, "Output has wrong output_block field"); addDiv(output); // loadData(getHtml(), "text/html", "UTF-8"); cell.saveOutput(getOutputBlock(), getHtml()); loadUrl(cell.getUrlString(getOutputBlock())); } public void set(String output_block) { if (cell.hasCachedOutput(output_block)) loadUrl(cell.getUrlString(output_block)); } public void set(CommandOutput output) { if (name == null) { name = output.outputBlock(); } if (!name.equals(output.outputBlock())) Log.e(TAG, "Output has wrong output_block field"); divs.clear(); add(output); } public String getOutputBlock() { return name; } }
12085952-sageandroid
app-v2/src/org/sagemath/droid/OutputBlock.java
Java
gpl3
4,441
package org.sagemath.droid; import org.json.JSONArray; import org.json.JSONException; import org.json.JSONObject; import android.content.Context; import android.text.format.Formatter; import android.util.Log; import android.widget.LinearLayout; import android.widget.SeekBar; import android.widget.SeekBar.OnSeekBarChangeListener; import android.widget.TextView; public class InteractContinuousSlider extends InteractControlBase implements OnSeekBarChangeListener { private final static String TAG = "InteractContinuousSlider"; protected String format; protected SeekBar seekBar; protected TextView nameValueText; public InteractContinuousSlider(InteractView interactView, String variable, Context context) { super(interactView, variable, context); nameValueText = new TextView(context); nameValueText.setMaxLines(1); nameValueText.setLayoutParams(new LinearLayout.LayoutParams( LinearLayout.LayoutParams.WRAP_CONTENT, LinearLayout.LayoutParams.WRAP_CONTENT, 0.0f)); nameValueText.setPadding( nameValueText.getPaddingLeft()+10, nameValueText.getPaddingTop()+5, nameValueText.getPaddingRight()+5, nameValueText.getPaddingBottom()); addView(nameValueText); seekBar = new SeekBar(context); seekBar.setMax(10000); LinearLayout.LayoutParams params = new LinearLayout.LayoutParams( LinearLayout.LayoutParams.MATCH_PARENT, LinearLayout.LayoutParams.WRAP_CONTENT, 1.0f); seekBar.setLayoutParams(params); // seekBar.setPadding(seekBar.getPaddingLeft() + 10, // seekBar.getPaddingTop(), // seekBar.getPaddingRight(), // seekBar.getPaddingBottom()); addView(seekBar); seekBar.setOnSeekBarChangeListener(this); format = variable + "=%3.2f"; } private double range_min = 0; private double range_max = 1; private double step = 0.1; public void setRange(double range_min, double range_max, double step) { this.range_min = range_min; this.range_max = range_max; this.step = step; updateValueText(); } public void setRange(JSONObject control) { JSONArray range; try { range = control.getJSONArray("range"); this.range_min = range.getDouble(0); this.range_max = range.getDouble(1); this.step = control.getDouble("step"); String s = control.getString("step"); int digits = Math.max( countDigitsAfterComma(control.getString("step")), countDigitsAfterComma(range.getString(0))); format = variable + "=%4." + digits + "f"; } catch (JSONException e) { Log.e(TAG, e.getLocalizedMessage()); setRange(0, 1 , 0.1); } updateValueText(); } public Object getValue() { int raw = seekBar.getProgress(); long i = Math.round(((double)raw) / seekBar.getMax() * (range_max - range_min) / step); double value = i * step + range_min; // range_max-range_min is not necessarily divisible by step value = Math.min(range_max, value); return value; } private void updateValueText() { nameValueText.setText(String.format(format, getValue())); } @Override public void onProgressChanged(SeekBar seekBar, int progress, boolean fromUser) { updateValueText(); } @Override public void onStartTrackingTouch(SeekBar seekBar) { } @Override public void onStopTrackingTouch(SeekBar seekBar) { interactView.notifyChange(this); } }
12085952-sageandroid
app-v2/src/org/sagemath/droid/InteractContinuousSlider.java
Java
gpl3
3,288
package org.sagemath.droid; import java.io.FileReader; import java.io.IOException; import java.io.InputStream; import java.util.LinkedList; import java.util.UUID; import javax.xml.parsers.DocumentBuilder; import javax.xml.parsers.DocumentBuilderFactory; import javax.xml.parsers.ParserConfigurationException; import org.w3c.dom.Document; import org.w3c.dom.Element; import org.w3c.dom.Node; import org.w3c.dom.NodeList; import org.xml.sax.InputSource; import org.xml.sax.SAXException; import android.util.Log; public class CellCollectionXMLParser { private static final String TAG = "CellCollectionXMLParser"; private Document dom; private LinkedList<CellData> data; protected void parseXML(InputStream inputStream){ dom = null; data = new LinkedList<CellData>(); DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance(); try { DocumentBuilder db = dbf.newDocumentBuilder(); InputSource is = new InputSource(inputStream); dom = db.parse(is); } catch (ParserConfigurationException e) { Log.e(TAG, "XML parse error: " + e.getLocalizedMessage()); } catch (SAXException e) { Log.e(TAG, "Wrong XML file structure: " + e.getLocalizedMessage()); } catch (IOException e) { Log.e(TAG, "I/O exeption: " + e.getLocalizedMessage()); } } public LinkedList<CellData> parse(InputStream inputStream) { parseXML(inputStream); if (dom != null) parseDocument(); return data; } private void parseDocument(){ Element root = dom.getDocumentElement(); NodeList nl = root.getElementsByTagName("cell"); if(nl != null && nl.getLength() > 0) { for(int i = 0 ; i < nl.getLength();i++) { Element element = (Element)nl.item(i); CellData cell = getCellData(element); data.add(cell); } } } private CellData getCellData(Element cellElement) { CellData cell = new CellData(); cell.group = getTextValue(cellElement, "group"); cell.title = getTextValue(cellElement, "title"); cell.description = getTextValue(cellElement, "description"); cell.input = getTextValue(cellElement, "input"); cell.rank = getIntValue(cellElement, "rank"); cell.uuid = getUuidValue(cellElement, "uuid"); return cell; } private String getTextValue(Element element, String tagName) { String textVal = null; NodeList nl = element.getElementsByTagName(tagName); if(nl != null && nl.getLength() > 0) { Element el = (Element)nl.item(0); textVal = el.getFirstChild().getNodeValue(); } return textVal.trim(); } private Integer getIntValue(Element element, String tagName) { return Integer.parseInt(getTextValue(element, tagName)); } private UUID getUuidValue(Element element, String tagName) { return UUID.fromString(getTextValue(element, tagName)); } }
12085952-sageandroid
app-v2/src/org/sagemath/droid/CellCollectionXMLParser.java
Java
gpl3
2,762
package org.sagemath.droid; import java.util.LinkedList; import android.content.Context; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.ArrayAdapter; import android.widget.TextView; public class CellListAdapter extends ArrayAdapter<CellData> { private final Context context; private LinkedList<CellData> cells; public CellListAdapter(Context context, LinkedList<CellData> cells) { super(context, R.layout.cell_list_item, cells); this.context = context; this.cells = cells; } static class ViewHolder { protected TextView titleView; protected TextView descriptionView; } @Override public View getView(int position, View convertView, ViewGroup parent) { View item; TextView titleView; TextView descriptionView; if (convertView == null) { LayoutInflater inflater = (LayoutInflater) context .getSystemService(Context.LAYOUT_INFLATER_SERVICE); item = inflater.inflate(R.layout.cell_list_item, parent, false); titleView = (TextView) item.findViewById(R.id.cell_title); descriptionView = (TextView) item.findViewById(R.id.cell_description); final ViewHolder viewHolder = new ViewHolder(); viewHolder.titleView = titleView; viewHolder.descriptionView = descriptionView; item.setTag(viewHolder); } else { item = convertView; ViewHolder viewHolder = (ViewHolder)convertView.getTag(); titleView = viewHolder.titleView; descriptionView = viewHolder.descriptionView; } CellData cell = cells.get(position); titleView.setText(cell.title); descriptionView.setText(cell.description); return item; } }
12085952-sageandroid
app-v2/src/org/sagemath/droid/CellListAdapter.java
Java
gpl3
1,644
package org.sagemath.droid; import java.util.LinkedList; import org.sagemath.droid.CellGroupsFragment.OnGroupSelectedListener; import android.content.Intent; import android.os.Bundle; import android.support.v4.app.ListFragment; import android.view.View; import android.widget.ArrayAdapter; import android.widget.ListView; public class CellListFragment extends ListFragment { private static final String TAG = "CellListFragment"; protected LinkedList<CellData> cells = new LinkedList<CellData>(); protected CellListAdapter adapter; @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); adapter = new CellListAdapter(getActivity(), cells); setListAdapter(adapter); } public void switchToGroup(String group) { CellCollection cellCollection = CellCollection.getInstance(); cells.clear(); if (group == null) cells.addAll(cellCollection.getCurrentGroup()); else cells.addAll(cellCollection.getGroup(group)); cellCollection.setCurrentCell(cells.getFirst()); if (adapter != null) adapter.notifyDataSetChanged(); } @Override public void onListItemClick(ListView l, View v, int position, long id) { super.onListItemClick(l, v, position, id); CellData cell = cells.get(position); CellCollection.getInstance().setCurrentCell(cell); Intent i = new Intent(getActivity().getApplicationContext(), SageActivity.class); startActivity(i); } }
12085952-sageandroid
app-v2/src/org/sagemath/droid/CellListFragment.java
Java
gpl3
1,439
package org.sagemath.droid; import android.content.Context; import android.widget.LinearLayout; public abstract class InteractControlBase extends LinearLayout { private final static String TAG = "InteractControlBase"; protected final String variable; protected final InteractView interactView; public InteractControlBase(InteractView interactView, String variable, Context context) { super(context); this.interactView = interactView; this.variable = variable; setFocusable(true); setFocusableInTouchMode(true); } protected String getVariableName() { return variable; } protected abstract Object getValue(); protected int countDigitsAfterComma(String s) { int pos = s.lastIndexOf('.'); if (pos == -1) return 0; else return s.length() - pos - 1; } }
12085952-sageandroid
app-v2/src/org/sagemath/droid/InteractControlBase.java
Java
gpl3
800
package org.sagemath.droid; import java.io.BufferedInputStream; import java.io.BufferedOutputStream; import java.io.DataInputStream; import java.io.DataOutputStream; import java.io.File; import java.io.FileInputStream; import java.io.FileNotFoundException; import java.io.FileOutputStream; import java.io.IOException; import java.io.OutputStream; import java.util.LinkedList; import java.util.UUID; import android.net.Uri; import android.util.Log; public class CellData { private final static String TAG = "CellData"; protected UUID uuid; protected String group; protected String title; protected String description; protected String input; protected Integer rank; protected LinkedList<String> outputBlocks; public String getGroup() { return group; } public String getTitle() { return title; } public String getDescription() { return description; } public String getInput() { return input; } private File cache; public File cacheDir() { if (cache != null) return cache; File base = CellCollection.getInstance().getCacheDirBase(); cache = new File(base, uuid.toString()); if (!cache.exists()) { boolean rc = cache.mkdir(); if (!rc) Log.e(TAG, "Unable to create directory "+cache.getAbsolutePath()); } return cache; } protected File cacheDirIndexFile(String output_block) { addOutputBlock(output_block); return new File(cacheDir(), output_block + ".html"); } public void saveOutput(String output_block, String html) { addOutputBlock(output_block); File f = cacheDirIndexFile(output_block); FileOutputStream os; try { os = new FileOutputStream(f); } catch (FileNotFoundException e) { Log.e(TAG, "Unable to save output: " + e.getLocalizedMessage()); return; } try { os.write(html.getBytes()); } catch (IOException e) { Log.e(TAG, "Unable to save output: " + e.getLocalizedMessage()); } finally { try { os.close(); } catch (IOException e) { Log.e(TAG, "Unable to save output: " + e.getLocalizedMessage()); } } } public String getUrlString(String block) { Uri uri = Uri.fromFile(cacheDirIndexFile(block)); return uri.toString(); } public boolean hasCachedOutput(String block) { return cacheDirIndexFile(block).exists(); } public void clearCache() { File[] files = cacheDir().listFiles(); for (File file : files) if (!file.delete()) Log.e(TAG, "Error deleting "+file); } private void addOutputBlock(String block) { if (outputBlocks == null) outputBlocks = new LinkedList<String>(); if (!outputBlocks.contains(block)) { outputBlocks.add(block); saveOutputBlocks(); } } private void saveOutputBlocks() { File file = new File(cacheDir(), "output_blocks"); try { saveOutputBlocks(file); } catch (IOException e) { Log.e(TAG, "Unable to save output_block list: "+e.getLocalizedMessage()); } } private void saveOutputBlocks(File file) throws IOException { FileOutputStream fos = new FileOutputStream(file); BufferedOutputStream bos = new BufferedOutputStream(fos); DataOutputStream dos = new DataOutputStream(bos); dos.writeInt(outputBlocks.size()); for (String block : outputBlocks) { dos.writeUTF(block); } // Log.e(TAG, "saved "+outputBlocks.size()+" output_block fields"); dos.close(); } private LinkedList<String> loadOutputBlocks(File file) throws IOException { LinkedList<String> result = new LinkedList<String>(); FileInputStream fis = new FileInputStream(file); BufferedInputStream bis = new BufferedInputStream(fis); DataInputStream dis = new DataInputStream(bis); int n = dis.readInt(); for (int i=0; i<n; i++) { String block = dis.readUTF(); } // Log.e(TAG, "read "+n+" output_block fields"); dis.close(); return result; } public LinkedList<String> getOutputBlocks() { if (outputBlocks != null) return outputBlocks; outputBlocks = new LinkedList<String>(); File file = new File(cacheDir(), "output_blocks"); if (!file.exists()) return outputBlocks; try { outputBlocks.addAll(loadOutputBlocks(file)); } catch (IOException e) { Log.e(TAG, "Unable to load output_block list: "+e.getLocalizedMessage()); } return outputBlocks; } }
12085952-sageandroid
app-v2/src/org/sagemath/droid/CellData.java
Java
gpl3
4,219
package org.sagemath.droid; import org.sagemath.droid.CellGroupsFragment.OnGroupSelectedListener; import com.example.android.actionbarcompat.ActionBarActivity; import android.app.Activity; import android.content.Intent; import android.os.Bundle; import android.view.MenuItem; public class CellListActivity extends ActionBarActivity { @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); CellCollection.initialize(getApplicationContext()); setContentView(R.layout.cell_list_fragment); CellListFragment listFragment = (CellListFragment) getSupportFragmentManager().findFragmentById(R.id.cell_list_fragment); Intent intent = getIntent(); if (intent == null) listFragment.switchToGroup(null); else { String group = intent.getStringExtra(CellActivity.INTENT_SWITCH_GROUP); listFragment.switchToGroup(group); } setTitle(CellCollection.getInstance().getCurrentCell().getGroup()); } @Override public boolean onOptionsItemSelected(MenuItem item) { switch (item.getItemId()) { case android.R.id.home: finish(); return true; } return super.onOptionsItemSelected(item); } }
12085952-sageandroid
app-v2/src/org/sagemath/droid/CellListActivity.java
Java
gpl3
1,219
package org.sagemath.droid; import java.util.Arrays; import java.util.Iterator; import java.util.LinkedList; import java.util.List; import java.util.ListIterator; import org.json.JSONArray; import org.json.JSONException; import org.json.JSONObject; import org.sagemath.singlecellserver.Interact; import android.content.Context; import android.util.Log; import android.widget.LinearLayout; import android.widget.SeekBar; import android.widget.SlidingDrawer; import android.widget.TableLayout; import android.widget.TableRow; public class InteractView extends TableLayout { private final static String TAG = "InteractView"; private Context context; private TableRow row_top, row_center, row_bottom; public InteractView(Context context) { super(context); this.context = context; setLayoutParams(new LayoutParams( LayoutParams.MATCH_PARENT, LayoutParams.WRAP_CONTENT)); } interface OnInteractListener { public void onInteractListener(Interact interact, String name, Object value); } private OnInteractListener listener; protected void setOnInteractListener(OnInteractListener listener) { this.listener = listener; } private Interact interact; private JSONObject layout; private List<String> layoutPositions = Arrays.asList( "top_left", "top_center", "top_right", "left", "right", "bottom_left", "bottom_center", "bottom_right"); public void set(Interact interact) { // Log.e(TAG, "set "+interact.toShortString()); this.interact = interact; removeAllViews(); JSONObject layout = interact.getLayout(); ListIterator<String> iter = layoutPositions.listIterator(); while (iter.hasNext()) { JSONArray variables; try { variables = layout.getJSONArray(iter.next()); for (int i=0; i<variables.length(); i++) addInteract(interact, variables.getString(i)); } catch (JSONException e) {} } } public void addInteract(Interact interact, String variable) { JSONObject controls = interact.getControls(); try { JSONObject control = controls.getJSONObject(variable); String control_type = control.getString("control_type"); if (control_type.equals("slider")) { String subtype = control.getString("subtype"); if (subtype.equals("discrete")) addDiscreteSlider(variable, control); else if (subtype.equals("continuous")) addContinuousSlider(variable, control); else Log.e(TAG, "Unknown slider type: "+subtype); } else if (control_type.equals("selector")) { addSelector(variable, control); } } catch (JSONException e) { Log.e(TAG, e.getLocalizedMessage()); } } // String variable = "n"; // JSONObject control = interact.getControls(); // try { // control = new JSONObject( //" {"+ //" \"raw\":true,"+ //" \"control_type\":\"slider\","+ //" \"display_value\":true,"+ //" \"default\":0,"+ //" \"range\":["+ //" 0,"+ //" 100"+ //" ],"+ //" \"subtype\":\"continuous\","+ //" \"label\":null,"+ //" \"step\":0.4"+ //" }"); // addSlider(variable, control); // } catch (JSONException e) { // e.printStackTrace(); // return; // } protected void addContinuousSlider(String variable, JSONObject control) throws JSONException { InteractContinuousSlider slider = new InteractContinuousSlider(this, variable, context); slider.setRange(control); addView(slider); } protected void addDiscreteSlider(String variable, JSONObject control) throws JSONException { InteractDiscreteSlider slider = new InteractDiscreteSlider(this, variable, context); slider.setValues(control); addView(slider); } protected void addSelector(String variable, JSONObject control) throws JSONException { InteractSelector selector = new InteractSelector(this, variable, context); selector.setValues(control); addView(selector); } protected void notifyChange(InteractControlBase view) { listener.onInteractListener(interact, view.getVariableName(), view.getValue()); } }
12085952-sageandroid
app-v2/src/org/sagemath/droid/InteractView.java
Java
gpl3
4,070
package org.sagemath.droid; import java.io.File; import java.io.IOException; import java.io.InputStream; import java.util.Collections; import java.util.Comparator; import java.util.LinkedList; import java.util.ListIterator; import java.util.UUID; import javax.xml.parsers.DocumentBuilder; import javax.xml.parsers.DocumentBuilderFactory; import javax.xml.parsers.ParserConfigurationException; import junit.framework.Assert; import org.w3c.dom.Document; import org.w3c.dom.Element; import org.w3c.dom.Node; import org.w3c.dom.NodeList; import org.xml.sax.InputSource; import org.xml.sax.SAXException; import android.content.Context; import android.util.Log; public class CellCollection { private final static String TAG = "CellCollection"; private static CellCollection instance = new CellCollection(); private LinkedList<CellData> data; private CellData current; private Context context; private CellCollection() {} public static void initialize(Context context) { if (instance.data != null) return; instance.context = context; instance.data = new LinkedList<CellData>(); CellCollectionXMLParser parser = new CellCollectionXMLParser(); InputStream ins = context.getResources().openRawResource(R.raw.cell_collection); instance.data.addAll(parser.parse(ins)); instance.current = instance.getGroup("My Worksheets").getFirst(); } public static CellCollection getInstance() { return instance; } public ListIterator<CellData> listIterator() { return data.listIterator(); } public CellData getCurrentCell() { return current; } public void setCurrentCell(CellData cell) { current = cell; } public LinkedList<CellData> getCurrentGroup() { return getGroup(current.group); } private LinkedList<String> groupsCache; public LinkedList<String> groups() { if (groupsCache != null) return groupsCache; LinkedList<String> g = new LinkedList<String>(); for (CellData cell : data) { if (g.contains(cell.group)) continue; g.add(cell.group); } Collections.sort(g); groupsCache = g; return g; } public LinkedList<CellData> getGroup(String group) { LinkedList<CellData> result = new LinkedList<CellData>(); for (CellData cell : data) if (cell.group.equals(group)) result.add(cell); Collections.sort(result, new CellComparator()); return result; } public static class CellComparator implements Comparator<CellData> { @Override public int compare(CellData c1, CellData c2) { int cmp = c2.rank.compareTo(c1.rank); if (cmp != 0) return cmp; return c1.title.compareToIgnoreCase(c2.title); } } protected File getCacheDirBase() { return context.getCacheDir(); } }
12085952-sageandroid
app-v2/src/org/sagemath/droid/CellCollection.java
Java
gpl3
2,697
package org.sagemath.droid; import java.util.LinkedList; import org.json.JSONArray; import org.json.JSONException; import org.json.JSONObject; import android.content.Context; import android.text.format.Formatter; import android.util.Log; import android.widget.LinearLayout; import android.widget.SeekBar; import android.widget.SeekBar.OnSeekBarChangeListener; import android.widget.TextView; public class InteractDiscreteSlider extends InteractControlBase implements OnSeekBarChangeListener { private final static String TAG = "InteractDiscreteSlider"; protected SeekBar seekBar; protected TextView nameValueText; public InteractDiscreteSlider(InteractView interactView, String variable, Context context) { super(interactView, variable, context); nameValueText = new TextView(context); nameValueText.setMaxLines(1); nameValueText.setLayoutParams(new LinearLayout.LayoutParams( LinearLayout.LayoutParams.WRAP_CONTENT, LinearLayout.LayoutParams.WRAP_CONTENT, 0.0f)); nameValueText.setPadding( nameValueText.getPaddingLeft()+10, nameValueText.getPaddingTop()+5, nameValueText.getPaddingRight()+5, nameValueText.getPaddingBottom()); addView(nameValueText); seekBar = new SeekBar(context); seekBar.setMax(1); LinearLayout.LayoutParams params = new LinearLayout.LayoutParams( LinearLayout.LayoutParams.MATCH_PARENT, LinearLayout.LayoutParams.WRAP_CONTENT, 1.0f); seekBar.setLayoutParams(params); addView(seekBar); seekBar.setOnSeekBarChangeListener(this); } private LinkedList<String> values = new LinkedList<String>(); public void setValues(LinkedList<String> values) { this.values = values; seekBar.setMax(this.values.size()-1); updateValueText(); } public void setValues(JSONObject control) { this.values.clear(); try { JSONArray values= control.getJSONArray("values"); for (int i=0; i<values.length(); i++) this.values.add( values.getString(i) ); } catch (JSONException e) { Log.e(TAG, e.getLocalizedMessage()); this.values.add("0"); this.values.add("1"); } seekBar.setMax(this.values.size()-1); updateValueText(); } public Integer getValue() { int raw = seekBar.getProgress(); return raw; } private void updateValueText() { nameValueText.setText(getVariableName() + "=" + values.get(getValue())); } @Override public void onProgressChanged(SeekBar seekBar, int progress, boolean fromUser) { updateValueText(); } @Override public void onStartTrackingTouch(SeekBar seekBar) { } @Override public void onStopTrackingTouch(SeekBar seekBar) { interactView.notifyChange(this); } }
12085952-sageandroid
app-v2/src/org/sagemath/droid/InteractDiscreteSlider.java
Java
gpl3
2,644
package org.sagemath.droid; import java.util.LinkedList; import org.json.JSONArray; import org.json.JSONException; import org.json.JSONObject; import android.content.Context; import android.text.format.Formatter; import android.util.Log; import android.view.View; import android.widget.AdapterView; import android.widget.ArrayAdapter; import android.widget.LinearLayout; import android.widget.SeekBar; import android.widget.AdapterView.OnItemSelectedListener; import android.widget.SeekBar.OnSeekBarChangeListener; import android.widget.Spinner; import android.widget.TextView; public class InteractSelector extends InteractControlBase implements OnItemSelectedListener { private final static String TAG = "InteractSelector"; protected Spinner spinner; protected ArrayAdapter<String> adapter; protected TextView nameValueText; protected int currentSelection = 0; public InteractSelector(InteractView interactView, String variable, Context context) { super(interactView, variable, context); nameValueText = new TextView(context); nameValueText.setMaxLines(1); // nameValueText.setLayoutParams(new LinearLayout.LayoutParams( // LinearLayout.LayoutParams.WRAP_CONTENT, // LinearLayout.LayoutParams.WRAP_CONTENT, 0.0f)); nameValueText.setPadding( nameValueText.getPaddingLeft()+10, nameValueText.getPaddingTop()+5, nameValueText.getPaddingRight()+5, nameValueText.getPaddingBottom()); addView(nameValueText); spinner = new Spinner(context); // LinearLayout.LayoutParams params = new LinearLayout.LayoutParams( // LinearLayout.LayoutParams.WRAP_CONTENT, // LinearLayout.LayoutParams.WRAP_CONTENT, 1.0f); // spinner.setLayoutParams(params); addView(spinner); spinner.setOnItemSelectedListener(this); adapter = new ArrayAdapter<String>(context, android.R.layout.simple_spinner_dropdown_item, values); spinner.setAdapter(adapter); } private LinkedList<String> values = new LinkedList<String>(); public void setValues(LinkedList<String> values) { this.values = values; adapter.notifyDataSetChanged(); currentSelection = 0; spinner.setSelection(0); updateValueText(); } public void setValues(JSONObject control) { this.values.clear(); try { JSONArray values= control.getJSONArray("value_labels"); for (int i=0; i<values.length(); i++) this.values.add( values.getString(i) ); } catch (JSONException e) { Log.e(TAG, e.getLocalizedMessage()); this.values.add("0"); this.values.add("1"); } adapter.notifyDataSetChanged(); currentSelection = 0; spinner.setSelection(0); updateValueText(); } public Integer getValue() { int raw = spinner.getSelectedItemPosition(); return raw; } private void updateValueText() { if (values.isEmpty() || getValue()==-1) return; Log.e(TAG, "value = "+getValue()); nameValueText.setText(getVariableName() + ":"); } @Override public void onItemSelected(AdapterView<?> parent, View view, int position, long arg3) { if (currentSelection == position) return; currentSelection = position; Log.e(TAG, "selected "+position); updateValueText(); interactView.notifyChange(this); } @Override public void onNothingSelected(AdapterView<?> parent) { } }
12085952-sageandroid
app-v2/src/org/sagemath/droid/InteractSelector.java
Java
gpl3
3,240
package org.sagemath.droid; import java.util.LinkedList; import javax.crypto.spec.IvParameterSpec; import android.content.Context; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.ArrayAdapter; import android.widget.TextView; public class CellGroupsAdapter extends ArrayAdapter<String> { private final Context context; private LinkedList<String> groups; public CellGroupsAdapter(Context context, LinkedList<String> groups) { super(context, R.layout.cell_groups_item, groups); this.context = context; this.groups = groups; selected = groups.indexOf(CellCollection.getInstance().getCurrentCell().getGroup()); } private int selected; public void setSelectedItem(int position) { selected = position; notifyDataSetChanged(); } @Override public View getView(int position, View convertView, ViewGroup parent) { TextView item; if (convertView == null) { LayoutInflater inflater = (LayoutInflater) context .getSystemService(Context.LAYOUT_INFLATER_SERVICE); item = (TextView) inflater.inflate(R.layout.cell_groups_item, parent, false); } else { item = (TextView) convertView; } item.setText(groups.get(position)); if (position == selected) item.setBackgroundResource(R.drawable.white); else item.setBackgroundResource(R.drawable.transparent); return item; } }
12085952-sageandroid
app-v2/src/org/sagemath/droid/CellGroupsAdapter.java
Java
gpl3
1,392
/* * Copyright 2011 The Android Open Source Project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.example.android.actionbarcompat; import android.app.Activity; import android.os.Build; import android.os.Bundle; import android.view.Menu; import android.view.MenuInflater; /** * An abstract class that handles some common action bar-related functionality in the app. This * class provides functionality useful for both phones and tablets, and does not require any Android * 3.0-specific features, although it uses them if available. * * Two implementations of this class are {@link ActionBarHelperBase} for a pre-Honeycomb version of * the action bar, and {@link ActionBarHelperHoneycomb}, which uses the built-in ActionBar features * in Android 3.0 and later. */ public abstract class ActionBarHelper { protected Activity mActivity; /** * Factory method for creating {@link ActionBarHelper} objects for a * given activity. Depending on which device the app is running, either a basic helper or * Honeycomb-specific helper will be returned. */ public static ActionBarHelper createInstance(Activity activity) { if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.ICE_CREAM_SANDWICH) { return new ActionBarHelperICS(activity); } else if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB) { return new ActionBarHelperHoneycomb(activity); } else { return new ActionBarHelperBase(activity); } } protected ActionBarHelper(Activity activity) { mActivity = activity; } /** * Action bar helper code to be run in {@link Activity#onCreate(android.os.Bundle)}. */ public void onCreate(Bundle savedInstanceState) { } /** * Action bar helper code to be run in {@link Activity#onPostCreate(android.os.Bundle)}. */ public void onPostCreate(Bundle savedInstanceState) { } /** * Action bar helper code to be run in {@link Activity#onCreateOptionsMenu(android.view.Menu)}. * * NOTE: Setting the visibility of menu items in <em>menu</em> is not currently supported. */ public boolean onCreateOptionsMenu(Menu menu) { return true; } /** * Action bar helper code to be run in {@link Activity#onTitleChanged(CharSequence, int)}. */ public void onTitleChanged(CharSequence title, int color) { } /** * Sets the indeterminate loading state of the item with ID {@link R.id.menu_refresh}. * (where the item ID was menu_refresh). */ public abstract void setRefreshActionItemState(boolean refreshing); /** * Returns a {@link MenuInflater} for use when inflating menus. The implementation of this * method in {@link ActionBarHelperBase} returns a wrapped menu inflater that can read * action bar metadata from a menu resource pre-Honeycomb. */ public MenuInflater getMenuInflater(MenuInflater superMenuInflater) { return superMenuInflater; } }
12085952-sageandroid
app-v2/src/com/example/android/actionbarcompat/ActionBarHelper.java
Java
gpl3
3,551
/* * Copyright 2011 The Android Open Source Project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.example.android.actionbarcompat; import android.content.ComponentName; import android.content.Context; import android.content.Intent; import android.content.res.Resources; import android.view.KeyEvent; import android.view.Menu; import android.view.MenuItem; import android.view.SubMenu; import java.util.ArrayList; /** * A <em>really</em> dumb implementation of the {@link android.view.Menu} interface, that's only * useful for our actionbar-compat purposes. See * <code>com.android.internal.view.menu.MenuBuilder</code> in AOSP for a more complete * implementation. */ public class SimpleMenu implements Menu { private Context mContext; private Resources mResources; private ArrayList<SimpleMenuItem> mItems; public SimpleMenu(Context context) { mContext = context; mResources = context.getResources(); mItems = new ArrayList<SimpleMenuItem>(); } public Context getContext() { return mContext; } public Resources getResources() { return mResources; } public MenuItem add(CharSequence title) { return addInternal(0, 0, title); } public MenuItem add(int titleRes) { return addInternal(0, 0, mResources.getString(titleRes)); } public MenuItem add(int groupId, int itemId, int order, CharSequence title) { return addInternal(itemId, order, title); } public MenuItem add(int groupId, int itemId, int order, int titleRes) { return addInternal(itemId, order, mResources.getString(titleRes)); } /** * Adds an item to the menu. The other add methods funnel to this. */ private MenuItem addInternal(int itemId, int order, CharSequence title) { final SimpleMenuItem item = new SimpleMenuItem(this, itemId, order, title); mItems.add(findInsertIndex(mItems, order), item); return item; } private static int findInsertIndex(ArrayList<? extends MenuItem> items, int order) { for (int i = items.size() - 1; i >= 0; i--) { MenuItem item = items.get(i); if (item.getOrder() <= order) { return i + 1; } } return 0; } public int findItemIndex(int id) { final int size = size(); for (int i = 0; i < size; i++) { SimpleMenuItem item = mItems.get(i); if (item.getItemId() == id) { return i; } } return -1; } public void removeItem(int itemId) { removeItemAtInt(findItemIndex(itemId)); } private void removeItemAtInt(int index) { if ((index < 0) || (index >= mItems.size())) { return; } mItems.remove(index); } public void clear() { mItems.clear(); } public MenuItem findItem(int id) { final int size = size(); for (int i = 0; i < size; i++) { SimpleMenuItem item = mItems.get(i); if (item.getItemId() == id) { return item; } } return null; } public int size() { return mItems.size(); } public MenuItem getItem(int index) { return mItems.get(index); } // Unsupported operations. public SubMenu addSubMenu(CharSequence charSequence) { throw new UnsupportedOperationException("This operation is not supported for SimpleMenu"); } public SubMenu addSubMenu(int titleRes) { throw new UnsupportedOperationException("This operation is not supported for SimpleMenu"); } public SubMenu addSubMenu(int groupId, int itemId, int order, CharSequence title) { throw new UnsupportedOperationException("This operation is not supported for SimpleMenu"); } public SubMenu addSubMenu(int groupId, int itemId, int order, int titleRes) { throw new UnsupportedOperationException("This operation is not supported for SimpleMenu"); } public int addIntentOptions(int i, int i1, int i2, ComponentName componentName, Intent[] intents, Intent intent, int i3, MenuItem[] menuItems) { throw new UnsupportedOperationException("This operation is not supported for SimpleMenu"); } public void removeGroup(int i) { throw new UnsupportedOperationException("This operation is not supported for SimpleMenu"); } public void setGroupCheckable(int i, boolean b, boolean b1) { throw new UnsupportedOperationException("This operation is not supported for SimpleMenu"); } public void setGroupVisible(int i, boolean b) { throw new UnsupportedOperationException("This operation is not supported for SimpleMenu"); } public void setGroupEnabled(int i, boolean b) { throw new UnsupportedOperationException("This operation is not supported for SimpleMenu"); } public boolean hasVisibleItems() { throw new UnsupportedOperationException("This operation is not supported for SimpleMenu"); } public void close() { throw new UnsupportedOperationException("This operation is not supported for SimpleMenu"); } public boolean performShortcut(int i, KeyEvent keyEvent, int i1) { throw new UnsupportedOperationException("This operation is not supported for SimpleMenu"); } public boolean isShortcutKey(int i, KeyEvent keyEvent) { throw new UnsupportedOperationException("This operation is not supported for SimpleMenu"); } public boolean performIdentifierAction(int i, int i1) { throw new UnsupportedOperationException("This operation is not supported for SimpleMenu"); } public void setQwertyMode(boolean b) { throw new UnsupportedOperationException("This operation is not supported for SimpleMenu"); } }
12085952-sageandroid
app-v2/src/com/example/android/actionbarcompat/SimpleMenu.java
Java
gpl3
6,417
/* * Copyright 2011 The Android Open Source Project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.example.android.actionbarcompat; import android.content.Intent; import android.graphics.drawable.Drawable; import android.view.ActionProvider; import android.view.ContextMenu; import android.view.MenuItem; import android.view.SubMenu; import android.view.View; /** * A <em>really</em> dumb implementation of the {@link android.view.MenuItem} interface, that's only * useful for our actionbar-compat purposes. See * <code>com.android.internal.view.menu.MenuItemImpl</code> in AOSP for a more complete * implementation. */ public class SimpleMenuItem implements MenuItem { private SimpleMenu mMenu; private final int mId; private final int mOrder; private CharSequence mTitle; private CharSequence mTitleCondensed; private Drawable mIconDrawable; private int mIconResId = 0; private boolean mEnabled = true; public SimpleMenuItem(SimpleMenu menu, int id, int order, CharSequence title) { mMenu = menu; mId = id; mOrder = order; mTitle = title; } public int getItemId() { return mId; } public int getOrder() { return mOrder; } public MenuItem setTitle(CharSequence title) { mTitle = title; return this; } public MenuItem setTitle(int titleRes) { return setTitle(mMenu.getContext().getString(titleRes)); } public CharSequence getTitle() { return mTitle; } public MenuItem setTitleCondensed(CharSequence title) { mTitleCondensed = title; return this; } public CharSequence getTitleCondensed() { return mTitleCondensed != null ? mTitleCondensed : mTitle; } public MenuItem setIcon(Drawable icon) { mIconResId = 0; mIconDrawable = icon; return this; } public MenuItem setIcon(int iconResId) { mIconDrawable = null; mIconResId = iconResId; return this; } public Drawable getIcon() { if (mIconDrawable != null) { return mIconDrawable; } if (mIconResId != 0) { return mMenu.getResources().getDrawable(mIconResId); } return null; } public MenuItem setEnabled(boolean enabled) { mEnabled = enabled; return this; } public boolean isEnabled() { return mEnabled; } // No-op operations. We use no-ops to allow inflation from menu XML. public int getGroupId() { // Noop return 0; } public View getActionView() { // Noop return null; } public MenuItem setActionProvider(ActionProvider actionProvider) { // Noop return this; } public ActionProvider getActionProvider() { // Noop return null; } public boolean expandActionView() { // Noop return false; } public boolean collapseActionView() { // Noop return false; } public boolean isActionViewExpanded() { // Noop return false; } @Override public MenuItem setOnActionExpandListener(OnActionExpandListener onActionExpandListener) { // Noop return this; } public MenuItem setIntent(Intent intent) { // Noop return this; } public Intent getIntent() { // Noop return null; } public MenuItem setShortcut(char c, char c1) { // Noop return this; } public MenuItem setNumericShortcut(char c) { // Noop return this; } public char getNumericShortcut() { // Noop return 0; } public MenuItem setAlphabeticShortcut(char c) { // Noop return this; } public char getAlphabeticShortcut() { // Noop return 0; } public MenuItem setCheckable(boolean b) { // Noop return this; } public boolean isCheckable() { // Noop return false; } public MenuItem setChecked(boolean b) { // Noop return this; } public boolean isChecked() { // Noop return false; } public MenuItem setVisible(boolean b) { // Noop return this; } public boolean isVisible() { // Noop return true; } public boolean hasSubMenu() { // Noop return false; } public SubMenu getSubMenu() { // Noop return null; } public MenuItem setOnMenuItemClickListener(OnMenuItemClickListener onMenuItemClickListener) { // Noop return this; } public ContextMenu.ContextMenuInfo getMenuInfo() { // Noop return null; } public void setShowAsAction(int i) { // Noop } public MenuItem setShowAsActionFlags(int i) { // Noop return null; } public MenuItem setActionView(View view) { // Noop return this; } public MenuItem setActionView(int i) { // Noop return this; } }
12085952-sageandroid
app-v2/src/com/example/android/actionbarcompat/SimpleMenuItem.java
Java
gpl3
5,673
/* * Copyright 2011 The Android Open Source Project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.example.android.actionbarcompat; import android.app.Activity; import android.content.Context; import android.view.Menu; import android.view.MenuItem; /** * An extension of {@link com.example.android.actionbarcompat.ActionBarHelper} that provides Android * 4.0-specific functionality for IceCreamSandwich devices. It thus requires API level 14. */ public class ActionBarHelperICS extends ActionBarHelperHoneycomb { protected ActionBarHelperICS(Activity activity) { super(activity); } @Override protected Context getActionBarThemedContext() { return mActivity.getActionBar().getThemedContext(); } }
12085952-sageandroid
app-v2/src/com/example/android/actionbarcompat/ActionBarHelperICS.java
Java
gpl3
1,267
/* * Copyright 2011 The Android Open Source Project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.example.android.actionbarcompat; import org.sagemath.droid.R; import android.app.Activity; import android.content.Context; import android.os.Bundle; import android.view.LayoutInflater; import android.view.Menu; import android.view.MenuInflater; import android.view.MenuItem; import android.view.View; /** * An extension of {@link ActionBarHelper} that provides Android 3.0-specific functionality for * Honeycomb tablets. It thus requires API level 11. */ public class ActionBarHelperHoneycomb extends ActionBarHelper { private Menu mOptionsMenu; private View mRefreshIndeterminateProgressView = null; protected ActionBarHelperHoneycomb(Activity activity) { super(activity); } @Override public boolean onCreateOptionsMenu(Menu menu) { mOptionsMenu = menu; return super.onCreateOptionsMenu(menu); } @Override public void setRefreshActionItemState(boolean refreshing) { // On Honeycomb, we can set the state of the refresh button by giving it a custom // action view. if (mOptionsMenu == null) { return; } final MenuItem refreshItem = mOptionsMenu.findItem(R.id.menu_refresh); if (refreshItem != null) { if (refreshing) { if (mRefreshIndeterminateProgressView == null) { LayoutInflater inflater = (LayoutInflater) getActionBarThemedContext().getSystemService( Context.LAYOUT_INFLATER_SERVICE); mRefreshIndeterminateProgressView = inflater.inflate( R.layout.actionbar_indeterminate_progress, null); } refreshItem.setActionView(mRefreshIndeterminateProgressView); } else { refreshItem.setActionView(null); } } } /** * Returns a {@link Context} suitable for inflating layouts for the action bar. The * implementation for this method in {@link ActionBarHelperICS} asks the action bar for a * themed context. */ protected Context getActionBarThemedContext() { return mActivity; } }
12085952-sageandroid
app-v2/src/com/example/android/actionbarcompat/ActionBarHelperHoneycomb.java
Java
gpl3
2,818
/* * Copyright 2011 The Android Open Source Project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.example.android.actionbarcompat; import org.sagemath.droid.R; import org.xmlpull.v1.XmlPullParser; import org.xmlpull.v1.XmlPullParserException; import android.app.Activity; import android.content.Context; import android.content.res.XmlResourceParser; import android.os.Bundle; import android.view.InflateException; import android.view.Menu; import android.view.MenuInflater; import android.view.MenuItem; import android.view.View; import android.view.ViewGroup; import android.view.Window; import android.widget.ImageButton; import android.widget.ImageView; import android.widget.LinearLayout; import android.widget.ProgressBar; import android.widget.TextView; import java.io.IOException; import java.util.HashSet; import java.util.Set; /** * A class that implements the action bar pattern for pre-Honeycomb devices. */ public class ActionBarHelperBase extends ActionBarHelper { private static final String MENU_RES_NAMESPACE = "http://schemas.android.com/apk/res/android"; private static final String MENU_ATTR_ID = "id"; private static final String MENU_ATTR_SHOW_AS_ACTION = "showAsAction"; protected Set<Integer> mActionItemIds = new HashSet<Integer>(); protected ActionBarHelperBase(Activity activity) { super(activity); } /**{@inheritDoc}*/ @Override public void onCreate(Bundle savedInstanceState) { mActivity.requestWindowFeature(Window.FEATURE_CUSTOM_TITLE); } /**{@inheritDoc}*/ @Override public void onPostCreate(Bundle savedInstanceState) { mActivity.getWindow().setFeatureInt(Window.FEATURE_CUSTOM_TITLE, R.layout.actionbar_compat); setupActionBar(); SimpleMenu menu = new SimpleMenu(mActivity); mActivity.onCreatePanelMenu(Window.FEATURE_OPTIONS_PANEL, menu); mActivity.onPrepareOptionsMenu(menu); for (int i = 0; i < menu.size(); i++) { MenuItem item = menu.getItem(i); if (mActionItemIds.contains(item.getItemId())) { addActionItemCompatFromMenuItem(item); } } } /** * Sets up the compatibility action bar with the given title. */ private void setupActionBar() { final ViewGroup actionBarCompat = getActionBarCompat(); if (actionBarCompat == null) { return; } LinearLayout.LayoutParams springLayoutParams = new LinearLayout.LayoutParams( 0, ViewGroup.LayoutParams.FILL_PARENT); springLayoutParams.weight = 1; // Add Home button SimpleMenu tempMenu = new SimpleMenu(mActivity); SimpleMenuItem homeItem = new SimpleMenuItem( tempMenu, android.R.id.home, 0, mActivity.getString(R.string.app_name)); homeItem.setIcon(R.drawable.icon); addActionItemCompatFromMenuItem(homeItem); // Add title text TextView titleText = new TextView(mActivity, null, R.attr.actionbarCompatTitleStyle); titleText.setLayoutParams(springLayoutParams); titleText.setText(mActivity.getTitle()); actionBarCompat.addView(titleText); } /**{@inheritDoc}*/ @Override public void setRefreshActionItemState(boolean refreshing) { View refreshButton = mActivity.findViewById(R.id.actionbar_compat_item_refresh); View refreshIndicator = mActivity.findViewById( R.id.actionbar_compat_item_refresh_progress); if (refreshButton != null) { refreshButton.setVisibility(refreshing ? View.GONE : View.VISIBLE); } if (refreshIndicator != null) { refreshIndicator.setVisibility(refreshing ? View.VISIBLE : View.GONE); } } /** * Action bar helper code to be run in {@link Activity#onCreateOptionsMenu(android.view.Menu)}. * * NOTE: This code will mark on-screen menu items as invisible. */ @Override public boolean onCreateOptionsMenu(Menu menu) { // Hides on-screen action items from the options menu. for (Integer id : mActionItemIds) { menu.findItem(id).setVisible(false); } return true; } /**{@inheritDoc}*/ @Override public void onTitleChanged(CharSequence title, int color) { TextView titleView = (TextView) mActivity.findViewById(R.id.actionbar_compat_title); if (titleView != null) { titleView.setText(title); } } /** * Returns a {@link android.view.MenuInflater} that can read action bar metadata on * pre-Honeycomb devices. */ public MenuInflater getMenuInflater(MenuInflater superMenuInflater) { return new WrappedMenuInflater(mActivity, superMenuInflater); } /** * Returns the {@link android.view.ViewGroup} for the action bar on phones (compatibility action * bar). Can return null, and will return null on Honeycomb. */ private ViewGroup getActionBarCompat() { return (ViewGroup) mActivity.findViewById(R.id.actionbar_compat); } /** * Adds an action button to the compatibility action bar, using menu information from a {@link * android.view.MenuItem}. If the menu item ID is <code>menu_refresh</code>, the menu item's * state can be changed to show a loading spinner using * {@link com.example.android.actionbarcompat.ActionBarHelperBase#setRefreshActionItemState(boolean)}. */ private View addActionItemCompatFromMenuItem(final MenuItem item) { final int itemId = item.getItemId(); final ViewGroup actionBar = getActionBarCompat(); if (actionBar == null) { return null; } // Create the button ImageButton actionButton = new ImageButton(mActivity, null, itemId == android.R.id.home ? R.attr.actionbarCompatItemHomeStyle : R.attr.actionbarCompatItemStyle); actionButton.setLayoutParams(new ViewGroup.LayoutParams( (int) mActivity.getResources().getDimension( itemId == android.R.id.home ? R.dimen.actionbar_compat_button_home_width : R.dimen.actionbar_compat_button_width), ViewGroup.LayoutParams.FILL_PARENT)); if (itemId == R.id.menu_refresh) { actionButton.setId(R.id.actionbar_compat_item_refresh); } actionButton.setImageDrawable(item.getIcon()); actionButton.setScaleType(ImageView.ScaleType.CENTER); actionButton.setContentDescription(item.getTitle()); actionButton.setOnClickListener(new View.OnClickListener() { public void onClick(View view) { mActivity.onMenuItemSelected(Window.FEATURE_OPTIONS_PANEL, item); } }); actionBar.addView(actionButton); if (item.getItemId() == R.id.menu_refresh) { // Refresh buttons should be stateful, and allow for indeterminate progress indicators, // so add those. ProgressBar indicator = new ProgressBar(mActivity, null, R.attr.actionbarCompatProgressIndicatorStyle); final int buttonWidth = mActivity.getResources().getDimensionPixelSize( R.dimen.actionbar_compat_button_width); final int buttonHeight = mActivity.getResources().getDimensionPixelSize( R.dimen.actionbar_compat_height); final int progressIndicatorWidth = buttonWidth / 2; LinearLayout.LayoutParams indicatorLayoutParams = new LinearLayout.LayoutParams( progressIndicatorWidth, progressIndicatorWidth); indicatorLayoutParams.setMargins( (buttonWidth - progressIndicatorWidth) / 2, (buttonHeight - progressIndicatorWidth) / 2, (buttonWidth - progressIndicatorWidth) / 2, 0); indicator.setLayoutParams(indicatorLayoutParams); indicator.setVisibility(View.GONE); indicator.setId(R.id.actionbar_compat_item_refresh_progress); actionBar.addView(indicator); } return actionButton; } /** * A {@link android.view.MenuInflater} that reads action bar metadata. */ private class WrappedMenuInflater extends MenuInflater { MenuInflater mInflater; public WrappedMenuInflater(Context context, MenuInflater inflater) { super(context); mInflater = inflater; } @Override public void inflate(int menuRes, Menu menu) { loadActionBarMetadata(menuRes); mInflater.inflate(menuRes, menu); } /** * Loads action bar metadata from a menu resource, storing a list of menu item IDs that * should be shown on-screen (i.e. those with showAsAction set to always or ifRoom). * @param menuResId */ private void loadActionBarMetadata(int menuResId) { XmlResourceParser parser = null; try { parser = mActivity.getResources().getXml(menuResId); int eventType = parser.getEventType(); int itemId; int showAsAction; boolean eof = false; while (!eof) { switch (eventType) { case XmlPullParser.START_TAG: if (!parser.getName().equals("item")) { break; } itemId = parser.getAttributeResourceValue(MENU_RES_NAMESPACE, MENU_ATTR_ID, 0); if (itemId == 0) { break; } showAsAction = parser.getAttributeIntValue(MENU_RES_NAMESPACE, MENU_ATTR_SHOW_AS_ACTION, -1); if (showAsAction == MenuItem.SHOW_AS_ACTION_ALWAYS || showAsAction == MenuItem.SHOW_AS_ACTION_IF_ROOM) { mActionItemIds.add(itemId); } break; case XmlPullParser.END_DOCUMENT: eof = true; break; } eventType = parser.next(); } } catch (XmlPullParserException e) { throw new InflateException("Error inflating menu XML", e); } catch (IOException e) { throw new InflateException("Error inflating menu XML", e); } finally { if (parser != null) { parser.close(); } } } } }
12085952-sageandroid
app-v2/src/com/example/android/actionbarcompat/ActionBarHelperBase.java
Java
gpl3
11,530
/* * Copyright 2011 The Android Open Source Project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.example.android.actionbarcompat; import android.app.Activity; import android.os.Bundle; import android.support.v4.app.FragmentActivity; import android.view.Menu; import android.view.MenuInflater; /** * A base activity that defers common functionality across app activities to an {@link * ActionBarHelper}. * * NOTE: dynamically marking menu items as invisible/visible is not currently supported. * * NOTE: this may used with the Android Compatibility Package by extending * android.support.v4.app.FragmentActivity instead of {@link Activity}. */ public abstract class ActionBarActivity extends FragmentActivity { final ActionBarHelper mActionBarHelper = ActionBarHelper.createInstance(this); /** * Returns the {@link ActionBarHelper} for this activity. */ protected ActionBarHelper getActionBarHelper() { return mActionBarHelper; } /**{@inheritDoc}*/ @Override public MenuInflater getMenuInflater() { return mActionBarHelper.getMenuInflater(super.getMenuInflater()); } /**{@inheritDoc}*/ @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); mActionBarHelper.onCreate(savedInstanceState); } /**{@inheritDoc}*/ @Override protected void onPostCreate(Bundle savedInstanceState) { super.onPostCreate(savedInstanceState); mActionBarHelper.onPostCreate(savedInstanceState); } /** * Base action bar-aware implementation for * {@link Activity#onCreateOptionsMenu(android.view.Menu)}. * * Note: marking menu items as invisible/visible is not currently supported. */ @Override public boolean onCreateOptionsMenu(Menu menu) { boolean retValue = false; retValue |= mActionBarHelper.onCreateOptionsMenu(menu); retValue |= super.onCreateOptionsMenu(menu); return retValue; } /**{@inheritDoc}*/ @Override protected void onTitleChanged(CharSequence title, int color) { mActionBarHelper.onTitleChanged(title, color); super.onTitleChanged(title, color); } }
12085952-sageandroid
app-v2/src/com/example/android/actionbarcompat/ActionBarActivity.java
Java
gpl3
2,756
/* * Copyright 2011 The Android Open Source Project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.example.android.actionbarcompat; import org.sagemath.droid.R; import android.os.Bundle; import android.view.Menu; import android.view.MenuInflater; import android.view.MenuItem; import android.view.View; import android.widget.Toast; public class MainActivity extends ActionBarActivity { private boolean mAlternateTitle = false; public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.main); // // findViewById(R.id.toggle_title).setOnClickListener(new View.OnClickListener() { // @Override // public void onClick(View view) { // if (mAlternateTitle) { // setTitle(R.string.app_name); // } else { // setTitle(R.string.alternate_title); // } // mAlternateTitle = !mAlternateTitle; // } // }); } @Override public boolean onCreateOptionsMenu(Menu menu) { MenuInflater menuInflater = getMenuInflater(); menuInflater.inflate(R.menu.main, menu); // Calling super after populating the menu is necessary here to ensure that the // action bar helpers have a chance to handle this event. return super.onCreateOptionsMenu(menu); } @Override public boolean onOptionsItemSelected(MenuItem item) { switch (item.getItemId()) { case android.R.id.home: Toast.makeText(this, "Tapped home", Toast.LENGTH_SHORT).show(); break; case R.id.menu_refresh: Toast.makeText(this, "Fake refreshing...", Toast.LENGTH_SHORT).show(); getActionBarHelper().setRefreshActionItemState(true); getWindow().getDecorView().postDelayed( new Runnable() { @Override public void run() { getActionBarHelper().setRefreshActionItemState(false); } }, 1000); break; case R.id.menu_search: Toast.makeText(this, "Tapped search", Toast.LENGTH_SHORT).show(); break; case R.id.menu_share: Toast.makeText(this, "Tapped share", Toast.LENGTH_SHORT).show(); break; } return super.onOptionsItemSelected(item); } }
12085952-sageandroid
app-v2/src/com/example/android/actionbarcompat/MainActivity.java
Java
gpl3
3,079
/** Automatically generated file. DO NOT MODIFY */ package org.sagemath.droid; public final class BuildConfig { public final static boolean DEBUG = true; }
12085952-sageandroid
app-v2/gen/org/sagemath/droid/BuildConfig.java
Java
gpl3
160
package android.text.format; import java.util.Calendar; import java.util.Date; public class Time { private final static String TAG = "Time"; private Date date; public void setToNow() { Calendar cal = Calendar.getInstance(); date = cal.getTime(); } public String toMillis(boolean ignoreDst) { return String.valueOf(date.getTime()); } }
12085952-sageandroid
commandline/src/android/text/format/Time.java
Java
gpl3
356
package android.util; public class Log { private static final String TAG = "Log"; public static void d(String tag, String msg) { System.out.println(tag + "\t" + msg); } public static void e(String tag, String msg) { System.out.println(tag + "\t" + msg); } }
12085952-sageandroid
commandline/src/android/util/Log.java
Java
gpl3
275
package org.json; /** * The JSONException is thrown by the JSON.org classes when things are amiss. * @author JSON.org * @version 2010-12-24 */ public class JSONException extends Exception { private static final long serialVersionUID = 0; private Throwable cause; /** * Constructs a JSONException with an explanatory message. * @param message Detail about the reason for the exception. */ public JSONException(String message) { super(message); } public JSONException(Throwable cause) { super(cause.getMessage()); this.cause = cause; } public Throwable getCause() { return this.cause; } }
12085952-sageandroid
commandline/src/org/json/JSONException.java
Java
gpl3
700
package org.json; /* Copyright (c) 2002 JSON.org 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 shall be used for Good, not Evil. 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. */ import java.util.Iterator; /** * This provides static methods to convert an XML text into a JSONObject, * and to covert a JSONObject into an XML text. * @author JSON.org * @version 2011-02-11 */ public class XML { /** The Character '&'. */ public static final Character AMP = new Character('&'); /** The Character '''. */ public static final Character APOS = new Character('\''); /** The Character '!'. */ public static final Character BANG = new Character('!'); /** The Character '='. */ public static final Character EQ = new Character('='); /** The Character '>'. */ public static final Character GT = new Character('>'); /** The Character '<'. */ public static final Character LT = new Character('<'); /** The Character '?'. */ public static final Character QUEST = new Character('?'); /** The Character '"'. */ public static final Character QUOT = new Character('"'); /** The Character '/'. */ public static final Character SLASH = new Character('/'); /** * Replace special characters with XML escapes: * <pre> * &amp; <small>(ampersand)</small> is replaced by &amp;amp; * &lt; <small>(less than)</small> is replaced by &amp;lt; * &gt; <small>(greater than)</small> is replaced by &amp;gt; * &quot; <small>(double quote)</small> is replaced by &amp;quot; * </pre> * @param string The string to be escaped. * @return The escaped string. */ public static String escape(String string) { StringBuffer sb = new StringBuffer(); for (int i = 0, length = string.length(); i < length; i++) { char c = string.charAt(i); switch (c) { case '&': sb.append("&amp;"); break; case '<': sb.append("&lt;"); break; case '>': sb.append("&gt;"); break; case '"': sb.append("&quot;"); break; case '\'': sb.append("&apos;"); break; default: sb.append(c); } } return sb.toString(); } /** * Throw an exception if the string contains whitespace. * Whitespace is not allowed in tagNames and attributes. * @param string * @throws JSONException */ public static void noSpace(String string) throws JSONException { int i, length = string.length(); if (length == 0) { throw new JSONException("Empty string."); } for (i = 0; i < length; i += 1) { if (Character.isWhitespace(string.charAt(i))) { throw new JSONException("'" + string + "' contains a space character."); } } } /** * Scan the content following the named tag, attaching it to the context. * @param x The XMLTokener containing the source string. * @param context The JSONObject that will include the new material. * @param name The tag name. * @return true if the close tag is processed. * @throws JSONException */ private static boolean parse(XMLTokener x, JSONObject context, String name) throws JSONException { char c; int i; JSONObject jsonobject = null; String string; String tagName; Object token; // Test for and skip past these forms: // <!-- ... --> // <! ... > // <![ ... ]]> // <? ... ?> // Report errors for these forms: // <> // <= // << token = x.nextToken(); // <! if (token == BANG) { c = x.next(); if (c == '-') { if (x.next() == '-') { x.skipPast("-->"); return false; } x.back(); } else if (c == '[') { token = x.nextToken(); if (token.equals("CDATA")) { if (x.next() == '[') { string = x.nextCDATA(); if (string.length() > 0) { context.accumulate("content", string); } return false; } } throw x.syntaxError("Expected 'CDATA['"); } i = 1; do { token = x.nextMeta(); if (token == null) { throw x.syntaxError("Missing '>' after '<!'."); } else if (token == LT) { i += 1; } else if (token == GT) { i -= 1; } } while (i > 0); return false; } else if (token == QUEST) { // <? x.skipPast("?>"); return false; } else if (token == SLASH) { // Close tag </ token = x.nextToken(); if (name == null) { throw x.syntaxError("Mismatched close tag " + token); } if (!token.equals(name)) { throw x.syntaxError("Mismatched " + name + " and " + token); } if (x.nextToken() != GT) { throw x.syntaxError("Misshaped close tag"); } return true; } else if (token instanceof Character) { throw x.syntaxError("Misshaped tag"); // Open tag < } else { tagName = (String)token; token = null; jsonobject = new JSONObject(); for (;;) { if (token == null) { token = x.nextToken(); } // attribute = value if (token instanceof String) { string = (String)token; token = x.nextToken(); if (token == EQ) { token = x.nextToken(); if (!(token instanceof String)) { throw x.syntaxError("Missing value"); } jsonobject.accumulate(string, XML.stringToValue((String)token)); token = null; } else { jsonobject.accumulate(string, ""); } // Empty tag <.../> } else if (token == SLASH) { if (x.nextToken() != GT) { throw x.syntaxError("Misshaped tag"); } if (jsonobject.length() > 0) { context.accumulate(tagName, jsonobject); } else { context.accumulate(tagName, ""); } return false; // Content, between <...> and </...> } else if (token == GT) { for (;;) { token = x.nextContent(); if (token == null) { if (tagName != null) { throw x.syntaxError("Unclosed tag " + tagName); } return false; } else if (token instanceof String) { string = (String)token; if (string.length() > 0) { jsonobject.accumulate("content", XML.stringToValue(string)); } // Nested element } else if (token == LT) { if (parse(x, jsonobject, tagName)) { if (jsonobject.length() == 0) { context.accumulate(tagName, ""); } else if (jsonobject.length() == 1 && jsonobject.opt("content") != null) { context.accumulate(tagName, jsonobject.opt("content")); } else { context.accumulate(tagName, jsonobject); } return false; } } } } else { throw x.syntaxError("Misshaped tag"); } } } } /** * Try to convert a string into a number, boolean, or null. If the string * can't be converted, return the string. This is much less ambitious than * JSONObject.stringToValue, especially because it does not attempt to * convert plus forms, octal forms, hex forms, or E forms lacking decimal * points. * @param string A String. * @return A simple JSON value. */ public static Object stringToValue(String string) { if (string.equals("")) { return string; } if (string.equalsIgnoreCase("true")) { return Boolean.TRUE; } if (string.equalsIgnoreCase("false")) { return Boolean.FALSE; } if (string.equalsIgnoreCase("null")) { return JSONObject.NULL; } if (string.equals("0")) { return new Integer(0); } // If it might be a number, try converting it. If that doesn't work, // return the string. try { char initial = string.charAt(0); boolean negative = false; if (initial == '-') { initial = string.charAt(1); negative = true; } if (initial == '0' && string.charAt(negative ? 2 : 1) == '0') { return string; } if ((initial >= '0' && initial <= '9')) { if (string.indexOf('.') >= 0) { return Double.valueOf(string); } else if (string.indexOf('e') < 0 && string.indexOf('E') < 0) { Long myLong = new Long(string); if (myLong.longValue() == myLong.intValue()) { return new Integer(myLong.intValue()); } else { return myLong; } } } } catch (Exception ignore) { } return string; } /** * Convert a well-formed (but not necessarily valid) XML string into a * JSONObject. Some information may be lost in this transformation * because JSON is a data format and XML is a document format. XML uses * elements, attributes, and content text, while JSON uses unordered * collections of name/value pairs and arrays of values. JSON does not * does not like to distinguish between elements and attributes. * Sequences of similar elements are represented as JSONArrays. Content * text may be placed in a "content" member. Comments, prologs, DTDs, and * <code>&lt;[ [ ]]></code> are ignored. * @param string The source string. * @return A JSONObject containing the structured data from the XML string. * @throws JSONException */ public static JSONObject toJSONObject(String string) throws JSONException { JSONObject jo = new JSONObject(); XMLTokener x = new XMLTokener(string); while (x.more() && x.skipPast("<")) { parse(x, jo, null); } return jo; } /** * Convert a JSONObject into a well-formed, element-normal XML string. * @param object A JSONObject. * @return A string. * @throws JSONException */ public static String toString(Object object) throws JSONException { return toString(object, null); } /** * Convert a JSONObject into a well-formed, element-normal XML string. * @param object A JSONObject. * @param tagName The optional name of the enclosing tag. * @return A string. * @throws JSONException */ public static String toString(Object object, String tagName) throws JSONException { StringBuffer sb = new StringBuffer(); int i; JSONArray ja; JSONObject jo; String key; Iterator keys; int length; String string; Object value; if (object instanceof JSONObject) { // Emit <tagName> if (tagName != null) { sb.append('<'); sb.append(tagName); sb.append('>'); } // Loop thru the keys. jo = (JSONObject)object; keys = jo.keys(); while (keys.hasNext()) { key = keys.next().toString(); value = jo.opt(key); if (value == null) { value = ""; } if (value instanceof String) { string = (String)value; } else { string = null; } // Emit content in body if (key.equals("content")) { if (value instanceof JSONArray) { ja = (JSONArray)value; length = ja.length(); for (i = 0; i < length; i += 1) { if (i > 0) { sb.append('\n'); } sb.append(escape(ja.get(i).toString())); } } else { sb.append(escape(value.toString())); } // Emit an array of similar keys } else if (value instanceof JSONArray) { ja = (JSONArray)value; length = ja.length(); for (i = 0; i < length; i += 1) { value = ja.get(i); if (value instanceof JSONArray) { sb.append('<'); sb.append(key); sb.append('>'); sb.append(toString(value)); sb.append("</"); sb.append(key); sb.append('>'); } else { sb.append(toString(value, key)); } } } else if (value.equals("")) { sb.append('<'); sb.append(key); sb.append("/>"); // Emit a new tag <k> } else { sb.append(toString(value, key)); } } if (tagName != null) { // Emit the </tagname> close tag sb.append("</"); sb.append(tagName); sb.append('>'); } return sb.toString(); // XML does not have good support for arrays. If an array appears in a place // where XML is lacking, synthesize an <array> element. } else { if (object.getClass().isArray()) { object = new JSONArray(object); } if (object instanceof JSONArray) { ja = (JSONArray)object; length = ja.length(); for (i = 0; i < length; i += 1) { sb.append(toString(ja.opt(i), tagName == null ? "array" : tagName)); } return sb.toString(); } else { string = (object == null) ? "null" : escape(object.toString()); return (tagName == null) ? "\"" + string + "\"" : (string.length() == 0) ? "<" + tagName + "/>" : "<" + tagName + ">" + string + "</" + tagName + ">"; } } } }
12085952-sageandroid
commandline/src/org/json/XML.java
Java
gpl3
17,113
package org.json; /* Copyright (c) 2008 JSON.org 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 shall be used for Good, not Evil. 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. */ import java.util.Iterator; /** * This provides static methods to convert an XML text into a JSONArray or * JSONObject, and to covert a JSONArray or JSONObject into an XML text using * the JsonML transform. * @author JSON.org * @version 2011-11-24 */ public class JSONML { /** * Parse XML values and store them in a JSONArray. * @param x The XMLTokener containing the source string. * @param arrayForm true if array form, false if object form. * @param ja The JSONArray that is containing the current tag or null * if we are at the outermost level. * @return A JSONArray if the value is the outermost tag, otherwise null. * @throws JSONException */ private static Object parse( XMLTokener x, boolean arrayForm, JSONArray ja ) throws JSONException { String attribute; char c; String closeTag = null; int i; JSONArray newja = null; JSONObject newjo = null; Object token; String tagName = null; // Test for and skip past these forms: // <!-- ... --> // <![ ... ]]> // <! ... > // <? ... ?> while (true) { if (!x.more()) { throw x.syntaxError("Bad XML"); } token = x.nextContent(); if (token == XML.LT) { token = x.nextToken(); if (token instanceof Character) { if (token == XML.SLASH) { // Close tag </ token = x.nextToken(); if (!(token instanceof String)) { throw new JSONException( "Expected a closing name instead of '" + token + "'."); } if (x.nextToken() != XML.GT) { throw x.syntaxError("Misshaped close tag"); } return token; } else if (token == XML.BANG) { // <! c = x.next(); if (c == '-') { if (x.next() == '-') { x.skipPast("-->"); } x.back(); } else if (c == '[') { token = x.nextToken(); if (token.equals("CDATA") && x.next() == '[') { if (ja != null) { ja.put(x.nextCDATA()); } } else { throw x.syntaxError("Expected 'CDATA['"); } } else { i = 1; do { token = x.nextMeta(); if (token == null) { throw x.syntaxError("Missing '>' after '<!'."); } else if (token == XML.LT) { i += 1; } else if (token == XML.GT) { i -= 1; } } while (i > 0); } } else if (token == XML.QUEST) { // <? x.skipPast("?>"); } else { throw x.syntaxError("Misshaped tag"); } // Open tag < } else { if (!(token instanceof String)) { throw x.syntaxError("Bad tagName '" + token + "'."); } tagName = (String)token; newja = new JSONArray(); newjo = new JSONObject(); if (arrayForm) { newja.put(tagName); if (ja != null) { ja.put(newja); } } else { newjo.put("tagName", tagName); if (ja != null) { ja.put(newjo); } } token = null; for (;;) { if (token == null) { token = x.nextToken(); } if (token == null) { throw x.syntaxError("Misshaped tag"); } if (!(token instanceof String)) { break; } // attribute = value attribute = (String)token; if (!arrayForm && (attribute == "tagName" || attribute == "childNode")) { throw x.syntaxError("Reserved attribute."); } token = x.nextToken(); if (token == XML.EQ) { token = x.nextToken(); if (!(token instanceof String)) { throw x.syntaxError("Missing value"); } newjo.accumulate(attribute, XML.stringToValue((String)token)); token = null; } else { newjo.accumulate(attribute, ""); } } if (arrayForm && newjo.length() > 0) { newja.put(newjo); } // Empty tag <.../> if (token == XML.SLASH) { if (x.nextToken() != XML.GT) { throw x.syntaxError("Misshaped tag"); } if (ja == null) { if (arrayForm) { return newja; } else { return newjo; } } // Content, between <...> and </...> } else { if (token != XML.GT) { throw x.syntaxError("Misshaped tag"); } closeTag = (String)parse(x, arrayForm, newja); if (closeTag != null) { if (!closeTag.equals(tagName)) { throw x.syntaxError("Mismatched '" + tagName + "' and '" + closeTag + "'"); } tagName = null; if (!arrayForm && newja.length() > 0) { newjo.put("childNodes", newja); } if (ja == null) { if (arrayForm) { return newja; } else { return newjo; } } } } } } else { if (ja != null) { ja.put(token instanceof String ? XML.stringToValue((String)token) : token); } } } } /** * Convert a well-formed (but not necessarily valid) XML string into a * JSONArray using the JsonML transform. Each XML tag is represented as * a JSONArray in which the first element is the tag name. If the tag has * attributes, then the second element will be JSONObject containing the * name/value pairs. If the tag contains children, then strings and * JSONArrays will represent the child tags. * Comments, prologs, DTDs, and <code>&lt;[ [ ]]></code> are ignored. * @param string The source string. * @return A JSONArray containing the structured data from the XML string. * @throws JSONException */ public static JSONArray toJSONArray(String string) throws JSONException { return toJSONArray(new XMLTokener(string)); } /** * Convert a well-formed (but not necessarily valid) XML string into a * JSONArray using the JsonML transform. Each XML tag is represented as * a JSONArray in which the first element is the tag name. If the tag has * attributes, then the second element will be JSONObject containing the * name/value pairs. If the tag contains children, then strings and * JSONArrays will represent the child content and tags. * Comments, prologs, DTDs, and <code>&lt;[ [ ]]></code> are ignored. * @param x An XMLTokener. * @return A JSONArray containing the structured data from the XML string. * @throws JSONException */ public static JSONArray toJSONArray(XMLTokener x) throws JSONException { return (JSONArray)parse(x, true, null); } /** * Convert a well-formed (but not necessarily valid) XML string into a * JSONObject using the JsonML transform. Each XML tag is represented as * a JSONObject with a "tagName" property. If the tag has attributes, then * the attributes will be in the JSONObject as properties. If the tag * contains children, the object will have a "childNodes" property which * will be an array of strings and JsonML JSONObjects. * Comments, prologs, DTDs, and <code>&lt;[ [ ]]></code> are ignored. * @param x An XMLTokener of the XML source text. * @return A JSONObject containing the structured data from the XML string. * @throws JSONException */ public static JSONObject toJSONObject(XMLTokener x) throws JSONException { return (JSONObject)parse(x, false, null); } /** * Convert a well-formed (but not necessarily valid) XML string into a * JSONObject using the JsonML transform. Each XML tag is represented as * a JSONObject with a "tagName" property. If the tag has attributes, then * the attributes will be in the JSONObject as properties. If the tag * contains children, the object will have a "childNodes" property which * will be an array of strings and JsonML JSONObjects. * Comments, prologs, DTDs, and <code>&lt;[ [ ]]></code> are ignored. * @param string The XML source text. * @return A JSONObject containing the structured data from the XML string. * @throws JSONException */ public static JSONObject toJSONObject(String string) throws JSONException { return toJSONObject(new XMLTokener(string)); } /** * Reverse the JSONML transformation, making an XML text from a JSONArray. * @param ja A JSONArray. * @return An XML string. * @throws JSONException */ public static String toString(JSONArray ja) throws JSONException { int i; JSONObject jo; String key; Iterator keys; int length; Object object; StringBuffer sb = new StringBuffer(); String tagName; String value; // Emit <tagName tagName = ja.getString(0); XML.noSpace(tagName); tagName = XML.escape(tagName); sb.append('<'); sb.append(tagName); object = ja.opt(1); if (object instanceof JSONObject) { i = 2; jo = (JSONObject)object; // Emit the attributes keys = jo.keys(); while (keys.hasNext()) { key = keys.next().toString(); XML.noSpace(key); value = jo.optString(key); if (value != null) { sb.append(' '); sb.append(XML.escape(key)); sb.append('='); sb.append('"'); sb.append(XML.escape(value)); sb.append('"'); } } } else { i = 1; } //Emit content in body length = ja.length(); if (i >= length) { sb.append('/'); sb.append('>'); } else { sb.append('>'); do { object = ja.get(i); i += 1; if (object != null) { if (object instanceof String) { sb.append(XML.escape(object.toString())); } else if (object instanceof JSONObject) { sb.append(toString((JSONObject)object)); } else if (object instanceof JSONArray) { sb.append(toString((JSONArray)object)); } } } while (i < length); sb.append('<'); sb.append('/'); sb.append(tagName); sb.append('>'); } return sb.toString(); } /** * Reverse the JSONML transformation, making an XML text from a JSONObject. * The JSONObject must contain a "tagName" property. If it has children, * then it must have a "childNodes" property containing an array of objects. * The other properties are attributes with string values. * @param jo A JSONObject. * @return An XML string. * @throws JSONException */ public static String toString(JSONObject jo) throws JSONException { StringBuffer sb = new StringBuffer(); int i; JSONArray ja; String key; Iterator keys; int length; Object object; String tagName; String value; //Emit <tagName tagName = jo.optString("tagName"); if (tagName == null) { return XML.escape(jo.toString()); } XML.noSpace(tagName); tagName = XML.escape(tagName); sb.append('<'); sb.append(tagName); //Emit the attributes keys = jo.keys(); while (keys.hasNext()) { key = keys.next().toString(); if (!key.equals("tagName") && !key.equals("childNodes")) { XML.noSpace(key); value = jo.optString(key); if (value != null) { sb.append(' '); sb.append(XML.escape(key)); sb.append('='); sb.append('"'); sb.append(XML.escape(value)); sb.append('"'); } } } //Emit content in body ja = jo.optJSONArray("childNodes"); if (ja == null) { sb.append('/'); sb.append('>'); } else { sb.append('>'); length = ja.length(); for (i = 0; i < length; i += 1) { object = ja.get(i); if (object != null) { if (object instanceof String) { sb.append(XML.escape(object.toString())); } else if (object instanceof JSONObject) { sb.append(toString((JSONObject)object)); } else if (object instanceof JSONArray) { sb.append(toString((JSONArray)object)); } else { sb.append(object.toString()); } } } sb.append('<'); sb.append('/'); sb.append(tagName); sb.append('>'); } return sb.toString(); } }
12085952-sageandroid
commandline/src/org/json/JSONML.java
Java
gpl3
15,093
package org.json; /* Copyright (c) 2002 JSON.org 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 shall be used for Good, not Evil. 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. */ /** * This provides static methods to convert comma delimited text into a * JSONArray, and to covert a JSONArray into comma delimited text. Comma * delimited text is a very popular format for data interchange. It is * understood by most database, spreadsheet, and organizer programs. * <p> * Each row of text represents a row in a table or a data record. Each row * ends with a NEWLINE character. Each row contains one or more values. * Values are separated by commas. A value can contain any character except * for comma, unless is is wrapped in single quotes or double quotes. * <p> * The first row usually contains the names of the columns. * <p> * A comma delimited list can be converted into a JSONArray of JSONObjects. * The names for the elements in the JSONObjects can be taken from the names * in the first row. * @author JSON.org * @version 2010-12-24 */ public class CDL { /** * Get the next value. The value can be wrapped in quotes. The value can * be empty. * @param x A JSONTokener of the source text. * @return The value string, or null if empty. * @throws JSONException if the quoted string is badly formed. */ private static String getValue(JSONTokener x) throws JSONException { char c; char q; StringBuffer sb; do { c = x.next(); } while (c == ' ' || c == '\t'); switch (c) { case 0: return null; case '"': case '\'': q = c; sb = new StringBuffer(); for (;;) { c = x.next(); if (c == q) { break; } if (c == 0 || c == '\n' || c == '\r') { throw x.syntaxError("Missing close quote '" + q + "'."); } sb.append(c); } return sb.toString(); case ',': x.back(); return ""; default: x.back(); return x.nextTo(','); } } /** * Produce a JSONArray of strings from a row of comma delimited values. * @param x A JSONTokener of the source text. * @return A JSONArray of strings. * @throws JSONException */ public static JSONArray rowToJSONArray(JSONTokener x) throws JSONException { JSONArray ja = new JSONArray(); for (;;) { String value = getValue(x); char c = x.next(); if (value == null || (ja.length() == 0 && value.length() == 0 && c != ',')) { return null; } ja.put(value); for (;;) { if (c == ',') { break; } if (c != ' ') { if (c == '\n' || c == '\r' || c == 0) { return ja; } throw x.syntaxError("Bad character '" + c + "' (" + (int)c + ")."); } c = x.next(); } } } /** * Produce a JSONObject from a row of comma delimited text, using a * parallel JSONArray of strings to provides the names of the elements. * @param names A JSONArray of names. This is commonly obtained from the * first row of a comma delimited text file using the rowToJSONArray * method. * @param x A JSONTokener of the source text. * @return A JSONObject combining the names and values. * @throws JSONException */ public static JSONObject rowToJSONObject(JSONArray names, JSONTokener x) throws JSONException { JSONArray ja = rowToJSONArray(x); return ja != null ? ja.toJSONObject(names) : null; } /** * Produce a comma delimited text row from a JSONArray. Values containing * the comma character will be quoted. Troublesome characters may be * removed. * @param ja A JSONArray of strings. * @return A string ending in NEWLINE. */ public static String rowToString(JSONArray ja) { StringBuffer sb = new StringBuffer(); for (int i = 0; i < ja.length(); i += 1) { if (i > 0) { sb.append(','); } Object object = ja.opt(i); if (object != null) { String string = object.toString(); if (string.length() > 0 && (string.indexOf(',') >= 0 || string.indexOf('\n') >= 0 || string.indexOf('\r') >= 0 || string.indexOf(0) >= 0 || string.charAt(0) == '"')) { sb.append('"'); int length = string.length(); for (int j = 0; j < length; j += 1) { char c = string.charAt(j); if (c >= ' ' && c != '"') { sb.append(c); } } sb.append('"'); } else { sb.append(string); } } } sb.append('\n'); return sb.toString(); } /** * Produce a JSONArray of JSONObjects from a comma delimited text string, * using the first row as a source of names. * @param string The comma delimited text. * @return A JSONArray of JSONObjects. * @throws JSONException */ public static JSONArray toJSONArray(String string) throws JSONException { return toJSONArray(new JSONTokener(string)); } /** * Produce a JSONArray of JSONObjects from a comma delimited text string, * using the first row as a source of names. * @param x The JSONTokener containing the comma delimited text. * @return A JSONArray of JSONObjects. * @throws JSONException */ public static JSONArray toJSONArray(JSONTokener x) throws JSONException { return toJSONArray(rowToJSONArray(x), x); } /** * Produce a JSONArray of JSONObjects from a comma delimited text string * using a supplied JSONArray as the source of element names. * @param names A JSONArray of strings. * @param string The comma delimited text. * @return A JSONArray of JSONObjects. * @throws JSONException */ public static JSONArray toJSONArray(JSONArray names, String string) throws JSONException { return toJSONArray(names, new JSONTokener(string)); } /** * Produce a JSONArray of JSONObjects from a comma delimited text string * using a supplied JSONArray as the source of element names. * @param names A JSONArray of strings. * @param x A JSONTokener of the source text. * @return A JSONArray of JSONObjects. * @throws JSONException */ public static JSONArray toJSONArray(JSONArray names, JSONTokener x) throws JSONException { if (names == null || names.length() == 0) { return null; } JSONArray ja = new JSONArray(); for (;;) { JSONObject jo = rowToJSONObject(names, x); if (jo == null) { break; } ja.put(jo); } if (ja.length() == 0) { return null; } return ja; } /** * Produce a comma delimited text from a JSONArray of JSONObjects. The * first row will be a list of names obtained by inspecting the first * JSONObject. * @param ja A JSONArray of JSONObjects. * @return A comma delimited text. * @throws JSONException */ public static String toString(JSONArray ja) throws JSONException { JSONObject jo = ja.optJSONObject(0); if (jo != null) { JSONArray names = jo.names(); if (names != null) { return rowToString(names) + toString(names, ja); } } return null; } /** * Produce a comma delimited text from a JSONArray of JSONObjects using * a provided list of names. The list of names is not included in the * output. * @param names A JSONArray of strings. * @param ja A JSONArray of JSONObjects. * @return A comma delimited text. * @throws JSONException */ public static String toString(JSONArray names, JSONArray ja) throws JSONException { if (names == null || names.length() == 0) { return null; } StringBuffer sb = new StringBuffer(); for (int i = 0; i < ja.length(); i += 1) { JSONObject jo = ja.optJSONObject(i); if (jo != null) { sb.append(rowToString(jo.toJSONArray(names))); } } return sb.toString(); } }
12085952-sageandroid
commandline/src/org/json/CDL.java
Java
gpl3
10,004
package org.json; /* Copyright (c) 2002 JSON.org 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 shall be used for Good, not Evil. 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. */ import java.util.Iterator; /** * Convert an HTTP header to a JSONObject and back. * @author JSON.org * @version 2010-12-24 */ public class HTTP { /** Carriage return/line feed. */ public static final String CRLF = "\r\n"; /** * Convert an HTTP header string into a JSONObject. It can be a request * header or a response header. A request header will contain * <pre>{ * Method: "POST" (for example), * "Request-URI": "/" (for example), * "HTTP-Version": "HTTP/1.1" (for example) * }</pre> * A response header will contain * <pre>{ * "HTTP-Version": "HTTP/1.1" (for example), * "Status-Code": "200" (for example), * "Reason-Phrase": "OK" (for example) * }</pre> * In addition, the other parameters in the header will be captured, using * the HTTP field names as JSON names, so that <pre> * Date: Sun, 26 May 2002 18:06:04 GMT * Cookie: Q=q2=PPEAsg--; B=677gi6ouf29bn&b=2&f=s * Cache-Control: no-cache</pre> * become * <pre>{... * Date: "Sun, 26 May 2002 18:06:04 GMT", * Cookie: "Q=q2=PPEAsg--; B=677gi6ouf29bn&b=2&f=s", * "Cache-Control": "no-cache", * ...}</pre> * It does no further checking or conversion. It does not parse dates. * It does not do '%' transforms on URLs. * @param string An HTTP header string. * @return A JSONObject containing the elements and attributes * of the XML string. * @throws JSONException */ public static JSONObject toJSONObject(String string) throws JSONException { JSONObject jo = new JSONObject(); HTTPTokener x = new HTTPTokener(string); String token; token = x.nextToken(); if (token.toUpperCase().startsWith("HTTP")) { // Response jo.put("HTTP-Version", token); jo.put("Status-Code", x.nextToken()); jo.put("Reason-Phrase", x.nextTo('\0')); x.next(); } else { // Request jo.put("Method", token); jo.put("Request-URI", x.nextToken()); jo.put("HTTP-Version", x.nextToken()); } // Fields while (x.more()) { String name = x.nextTo(':'); x.next(':'); jo.put(name, x.nextTo('\0')); x.next(); } return jo; } /** * Convert a JSONObject into an HTTP header. A request header must contain * <pre>{ * Method: "POST" (for example), * "Request-URI": "/" (for example), * "HTTP-Version": "HTTP/1.1" (for example) * }</pre> * A response header must contain * <pre>{ * "HTTP-Version": "HTTP/1.1" (for example), * "Status-Code": "200" (for example), * "Reason-Phrase": "OK" (for example) * }</pre> * Any other members of the JSONObject will be output as HTTP fields. * The result will end with two CRLF pairs. * @param jo A JSONObject * @return An HTTP header string. * @throws JSONException if the object does not contain enough * information. */ public static String toString(JSONObject jo) throws JSONException { Iterator keys = jo.keys(); String string; StringBuffer sb = new StringBuffer(); if (jo.has("Status-Code") && jo.has("Reason-Phrase")) { sb.append(jo.getString("HTTP-Version")); sb.append(' '); sb.append(jo.getString("Status-Code")); sb.append(' '); sb.append(jo.getString("Reason-Phrase")); } else if (jo.has("Method") && jo.has("Request-URI")) { sb.append(jo.getString("Method")); sb.append(' '); sb.append('"'); sb.append(jo.getString("Request-URI")); sb.append('"'); sb.append(' '); sb.append(jo.getString("HTTP-Version")); } else { throw new JSONException("Not enough material for an HTTP header."); } sb.append(CRLF); while (keys.hasNext()) { string = keys.next().toString(); if (!string.equals("HTTP-Version") && !string.equals("Status-Code") && !string.equals("Reason-Phrase") && !string.equals("Method") && !string.equals("Request-URI") && !jo.isNull(string)) { sb.append(string); sb.append(": "); sb.append(jo.getString(string)); sb.append(CRLF); } } sb.append(CRLF); return sb.toString(); } }
12085952-sageandroid
commandline/src/org/json/HTTP.java
Java
gpl3
5,919
package org.json; /* Copyright (c) 2002 JSON.org 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 shall be used for Good, not Evil. 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. */ /** * Convert a web browser cookie specification to a JSONObject and back. * JSON and Cookies are both notations for name/value pairs. * @author JSON.org * @version 2010-12-24 */ public class Cookie { /** * Produce a copy of a string in which the characters '+', '%', '=', ';' * and control characters are replaced with "%hh". This is a gentle form * of URL encoding, attempting to cause as little distortion to the * string as possible. The characters '=' and ';' are meta characters in * cookies. By convention, they are escaped using the URL-encoding. This is * only a convention, not a standard. Often, cookies are expected to have * encoded values. We encode '=' and ';' because we must. We encode '%' and * '+' because they are meta characters in URL encoding. * @param string The source string. * @return The escaped result. */ public static String escape(String string) { char c; String s = string.trim(); StringBuffer sb = new StringBuffer(); int length = s.length(); for (int i = 0; i < length; i += 1) { c = s.charAt(i); if (c < ' ' || c == '+' || c == '%' || c == '=' || c == ';') { sb.append('%'); sb.append(Character.forDigit((char)((c >>> 4) & 0x0f), 16)); sb.append(Character.forDigit((char)(c & 0x0f), 16)); } else { sb.append(c); } } return sb.toString(); } /** * Convert a cookie specification string into a JSONObject. The string * will contain a name value pair separated by '='. The name and the value * will be unescaped, possibly converting '+' and '%' sequences. The * cookie properties may follow, separated by ';', also represented as * name=value (except the secure property, which does not have a value). * The name will be stored under the key "name", and the value will be * stored under the key "value". This method does not do checking or * validation of the parameters. It only converts the cookie string into * a JSONObject. * @param string The cookie specification string. * @return A JSONObject containing "name", "value", and possibly other * members. * @throws JSONException */ public static JSONObject toJSONObject(String string) throws JSONException { String name; JSONObject jo = new JSONObject(); Object value; JSONTokener x = new JSONTokener(string); jo.put("name", x.nextTo('=')); x.next('='); jo.put("value", x.nextTo(';')); x.next(); while (x.more()) { name = unescape(x.nextTo("=;")); if (x.next() != '=') { if (name.equals("secure")) { value = Boolean.TRUE; } else { throw x.syntaxError("Missing '=' in cookie parameter."); } } else { value = unescape(x.nextTo(';')); x.next(); } jo.put(name, value); } return jo; } /** * Convert a JSONObject into a cookie specification string. The JSONObject * must contain "name" and "value" members. * If the JSONObject contains "expires", "domain", "path", or "secure" * members, they will be appended to the cookie specification string. * All other members are ignored. * @param jo A JSONObject * @return A cookie specification string * @throws JSONException */ public static String toString(JSONObject jo) throws JSONException { StringBuffer sb = new StringBuffer(); sb.append(escape(jo.getString("name"))); sb.append("="); sb.append(escape(jo.getString("value"))); if (jo.has("expires")) { sb.append(";expires="); sb.append(jo.getString("expires")); } if (jo.has("domain")) { sb.append(";domain="); sb.append(escape(jo.getString("domain"))); } if (jo.has("path")) { sb.append(";path="); sb.append(escape(jo.getString("path"))); } if (jo.optBoolean("secure")) { sb.append(";secure"); } return sb.toString(); } /** * Convert <code>%</code><i>hh</i> sequences to single characters, and * convert plus to space. * @param string A string that may contain * <code>+</code>&nbsp;<small>(plus)</small> and * <code>%</code><i>hh</i> sequences. * @return The unescaped string. */ public static String unescape(String string) { int length = string.length(); StringBuffer sb = new StringBuffer(); for (int i = 0; i < length; ++i) { char c = string.charAt(i); if (c == '+') { c = ' '; } else if (c == '%' && i + 2 < length) { int d = JSONTokener.dehexchar(string.charAt(i + 1)); int e = JSONTokener.dehexchar(string.charAt(i + 2)); if (d >= 0 && e >= 0) { c = (char)(d * 16 + e); i += 2; } } sb.append(c); } return sb.toString(); } }
12085952-sageandroid
commandline/src/org/json/Cookie.java
Java
gpl3
6,675
package org.json; /* Copyright (c) 2002 JSON.org 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 shall be used for Good, not Evil. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ /** * The HTTPTokener extends the JSONTokener to provide additional methods * for the parsing of HTTP headers. * @author JSON.org * @version 2010-12-24 */ public class HTTPTokener extends JSONTokener { /** * Construct an HTTPTokener from a string. * @param string A source string. */ public HTTPTokener(String string) { super(string); } /** * Get the next token or string. This is used in parsing HTTP headers. * @throws JSONException * @return A String. */ public String nextToken() throws JSONException { char c; char q; StringBuffer sb = new StringBuffer(); do { c = next(); } while (Character.isWhitespace(c)); if (c == '"' || c == '\'') { q = c; for (;;) { c = next(); if (c < ' ') { throw syntaxError("Unterminated string."); } if (c == q) { return sb.toString(); } sb.append(c); } } for (;;) { if (c == 0 || Character.isWhitespace(c)) { return sb.toString(); } sb.append(c); c = next(); } } }
12085952-sageandroid
commandline/src/org/json/HTTPTokener.java
Java
gpl3
2,499
package org.json; /* Copyright (c) 2002 JSON.org 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 shall be used for Good, not Evil. 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. */ import java.io.IOException; import java.io.Writer; import java.lang.reflect.Field; import java.lang.reflect.Modifier; import java.lang.reflect.Method; import java.util.Collection; import java.util.Enumeration; import java.util.HashMap; import java.util.Iterator; import java.util.Locale; import java.util.Map; import java.util.ResourceBundle; /** * A JSONObject is an unordered collection of name/value pairs. Its * external form is a string wrapped in curly braces with colons between the * names and values, and commas between the values and names. The internal form * is an object having <code>get</code> and <code>opt</code> methods for * accessing the values by name, and <code>put</code> methods for adding or * replacing values by name. The values can be any of these types: * <code>Boolean</code>, <code>JSONArray</code>, <code>JSONObject</code>, * <code>Number</code>, <code>String</code>, or the <code>JSONObject.NULL</code> * object. A JSONObject constructor can be used to convert an external form * JSON text into an internal form whose values can be retrieved with the * <code>get</code> and <code>opt</code> methods, or to convert values into a * JSON text using the <code>put</code> and <code>toString</code> methods. * A <code>get</code> method returns a value if one can be found, and throws an * exception if one cannot be found. An <code>opt</code> method returns a * default value instead of throwing an exception, and so is useful for * obtaining optional values. * <p> * The generic <code>get()</code> and <code>opt()</code> methods return an * object, which you can cast or query for type. There are also typed * <code>get</code> and <code>opt</code> methods that do type checking and type * coercion for you. The opt methods differ from the get methods in that they * do not throw. Instead, they return a specified value, such as null. * <p> * The <code>put</code> methods add or replace values in an object. For example, * <pre>myString = new JSONObject().put("JSON", "Hello, World!").toString();</pre> * produces the string <code>{"JSON": "Hello, World"}</code>. * <p> * The texts produced by the <code>toString</code> methods strictly conform to * the JSON syntax rules. * The constructors are more forgiving in the texts they will accept: * <ul> * <li>An extra <code>,</code>&nbsp;<small>(comma)</small> may appear just * before the closing brace.</li> * <li>Strings may be quoted with <code>'</code>&nbsp;<small>(single * quote)</small>.</li> * <li>Strings do not need to be quoted at all if they do not begin with a quote * or single quote, and if they do not contain leading or trailing spaces, * and if they do not contain any of these characters: * <code>{ } [ ] / \ : , = ; #</code> and if they do not look like numbers * and if they are not the reserved words <code>true</code>, * <code>false</code>, or <code>null</code>.</li> * <li>Keys can be followed by <code>=</code> or <code>=></code> as well as * by <code>:</code>.</li> * <li>Values can be followed by <code>;</code> <small>(semicolon)</small> as * well as by <code>,</code> <small>(comma)</small>.</li> * </ul> * @author JSON.org * @version 2011-11-24 */ public class JSONObject { /** * JSONObject.NULL is equivalent to the value that JavaScript calls null, * whilst Java's null is equivalent to the value that JavaScript calls * undefined. */ private static final class Null { /** * There is only intended to be a single instance of the NULL object, * so the clone method returns itself. * @return NULL. */ protected final Object clone() { return this; } /** * A Null object is equal to the null value and to itself. * @param object An object to test for nullness. * @return true if the object parameter is the JSONObject.NULL object * or null. */ public boolean equals(Object object) { return object == null || object == this; } /** * Get the "null" string value. * @return The string "null". */ public String toString() { return "null"; } } /** * The map where the JSONObject's properties are kept. */ private final Map map; /** * It is sometimes more convenient and less ambiguous to have a * <code>NULL</code> object than to use Java's <code>null</code> value. * <code>JSONObject.NULL.equals(null)</code> returns <code>true</code>. * <code>JSONObject.NULL.toString()</code> returns <code>"null"</code>. */ public static final Object NULL = new Null(); /** * Construct an empty JSONObject. */ public JSONObject() { this.map = new HashMap(); } /** * Construct a JSONObject from a subset of another JSONObject. * An array of strings is used to identify the keys that should be copied. * Missing keys are ignored. * @param jo A JSONObject. * @param names An array of strings. * @throws JSONException * @exception JSONException If a value is a non-finite number or if a name is duplicated. */ public JSONObject(JSONObject jo, String[] names) { this(); for (int i = 0; i < names.length; i += 1) { try { this.putOnce(names[i], jo.opt(names[i])); } catch (Exception ignore) { } } } /** * Construct a JSONObject from a JSONTokener. * @param x A JSONTokener object containing the source string. * @throws JSONException If there is a syntax error in the source string * or a duplicated key. */ public JSONObject(JSONTokener x) throws JSONException { this(); char c; String key; if (x.nextClean() != '{') { throw x.syntaxError("A JSONObject text must begin with '{'"); } for (;;) { c = x.nextClean(); switch (c) { case 0: throw x.syntaxError("A JSONObject text must end with '}'"); case '}': return; default: x.back(); key = x.nextValue().toString(); } // The key is followed by ':'. We will also tolerate '=' or '=>'. c = x.nextClean(); if (c == '=') { if (x.next() != '>') { x.back(); } } else if (c != ':') { throw x.syntaxError("Expected a ':' after a key"); } this.putOnce(key, x.nextValue()); // Pairs are separated by ','. We will also tolerate ';'. switch (x.nextClean()) { case ';': case ',': if (x.nextClean() == '}') { return; } x.back(); break; case '}': return; default: throw x.syntaxError("Expected a ',' or '}'"); } } } /** * Construct a JSONObject from a Map. * * @param map A map object that can be used to initialize the contents of * the JSONObject. * @throws JSONException */ public JSONObject(Map map) { this.map = new HashMap(); if (map != null) { Iterator i = map.entrySet().iterator(); while (i.hasNext()) { Map.Entry e = (Map.Entry)i.next(); Object value = e.getValue(); if (value != null) { this.map.put(e.getKey(), wrap(value)); } } } } /** * Construct a JSONObject from an Object using bean getters. * It reflects on all of the public methods of the object. * For each of the methods with no parameters and a name starting * with <code>"get"</code> or <code>"is"</code> followed by an uppercase letter, * the method is invoked, and a key and the value returned from the getter method * are put into the new JSONObject. * * The key is formed by removing the <code>"get"</code> or <code>"is"</code> prefix. * If the second remaining character is not upper case, then the first * character is converted to lower case. * * For example, if an object has a method named <code>"getName"</code>, and * if the result of calling <code>object.getName()</code> is <code>"Larry Fine"</code>, * then the JSONObject will contain <code>"name": "Larry Fine"</code>. * * @param bean An object that has getter methods that should be used * to make a JSONObject. */ public JSONObject(Object bean) { this(); this.populateMap(bean); } /** * Construct a JSONObject from an Object, using reflection to find the * public members. The resulting JSONObject's keys will be the strings * from the names array, and the values will be the field values associated * with those keys in the object. If a key is not found or not visible, * then it will not be copied into the new JSONObject. * @param object An object that has fields that should be used to make a * JSONObject. * @param names An array of strings, the names of the fields to be obtained * from the object. */ public JSONObject(Object object, String names[]) { this(); Class c = object.getClass(); for (int i = 0; i < names.length; i += 1) { String name = names[i]; try { this.putOpt(name, c.getField(name).get(object)); } catch (Exception ignore) { } } } /** * Construct a JSONObject from a source JSON text string. * This is the most commonly used JSONObject constructor. * @param source A string beginning * with <code>{</code>&nbsp;<small>(left brace)</small> and ending * with <code>}</code>&nbsp;<small>(right brace)</small>. * @exception JSONException If there is a syntax error in the source * string or a duplicated key. */ public JSONObject(String source) throws JSONException { this(new JSONTokener(source)); } /** * Construct a JSONObject from a ResourceBundle. * @param baseName The ResourceBundle base name. * @param locale The Locale to load the ResourceBundle for. * @throws JSONException If any JSONExceptions are detected. */ public JSONObject(String baseName, Locale locale) throws JSONException { this(); ResourceBundle bundle = ResourceBundle.getBundle(baseName, locale, Thread.currentThread().getContextClassLoader()); // Iterate through the keys in the bundle. Enumeration keys = bundle.getKeys(); while (keys.hasMoreElements()) { Object key = keys.nextElement(); if (key instanceof String) { // Go through the path, ensuring that there is a nested JSONObject for each // segment except the last. Add the value using the last segment's name into // the deepest nested JSONObject. String[] path = ((String)key).split("\\."); int last = path.length - 1; JSONObject target = this; for (int i = 0; i < last; i += 1) { String segment = path[i]; JSONObject nextTarget = target.optJSONObject(segment); if (nextTarget == null) { nextTarget = new JSONObject(); target.put(segment, nextTarget); } target = nextTarget; } target.put(path[last], bundle.getString((String)key)); } } } /** * Accumulate values under a key. It is similar to the put method except * that if there is already an object stored under the key then a * JSONArray is stored under the key to hold all of the accumulated values. * If there is already a JSONArray, then the new value is appended to it. * In contrast, the put method replaces the previous value. * * If only one value is accumulated that is not a JSONArray, then the * result will be the same as using put. But if multiple values are * accumulated, then the result will be like append. * @param key A key string. * @param value An object to be accumulated under the key. * @return this. * @throws JSONException If the value is an invalid number * or if the key is null. */ public JSONObject accumulate( String key, Object value ) throws JSONException { testValidity(value); Object object = this.opt(key); if (object == null) { this.put(key, value instanceof JSONArray ? new JSONArray().put(value) : value); } else if (object instanceof JSONArray) { ((JSONArray)object).put(value); } else { this.put(key, new JSONArray().put(object).put(value)); } return this; } /** * Append values to the array under a key. If the key does not exist in the * JSONObject, then the key is put in the JSONObject with its value being a * JSONArray containing the value parameter. If the key was already * associated with a JSONArray, then the value parameter is appended to it. * @param key A key string. * @param value An object to be accumulated under the key. * @return this. * @throws JSONException If the key is null or if the current value * associated with the key is not a JSONArray. */ public JSONObject append(String key, Object value) throws JSONException { testValidity(value); Object object = this.opt(key); if (object == null) { this.put(key, new JSONArray().put(value)); } else if (object instanceof JSONArray) { this.put(key, ((JSONArray)object).put(value)); } else { throw new JSONException("JSONObject[" + key + "] is not a JSONArray."); } return this; } /** * Produce a string from a double. The string "null" will be returned if * the number is not finite. * @param d A double. * @return A String. */ public static String doubleToString(double d) { if (Double.isInfinite(d) || Double.isNaN(d)) { return "null"; } // Shave off trailing zeros and decimal point, if possible. String string = Double.toString(d); if (string.indexOf('.') > 0 && string.indexOf('e') < 0 && string.indexOf('E') < 0) { while (string.endsWith("0")) { string = string.substring(0, string.length() - 1); } if (string.endsWith(".")) { string = string.substring(0, string.length() - 1); } } return string; } /** * Get the value object associated with a key. * * @param key A key string. * @return The object associated with the key. * @throws JSONException if the key is not found. */ public Object get(String key) throws JSONException { if (key == null) { throw new JSONException("Null key."); } Object object = this.opt(key); if (object == null) { throw new JSONException("JSONObject[" + quote(key) + "] not found."); } return object; } /** * Get the boolean value associated with a key. * * @param key A key string. * @return The truth. * @throws JSONException * if the value is not a Boolean or the String "true" or "false". */ public boolean getBoolean(String key) throws JSONException { Object object = this.get(key); if (object.equals(Boolean.FALSE) || (object instanceof String && ((String)object).equalsIgnoreCase("false"))) { return false; } else if (object.equals(Boolean.TRUE) || (object instanceof String && ((String)object).equalsIgnoreCase("true"))) { return true; } throw new JSONException("JSONObject[" + quote(key) + "] is not a Boolean."); } /** * Get the double value associated with a key. * @param key A key string. * @return The numeric value. * @throws JSONException if the key is not found or * if the value is not a Number object and cannot be converted to a number. */ public double getDouble(String key) throws JSONException { Object object = this.get(key); try { return object instanceof Number ? ((Number)object).doubleValue() : Double.parseDouble((String)object); } catch (Exception e) { throw new JSONException("JSONObject[" + quote(key) + "] is not a number."); } } /** * Get the int value associated with a key. * * @param key A key string. * @return The integer value. * @throws JSONException if the key is not found or if the value cannot * be converted to an integer. */ public int getInt(String key) throws JSONException { Object object = this.get(key); try { return object instanceof Number ? ((Number)object).intValue() : Integer.parseInt((String)object); } catch (Exception e) { throw new JSONException("JSONObject[" + quote(key) + "] is not an int."); } } /** * Get the JSONArray value associated with a key. * * @param key A key string. * @return A JSONArray which is the value. * @throws JSONException if the key is not found or * if the value is not a JSONArray. */ public JSONArray getJSONArray(String key) throws JSONException { Object object = this.get(key); if (object instanceof JSONArray) { return (JSONArray)object; } throw new JSONException("JSONObject[" + quote(key) + "] is not a JSONArray."); } /** * Get the JSONObject value associated with a key. * * @param key A key string. * @return A JSONObject which is the value. * @throws JSONException if the key is not found or * if the value is not a JSONObject. */ public JSONObject getJSONObject(String key) throws JSONException { Object object = this.get(key); if (object instanceof JSONObject) { return (JSONObject)object; } throw new JSONException("JSONObject[" + quote(key) + "] is not a JSONObject."); } /** * Get the long value associated with a key. * * @param key A key string. * @return The long value. * @throws JSONException if the key is not found or if the value cannot * be converted to a long. */ public long getLong(String key) throws JSONException { Object object = this.get(key); try { return object instanceof Number ? ((Number)object).longValue() : Long.parseLong((String)object); } catch (Exception e) { throw new JSONException("JSONObject[" + quote(key) + "] is not a long."); } } /** * Get an array of field names from a JSONObject. * * @return An array of field names, or null if there are no names. */ public static String[] getNames(JSONObject jo) { int length = jo.length(); if (length == 0) { return null; } Iterator iterator = jo.keys(); String[] names = new String[length]; int i = 0; while (iterator.hasNext()) { names[i] = (String)iterator.next(); i += 1; } return names; } /** * Get an array of field names from an Object. * * @return An array of field names, or null if there are no names. */ public static String[] getNames(Object object) { if (object == null) { return null; } Class klass = object.getClass(); Field[] fields = klass.getFields(); int length = fields.length; if (length == 0) { return null; } String[] names = new String[length]; for (int i = 0; i < length; i += 1) { names[i] = fields[i].getName(); } return names; } /** * Get the string associated with a key. * * @param key A key string. * @return A string which is the value. * @throws JSONException if there is no string value for the key. */ public String getString(String key) throws JSONException { Object object = this.get(key); if (object instanceof String) { return (String)object; } throw new JSONException("JSONObject[" + quote(key) + "] not a string."); } /** * Determine if the JSONObject contains a specific key. * @param key A key string. * @return true if the key exists in the JSONObject. */ public boolean has(String key) { return this.map.containsKey(key); } /** * Increment a property of a JSONObject. If there is no such property, * create one with a value of 1. If there is such a property, and if * it is an Integer, Long, Double, or Float, then add one to it. * @param key A key string. * @return this. * @throws JSONException If there is already a property with this name * that is not an Integer, Long, Double, or Float. */ public JSONObject increment(String key) throws JSONException { Object value = this.opt(key); if (value == null) { this.put(key, 1); } else if (value instanceof Integer) { this.put(key, ((Integer)value).intValue() + 1); } else if (value instanceof Long) { this.put(key, ((Long)value).longValue() + 1); } else if (value instanceof Double) { this.put(key, ((Double)value).doubleValue() + 1); } else if (value instanceof Float) { this.put(key, ((Float)value).floatValue() + 1); } else { throw new JSONException("Unable to increment [" + quote(key) + "]."); } return this; } /** * Determine if the value associated with the key is null or if there is * no value. * @param key A key string. * @return true if there is no value associated with the key or if * the value is the JSONObject.NULL object. */ public boolean isNull(String key) { return JSONObject.NULL.equals(this.opt(key)); } /** * Get an enumeration of the keys of the JSONObject. * * @return An iterator of the keys. */ public Iterator keys() { return this.map.keySet().iterator(); } /** * Get the number of keys stored in the JSONObject. * * @return The number of keys in the JSONObject. */ public int length() { return this.map.size(); } /** * Produce a JSONArray containing the names of the elements of this * JSONObject. * @return A JSONArray containing the key strings, or null if the JSONObject * is empty. */ public JSONArray names() { JSONArray ja = new JSONArray(); Iterator keys = this.keys(); while (keys.hasNext()) { ja.put(keys.next()); } return ja.length() == 0 ? null : ja; } /** * Produce a string from a Number. * @param number A Number * @return A String. * @throws JSONException If n is a non-finite number. */ public static String numberToString(Number number) throws JSONException { if (number == null) { throw new JSONException("Null pointer"); } testValidity(number); // Shave off trailing zeros and decimal point, if possible. String string = number.toString(); if (string.indexOf('.') > 0 && string.indexOf('e') < 0 && string.indexOf('E') < 0) { while (string.endsWith("0")) { string = string.substring(0, string.length() - 1); } if (string.endsWith(".")) { string = string.substring(0, string.length() - 1); } } return string; } /** * Get an optional value associated with a key. * @param key A key string. * @return An object which is the value, or null if there is no value. */ public Object opt(String key) { return key == null ? null : this.map.get(key); } /** * Get an optional boolean associated with a key. * It returns false if there is no such key, or if the value is not * Boolean.TRUE or the String "true". * * @param key A key string. * @return The truth. */ public boolean optBoolean(String key) { return this.optBoolean(key, false); } /** * Get an optional boolean associated with a key. * It returns the defaultValue if there is no such key, or if it is not * a Boolean or the String "true" or "false" (case insensitive). * * @param key A key string. * @param defaultValue The default. * @return The truth. */ public boolean optBoolean(String key, boolean defaultValue) { try { return this.getBoolean(key); } catch (Exception e) { return defaultValue; } } /** * Get an optional double associated with a key, * or NaN if there is no such key or if its value is not a number. * If the value is a string, an attempt will be made to evaluate it as * a number. * * @param key A string which is the key. * @return An object which is the value. */ public double optDouble(String key) { return this.optDouble(key, Double.NaN); } /** * Get an optional double associated with a key, or the * defaultValue if there is no such key or if its value is not a number. * If the value is a string, an attempt will be made to evaluate it as * a number. * * @param key A key string. * @param defaultValue The default. * @return An object which is the value. */ public double optDouble(String key, double defaultValue) { try { return this.getDouble(key); } catch (Exception e) { return defaultValue; } } /** * Get an optional int value associated with a key, * or zero if there is no such key or if the value is not a number. * If the value is a string, an attempt will be made to evaluate it as * a number. * * @param key A key string. * @return An object which is the value. */ public int optInt(String key) { return this.optInt(key, 0); } /** * Get an optional int value associated with a key, * or the default if there is no such key or if the value is not a number. * If the value is a string, an attempt will be made to evaluate it as * a number. * * @param key A key string. * @param defaultValue The default. * @return An object which is the value. */ public int optInt(String key, int defaultValue) { try { return this.getInt(key); } catch (Exception e) { return defaultValue; } } /** * Get an optional JSONArray associated with a key. * It returns null if there is no such key, or if its value is not a * JSONArray. * * @param key A key string. * @return A JSONArray which is the value. */ public JSONArray optJSONArray(String key) { Object o = this.opt(key); return o instanceof JSONArray ? (JSONArray)o : null; } /** * Get an optional JSONObject associated with a key. * It returns null if there is no such key, or if its value is not a * JSONObject. * * @param key A key string. * @return A JSONObject which is the value. */ public JSONObject optJSONObject(String key) { Object object = this.opt(key); return object instanceof JSONObject ? (JSONObject)object : null; } /** * Get an optional long value associated with a key, * or zero if there is no such key or if the value is not a number. * If the value is a string, an attempt will be made to evaluate it as * a number. * * @param key A key string. * @return An object which is the value. */ public long optLong(String key) { return this.optLong(key, 0); } /** * Get an optional long value associated with a key, * or the default if there is no such key or if the value is not a number. * If the value is a string, an attempt will be made to evaluate it as * a number. * * @param key A key string. * @param defaultValue The default. * @return An object which is the value. */ public long optLong(String key, long defaultValue) { try { return this.getLong(key); } catch (Exception e) { return defaultValue; } } /** * Get an optional string associated with a key. * It returns an empty string if there is no such key. If the value is not * a string and is not null, then it is converted to a string. * * @param key A key string. * @return A string which is the value. */ public String optString(String key) { return this.optString(key, ""); } /** * Get an optional string associated with a key. * It returns the defaultValue if there is no such key. * * @param key A key string. * @param defaultValue The default. * @return A string which is the value. */ public String optString(String key, String defaultValue) { Object object = this.opt(key); return NULL.equals(object) ? defaultValue : object.toString(); } private void populateMap(Object bean) { Class klass = bean.getClass(); // If klass is a System class then set includeSuperClass to false. boolean includeSuperClass = klass.getClassLoader() != null; Method[] methods = includeSuperClass ? klass.getMethods() : klass.getDeclaredMethods(); for (int i = 0; i < methods.length; i += 1) { try { Method method = methods[i]; if (Modifier.isPublic(method.getModifiers())) { String name = method.getName(); String key = ""; if (name.startsWith("get")) { if (name.equals("getClass") || name.equals("getDeclaringClass")) { key = ""; } else { key = name.substring(3); } } else if (name.startsWith("is")) { key = name.substring(2); } if (key.length() > 0 && Character.isUpperCase(key.charAt(0)) && method.getParameterTypes().length == 0) { if (key.length() == 1) { key = key.toLowerCase(); } else if (!Character.isUpperCase(key.charAt(1))) { key = key.substring(0, 1).toLowerCase() + key.substring(1); } Object result = method.invoke(bean, (Object[])null); if (result != null) { this.map.put(key, wrap(result)); } } } } catch (Exception ignore) { } } } /** * Put a key/boolean pair in the JSONObject. * * @param key A key string. * @param value A boolean which is the value. * @return this. * @throws JSONException If the key is null. */ public JSONObject put(String key, boolean value) throws JSONException { this.put(key, value ? Boolean.TRUE : Boolean.FALSE); return this; } /** * Put a key/value pair in the JSONObject, where the value will be a * JSONArray which is produced from a Collection. * @param key A key string. * @param value A Collection value. * @return this. * @throws JSONException */ public JSONObject put(String key, Collection value) throws JSONException { this.put(key, new JSONArray(value)); return this; } /** * Put a key/double pair in the JSONObject. * * @param key A key string. * @param value A double which is the value. * @return this. * @throws JSONException If the key is null or if the number is invalid. */ public JSONObject put(String key, double value) throws JSONException { this.put(key, new Double(value)); return this; } /** * Put a key/int pair in the JSONObject. * * @param key A key string. * @param value An int which is the value. * @return this. * @throws JSONException If the key is null. */ public JSONObject put(String key, int value) throws JSONException { this.put(key, new Integer(value)); return this; } /** * Put a key/long pair in the JSONObject. * * @param key A key string. * @param value A long which is the value. * @return this. * @throws JSONException If the key is null. */ public JSONObject put(String key, long value) throws JSONException { this.put(key, new Long(value)); return this; } /** * Put a key/value pair in the JSONObject, where the value will be a * JSONObject which is produced from a Map. * @param key A key string. * @param value A Map value. * @return this. * @throws JSONException */ public JSONObject put(String key, Map value) throws JSONException { this.put(key, new JSONObject(value)); return this; } /** * Put a key/value pair in the JSONObject. If the value is null, * then the key will be removed from the JSONObject if it is present. * @param key A key string. * @param value An object which is the value. It should be of one of these * types: Boolean, Double, Integer, JSONArray, JSONObject, Long, String, * or the JSONObject.NULL object. * @return this. * @throws JSONException If the value is non-finite number * or if the key is null. */ public JSONObject put(String key, Object value) throws JSONException { if (key == null) { throw new JSONException("Null key."); } if (value != null) { testValidity(value); this.map.put(key, value); } else { this.remove(key); } return this; } /** * Put a key/value pair in the JSONObject, but only if the key and the * value are both non-null, and only if there is not already a member * with that name. * @param key * @param value * @return his. * @throws JSONException if the key is a duplicate */ public JSONObject putOnce(String key, Object value) throws JSONException { if (key != null && value != null) { if (this.opt(key) != null) { throw new JSONException("Duplicate key \"" + key + "\""); } this.put(key, value); } return this; } /** * Put a key/value pair in the JSONObject, but only if the * key and the value are both non-null. * @param key A key string. * @param value An object which is the value. It should be of one of these * types: Boolean, Double, Integer, JSONArray, JSONObject, Long, String, * or the JSONObject.NULL object. * @return this. * @throws JSONException If the value is a non-finite number. */ public JSONObject putOpt(String key, Object value) throws JSONException { if (key != null && value != null) { this.put(key, value); } return this; } /** * Produce a string in double quotes with backslash sequences in all the * right places. A backslash will be inserted within </, producing <\/, * allowing JSON text to be delivered in HTML. In JSON text, a string * cannot contain a control character or an unescaped quote or backslash. * @param string A String * @return A String correctly formatted for insertion in a JSON text. */ public static String quote(String string) { if (string == null || string.length() == 0) { return "\"\""; } char b; char c = 0; String hhhh; int i; int len = string.length(); StringBuffer sb = new StringBuffer(len + 4); sb.append('"'); for (i = 0; i < len; i += 1) { b = c; c = string.charAt(i); switch (c) { case '\\': case '"': sb.append('\\'); sb.append(c); break; case '/': if (b == '<') { sb.append('\\'); } sb.append(c); break; case '\b': sb.append("\\b"); break; case '\t': sb.append("\\t"); break; case '\n': sb.append("\\n"); break; case '\f': sb.append("\\f"); break; case '\r': sb.append("\\r"); break; default: if (c < ' ' || (c >= '\u0080' && c < '\u00a0') || (c >= '\u2000' && c < '\u2100')) { hhhh = "000" + Integer.toHexString(c); sb.append("\\u" + hhhh.substring(hhhh.length() - 4)); } else { sb.append(c); } } } sb.append('"'); return sb.toString(); } /** * Remove a name and its value, if present. * @param key The name to be removed. * @return The value that was associated with the name, * or null if there was no value. */ public Object remove(String key) { return this.map.remove(key); } /** * Try to convert a string into a number, boolean, or null. If the string * can't be converted, return the string. * @param string A String. * @return A simple JSON value. */ public static Object stringToValue(String string) { Double d; if (string.equals("")) { return string; } if (string.equalsIgnoreCase("true")) { return Boolean.TRUE; } if (string.equalsIgnoreCase("false")) { return Boolean.FALSE; } if (string.equalsIgnoreCase("null")) { return JSONObject.NULL; } /* * If it might be a number, try converting it. * If a number cannot be produced, then the value will just * be a string. Note that the plus and implied string * conventions are non-standard. A JSON parser may accept * non-JSON forms as long as it accepts all correct JSON forms. */ char b = string.charAt(0); if ((b >= '0' && b <= '9') || b == '.' || b == '-' || b == '+') { try { if (string.indexOf('.') > -1 || string.indexOf('e') > -1 || string.indexOf('E') > -1) { d = Double.valueOf(string); if (!d.isInfinite() && !d.isNaN()) { return d; } } else { Long myLong = new Long(string); if (myLong.longValue() == myLong.intValue()) { return new Integer(myLong.intValue()); } else { return myLong; } } } catch (Exception ignore) { } } return string; } /** * Throw an exception if the object is a NaN or infinite number. * @param o The object to test. * @throws JSONException If o is a non-finite number. */ public static void testValidity(Object o) throws JSONException { if (o != null) { if (o instanceof Double) { if (((Double)o).isInfinite() || ((Double)o).isNaN()) { throw new JSONException( "JSON does not allow non-finite numbers."); } } else if (o instanceof Float) { if (((Float)o).isInfinite() || ((Float)o).isNaN()) { throw new JSONException( "JSON does not allow non-finite numbers."); } } } } /** * Produce a JSONArray containing the values of the members of this * JSONObject. * @param names A JSONArray containing a list of key strings. This * determines the sequence of the values in the result. * @return A JSONArray of values. * @throws JSONException If any of the values are non-finite numbers. */ public JSONArray toJSONArray(JSONArray names) throws JSONException { if (names == null || names.length() == 0) { return null; } JSONArray ja = new JSONArray(); for (int i = 0; i < names.length(); i += 1) { ja.put(this.opt(names.getString(i))); } return ja; } /** * Make a JSON text of this JSONObject. For compactness, no whitespace * is added. If this would not result in a syntactically correct JSON text, * then null will be returned instead. * <p> * Warning: This method assumes that the data structure is acyclical. * * @return a printable, displayable, portable, transmittable * representation of the object, beginning * with <code>{</code>&nbsp;<small>(left brace)</small> and ending * with <code>}</code>&nbsp;<small>(right brace)</small>. */ public String toString() { try { Iterator keys = this.keys(); StringBuffer sb = new StringBuffer("{"); while (keys.hasNext()) { if (sb.length() > 1) { sb.append(','); } Object o = keys.next(); sb.append(quote(o.toString())); sb.append(':'); sb.append(valueToString(this.map.get(o))); } sb.append('}'); return sb.toString(); } catch (Exception e) { return null; } } /** * Make a prettyprinted JSON text of this JSONObject. * <p> * Warning: This method assumes that the data structure is acyclical. * @param indentFactor The number of spaces to add to each level of * indentation. * @return a printable, displayable, portable, transmittable * representation of the object, beginning * with <code>{</code>&nbsp;<small>(left brace)</small> and ending * with <code>}</code>&nbsp;<small>(right brace)</small>. * @throws JSONException If the object contains an invalid number. */ public String toString(int indentFactor) throws JSONException { return this.toString(indentFactor, 0); } /** * Make a prettyprinted JSON text of this JSONObject. * <p> * Warning: This method assumes that the data structure is acyclical. * @param indentFactor The number of spaces to add to each level of * indentation. * @param indent The indentation of the top level. * @return a printable, displayable, transmittable * representation of the object, beginning * with <code>{</code>&nbsp;<small>(left brace)</small> and ending * with <code>}</code>&nbsp;<small>(right brace)</small>. * @throws JSONException If the object contains an invalid number. */ String toString(int indentFactor, int indent) throws JSONException { int i; int length = this.length(); if (length == 0) { return "{}"; } Iterator keys = this.keys(); int newindent = indent + indentFactor; Object object; StringBuffer sb = new StringBuffer("{"); if (length == 1) { object = keys.next(); sb.append(quote(object.toString())); sb.append(": "); sb.append(valueToString(this.map.get(object), indentFactor, indent)); } else { while (keys.hasNext()) { object = keys.next(); if (sb.length() > 1) { sb.append(",\n"); } else { sb.append('\n'); } for (i = 0; i < newindent; i += 1) { sb.append(' '); } sb.append(quote(object.toString())); sb.append(": "); sb.append(valueToString(this.map.get(object), indentFactor, newindent)); } if (sb.length() > 1) { sb.append('\n'); for (i = 0; i < indent; i += 1) { sb.append(' '); } } } sb.append('}'); return sb.toString(); } /** * Make a JSON text of an Object value. If the object has an * value.toJSONString() method, then that method will be used to produce * the JSON text. The method is required to produce a strictly * conforming text. If the object does not contain a toJSONString * method (which is the most common case), then a text will be * produced by other means. If the value is an array or Collection, * then a JSONArray will be made from it and its toJSONString method * will be called. If the value is a MAP, then a JSONObject will be made * from it and its toJSONString method will be called. Otherwise, the * value's toString method will be called, and the result will be quoted. * * <p> * Warning: This method assumes that the data structure is acyclical. * @param value The value to be serialized. * @return a printable, displayable, transmittable * representation of the object, beginning * with <code>{</code>&nbsp;<small>(left brace)</small> and ending * with <code>}</code>&nbsp;<small>(right brace)</small>. * @throws JSONException If the value is or contains an invalid number. */ public static String valueToString(Object value) throws JSONException { if (value == null || value.equals(null)) { return "null"; } if (value instanceof JSONString) { Object object; try { object = ((JSONString)value).toJSONString(); } catch (Exception e) { throw new JSONException(e); } if (object instanceof String) { return (String)object; } throw new JSONException("Bad value from toJSONString: " + object); } if (value instanceof Number) { return numberToString((Number) value); } if (value instanceof Boolean || value instanceof JSONObject || value instanceof JSONArray) { return value.toString(); } if (value instanceof Map) { return new JSONObject((Map)value).toString(); } if (value instanceof Collection) { return new JSONArray((Collection)value).toString(); } if (value.getClass().isArray()) { return new JSONArray(value).toString(); } return quote(value.toString()); } /** * Make a prettyprinted JSON text of an object value. * <p> * Warning: This method assumes that the data structure is acyclical. * @param value The value to be serialized. * @param indentFactor The number of spaces to add to each level of * indentation. * @param indent The indentation of the top level. * @return a printable, displayable, transmittable * representation of the object, beginning * with <code>{</code>&nbsp;<small>(left brace)</small> and ending * with <code>}</code>&nbsp;<small>(right brace)</small>. * @throws JSONException If the object contains an invalid number. */ static String valueToString( Object value, int indentFactor, int indent ) throws JSONException { if (value == null || value.equals(null)) { return "null"; } try { if (value instanceof JSONString) { Object o = ((JSONString)value).toJSONString(); if (o instanceof String) { return (String)o; } } } catch (Exception ignore) { } if (value instanceof Number) { return numberToString((Number) value); } if (value instanceof Boolean) { return value.toString(); } if (value instanceof JSONObject) { return ((JSONObject)value).toString(indentFactor, indent); } if (value instanceof JSONArray) { return ((JSONArray)value).toString(indentFactor, indent); } if (value instanceof Map) { return new JSONObject((Map)value).toString(indentFactor, indent); } if (value instanceof Collection) { return new JSONArray((Collection)value).toString(indentFactor, indent); } if (value.getClass().isArray()) { return new JSONArray(value).toString(indentFactor, indent); } return quote(value.toString()); } /** * Wrap an object, if necessary. If the object is null, return the NULL * object. If it is an array or collection, wrap it in a JSONArray. If * it is a map, wrap it in a JSONObject. If it is a standard property * (Double, String, et al) then it is already wrapped. Otherwise, if it * comes from one of the java packages, turn it into a string. And if * it doesn't, try to wrap it in a JSONObject. If the wrapping fails, * then null is returned. * * @param object The object to wrap * @return The wrapped value */ public static Object wrap(Object object) { try { if (object == null) { return NULL; } if (object instanceof JSONObject || object instanceof JSONArray || NULL.equals(object) || object instanceof JSONString || object instanceof Byte || object instanceof Character || object instanceof Short || object instanceof Integer || object instanceof Long || object instanceof Boolean || object instanceof Float || object instanceof Double || object instanceof String) { return object; } if (object instanceof Collection) { return new JSONArray((Collection)object); } if (object.getClass().isArray()) { return new JSONArray(object); } if (object instanceof Map) { return new JSONObject((Map)object); } Package objectPackage = object.getClass().getPackage(); String objectPackageName = objectPackage != null ? objectPackage.getName() : ""; if ( objectPackageName.startsWith("java.") || objectPackageName.startsWith("javax.") || object.getClass().getClassLoader() == null ) { return object.toString(); } return new JSONObject(object); } catch(Exception exception) { return null; } } /** * Write the contents of the JSONObject as JSON text to a writer. * For compactness, no whitespace is added. * <p> * Warning: This method assumes that the data structure is acyclical. * * @return The writer. * @throws JSONException */ public Writer write(Writer writer) throws JSONException { try { boolean commanate = false; Iterator keys = this.keys(); writer.write('{'); while (keys.hasNext()) { if (commanate) { writer.write(','); } Object key = keys.next(); writer.write(quote(key.toString())); writer.write(':'); Object value = this.map.get(key); if (value instanceof JSONObject) { ((JSONObject)value).write(writer); } else if (value instanceof JSONArray) { ((JSONArray)value).write(writer); } else { writer.write(valueToString(value)); } commanate = true; } writer.write('}'); return writer; } catch (IOException exception) { throw new JSONException(exception); } } }
12085952-sageandroid
commandline/src/org/json/JSONObject.java
Java
gpl3
55,756
package org.json; /* Copyright (c) 2006 JSON.org 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 shall be used for Good, not Evil. 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. */ import java.io.StringWriter; /** * JSONStringer provides a quick and convenient way of producing JSON text. * The texts produced strictly conform to JSON syntax rules. No whitespace is * added, so the results are ready for transmission or storage. Each instance of * JSONStringer can produce one JSON text. * <p> * A JSONStringer instance provides a <code>value</code> method for appending * values to the * text, and a <code>key</code> * method for adding keys before values in objects. There are <code>array</code> * and <code>endArray</code> methods that make and bound array values, and * <code>object</code> and <code>endObject</code> methods which make and bound * object values. All of these methods return the JSONWriter instance, * permitting cascade style. For example, <pre> * myString = new JSONStringer() * .object() * .key("JSON") * .value("Hello, World!") * .endObject() * .toString();</pre> which produces the string <pre> * {"JSON":"Hello, World!"}</pre> * <p> * The first method called must be <code>array</code> or <code>object</code>. * There are no methods for adding commas or colons. JSONStringer adds them for * you. Objects and arrays can be nested up to 20 levels deep. * <p> * This can sometimes be easier than using a JSONObject to build a string. * @author JSON.org * @version 2008-09-18 */ public class JSONStringer extends JSONWriter { /** * Make a fresh JSONStringer. It can be used to build one JSON text. */ public JSONStringer() { super(new StringWriter()); } /** * Return the JSON text. This method is used to obtain the product of the * JSONStringer instance. It will return <code>null</code> if there was a * problem in the construction of the JSON text (such as the calls to * <code>array</code> were not properly balanced with calls to * <code>endArray</code>). * @return The JSON text. */ public String toString() { return this.mode == 'd' ? this.writer.toString() : null; } }
12085952-sageandroid
commandline/src/org/json/JSONStringer.java
Java
gpl3
3,266
package org.json; /* Copyright (c) 2002 JSON.org 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 shall be used for Good, not Evil. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ /** * The XMLTokener extends the JSONTokener to provide additional methods * for the parsing of XML texts. * @author JSON.org * @version 2010-12-24 */ public class XMLTokener extends JSONTokener { /** The table of entity values. It initially contains Character values for * amp, apos, gt, lt, quot. */ public static final java.util.HashMap entity; static { entity = new java.util.HashMap(8); entity.put("amp", XML.AMP); entity.put("apos", XML.APOS); entity.put("gt", XML.GT); entity.put("lt", XML.LT); entity.put("quot", XML.QUOT); } /** * Construct an XMLTokener from a string. * @param s A source string. */ public XMLTokener(String s) { super(s); } /** * Get the text in the CDATA block. * @return The string up to the <code>]]&gt;</code>. * @throws JSONException If the <code>]]&gt;</code> is not found. */ public String nextCDATA() throws JSONException { char c; int i; StringBuffer sb = new StringBuffer(); for (;;) { c = next(); if (end()) { throw syntaxError("Unclosed CDATA"); } sb.append(c); i = sb.length() - 3; if (i >= 0 && sb.charAt(i) == ']' && sb.charAt(i + 1) == ']' && sb.charAt(i + 2) == '>') { sb.setLength(i); return sb.toString(); } } } /** * Get the next XML outer token, trimming whitespace. There are two kinds * of tokens: the '<' character which begins a markup tag, and the content * text between markup tags. * * @return A string, or a '<' Character, or null if there is no more * source text. * @throws JSONException */ public Object nextContent() throws JSONException { char c; StringBuffer sb; do { c = next(); } while (Character.isWhitespace(c)); if (c == 0) { return null; } if (c == '<') { return XML.LT; } sb = new StringBuffer(); for (;;) { if (c == '<' || c == 0) { back(); return sb.toString().trim(); } if (c == '&') { sb.append(nextEntity(c)); } else { sb.append(c); } c = next(); } } /** * Return the next entity. These entities are translated to Characters: * <code>&amp; &apos; &gt; &lt; &quot;</code>. * @param ampersand An ampersand character. * @return A Character or an entity String if the entity is not recognized. * @throws JSONException If missing ';' in XML entity. */ public Object nextEntity(char ampersand) throws JSONException { StringBuffer sb = new StringBuffer(); for (;;) { char c = next(); if (Character.isLetterOrDigit(c) || c == '#') { sb.append(Character.toLowerCase(c)); } else if (c == ';') { break; } else { throw syntaxError("Missing ';' in XML entity: &" + sb); } } String string = sb.toString(); Object object = entity.get(string); return object != null ? object : ampersand + string + ";"; } /** * Returns the next XML meta token. This is used for skipping over <!...> * and <?...?> structures. * @return Syntax characters (<code>< > / = ! ?</code>) are returned as * Character, and strings and names are returned as Boolean. We don't care * what the values actually are. * @throws JSONException If a string is not properly closed or if the XML * is badly structured. */ public Object nextMeta() throws JSONException { char c; char q; do { c = next(); } while (Character.isWhitespace(c)); switch (c) { case 0: throw syntaxError("Misshaped meta tag"); case '<': return XML.LT; case '>': return XML.GT; case '/': return XML.SLASH; case '=': return XML.EQ; case '!': return XML.BANG; case '?': return XML.QUEST; case '"': case '\'': q = c; for (;;) { c = next(); if (c == 0) { throw syntaxError("Unterminated string"); } if (c == q) { return Boolean.TRUE; } } default: for (;;) { c = next(); if (Character.isWhitespace(c)) { return Boolean.TRUE; } switch (c) { case 0: case '<': case '>': case '/': case '=': case '!': case '?': case '"': case '\'': back(); return Boolean.TRUE; } } } } /** * Get the next XML Token. These tokens are found inside of angle * brackets. It may be one of these characters: <code>/ > = ! ?</code> or it * may be a string wrapped in single quotes or double quotes, or it may be a * name. * @return a String or a Character. * @throws JSONException If the XML is not well formed. */ public Object nextToken() throws JSONException { char c; char q; StringBuffer sb; do { c = next(); } while (Character.isWhitespace(c)); switch (c) { case 0: throw syntaxError("Misshaped element"); case '<': throw syntaxError("Misplaced '<'"); case '>': return XML.GT; case '/': return XML.SLASH; case '=': return XML.EQ; case '!': return XML.BANG; case '?': return XML.QUEST; // Quoted string case '"': case '\'': q = c; sb = new StringBuffer(); for (;;) { c = next(); if (c == 0) { throw syntaxError("Unterminated string"); } if (c == q) { return sb.toString(); } if (c == '&') { sb.append(nextEntity(c)); } else { sb.append(c); } } default: // Name sb = new StringBuffer(); for (;;) { sb.append(c); c = next(); if (Character.isWhitespace(c)) { return sb.toString(); } switch (c) { case 0: return sb.toString(); case '>': case '/': case '=': case '!': case '?': case '[': case ']': back(); return sb.toString(); case '<': case '"': case '\'': throw syntaxError("Bad character in a name"); } } } } /** * Skip characters until past the requested string. * If it is not found, we are left at the end of the source with a result of false. * @param to A string to skip past. * @throws JSONException */ public boolean skipPast(String to) throws JSONException { boolean b; char c; int i; int j; int offset = 0; int length = to.length(); char[] circle = new char[length]; /* * First fill the circle buffer with as many characters as are in the * to string. If we reach an early end, bail. */ for (i = 0; i < length; i += 1) { c = next(); if (c == 0) { return false; } circle[i] = c; } /* * We will loop, possibly for all of the remaining characters. */ for (;;) { j = offset; b = true; /* * Compare the circle buffer with the to string. */ for (i = 0; i < length; i += 1) { if (circle[j] != to.charAt(i)) { b = false; break; } j += 1; if (j >= length) { j -= length; } } /* * If we exit the loop with b intact, then victory is ours. */ if (b) { return true; } /* * Get the next character. If there isn't one, then defeat is ours. */ c = next(); if (c == 0) { return false; } /* * Shove the character in the circle buffer and advance the * circle offset. The offset is mod n. */ circle[offset] = c; offset += 1; if (offset >= length) { offset -= length; } } } }
12085952-sageandroid
commandline/src/org/json/XMLTokener.java
Java
gpl3
10,758
package org.json; import java.io.BufferedReader; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import java.io.Reader; import java.io.StringReader; /* Copyright (c) 2002 JSON.org 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 shall be used for Good, not Evil. 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. */ /** * A JSONTokener takes a source string and extracts characters and tokens from * it. It is used by the JSONObject and JSONArray constructors to parse * JSON source strings. * @author JSON.org * @version 2011-11-24 */ public class JSONTokener { private int character; private boolean eof; private int index; private int line; private char previous; private final Reader reader; private boolean usePrevious; /** * Construct a JSONTokener from a Reader. * * @param reader A reader. */ public JSONTokener(Reader reader) { this.reader = reader.markSupported() ? reader : new BufferedReader(reader); this.eof = false; this.usePrevious = false; this.previous = 0; this.index = 0; this.character = 1; this.line = 1; } /** * Construct a JSONTokener from an InputStream. */ public JSONTokener(InputStream inputStream) throws JSONException { this(new InputStreamReader(inputStream)); } /** * Construct a JSONTokener from a string. * * @param s A source string. */ public JSONTokener(String s) { this(new StringReader(s)); } /** * Back up one character. This provides a sort of lookahead capability, * so that you can test for a digit or letter before attempting to parse * the next number or identifier. */ public void back() throws JSONException { if (this.usePrevious || this.index <= 0) { throw new JSONException("Stepping back two steps is not supported"); } this.index -= 1; this.character -= 1; this.usePrevious = true; this.eof = false; } /** * Get the hex value of a character (base16). * @param c A character between '0' and '9' or between 'A' and 'F' or * between 'a' and 'f'. * @return An int between 0 and 15, or -1 if c was not a hex digit. */ public static int dehexchar(char c) { if (c >= '0' && c <= '9') { return c - '0'; } if (c >= 'A' && c <= 'F') { return c - ('A' - 10); } if (c >= 'a' && c <= 'f') { return c - ('a' - 10); } return -1; } public boolean end() { return this.eof && !this.usePrevious; } /** * Determine if the source string still contains characters that next() * can consume. * @return true if not yet at the end of the source. */ public boolean more() throws JSONException { this.next(); if (this.end()) { return false; } this.back(); return true; } /** * Get the next character in the source string. * * @return The next character, or 0 if past the end of the source string. */ public char next() throws JSONException { int c; if (this.usePrevious) { this.usePrevious = false; c = this.previous; } else { try { c = this.reader.read(); } catch (IOException exception) { throw new JSONException(exception); } if (c <= 0) { // End of stream this.eof = true; c = 0; } } this.index += 1; if (this.previous == '\r') { this.line += 1; this.character = c == '\n' ? 0 : 1; } else if (c == '\n') { this.line += 1; this.character = 0; } else { this.character += 1; } this.previous = (char) c; return this.previous; } /** * Consume the next character, and check that it matches a specified * character. * @param c The character to match. * @return The character. * @throws JSONException if the character does not match. */ public char next(char c) throws JSONException { char n = this.next(); if (n != c) { throw this.syntaxError("Expected '" + c + "' and instead saw '" + n + "'"); } return n; } /** * Get the next n characters. * * @param n The number of characters to take. * @return A string of n characters. * @throws JSONException * Substring bounds error if there are not * n characters remaining in the source string. */ public String next(int n) throws JSONException { if (n == 0) { return ""; } char[] chars = new char[n]; int pos = 0; while (pos < n) { chars[pos] = this.next(); if (this.end()) { throw this.syntaxError("Substring bounds error"); } pos += 1; } return new String(chars); } /** * Get the next char in the string, skipping whitespace. * @throws JSONException * @return A character, or 0 if there are no more characters. */ public char nextClean() throws JSONException { for (;;) { char c = this.next(); if (c == 0 || c > ' ') { return c; } } } /** * Return the characters up to the next close quote character. * Backslash processing is done. The formal JSON format does not * allow strings in single quotes, but an implementation is allowed to * accept them. * @param quote The quoting character, either * <code>"</code>&nbsp;<small>(double quote)</small> or * <code>'</code>&nbsp;<small>(single quote)</small>. * @return A String. * @throws JSONException Unterminated string. */ public String nextString(char quote) throws JSONException { char c; StringBuffer sb = new StringBuffer(); for (;;) { c = this.next(); switch (c) { case 0: case '\n': case '\r': throw this.syntaxError("Unterminated string"); case '\\': c = this.next(); switch (c) { case 'b': sb.append('\b'); break; case 't': sb.append('\t'); break; case 'n': sb.append('\n'); break; case 'f': sb.append('\f'); break; case 'r': sb.append('\r'); break; case 'u': sb.append((char)Integer.parseInt(this.next(4), 16)); break; case '"': case '\'': case '\\': case '/': sb.append(c); break; default: throw this.syntaxError("Illegal escape."); } break; default: if (c == quote) { return sb.toString(); } sb.append(c); } } } /** * Get the text up but not including the specified character or the * end of line, whichever comes first. * @param delimiter A delimiter character. * @return A string. */ public String nextTo(char delimiter) throws JSONException { StringBuffer sb = new StringBuffer(); for (;;) { char c = this.next(); if (c == delimiter || c == 0 || c == '\n' || c == '\r') { if (c != 0) { this.back(); } return sb.toString().trim(); } sb.append(c); } } /** * Get the text up but not including one of the specified delimiter * characters or the end of line, whichever comes first. * @param delimiters A set of delimiter characters. * @return A string, trimmed. */ public String nextTo(String delimiters) throws JSONException { char c; StringBuffer sb = new StringBuffer(); for (;;) { c = this.next(); if (delimiters.indexOf(c) >= 0 || c == 0 || c == '\n' || c == '\r') { if (c != 0) { this.back(); } return sb.toString().trim(); } sb.append(c); } } /** * Get the next value. The value can be a Boolean, Double, Integer, * JSONArray, JSONObject, Long, or String, or the JSONObject.NULL object. * @throws JSONException If syntax error. * * @return An object. */ public Object nextValue() throws JSONException { char c = this.nextClean(); String string; switch (c) { case '"': case '\'': return this.nextString(c); case '{': this.back(); return new JSONObject(this); case '[': this.back(); return new JSONArray(this); } /* * Handle unquoted text. This could be the values true, false, or * null, or it can be a number. An implementation (such as this one) * is allowed to also accept non-standard forms. * * Accumulate characters until we reach the end of the text or a * formatting character. */ StringBuffer sb = new StringBuffer(); while (c >= ' ' && ",:]}/\\\"[{;=#".indexOf(c) < 0) { sb.append(c); c = this.next(); } this.back(); string = sb.toString().trim(); if (string.equals("")) { throw this.syntaxError("Missing value"); } return JSONObject.stringToValue(string); } /** * Skip characters until the next character is the requested character. * If the requested character is not found, no characters are skipped. * @param to A character to skip to. * @return The requested character, or zero if the requested character * is not found. */ public char skipTo(char to) throws JSONException { char c; try { int startIndex = this.index; int startCharacter = this.character; int startLine = this.line; this.reader.mark(Integer.MAX_VALUE); do { c = this.next(); if (c == 0) { this.reader.reset(); this.index = startIndex; this.character = startCharacter; this.line = startLine; return c; } } while (c != to); } catch (IOException exc) { throw new JSONException(exc); } this.back(); return c; } /** * Make a JSONException to signal a syntax error. * * @param message The error message. * @return A JSONException object, suitable for throwing */ public JSONException syntaxError(String message) { return new JSONException(message + this.toString()); } /** * Make a printable string of this JSONTokener. * * @return " at {index} [character {character} line {line}]" */ public String toString() { return " at " + this.index + " [character " + this.character + " line " + this.line + "]"; } }
12085952-sageandroid
commandline/src/org/json/JSONTokener.java
Java
gpl3
12,847
package org.json; /* Copyright (c) 2002 JSON.org 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 shall be used for Good, not Evil. 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. */ import java.util.Iterator; /** * Convert a web browser cookie list string to a JSONObject and back. * @author JSON.org * @version 2010-12-24 */ public class CookieList { /** * Convert a cookie list into a JSONObject. A cookie list is a sequence * of name/value pairs. The names are separated from the values by '='. * The pairs are separated by ';'. The names and the values * will be unescaped, possibly converting '+' and '%' sequences. * * To add a cookie to a cooklist, * cookielistJSONObject.put(cookieJSONObject.getString("name"), * cookieJSONObject.getString("value")); * @param string A cookie list string * @return A JSONObject * @throws JSONException */ public static JSONObject toJSONObject(String string) throws JSONException { JSONObject jo = new JSONObject(); JSONTokener x = new JSONTokener(string); while (x.more()) { String name = Cookie.unescape(x.nextTo('=')); x.next('='); jo.put(name, Cookie.unescape(x.nextTo(';'))); x.next(); } return jo; } /** * Convert a JSONObject into a cookie list. A cookie list is a sequence * of name/value pairs. The names are separated from the values by '='. * The pairs are separated by ';'. The characters '%', '+', '=', and ';' * in the names and values are replaced by "%hh". * @param jo A JSONObject * @return A cookie list string * @throws JSONException */ public static String toString(JSONObject jo) throws JSONException { boolean b = false; Iterator keys = jo.keys(); String string; StringBuffer sb = new StringBuffer(); while (keys.hasNext()) { string = keys.next().toString(); if (!jo.isNull(string)) { if (b) { sb.append(';'); } sb.append(Cookie.escape(string)); sb.append("="); sb.append(Cookie.escape(jo.getString(string))); b = true; } } return sb.toString(); } }
12085952-sageandroid
commandline/src/org/json/CookieList.java
Java
gpl3
3,394
package org.json; /** * The <code>JSONString</code> interface allows a <code>toJSONString()</code> * method so that a class can change the behavior of * <code>JSONObject.toString()</code>, <code>JSONArray.toString()</code>, * and <code>JSONWriter.value(</code>Object<code>)</code>. The * <code>toJSONString</code> method will be used instead of the default behavior * of using the Object's <code>toString()</code> method and quoting the result. */ public interface JSONString { /** * The <code>toJSONString</code> method allows a class to produce its own JSON * serialization. * * @return A strictly syntactically correct JSON text. */ public String toJSONString(); }
12085952-sageandroid
commandline/src/org/json/JSONString.java
Java
gpl3
712
package org.json; import java.util.ArrayList; import java.util.Collection; import java.util.Iterator; import java.util.List; import java.util.Map; import java.io.StringWriter; import junit.framework.TestCase; /* Copyright (c) 2002 JSON.org 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 shall be used for Good, not Evil. 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. */ /** * Test class. This file is not formally a member of the org.json library. * It is just a test tool. * * Issue: JSONObject does not specify the ordering of keys, so simple-minded * comparisons of .toString to a string literal are likely to fail. * * @author JSON.org * @version 2011-10-25 */ public class Test extends TestCase { public Test(String name) { super(name); } protected void setUp() throws Exception { super.setUp(); } protected void tearDown() throws Exception { super.tearDown(); } public void testXML() throws Exception { JSONObject jsonobject; String string; jsonobject = XML.toJSONObject("<![CDATA[This is a collection of test patterns and examples for org.json.]]> Ignore the stuff past the end. "); assertEquals("{\"content\":\"This is a collection of test patterns and examples for org.json.\"}", jsonobject.toString()); assertEquals("This is a collection of test patterns and examples for org.json.", jsonobject.getString("content")); string = "<test><blank></blank><empty/></test>"; jsonobject = XML.toJSONObject(string); assertEquals("{\"test\": {\n \"blank\": \"\",\n \"empty\": \"\"\n}}", jsonobject.toString(2)); assertEquals("<test><blank/><empty/></test>", XML.toString(jsonobject)); string = "<subsonic-response><playlists><playlist id=\"476c65652e6d3375\" int=\"12345678901234567890123456789012345678901234567890213991133777039355058536718668104339937\"/><playlist id=\"50617274792e78737066\"/></playlists></subsonic-response>"; jsonobject = XML.toJSONObject(string); assertEquals("{\"subsonic-response\":{\"playlists\":{\"playlist\":[{\"id\":\"476c65652e6d3375\",\"int\":\"12345678901234567890123456789012345678901234567890213991133777039355058536718668104339937\"},{\"id\":\"50617274792e78737066\"}]}}}", jsonobject.toString()); } public void testNull() throws Exception { JSONObject jsonobject; jsonobject = new JSONObject("{\"message\":\"null\"}"); assertFalse(jsonobject.isNull("message")); assertEquals("null", jsonobject.getString("message")); jsonobject = new JSONObject("{\"message\":null}"); assertTrue(jsonobject.isNull("message")); } public void testJSON() throws Exception { double eps = 2.220446049250313e-16; Iterator iterator; JSONArray jsonarray; JSONObject jsonobject; JSONStringer jsonstringer; Object object; String string; Beany beanie = new Beany("A beany object", 42, true); string = "[001122334455]"; jsonarray = new JSONArray(string); assertEquals("[1122334455]", jsonarray.toString()); string = "[666e666]"; jsonarray = new JSONArray(string); assertEquals("[\"666e666\"]", jsonarray.toString()); string = "[00.10]"; jsonarray = new JSONArray(string); assertEquals("[0.1]", jsonarray.toString()); jsonobject = new JSONObject(); object = null; jsonobject.put("booga", object); jsonobject.put("wooga", JSONObject.NULL); assertEquals("{\"wooga\":null}", jsonobject.toString()); assertTrue(jsonobject.isNull("booga")); jsonobject = new JSONObject(); jsonobject.increment("two"); jsonobject.increment("two"); assertEquals("{\"two\":2}", jsonobject.toString()); assertEquals(2, jsonobject.getInt("two")); string = "{ \"list of lists\" : [ [1, 2, 3], [4, 5, 6], ] }"; jsonobject = new JSONObject(string); assertEquals("{\"list of lists\": [\n" + " [\n" + " 1,\n" + " 2,\n" + " 3\n" + " ],\n" + " [\n" + " 4,\n" + " 5,\n" + " 6\n" + " ]\n" + "]}", jsonobject.toString(4)); assertEquals("<list of lists><array>1</array><array>2</array><array>3</array></list of lists><list of lists><array>4</array><array>5</array><array>6</array></list of lists>", XML.toString(jsonobject)); string = "<recipe name=\"bread\" prep_time=\"5 mins\" cook_time=\"3 hours\"> <title>Basic bread</title> <ingredient amount=\"8\" unit=\"dL\">Flour</ingredient> <ingredient amount=\"10\" unit=\"grams\">Yeast</ingredient> <ingredient amount=\"4\" unit=\"dL\" state=\"warm\">Water</ingredient> <ingredient amount=\"1\" unit=\"teaspoon\">Salt</ingredient> <instructions> <step>Mix all ingredients together.</step> <step>Knead thoroughly.</step> <step>Cover with a cloth, and leave for one hour in warm room.</step> <step>Knead again.</step> <step>Place in a bread baking tin.</step> <step>Cover with a cloth, and leave for one hour in warm room.</step> <step>Bake in the oven at 180(degrees)C for 30 minutes.</step> </instructions> </recipe> "; jsonobject = XML.toJSONObject(string); assertEquals("{\"recipe\": {\n \"title\": \"Basic bread\",\n \"cook_time\": \"3 hours\",\n \"instructions\": {\"step\": [\n \"Mix all ingredients together.\",\n \"Knead thoroughly.\",\n \"Cover with a cloth, and leave for one hour in warm room.\",\n \"Knead again.\",\n \"Place in a bread baking tin.\",\n \"Cover with a cloth, and leave for one hour in warm room.\",\n \"Bake in the oven at 180(degrees)C for 30 minutes.\"\n ]},\n \"name\": \"bread\",\n \"ingredient\": [\n {\n \"content\": \"Flour\",\n \"amount\": 8,\n \"unit\": \"dL\"\n },\n {\n \"content\": \"Yeast\",\n \"amount\": 10,\n \"unit\": \"grams\"\n },\n {\n \"content\": \"Water\",\n \"amount\": 4,\n \"unit\": \"dL\",\n \"state\": \"warm\"\n },\n {\n \"content\": \"Salt\",\n \"amount\": 1,\n \"unit\": \"teaspoon\"\n }\n ],\n \"prep_time\": \"5 mins\"\n}}", jsonobject.toString(4)); jsonobject = JSONML.toJSONObject(string); assertEquals("{\"cook_time\":\"3 hours\",\"name\":\"bread\",\"tagName\":\"recipe\",\"childNodes\":[{\"tagName\":\"title\",\"childNodes\":[\"Basic bread\"]},{\"amount\":8,\"unit\":\"dL\",\"tagName\":\"ingredient\",\"childNodes\":[\"Flour\"]},{\"amount\":10,\"unit\":\"grams\",\"tagName\":\"ingredient\",\"childNodes\":[\"Yeast\"]},{\"amount\":4,\"unit\":\"dL\",\"tagName\":\"ingredient\",\"state\":\"warm\",\"childNodes\":[\"Water\"]},{\"amount\":1,\"unit\":\"teaspoon\",\"tagName\":\"ingredient\",\"childNodes\":[\"Salt\"]},{\"tagName\":\"instructions\",\"childNodes\":[{\"tagName\":\"step\",\"childNodes\":[\"Mix all ingredients together.\"]},{\"tagName\":\"step\",\"childNodes\":[\"Knead thoroughly.\"]},{\"tagName\":\"step\",\"childNodes\":[\"Cover with a cloth, and leave for one hour in warm room.\"]},{\"tagName\":\"step\",\"childNodes\":[\"Knead again.\"]},{\"tagName\":\"step\",\"childNodes\":[\"Place in a bread baking tin.\"]},{\"tagName\":\"step\",\"childNodes\":[\"Cover with a cloth, and leave for one hour in warm room.\"]},{\"tagName\":\"step\",\"childNodes\":[\"Bake in the oven at 180(degrees)C for 30 minutes.\"]}]}],\"prep_time\":\"5 mins\"}", jsonobject.toString()); assertEquals("<recipe cook_time=\"3 hours\" name=\"bread\" prep_time=\"5 mins\"><title>Basic bread</title><ingredient amount=\"8\" unit=\"dL\">Flour</ingredient><ingredient amount=\"10\" unit=\"grams\">Yeast</ingredient><ingredient amount=\"4\" unit=\"dL\" state=\"warm\">Water</ingredient><ingredient amount=\"1\" unit=\"teaspoon\">Salt</ingredient><instructions><step>Mix all ingredients together.</step><step>Knead thoroughly.</step><step>Cover with a cloth, and leave for one hour in warm room.</step><step>Knead again.</step><step>Place in a bread baking tin.</step><step>Cover with a cloth, and leave for one hour in warm room.</step><step>Bake in the oven at 180(degrees)C for 30 minutes.</step></instructions></recipe>", JSONML.toString(jsonobject)); jsonarray = JSONML.toJSONArray(string); assertEquals("[\n \"recipe\",\n {\n \"cook_time\": \"3 hours\",\n \"name\": \"bread\",\n \"prep_time\": \"5 mins\"\n },\n [\n \"title\",\n \"Basic bread\"\n ],\n [\n \"ingredient\",\n {\n \"amount\": 8,\n \"unit\": \"dL\"\n },\n \"Flour\"\n ],\n [\n \"ingredient\",\n {\n \"amount\": 10,\n \"unit\": \"grams\"\n },\n \"Yeast\"\n ],\n [\n \"ingredient\",\n {\n \"amount\": 4,\n \"unit\": \"dL\",\n \"state\": \"warm\"\n },\n \"Water\"\n ],\n [\n \"ingredient\",\n {\n \"amount\": 1,\n \"unit\": \"teaspoon\"\n },\n \"Salt\"\n ],\n [\n \"instructions\",\n [\n \"step\",\n \"Mix all ingredients together.\"\n ],\n [\n \"step\",\n \"Knead thoroughly.\"\n ],\n [\n \"step\",\n \"Cover with a cloth, and leave for one hour in warm room.\"\n ],\n [\n \"step\",\n \"Knead again.\"\n ],\n [\n \"step\",\n \"Place in a bread baking tin.\"\n ],\n [\n \"step\",\n \"Cover with a cloth, and leave for one hour in warm room.\"\n ],\n [\n \"step\",\n \"Bake in the oven at 180(degrees)C for 30 minutes.\"\n ]\n ]\n]", jsonarray.toString(4)); assertEquals("<recipe cook_time=\"3 hours\" name=\"bread\" prep_time=\"5 mins\"><title>Basic bread</title><ingredient amount=\"8\" unit=\"dL\">Flour</ingredient><ingredient amount=\"10\" unit=\"grams\">Yeast</ingredient><ingredient amount=\"4\" unit=\"dL\" state=\"warm\">Water</ingredient><ingredient amount=\"1\" unit=\"teaspoon\">Salt</ingredient><instructions><step>Mix all ingredients together.</step><step>Knead thoroughly.</step><step>Cover with a cloth, and leave for one hour in warm room.</step><step>Knead again.</step><step>Place in a bread baking tin.</step><step>Cover with a cloth, and leave for one hour in warm room.</step><step>Bake in the oven at 180(degrees)C for 30 minutes.</step></instructions></recipe>", JSONML.toString(jsonarray)); string = "<div id=\"demo\" class=\"JSONML\"><p>JSONML is a transformation between <b>JSON</b> and <b>XML</b> that preserves ordering of document features.</p><p>JSONML can work with JSON arrays or JSON objects.</p><p>Three<br/>little<br/>words</p></div>"; jsonobject = JSONML.toJSONObject(string); assertEquals("{\n \"id\": \"demo\",\n \"tagName\": \"div\",\n \"class\": \"JSONML\",\n \"childNodes\": [\n {\n \"tagName\": \"p\",\n \"childNodes\": [\n \"JSONML is a transformation between\",\n {\n \"tagName\": \"b\",\n \"childNodes\": [\"JSON\"]\n },\n \"and\",\n {\n \"tagName\": \"b\",\n \"childNodes\": [\"XML\"]\n },\n \"that preserves ordering of document features.\"\n ]\n },\n {\n \"tagName\": \"p\",\n \"childNodes\": [\"JSONML can work with JSON arrays or JSON objects.\"]\n },\n {\n \"tagName\": \"p\",\n \"childNodes\": [\n \"Three\",\n {\"tagName\": \"br\"},\n \"little\",\n {\"tagName\": \"br\"},\n \"words\"\n ]\n }\n ]\n}", jsonobject.toString(4)); assertEquals("<div id=\"demo\" class=\"JSONML\"><p>JSONML is a transformation between<b>JSON</b>and<b>XML</b>that preserves ordering of document features.</p><p>JSONML can work with JSON arrays or JSON objects.</p><p>Three<br/>little<br/>words</p></div>", JSONML.toString(jsonobject)); jsonarray = JSONML.toJSONArray(string); assertEquals("[\n \"div\",\n {\n \"id\": \"demo\",\n \"class\": \"JSONML\"\n },\n [\n \"p\",\n \"JSONML is a transformation between\",\n [\n \"b\",\n \"JSON\"\n ],\n \"and\",\n [\n \"b\",\n \"XML\"\n ],\n \"that preserves ordering of document features.\"\n ],\n [\n \"p\",\n \"JSONML can work with JSON arrays or JSON objects.\"\n ],\n [\n \"p\",\n \"Three\",\n [\"br\"],\n \"little\",\n [\"br\"],\n \"words\"\n ]\n]", jsonarray.toString(4)); assertEquals("<div id=\"demo\" class=\"JSONML\"><p>JSONML is a transformation between<b>JSON</b>and<b>XML</b>that preserves ordering of document features.</p><p>JSONML can work with JSON arrays or JSON objects.</p><p>Three<br/>little<br/>words</p></div>", JSONML.toString(jsonarray)); string = "{\"xmlns:soap\":\"http://www.w3.org/2003/05/soap-envelope\",\"tagName\":\"soap:Envelope\",\"childNodes\":[{\"tagName\":\"soap:Header\"},{\"tagName\":\"soap:Body\",\"childNodes\":[{\"tagName\":\"ws:listProducts\",\"childNodes\":[{\"tagName\":\"ws:delay\",\"childNodes\":[1]}]}]}],\"xmlns:ws\":\"http://warehouse.acme.com/ws\"}"; jsonobject = new JSONObject(string); assertEquals("<soap:Envelope xmlns:soap=\"http://www.w3.org/2003/05/soap-envelope\" xmlns:ws=\"http://warehouse.acme.com/ws\"><soap:Header/><soap:Body><ws:listProducts><ws:delay>1</ws:delay></ws:listProducts></soap:Body></soap:Envelope>", JSONML.toString(jsonobject)); string = "<person created=\"2006-11-11T19:23\" modified=\"2006-12-31T23:59\">\n <firstName>Robert</firstName>\n <lastName>Smith</lastName>\n <address type=\"home\">\n <street>12345 Sixth Ave</street>\n <city>Anytown</city>\n <state>CA</state>\n <postalCode>98765-4321</postalCode>\n </address>\n </person>"; jsonobject = XML.toJSONObject(string); assertEquals("{\"person\": {\n \"lastName\": \"Smith\",\n \"address\": {\n \"postalCode\": \"98765-4321\",\n \"street\": \"12345 Sixth Ave\",\n \"state\": \"CA\",\n \"type\": \"home\",\n \"city\": \"Anytown\"\n },\n \"created\": \"2006-11-11T19:23\",\n \"firstName\": \"Robert\",\n \"modified\": \"2006-12-31T23:59\"\n}}", jsonobject.toString(4)); string = "{ \"entity\": { \"imageURL\": \"\", \"name\": \"IXXXXXXXXXXXXX\", \"id\": 12336, \"ratingCount\": null, \"averageRating\": null } }"; jsonobject = new JSONObject(string); assertEquals("{\"entity\": {\n \"id\": 12336,\n \"averageRating\": null,\n \"ratingCount\": null,\n \"name\": \"IXXXXXXXXXXXXX\",\n \"imageURL\": \"\"\n}}", jsonobject.toString(2)); jsonstringer = new JSONStringer(); string = jsonstringer .object() .key("single") .value("MARIE HAA'S") .key("Johnny") .value("MARIE HAA\\'S") .key("foo") .value("bar") .key("baz") .array() .object() .key("quux") .value("Thanks, Josh!") .endObject() .endArray() .key("obj keys") .value(JSONObject.getNames(beanie)) .endObject() .toString(); assertEquals("{\"single\":\"MARIE HAA'S\",\"Johnny\":\"MARIE HAA\\\\'S\",\"foo\":\"bar\",\"baz\":[{\"quux\":\"Thanks, Josh!\"}],\"obj keys\":[\"aString\",\"aNumber\",\"aBoolean\"]}" , string); assertEquals("{\"a\":[[[\"b\"]]]}" , new JSONStringer() .object() .key("a") .array() .array() .array() .value("b") .endArray() .endArray() .endArray() .endObject() .toString()); jsonstringer = new JSONStringer(); jsonstringer.array(); jsonstringer.value(1); jsonstringer.array(); jsonstringer.value(null); jsonstringer.array(); jsonstringer.object(); jsonstringer.key("empty-array").array().endArray(); jsonstringer.key("answer").value(42); jsonstringer.key("null").value(null); jsonstringer.key("false").value(false); jsonstringer.key("true").value(true); jsonstringer.key("big").value(123456789e+88); jsonstringer.key("small").value(123456789e-88); jsonstringer.key("empty-object").object().endObject(); jsonstringer.key("long"); jsonstringer.value(9223372036854775807L); jsonstringer.endObject(); jsonstringer.value("two"); jsonstringer.endArray(); jsonstringer.value(true); jsonstringer.endArray(); jsonstringer.value(98.6); jsonstringer.value(-100.0); jsonstringer.object(); jsonstringer.endObject(); jsonstringer.object(); jsonstringer.key("one"); jsonstringer.value(1.00); jsonstringer.endObject(); jsonstringer.value(beanie); jsonstringer.endArray(); assertEquals("[1,[null,[{\"empty-array\":[],\"answer\":42,\"null\":null,\"false\":false,\"true\":true,\"big\":1.23456789E96,\"small\":1.23456789E-80,\"empty-object\":{},\"long\":9223372036854775807},\"two\"],true],98.6,-100,{},{\"one\":1},{\"A beany object\":42}]", jsonstringer.toString()); assertEquals("[\n 1,\n [\n null,\n [\n {\n \"empty-array\": [],\n \"empty-object\": {},\n \"answer\": 42,\n \"true\": true,\n \"false\": false,\n \"long\": 9223372036854775807,\n \"big\": 1.23456789E96,\n \"small\": 1.23456789E-80,\n \"null\": null\n },\n \"two\"\n ],\n true\n ],\n 98.6,\n -100,\n {},\n {\"one\": 1},\n {\"A beany object\": 42}\n]", new JSONArray(jsonstringer.toString()).toString(4)); int ar[] = {1, 2, 3}; JSONArray ja = new JSONArray(ar); assertEquals("[1,2,3]", ja.toString()); assertEquals("<array>1</array><array>2</array><array>3</array>", XML.toString(ar)); String sa[] = {"aString", "aNumber", "aBoolean"}; jsonobject = new JSONObject(beanie, sa); jsonobject.put("Testing JSONString interface", beanie); assertEquals("{\n \"aBoolean\": true,\n \"aNumber\": 42,\n \"aString\": \"A beany object\",\n \"Testing JSONString interface\": {\"A beany object\":42}\n}", jsonobject.toString(4)); jsonobject = new JSONObject("{slashes: '///', closetag: '</script>', backslash:'\\\\', ei: {quotes: '\"\\''},eo: {a: '\"quoted\"', b:\"don't\"}, quotes: [\"'\", '\"']}"); assertEquals("{\n \"quotes\": [\n \"'\",\n \"\\\"\"\n ],\n \"slashes\": \"///\",\n \"ei\": {\"quotes\": \"\\\"'\"},\n \"eo\": {\n \"b\": \"don't\",\n \"a\": \"\\\"quoted\\\"\"\n },\n \"closetag\": \"<\\/script>\",\n \"backslash\": \"\\\\\"\n}", jsonobject.toString(2)); assertEquals("<quotes>&apos;</quotes><quotes>&quot;</quotes><slashes>///</slashes><ei><quotes>&quot;&apos;</quotes></ei><eo><b>don&apos;t</b><a>&quot;quoted&quot;</a></eo><closetag>&lt;/script&gt;</closetag><backslash>\\</backslash>", XML.toString(jsonobject)); jsonobject = new JSONObject( "{foo: [true, false,9876543210, 0.0, 1.00000001, 1.000000000001, 1.00000000000000001," + " .00000000000000001, 2.00, 0.1, 2e100, -32,[],{}, \"string\"], " + " to : null, op : 'Good'," + "ten:10} postfix comment"); jsonobject.put("String", "98.6"); jsonobject.put("JSONObject", new JSONObject()); jsonobject.put("JSONArray", new JSONArray()); jsonobject.put("int", 57); jsonobject.put("double", 123456789012345678901234567890.); jsonobject.put("true", true); jsonobject.put("false", false); jsonobject.put("null", JSONObject.NULL); jsonobject.put("bool", "true"); jsonobject.put("zero", -0.0); jsonobject.put("\\u2028", "\u2028"); jsonobject.put("\\u2029", "\u2029"); jsonarray = jsonobject.getJSONArray("foo"); jsonarray.put(666); jsonarray.put(2001.99); jsonarray.put("so \"fine\"."); jsonarray.put("so <fine>."); jsonarray.put(true); jsonarray.put(false); jsonarray.put(new JSONArray()); jsonarray.put(new JSONObject()); jsonobject.put("keys", JSONObject.getNames(jsonobject)); assertEquals("{\n \"to\": null,\n \"ten\": 10,\n \"JSONObject\": {},\n \"JSONArray\": [],\n \"op\": \"Good\",\n \"keys\": [\n \"to\",\n \"ten\",\n \"JSONObject\",\n \"JSONArray\",\n \"op\",\n \"int\",\n \"true\",\n \"foo\",\n \"zero\",\n \"double\",\n \"String\",\n \"false\",\n \"bool\",\n \"\\\\u2028\",\n \"\\\\u2029\",\n \"null\"\n ],\n \"int\": 57,\n \"true\": true,\n \"foo\": [\n true,\n false,\n 9876543210,\n 0,\n 1.00000001,\n 1.000000000001,\n 1,\n 1.0E-17,\n 2,\n 0.1,\n 2.0E100,\n -32,\n [],\n {},\n \"string\",\n 666,\n 2001.99,\n \"so \\\"fine\\\".\",\n \"so <fine>.\",\n true,\n false,\n [],\n {}\n ],\n \"zero\": -0,\n \"double\": 1.2345678901234568E29,\n \"String\": \"98.6\",\n \"false\": false,\n \"bool\": \"true\",\n \"\\\\u2028\": \"\\u2028\",\n \"\\\\u2029\": \"\\u2029\",\n \"null\": null\n}", jsonobject.toString(4)); assertEquals("<to>null</to><ten>10</ten><JSONObject></JSONObject><op>Good</op><keys>to</keys><keys>ten</keys><keys>JSONObject</keys><keys>JSONArray</keys><keys>op</keys><keys>int</keys><keys>true</keys><keys>foo</keys><keys>zero</keys><keys>double</keys><keys>String</keys><keys>false</keys><keys>bool</keys><keys>\\u2028</keys><keys>\\u2029</keys><keys>null</keys><int>57</int><true>true</true><foo>true</foo><foo>false</foo><foo>9876543210</foo><foo>0.0</foo><foo>1.00000001</foo><foo>1.000000000001</foo><foo>1.0</foo><foo>1.0E-17</foo><foo>2.0</foo><foo>0.1</foo><foo>2.0E100</foo><foo>-32</foo><foo></foo><foo></foo><foo>string</foo><foo>666</foo><foo>2001.99</foo><foo>so &quot;fine&quot;.</foo><foo>so &lt;fine&gt;.</foo><foo>true</foo><foo>false</foo><foo></foo><foo></foo><zero>-0.0</zero><double>1.2345678901234568E29</double><String>98.6</String><false>false</false><bool>true</bool><\\u2028>\u2028</\\u2028><\\u2029>\u2029</\\u2029><null>null</null>", XML.toString(jsonobject)); assertEquals(98.6d, jsonobject.getDouble("String"), eps); assertTrue(jsonobject.getBoolean("bool")); assertEquals("[true,false,9876543210,0,1.00000001,1.000000000001,1,1.0E-17,2,0.1,2.0E100,-32,[],{},\"string\",666,2001.99,\"so \\\"fine\\\".\",\"so <fine>.\",true,false,[],{}]", jsonobject.getJSONArray("foo").toString()); assertEquals("Good", jsonobject.getString("op")); assertEquals(10, jsonobject.getInt("ten")); assertFalse(jsonobject.optBoolean("oops")); string = "<xml one = 1 two=' \"2\" '><five></five>First \u0009&lt;content&gt;<five></five> This is \"content\". <three> 3 </three>JSON does not preserve the sequencing of elements and contents.<three> III </three> <three> T H R E E</three><four/>Content text is an implied structure in XML. <six content=\"6\"/>JSON does not have implied structure:<seven>7</seven>everything is explicit.<![CDATA[CDATA blocks<are><supported>!]]></xml>"; jsonobject = XML.toJSONObject(string); assertEquals("{\"xml\": {\n \"content\": [\n \"First \\t<content>\",\n \"This is \\\"content\\\".\",\n \"JSON does not preserve the sequencing of elements and contents.\",\n \"Content text is an implied structure in XML.\",\n \"JSON does not have implied structure:\",\n \"everything is explicit.\",\n \"CDATA blocks<are><supported>!\"\n ],\n \"two\": \" \\\"2\\\" \",\n \"seven\": 7,\n \"five\": [\n \"\",\n \"\"\n ],\n \"one\": 1,\n \"three\": [\n 3,\n \"III\",\n \"T H R E E\"\n ],\n \"four\": \"\",\n \"six\": {\"content\": 6}\n}}", jsonobject.toString(2)); assertEquals("<xml>First \t&lt;content&gt;\n" + "This is &quot;content&quot;.\n" + "JSON does not preserve the sequencing of elements and contents.\n" + "Content text is an implied structure in XML.\n" + "JSON does not have implied structure:\n" + "everything is explicit.\n" + "CDATA blocks&lt;are&gt;&lt;supported&gt;!<two> &quot;2&quot; </two><seven>7</seven><five/><five/><one>1</one><three>3</three><three>III</three><three>T H R E E</three><four/><six>6</six></xml>", XML.toString(jsonobject)); ja = JSONML.toJSONArray(string); assertEquals("[\n \"xml\",\n {\n \"two\": \" \\\"2\\\" \",\n \"one\": 1\n },\n [\"five\"],\n \"First \\t<content>\",\n [\"five\"],\n \"This is \\\"content\\\".\",\n [\n \"three\",\n 3\n ],\n \"JSON does not preserve the sequencing of elements and contents.\",\n [\n \"three\",\n \"III\"\n ],\n [\n \"three\",\n \"T H R E E\"\n ],\n [\"four\"],\n \"Content text is an implied structure in XML.\",\n [\n \"six\",\n {\"content\": 6}\n ],\n \"JSON does not have implied structure:\",\n [\n \"seven\",\n 7\n ],\n \"everything is explicit.\",\n \"CDATA blocks<are><supported>!\"\n]", ja.toString(4)); assertEquals("<xml two=\" &quot;2&quot; \" one=\"1\"><five/>First \t&lt;content&gt;<five/>This is &quot;content&quot;.<three></three>JSON does not preserve the sequencing of elements and contents.<three>III</three><three>T H R E E</three><four/>Content text is an implied structure in XML.<six content=\"6\"/>JSON does not have implied structure:<seven></seven>everything is explicit.CDATA blocks&lt;are&gt;&lt;supported&gt;!</xml>", JSONML.toString(ja)); string = "<xml do='0'>uno<a re='1' mi='2'>dos<b fa='3'/>tres<c>true</c>quatro</a>cinqo<d>seis<e/></d></xml>"; ja = JSONML.toJSONArray(string); assertEquals("[\n \"xml\",\n {\"do\": 0},\n \"uno\",\n [\n \"a\",\n {\n \"re\": 1,\n \"mi\": 2\n },\n \"dos\",\n [\n \"b\",\n {\"fa\": 3}\n ],\n \"tres\",\n [\n \"c\",\n true\n ],\n \"quatro\"\n ],\n \"cinqo\",\n [\n \"d\",\n \"seis\",\n [\"e\"]\n ]\n]", ja.toString(4)); assertEquals("<xml do=\"0\">uno<a re=\"1\" mi=\"2\">dos<b fa=\"3\"/>tres<c></c>quatro</a>cinqo<d>seis<e/></d></xml>", JSONML.toString(ja)); string = "<mapping><empty/> <class name = \"Customer\"> <field name = \"ID\" type = \"string\"> <bind-xml name=\"ID\" node=\"attribute\"/> </field> <field name = \"FirstName\" type = \"FirstName\"/> <field name = \"MI\" type = \"MI\"/> <field name = \"LastName\" type = \"LastName\"/> </class> <class name = \"FirstName\"> <field name = \"text\"> <bind-xml name = \"text\" node = \"text\"/> </field> </class> <class name = \"MI\"> <field name = \"text\"> <bind-xml name = \"text\" node = \"text\"/> </field> </class> <class name = \"LastName\"> <field name = \"text\"> <bind-xml name = \"text\" node = \"text\"/> </field> </class></mapping>"; jsonobject = XML.toJSONObject(string); assertEquals("{\"mapping\": {\n \"empty\": \"\",\n \"class\": [\n {\n \"field\": [\n {\n \"bind-xml\": {\n \"node\": \"attribute\",\n \"name\": \"ID\"\n },\n \"name\": \"ID\",\n \"type\": \"string\"\n },\n {\n \"name\": \"FirstName\",\n \"type\": \"FirstName\"\n },\n {\n \"name\": \"MI\",\n \"type\": \"MI\"\n },\n {\n \"name\": \"LastName\",\n \"type\": \"LastName\"\n }\n ],\n \"name\": \"Customer\"\n },\n {\n \"field\": {\n \"bind-xml\": {\n \"node\": \"text\",\n \"name\": \"text\"\n },\n \"name\": \"text\"\n },\n \"name\": \"FirstName\"\n },\n {\n \"field\": {\n \"bind-xml\": {\n \"node\": \"text\",\n \"name\": \"text\"\n },\n \"name\": \"text\"\n },\n \"name\": \"MI\"\n },\n {\n \"field\": {\n \"bind-xml\": {\n \"node\": \"text\",\n \"name\": \"text\"\n },\n \"name\": \"text\"\n },\n \"name\": \"LastName\"\n }\n ]\n}}", jsonobject.toString(2)); assertEquals("<mapping><empty/><class><field><bind-xml><node>attribute</node><name>ID</name></bind-xml><name>ID</name><type>string</type></field><field><name>FirstName</name><type>FirstName</type></field><field><name>MI</name><type>MI</type></field><field><name>LastName</name><type>LastName</type></field><name>Customer</name></class><class><field><bind-xml><node>text</node><name>text</name></bind-xml><name>text</name></field><name>FirstName</name></class><class><field><bind-xml><node>text</node><name>text</name></bind-xml><name>text</name></field><name>MI</name></class><class><field><bind-xml><node>text</node><name>text</name></bind-xml><name>text</name></field><name>LastName</name></class></mapping>", XML.toString(jsonobject)); ja = JSONML.toJSONArray(string); assertEquals("[\n \"mapping\",\n [\"empty\"],\n [\n \"class\",\n {\"name\": \"Customer\"},\n [\n \"field\",\n {\n \"name\": \"ID\",\n \"type\": \"string\"\n },\n [\n \"bind-xml\",\n {\n \"node\": \"attribute\",\n \"name\": \"ID\"\n }\n ]\n ],\n [\n \"field\",\n {\n \"name\": \"FirstName\",\n \"type\": \"FirstName\"\n }\n ],\n [\n \"field\",\n {\n \"name\": \"MI\",\n \"type\": \"MI\"\n }\n ],\n [\n \"field\",\n {\n \"name\": \"LastName\",\n \"type\": \"LastName\"\n }\n ]\n ],\n [\n \"class\",\n {\"name\": \"FirstName\"},\n [\n \"field\",\n {\"name\": \"text\"},\n [\n \"bind-xml\",\n {\n \"node\": \"text\",\n \"name\": \"text\"\n }\n ]\n ]\n ],\n [\n \"class\",\n {\"name\": \"MI\"},\n [\n \"field\",\n {\"name\": \"text\"},\n [\n \"bind-xml\",\n {\n \"node\": \"text\",\n \"name\": \"text\"\n }\n ]\n ]\n ],\n [\n \"class\",\n {\"name\": \"LastName\"},\n [\n \"field\",\n {\"name\": \"text\"},\n [\n \"bind-xml\",\n {\n \"node\": \"text\",\n \"name\": \"text\"\n }\n ]\n ]\n ]\n]", ja.toString(4)); assertEquals("<mapping><empty/><class name=\"Customer\"><field name=\"ID\" type=\"string\"><bind-xml node=\"attribute\" name=\"ID\"/></field><field name=\"FirstName\" type=\"FirstName\"/><field name=\"MI\" type=\"MI\"/><field name=\"LastName\" type=\"LastName\"/></class><class name=\"FirstName\"><field name=\"text\"><bind-xml node=\"text\" name=\"text\"/></field></class><class name=\"MI\"><field name=\"text\"><bind-xml node=\"text\" name=\"text\"/></field></class><class name=\"LastName\"><field name=\"text\"><bind-xml node=\"text\" name=\"text\"/></field></class></mapping>", JSONML.toString(ja)); jsonobject = XML.toJSONObject("<?xml version=\"1.0\" ?><Book Author=\"Anonymous\"><Title>Sample Book</Title><Chapter id=\"1\">This is chapter 1. It is not very long or interesting.</Chapter><Chapter id=\"2\">This is chapter 2. Although it is longer than chapter 1, it is not any more interesting.</Chapter></Book>"); assertEquals("{\"Book\": {\n \"Chapter\": [\n {\n \"content\": \"This is chapter 1. It is not very long or interesting.\",\n \"id\": 1\n },\n {\n \"content\": \"This is chapter 2. Although it is longer than chapter 1, it is not any more interesting.\",\n \"id\": 2\n }\n ],\n \"Author\": \"Anonymous\",\n \"Title\": \"Sample Book\"\n}}", jsonobject.toString(2)); assertEquals("<Book><Chapter>This is chapter 1. It is not very long or interesting.<id>1</id></Chapter><Chapter>This is chapter 2. Although it is longer than chapter 1, it is not any more interesting.<id>2</id></Chapter><Author>Anonymous</Author><Title>Sample Book</Title></Book>", XML.toString(jsonobject)); jsonobject = XML.toJSONObject("<!DOCTYPE bCard 'http://www.cs.caltech.edu/~adam/schemas/bCard'><bCard><?xml default bCard firstname = '' lastname = '' company = '' email = '' homepage = ''?><bCard firstname = 'Rohit' lastname = 'Khare' company = 'MCI' email = 'khare@mci.net' homepage = 'http://pest.w3.org/'/><bCard firstname = 'Adam' lastname = 'Rifkin' company = 'Caltech Infospheres Project' email = 'adam@cs.caltech.edu' homepage = 'http://www.cs.caltech.edu/~adam/'/></bCard>"); assertEquals("{\"bCard\": {\"bCard\": [\n {\n \"email\": \"khare@mci.net\",\n \"company\": \"MCI\",\n \"lastname\": \"Khare\",\n \"firstname\": \"Rohit\",\n \"homepage\": \"http://pest.w3.org/\"\n },\n {\n \"email\": \"adam@cs.caltech.edu\",\n \"company\": \"Caltech Infospheres Project\",\n \"lastname\": \"Rifkin\",\n \"firstname\": \"Adam\",\n \"homepage\": \"http://www.cs.caltech.edu/~adam/\"\n }\n]}}", jsonobject.toString(2)); assertEquals("<bCard><bCard><email>khare@mci.net</email><company>MCI</company><lastname>Khare</lastname><firstname>Rohit</firstname><homepage>http://pest.w3.org/</homepage></bCard><bCard><email>adam@cs.caltech.edu</email><company>Caltech Infospheres Project</company><lastname>Rifkin</lastname><firstname>Adam</firstname><homepage>http://www.cs.caltech.edu/~adam/</homepage></bCard></bCard>", XML.toString(jsonobject)); jsonobject = XML.toJSONObject("<?xml version=\"1.0\"?><customer> <firstName> <text>Fred</text> </firstName> <ID>fbs0001</ID> <lastName> <text>Scerbo</text> </lastName> <MI> <text>B</text> </MI></customer>"); assertEquals("{\"customer\": {\n \"lastName\": {\"text\": \"Scerbo\"},\n \"MI\": {\"text\": \"B\"},\n \"ID\": \"fbs0001\",\n \"firstName\": {\"text\": \"Fred\"}\n}}", jsonobject.toString(2)); assertEquals("<customer><lastName><text>Scerbo</text></lastName><MI><text>B</text></MI><ID>fbs0001</ID><firstName><text>Fred</text></firstName></customer>", XML.toString(jsonobject)); jsonobject = XML.toJSONObject("<!ENTITY tp-address PUBLIC '-//ABC University::Special Collections Library//TEXT (titlepage: name and address)//EN' 'tpspcoll.sgm'><list type='simple'><head>Repository Address </head><item>Special Collections Library</item><item>ABC University</item><item>Main Library, 40 Circle Drive</item><item>Ourtown, Pennsylvania</item><item>17654 USA</item></list>"); assertEquals("{\"list\":{\"item\":[\"Special Collections Library\",\"ABC University\",\"Main Library, 40 Circle Drive\",\"Ourtown, Pennsylvania\",\"17654 USA\"],\"head\":\"Repository Address\",\"type\":\"simple\"}}", jsonobject.toString()); assertEquals("<list><item>Special Collections Library</item><item>ABC University</item><item>Main Library, 40 Circle Drive</item><item>Ourtown, Pennsylvania</item><item>17654 USA</item><head>Repository Address</head><type>simple</type></list>", XML.toString(jsonobject)); jsonobject = XML.toJSONObject("<test intertag zero=0 status=ok><empty/>deluxe<blip sweet=true>&amp;&quot;toot&quot;&toot;&#x41;</blip><x>eks</x><w>bonus</w><w>bonus2</w></test>"); assertEquals("{\"test\": {\n \"w\": [\n \"bonus\",\n \"bonus2\"\n ],\n \"content\": \"deluxe\",\n \"intertag\": \"\",\n \"status\": \"ok\",\n \"blip\": {\n \"content\": \"&\\\"toot\\\"&toot;&#x41;\",\n \"sweet\": true\n },\n \"empty\": \"\",\n \"zero\": 0,\n \"x\": \"eks\"\n}}", jsonobject.toString(2)); assertEquals("<test><w>bonus</w><w>bonus2</w>deluxe<intertag/><status>ok</status><blip>&amp;&quot;toot&quot;&amp;toot;&amp;#x41;<sweet>true</sweet></blip><empty/><zero>0</zero><x>eks</x></test>", XML.toString(jsonobject)); jsonobject = HTTP.toJSONObject("GET / HTTP/1.0\nAccept: image/gif, image/x-xbitmap, image/jpeg, image/pjpeg, application/vnd.ms-powerpoint, application/vnd.ms-excel, application/msword, */*\nAccept-Language: en-us\nUser-Agent: Mozilla/4.0 (compatible; MSIE 5.5; Windows 98; Win 9x 4.90; T312461; Q312461)\nHost: www.nokko.com\nConnection: keep-alive\nAccept-encoding: gzip, deflate\n"); assertEquals("{\n \"Accept-Language\": \"en-us\",\n \"Request-URI\": \"/\",\n \"Host\": \"www.nokko.com\",\n \"Method\": \"GET\",\n \"Accept-encoding\": \"gzip, deflate\",\n \"User-Agent\": \"Mozilla/4.0 (compatible; MSIE 5.5; Windows 98; Win 9x 4.90; T312461; Q312461)\",\n \"HTTP-Version\": \"HTTP/1.0\",\n \"Connection\": \"keep-alive\",\n \"Accept\": \"image/gif, image/x-xbitmap, image/jpeg, image/pjpeg, application/vnd.ms-powerpoint, application/vnd.ms-excel, application/msword, */*\"\n}", jsonobject.toString(2)); assertEquals("GET \"/\" HTTP/1.0\r\n" + "Accept-Language: en-us\r\n" + "Host: www.nokko.com\r\n" + "Accept-encoding: gzip, deflate\r\n" + "User-Agent: Mozilla/4.0 (compatible; MSIE 5.5; Windows 98; Win 9x 4.90; T312461; Q312461)\r\n" + "Connection: keep-alive\r\n" + "Accept: image/gif, image/x-xbitmap, image/jpeg, image/pjpeg, application/vnd.ms-powerpoint, application/vnd.ms-excel, application/msword, */*\r\n\r\n", HTTP.toString(jsonobject)); jsonobject = HTTP.toJSONObject("HTTP/1.1 200 Oki Doki\nDate: Sun, 26 May 2002 17:38:52 GMT\nServer: Apache/1.3.23 (Unix) mod_perl/1.26\nKeep-Alive: timeout=15, max=100\nConnection: Keep-Alive\nTransfer-Encoding: chunked\nContent-Type: text/html\n"); assertEquals("{\n \"Reason-Phrase\": \"Oki Doki\",\n \"Status-Code\": \"200\",\n \"Transfer-Encoding\": \"chunked\",\n \"Date\": \"Sun, 26 May 2002 17:38:52 GMT\",\n \"Keep-Alive\": \"timeout=15, max=100\",\n \"HTTP-Version\": \"HTTP/1.1\",\n \"Content-Type\": \"text/html\",\n \"Connection\": \"Keep-Alive\",\n \"Server\": \"Apache/1.3.23 (Unix) mod_perl/1.26\"\n}", jsonobject.toString(2)); assertEquals("HTTP/1.1 200 Oki Doki\r\n" + "Transfer-Encoding: chunked\r\n" + "Date: Sun, 26 May 2002 17:38:52 GMT\r\n" + "Keep-Alive: timeout=15, max=100\r\n" + "Content-Type: text/html\r\n" + "Connection: Keep-Alive\r\n" + "Server: Apache/1.3.23 (Unix) mod_perl/1.26\r\n\r\n", HTTP.toString(jsonobject)); jsonobject = new JSONObject("{nix: null, nux: false, null: 'null', 'Request-URI': '/', Method: 'GET', 'HTTP-Version': 'HTTP/1.0'}"); assertEquals("{\n \"Request-URI\": \"/\",\n \"nix\": null,\n \"nux\": false,\n \"Method\": \"GET\",\n \"HTTP-Version\": \"HTTP/1.0\",\n \"null\": \"null\"\n}", jsonobject.toString(2)); assertTrue(jsonobject.isNull("nix")); assertTrue(jsonobject.has("nix")); assertEquals("<Request-URI>/</Request-URI><nix>null</nix><nux>false</nux><Method>GET</Method><HTTP-Version>HTTP/1.0</HTTP-Version><null>null</null>", XML.toString(jsonobject)); jsonobject = XML.toJSONObject("<?xml version='1.0' encoding='UTF-8'?>" + "\n\n" + "<SOAP-ENV:Envelope" + " xmlns:SOAP-ENV=\"http://schemas.xmlsoap.org/soap/envelope/\"" + " xmlns:xsi=\"http://www.w3.org/1999/XMLSchema-instance\"" + " xmlns:xsd=\"http://www.w3.org/1999/XMLSchema\">" + "<SOAP-ENV:Body><ns1:doGoogleSearch" + " xmlns:ns1=\"urn:GoogleSearch\"" + " SOAP-ENV:encodingStyle=\"http://schemas.xmlsoap.org/soap/encoding/\">" + "<key xsi:type=\"xsd:string\">GOOGLEKEY</key> <q" + " xsi:type=\"xsd:string\">'+search+'</q> <start" + " xsi:type=\"xsd:int\">0</start> <maxResults" + " xsi:type=\"xsd:int\">10</maxResults> <filter" + " xsi:type=\"xsd:boolean\">true</filter> <restrict" + " xsi:type=\"xsd:string\"></restrict> <safeSearch" + " xsi:type=\"xsd:boolean\">false</safeSearch> <lr" + " xsi:type=\"xsd:string\"></lr> <ie" + " xsi:type=\"xsd:string\">latin1</ie> <oe" + " xsi:type=\"xsd:string\">latin1</oe>" + "</ns1:doGoogleSearch>" + "</SOAP-ENV:Body></SOAP-ENV:Envelope>"); assertEquals("{\"SOAP-ENV:Envelope\": {\n \"SOAP-ENV:Body\": {\"ns1:doGoogleSearch\": {\n \"oe\": {\n \"content\": \"latin1\",\n \"xsi:type\": \"xsd:string\"\n },\n \"SOAP-ENV:encodingStyle\": \"http://schemas.xmlsoap.org/soap/encoding/\",\n \"lr\": {\"xsi:type\": \"xsd:string\"},\n \"start\": {\n \"content\": 0,\n \"xsi:type\": \"xsd:int\"\n },\n \"q\": {\n \"content\": \"'+search+'\",\n \"xsi:type\": \"xsd:string\"\n },\n \"ie\": {\n \"content\": \"latin1\",\n \"xsi:type\": \"xsd:string\"\n },\n \"safeSearch\": {\n \"content\": false,\n \"xsi:type\": \"xsd:boolean\"\n },\n \"xmlns:ns1\": \"urn:GoogleSearch\",\n \"restrict\": {\"xsi:type\": \"xsd:string\"},\n \"filter\": {\n \"content\": true,\n \"xsi:type\": \"xsd:boolean\"\n },\n \"maxResults\": {\n \"content\": 10,\n \"xsi:type\": \"xsd:int\"\n },\n \"key\": {\n \"content\": \"GOOGLEKEY\",\n \"xsi:type\": \"xsd:string\"\n }\n }},\n \"xmlns:xsd\": \"http://www.w3.org/1999/XMLSchema\",\n \"xmlns:xsi\": \"http://www.w3.org/1999/XMLSchema-instance\",\n \"xmlns:SOAP-ENV\": \"http://schemas.xmlsoap.org/soap/envelope/\"\n}}", jsonobject.toString(2)); assertEquals("<SOAP-ENV:Envelope><SOAP-ENV:Body><ns1:doGoogleSearch><oe>latin1<xsi:type>xsd:string</xsi:type></oe><SOAP-ENV:encodingStyle>http://schemas.xmlsoap.org/soap/encoding/</SOAP-ENV:encodingStyle><lr><xsi:type>xsd:string</xsi:type></lr><start>0<xsi:type>xsd:int</xsi:type></start><q>&apos;+search+&apos;<xsi:type>xsd:string</xsi:type></q><ie>latin1<xsi:type>xsd:string</xsi:type></ie><safeSearch>false<xsi:type>xsd:boolean</xsi:type></safeSearch><xmlns:ns1>urn:GoogleSearch</xmlns:ns1><restrict><xsi:type>xsd:string</xsi:type></restrict><filter>true<xsi:type>xsd:boolean</xsi:type></filter><maxResults>10<xsi:type>xsd:int</xsi:type></maxResults><key>GOOGLEKEY<xsi:type>xsd:string</xsi:type></key></ns1:doGoogleSearch></SOAP-ENV:Body><xmlns:xsd>http://www.w3.org/1999/XMLSchema</xmlns:xsd><xmlns:xsi>http://www.w3.org/1999/XMLSchema-instance</xmlns:xsi><xmlns:SOAP-ENV>http://schemas.xmlsoap.org/soap/envelope/</xmlns:SOAP-ENV></SOAP-ENV:Envelope>", XML.toString(jsonobject)); jsonobject = new JSONObject("{Envelope: {Body: {\"ns1:doGoogleSearch\": {oe: \"latin1\", filter: true, q: \"'+search+'\", key: \"GOOGLEKEY\", maxResults: 10, \"SOAP-ENV:encodingStyle\": \"http://schemas.xmlsoap.org/soap/encoding/\", start: 0, ie: \"latin1\", safeSearch:false, \"xmlns:ns1\": \"urn:GoogleSearch\"}}}}"); assertEquals("{\"Envelope\": {\"Body\": {\"ns1:doGoogleSearch\": {\n \"oe\": \"latin1\",\n \"SOAP-ENV:encodingStyle\": \"http://schemas.xmlsoap.org/soap/encoding/\",\n \"start\": 0,\n \"q\": \"'+search+'\",\n \"ie\": \"latin1\",\n \"safeSearch\": false,\n \"xmlns:ns1\": \"urn:GoogleSearch\",\n \"maxResults\": 10,\n \"key\": \"GOOGLEKEY\",\n \"filter\": true\n}}}}", jsonobject.toString(2)); assertEquals("<Envelope><Body><ns1:doGoogleSearch><oe>latin1</oe><SOAP-ENV:encodingStyle>http://schemas.xmlsoap.org/soap/encoding/</SOAP-ENV:encodingStyle><start>0</start><q>&apos;+search+&apos;</q><ie>latin1</ie><safeSearch>false</safeSearch><xmlns:ns1>urn:GoogleSearch</xmlns:ns1><maxResults>10</maxResults><key>GOOGLEKEY</key><filter>true</filter></ns1:doGoogleSearch></Body></Envelope>", XML.toString(jsonobject)); jsonobject = CookieList.toJSONObject(" f%oo = b+l=ah ; o;n%40e = t.wo "); assertEquals("{\n \"o;n@e\": \"t.wo\",\n \"f%oo\": \"b l=ah\"\n}", jsonobject.toString(2)); assertEquals("o%3bn@e=t.wo;f%25oo=b l%3dah", CookieList.toString(jsonobject)); jsonobject = Cookie.toJSONObject("f%oo=blah; secure ;expires = April 24, 2002"); assertEquals("{\n" + " \"expires\": \"April 24, 2002\",\n" + " \"name\": \"f%oo\",\n" + " \"secure\": true,\n" + " \"value\": \"blah\"\n" + "}", jsonobject.toString(2)); assertEquals("f%25oo=blah;expires=April 24, 2002;secure", Cookie.toString(jsonobject)); jsonobject = new JSONObject("{script: 'It is not allowed in HTML to send a close script tag in a string<script>because it confuses browsers</script>so we insert a backslash before the /'}"); assertEquals("{\"script\":\"It is not allowed in HTML to send a close script tag in a string<script>because it confuses browsers<\\/script>so we insert a backslash before the /\"}", jsonobject.toString()); JSONTokener jsontokener = new JSONTokener("{op:'test', to:'session', pre:1}{op:'test', to:'session', pre:2}"); jsonobject = new JSONObject(jsontokener); assertEquals("{\"to\":\"session\",\"op\":\"test\",\"pre\":1}", jsonobject.toString()); assertEquals(1, jsonobject.optInt("pre")); int i = jsontokener.skipTo('{'); assertEquals(123, i); jsonobject = new JSONObject(jsontokener); assertEquals("{\"to\":\"session\",\"op\":\"test\",\"pre\":2}", jsonobject.toString()); jsonarray = CDL.toJSONArray("Comma delimited list test, '\"Strip\"Quotes', 'quote, comma', No quotes, 'Single Quotes', \"Double Quotes\"\n1,'2',\"3\"\n,'It is \"good,\"', \"It works.\"\n\n"); string = CDL.toString(jsonarray); assertEquals("\"quote, comma\",\"StripQuotes\",Comma delimited list test\n" + "3,2,1\n" + "It works.,\"It is good,\",\n", string); assertEquals("[\n {\n \"quote, comma\": \"3\",\n \"\\\"Strip\\\"Quotes\": \"2\",\n \"Comma delimited list test\": \"1\"\n },\n {\n \"quote, comma\": \"It works.\",\n \"\\\"Strip\\\"Quotes\": \"It is \\\"good,\\\"\",\n \"Comma delimited list test\": \"\"\n }\n]", jsonarray.toString(1)); jsonarray = CDL.toJSONArray(string); assertEquals("[\n {\n \"quote, comma\": \"3\",\n \"StripQuotes\": \"2\",\n \"Comma delimited list test\": \"1\"\n },\n {\n \"quote, comma\": \"It works.\",\n \"StripQuotes\": \"It is good,\",\n \"Comma delimited list test\": \"\"\n }\n]", jsonarray.toString(1)); jsonarray = new JSONArray(" [\"<escape>\", next is an implied null , , ok,] "); assertEquals("[\"<escape>\",\"next is an implied null\",null,\"ok\"]", jsonarray.toString()); assertEquals("<array>&lt;escape&gt;</array><array>next is an implied null</array><array>null</array><array>ok</array>", XML.toString(jsonarray)); jsonobject = new JSONObject("{ fun => with non-standard forms ; forgiving => This package can be used to parse formats that are similar to but not stricting conforming to JSON; why=To make it easier to migrate existing data to JSON,one = [[1.00]]; uno=[[{1=>1}]];'+':+6e66 ;pluses=+++;empty = '' , 'double':0.666,true: TRUE, false: FALSE, null=NULL;[true] = [[!,@;*]]; string=> o. k. ; \r oct=0666; hex=0x666; dec=666; o=0999; noh=0x0x}"); assertEquals("{\n \"noh\": \"0x0x\",\n \"one\": [[1]],\n \"o\": 999,\n \"+\": 6.0E66,\n \"true\": true,\n \"forgiving\": \"This package can be used to parse formats that are similar to but not stricting conforming to JSON\",\n \"fun\": \"with non-standard forms\",\n \"double\": 0.666,\n \"uno\": [[{\"1\": 1}]],\n \"dec\": 666,\n \"oct\": 666,\n \"hex\": \"0x666\",\n \"string\": \"o. k.\",\n \"empty\": \"\",\n \"false\": false,\n \"[true]\": [[\n \"!\",\n \"@\",\n \"*\"\n ]],\n \"pluses\": \"+++\",\n \"why\": \"To make it easier to migrate existing data to JSON\",\n \"null\": null\n}", jsonobject.toString(1)); assertTrue(jsonobject.getBoolean("true")); assertFalse(jsonobject.getBoolean("false")); jsonobject = new JSONObject(jsonobject, new String[]{"dec", "oct", "hex", "missing"}); assertEquals("{\n \"oct\": 666,\n \"dec\": 666,\n \"hex\": \"0x666\"\n}", jsonobject.toString(1)); assertEquals("[[\"<escape>\",\"next is an implied null\",null,\"ok\"],{\"oct\":666,\"dec\":666,\"hex\":\"0x666\"}]", new JSONStringer().array().value(jsonarray).value(jsonobject).endArray().toString()); jsonobject = new JSONObject("{string: \"98.6\", long: 2147483648, int: 2147483647, longer: 9223372036854775807, double: 9223372036854775808}"); assertEquals("{\n \"int\": 2147483647,\n \"string\": \"98.6\",\n \"longer\": 9223372036854775807,\n \"double\": \"9223372036854775808\",\n \"long\": 2147483648\n}", jsonobject.toString(1)); // getInt assertEquals(2147483647, jsonobject.getInt("int")); assertEquals(-2147483648, jsonobject.getInt("long")); assertEquals(-1, jsonobject.getInt("longer")); try { jsonobject.getInt("double"); fail("should fail with - JSONObject[\"double\"] is not an int."); } catch (JSONException expected) { } try { jsonobject.getInt("string"); fail("should fail with - JSONObject[\"string\"] is not an int."); } catch (JSONException expected) { } // getLong assertEquals(2147483647, jsonobject.getLong("int")); assertEquals(2147483648l, jsonobject.getLong("long")); assertEquals(9223372036854775807l, jsonobject.getLong("longer")); try { jsonobject.getLong("double"); fail("should fail with - JSONObject[\"double\"] is not a long."); } catch (JSONException expected) { } try { jsonobject.getLong("string"); fail("should fail with - JSONObject[\"string\"] is not a long."); } catch (JSONException expected) { } // getDouble assertEquals(2.147483647E9, jsonobject.getDouble("int"), eps); assertEquals(2.147483648E9, jsonobject.getDouble("long"), eps); assertEquals(9.223372036854776E18, jsonobject.getDouble("longer"), eps); assertEquals(9223372036854775808d, jsonobject.getDouble("double"), eps); assertEquals(98.6, jsonobject.getDouble("string"), eps); jsonobject.put("good sized", 9223372036854775807L); assertEquals("{\n \"int\": 2147483647,\n \"string\": \"98.6\",\n \"longer\": 9223372036854775807,\n \"good sized\": 9223372036854775807,\n \"double\": \"9223372036854775808\",\n \"long\": 2147483648\n}", jsonobject.toString(1)); jsonarray = new JSONArray("[2147483647, 2147483648, 9223372036854775807, 9223372036854775808]"); assertEquals("[\n 2147483647,\n 2147483648,\n 9223372036854775807,\n \"9223372036854775808\"\n]", jsonarray.toString(1)); List expectedKeys = new ArrayList(6); expectedKeys.add("int"); expectedKeys.add("string"); expectedKeys.add("longer"); expectedKeys.add("good sized"); expectedKeys.add("double"); expectedKeys.add("long"); iterator = jsonobject.keys(); while (iterator.hasNext()) { string = (String) iterator.next(); assertTrue(expectedKeys.remove(string)); } assertEquals(0, expectedKeys.size()); // accumulate jsonobject = new JSONObject(); jsonobject.accumulate("stooge", "Curly"); jsonobject.accumulate("stooge", "Larry"); jsonobject.accumulate("stooge", "Moe"); jsonarray = jsonobject.getJSONArray("stooge"); jsonarray.put(5, "Shemp"); assertEquals("{\"stooge\": [\n" + " \"Curly\",\n" + " \"Larry\",\n" + " \"Moe\",\n" + " null,\n" + " null,\n" + " \"Shemp\"\n" + "]}", jsonobject.toString(4)); // write assertEquals("{\"stooge\":[\"Curly\",\"Larry\",\"Moe\",null,null,\"Shemp\"]}", jsonobject.write(new StringWriter()).toString()); string = "<xml empty><a></a><a>1</a><a>22</a><a>333</a></xml>"; jsonobject = XML.toJSONObject(string); assertEquals("{\"xml\": {\n" + " \"a\": [\n" + " \"\",\n" + " 1,\n" + " 22,\n" + " 333\n" + " ],\n" + " \"empty\": \"\"\n" + "}}", jsonobject.toString(4)); assertEquals("<xml><a/><a>1</a><a>22</a><a>333</a><empty/></xml>", XML.toString(jsonobject)); string = "<book><chapter>Content of the first chapter</chapter><chapter>Content of the second chapter <chapter>Content of the first subchapter</chapter> <chapter>Content of the second subchapter</chapter></chapter><chapter>Third Chapter</chapter></book>"; jsonobject = XML.toJSONObject(string); assertEquals("{\"book\": {\"chapter\": [\n \"Content of the first chapter\",\n {\n \"content\": \"Content of the second chapter\",\n \"chapter\": [\n \"Content of the first subchapter\",\n \"Content of the second subchapter\"\n ]\n },\n \"Third Chapter\"\n]}}", jsonobject.toString(1)); assertEquals("<book><chapter>Content of the first chapter</chapter><chapter>Content of the second chapter<chapter>Content of the first subchapter</chapter><chapter>Content of the second subchapter</chapter></chapter><chapter>Third Chapter</chapter></book>", XML.toString(jsonobject)); jsonarray = JSONML.toJSONArray(string); assertEquals("[\n" + " \"book\",\n" + " [\n" + " \"chapter\",\n" + " \"Content of the first chapter\"\n" + " ],\n" + " [\n" + " \"chapter\",\n" + " \"Content of the second chapter\",\n" + " [\n" + " \"chapter\",\n" + " \"Content of the first subchapter\"\n" + " ],\n" + " [\n" + " \"chapter\",\n" + " \"Content of the second subchapter\"\n" + " ]\n" + " ],\n" + " [\n" + " \"chapter\",\n" + " \"Third Chapter\"\n" + " ]\n" + "]", jsonarray.toString(4)); assertEquals("<book><chapter>Content of the first chapter</chapter><chapter>Content of the second chapter<chapter>Content of the first subchapter</chapter><chapter>Content of the second subchapter</chapter></chapter><chapter>Third Chapter</chapter></book>", JSONML.toString(jsonarray)); Collection collection = null; Map map = null; jsonobject = new JSONObject(map); jsonarray = new JSONArray(collection); jsonobject.append("stooge", "Joe DeRita"); jsonobject.append("stooge", "Shemp"); jsonobject.accumulate("stooges", "Curly"); jsonobject.accumulate("stooges", "Larry"); jsonobject.accumulate("stooges", "Moe"); jsonobject.accumulate("stoogearray", jsonobject.get("stooges")); jsonobject.put("map", map); jsonobject.put("collection", collection); jsonobject.put("array", jsonarray); jsonarray.put(map); jsonarray.put(collection); assertEquals("{\"stooge\":[\"Joe DeRita\",\"Shemp\"],\"map\":{},\"stooges\":[\"Curly\",\"Larry\",\"Moe\"],\"collection\":[],\"stoogearray\":[[\"Curly\",\"Larry\",\"Moe\"]],\"array\":[{},[]]}", jsonobject.toString()); string = "{plist=Apple; AnimalSmells = { pig = piggish; lamb = lambish; worm = wormy; }; AnimalSounds = { pig = oink; lamb = baa; worm = baa; Lisa = \"Why is the worm talking like a lamb?\" } ; AnimalColors = { pig = pink; lamb = black; worm = pink; } } "; jsonobject = new JSONObject(string); assertEquals("{\"AnimalColors\":{\"worm\":\"pink\",\"lamb\":\"black\",\"pig\":\"pink\"},\"plist\":\"Apple\",\"AnimalSounds\":{\"worm\":\"baa\",\"Lisa\":\"Why is the worm talking like a lamb?\",\"lamb\":\"baa\",\"pig\":\"oink\"},\"AnimalSmells\":{\"worm\":\"wormy\",\"lamb\":\"lambish\",\"pig\":\"piggish\"}}", jsonobject.toString()); string = " [\"San Francisco\", \"New York\", \"Seoul\", \"London\", \"Seattle\", \"Shanghai\"]"; jsonarray = new JSONArray(string); assertEquals("[\"San Francisco\",\"New York\",\"Seoul\",\"London\",\"Seattle\",\"Shanghai\"]", jsonarray.toString()); string = "<a ichi='1' ni='2'><b>The content of b</b> and <c san='3'>The content of c</c><d>do</d><e></e><d>re</d><f/><d>mi</d></a>"; jsonobject = XML.toJSONObject(string); assertEquals("{\"a\":{\"f\":\"\",\"content\":\"and\",\"d\":[\"do\",\"re\",\"mi\"],\"ichi\":1,\"e\":\"\",\"b\":\"The content of b\",\"c\":{\"content\":\"The content of c\",\"san\":3},\"ni\":2}}", jsonobject.toString()); assertEquals("<a><f/>and<d>do</d><d>re</d><d>mi</d><ichi>1</ichi><e/><b>The content of b</b><c>The content of c<san>3</san></c><ni>2</ni></a>", XML.toString(jsonobject)); ja = JSONML.toJSONArray(string); assertEquals("[\n" + " \"a\",\n" + " {\n" + " \"ichi\": 1,\n" + " \"ni\": 2\n" + " },\n" + " [\n" + " \"b\",\n" + " \"The content of b\"\n" + " ],\n" + " \"and\",\n" + " [\n" + " \"c\",\n" + " {\"san\": 3},\n" + " \"The content of c\"\n" + " ],\n" + " [\n" + " \"d\",\n" + " \"do\"\n" + " ],\n" + " [\"e\"],\n" + " [\n" + " \"d\",\n" + " \"re\"\n" + " ],\n" + " [\"f\"],\n" + " [\n" + " \"d\",\n" + " \"mi\"\n" + " ]\n" + "]", ja.toString(4)); assertEquals("<a ichi=\"1\" ni=\"2\"><b>The content of b</b>and<c san=\"3\">The content of c</c><d>do</d><e/><d>re</d><f/><d>mi</d></a>", JSONML.toString(ja)); string = "<Root><MsgType type=\"node\"><BatchType type=\"string\">111111111111111</BatchType></MsgType></Root>"; jsonobject = JSONML.toJSONObject(string); assertEquals("{\"tagName\":\"Root\",\"childNodes\":[{\"tagName\":\"MsgType\",\"childNodes\":[{\"tagName\":\"BatchType\",\"childNodes\":[111111111111111],\"type\":\"string\"}],\"type\":\"node\"}]}", jsonobject.toString()); ja = JSONML.toJSONArray(string); assertEquals("[\"Root\",[\"MsgType\",{\"type\":\"node\"},[\"BatchType\",{\"type\":\"string\"},111111111111111]]]", ja.toString()); } public void testExceptions() throws Exception { JSONArray jsonarray = null; JSONObject jsonobject; String string; try { jsonarray = new JSONArray("[\n\r\n\r}"); System.out.println(jsonarray.toString()); fail("expecting JSONException here."); } catch (JSONException jsone) { assertEquals("Missing value at 5 [character 0 line 4]", jsone.getMessage()); } try { jsonarray = new JSONArray("<\n\r\n\r "); System.out.println(jsonarray.toString()); fail("expecting JSONException here."); } catch (JSONException jsone) { assertEquals("A JSONArray text must start with '[' at 1 [character 2 line 1]", jsone.getMessage()); } try { jsonarray = new JSONArray(); jsonarray.put(Double.NEGATIVE_INFINITY); jsonarray.put(Double.NaN); System.out.println(jsonarray.toString()); fail("expecting JSONException here."); } catch (JSONException jsone) { assertEquals("JSON does not allow non-finite numbers.", jsone.getMessage()); } jsonobject = new JSONObject(); try { System.out.println(jsonobject.getDouble("stooge")); fail("expecting JSONException here."); } catch (JSONException jsone) { assertEquals("JSONObject[\"stooge\"] not found.", jsone.getMessage()); } try { System.out.println(jsonobject.getDouble("howard")); fail("expecting JSONException here."); } catch (JSONException jsone) { assertEquals("JSONObject[\"howard\"] not found.", jsone.getMessage()); } try { System.out.println(jsonobject.put(null, "howard")); fail("expecting JSONException here."); } catch (JSONException jsone) { assertEquals("Null key.", jsone.getMessage()); } try { System.out.println(jsonarray.getDouble(0)); fail("expecting JSONException here."); } catch (JSONException jsone) { assertEquals("JSONArray[0] not found.", jsone.getMessage()); } try { System.out.println(jsonarray.get(-1)); fail("expecting JSONException here."); } catch (JSONException jsone) { assertEquals("JSONArray[-1] not found.", jsone.getMessage()); } try { System.out.println(jsonarray.put(Double.NaN)); fail("expecting JSONException here."); } catch (JSONException jsone) { assertEquals("JSON does not allow non-finite numbers.", jsone.getMessage()); } try { jsonobject = XML.toJSONObject("<a><b> "); fail("expecting JSONException here."); } catch (JSONException jsone) { assertEquals("Unclosed tag b at 11 [character 12 line 1]", jsone.getMessage()); } try { jsonobject = XML.toJSONObject("<a></b> "); fail("expecting JSONException here."); } catch (JSONException jsone) { assertEquals("Mismatched a and b at 6 [character 7 line 1]", jsone.getMessage()); } try { jsonobject = XML.toJSONObject("<a></a "); fail("expecting JSONException here."); } catch (JSONException jsone) { assertEquals("Misshaped element at 11 [character 12 line 1]", jsone.getMessage()); } try { jsonarray = new JSONArray(new Object()); System.out.println(jsonarray.toString()); fail("expecting JSONException here."); } catch (JSONException jsone) { assertEquals("JSONArray initial value should be a string or collection or array.", jsone.getMessage()); } try { string = "[)"; jsonarray = new JSONArray(string); System.out.println(jsonarray.toString()); fail("expecting JSONException here."); } catch (JSONException jsone) { assertEquals("Expected a ',' or ']' at 3 [character 4 line 1]", jsone.getMessage()); } try { string = "<xml"; jsonarray = JSONML.toJSONArray(string); System.out.println(jsonarray.toString(4)); fail("expecting JSONException here."); } catch (JSONException jsone) { assertEquals("Misshaped element at 6 [character 7 line 1]", jsone.getMessage()); } try { string = "<right></wrong>"; jsonarray = JSONML.toJSONArray(string); System.out.println(jsonarray.toString(4)); fail("expecting JSONException here."); } catch (JSONException jsone) { assertEquals("Mismatched 'right' and 'wrong' at 15 [character 16 line 1]", jsone.getMessage()); } try { string = "This ain't XML."; jsonarray = JSONML.toJSONArray(string); System.out.println(jsonarray.toString(4)); fail("expecting JSONException here."); } catch (JSONException jsone) { assertEquals("Bad XML at 17 [character 18 line 1]", jsone.getMessage()); } try { string = "{\"koda\": true, \"koda\": true}"; jsonobject = new JSONObject(string); System.out.println(jsonobject.toString(4)); fail("expecting JSONException here."); } catch (JSONException jsone) { assertEquals("Duplicate key \"koda\"", jsone.getMessage()); } try { JSONStringer jj = new JSONStringer(); string = jj .object() .key("bosanda") .value("MARIE HAA'S") .key("bosanda") .value("MARIE HAA\\'S") .endObject() .toString(); System.out.println(jsonobject.toString(4)); fail("expecting JSONException here."); } catch (JSONException jsone) { assertEquals("Duplicate key \"bosanda\"", jsone.getMessage()); } } /** * Beany is a typical class that implements JSONString. It also * provides some beany methods that can be used to * construct a JSONObject. It also demonstrates constructing * a JSONObject with an array of names. */ class Beany implements JSONString { public String aString; public double aNumber; public boolean aBoolean; public Beany(String string, double d, boolean b) { this.aString = string; this.aNumber = d; this.aBoolean = b; } public double getNumber() { return this.aNumber; } public String getString() { return this.aString; } public boolean isBoolean() { return this.aBoolean; } public String getBENT() { return "All uppercase key"; } public String getX() { return "x"; } public String toJSONString() { return "{" + JSONObject.quote(this.aString) + ":" + JSONObject.doubleToString(this.aNumber) + "}"; } public String toString() { return this.getString() + " " + this.getNumber() + " " + this.isBoolean() + "." + this.getBENT() + " " + this.getX(); } } }
12085952-sageandroid
commandline/src/org/json/Test.java
Java
gpl3
71,256
package org.json; import java.io.IOException; import java.io.Writer; /* Copyright (c) 2006 JSON.org 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 shall be used for Good, not Evil. 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. */ /** * JSONWriter provides a quick and convenient way of producing JSON text. * The texts produced strictly conform to JSON syntax rules. No whitespace is * added, so the results are ready for transmission or storage. Each instance of * JSONWriter can produce one JSON text. * <p> * A JSONWriter instance provides a <code>value</code> method for appending * values to the * text, and a <code>key</code> * method for adding keys before values in objects. There are <code>array</code> * and <code>endArray</code> methods that make and bound array values, and * <code>object</code> and <code>endObject</code> methods which make and bound * object values. All of these methods return the JSONWriter instance, * permitting a cascade style. For example, <pre> * new JSONWriter(myWriter) * .object() * .key("JSON") * .value("Hello, World!") * .endObject();</pre> which writes <pre> * {"JSON":"Hello, World!"}</pre> * <p> * The first method called must be <code>array</code> or <code>object</code>. * There are no methods for adding commas or colons. JSONWriter adds them for * you. Objects and arrays can be nested up to 20 levels deep. * <p> * This can sometimes be easier than using a JSONObject to build a string. * @author JSON.org * @version 2011-11-24 */ public class JSONWriter { private static final int maxdepth = 200; /** * The comma flag determines if a comma should be output before the next * value. */ private boolean comma; /** * The current mode. Values: * 'a' (array), * 'd' (done), * 'i' (initial), * 'k' (key), * 'o' (object). */ protected char mode; /** * The object/array stack. */ private final JSONObject stack[]; /** * The stack top index. A value of 0 indicates that the stack is empty. */ private int top; /** * The writer that will receive the output. */ protected Writer writer; /** * Make a fresh JSONWriter. It can be used to build one JSON text. */ public JSONWriter(Writer w) { this.comma = false; this.mode = 'i'; this.stack = new JSONObject[maxdepth]; this.top = 0; this.writer = w; } /** * Append a value. * @param string A string value. * @return this * @throws JSONException If the value is out of sequence. */ private JSONWriter append(String string) throws JSONException { if (string == null) { throw new JSONException("Null pointer"); } if (this.mode == 'o' || this.mode == 'a') { try { if (this.comma && this.mode == 'a') { this.writer.write(','); } this.writer.write(string); } catch (IOException e) { throw new JSONException(e); } if (this.mode == 'o') { this.mode = 'k'; } this.comma = true; return this; } throw new JSONException("Value out of sequence."); } /** * Begin appending a new array. All values until the balancing * <code>endArray</code> will be appended to this array. The * <code>endArray</code> method must be called to mark the array's end. * @return this * @throws JSONException If the nesting is too deep, or if the object is * started in the wrong place (for example as a key or after the end of the * outermost array or object). */ public JSONWriter array() throws JSONException { if (this.mode == 'i' || this.mode == 'o' || this.mode == 'a') { this.push(null); this.append("["); this.comma = false; return this; } throw new JSONException("Misplaced array."); } /** * End something. * @param mode Mode * @param c Closing character * @return this * @throws JSONException If unbalanced. */ private JSONWriter end(char mode, char c) throws JSONException { if (this.mode != mode) { throw new JSONException(mode == 'a' ? "Misplaced endArray." : "Misplaced endObject."); } this.pop(mode); try { this.writer.write(c); } catch (IOException e) { throw new JSONException(e); } this.comma = true; return this; } /** * End an array. This method most be called to balance calls to * <code>array</code>. * @return this * @throws JSONException If incorrectly nested. */ public JSONWriter endArray() throws JSONException { return this.end('a', ']'); } /** * End an object. This method most be called to balance calls to * <code>object</code>. * @return this * @throws JSONException If incorrectly nested. */ public JSONWriter endObject() throws JSONException { return this.end('k', '}'); } /** * Append a key. The key will be associated with the next value. In an * object, every value must be preceded by a key. * @param string A key string. * @return this * @throws JSONException If the key is out of place. For example, keys * do not belong in arrays or if the key is null. */ public JSONWriter key(String string) throws JSONException { if (string == null) { throw new JSONException("Null key."); } if (this.mode == 'k') { try { this.stack[this.top - 1].putOnce(string, Boolean.TRUE); if (this.comma) { this.writer.write(','); } this.writer.write(JSONObject.quote(string)); this.writer.write(':'); this.comma = false; this.mode = 'o'; return this; } catch (IOException e) { throw new JSONException(e); } } throw new JSONException("Misplaced key."); } /** * Begin appending a new object. All keys and values until the balancing * <code>endObject</code> will be appended to this object. The * <code>endObject</code> method must be called to mark the object's end. * @return this * @throws JSONException If the nesting is too deep, or if the object is * started in the wrong place (for example as a key or after the end of the * outermost array or object). */ public JSONWriter object() throws JSONException { if (this.mode == 'i') { this.mode = 'o'; } if (this.mode == 'o' || this.mode == 'a') { this.append("{"); this.push(new JSONObject()); this.comma = false; return this; } throw new JSONException("Misplaced object."); } /** * Pop an array or object scope. * @param c The scope to close. * @throws JSONException If nesting is wrong. */ private void pop(char c) throws JSONException { if (this.top <= 0) { throw new JSONException("Nesting error."); } char m = this.stack[this.top - 1] == null ? 'a' : 'k'; if (m != c) { throw new JSONException("Nesting error."); } this.top -= 1; this.mode = this.top == 0 ? 'd' : this.stack[this.top - 1] == null ? 'a' : 'k'; } /** * Push an array or object scope. * @param c The scope to open. * @throws JSONException If nesting is too deep. */ private void push(JSONObject jo) throws JSONException { if (this.top >= maxdepth) { throw new JSONException("Nesting too deep."); } this.stack[this.top] = jo; this.mode = jo == null ? 'a' : 'k'; this.top += 1; } /** * Append either the value <code>true</code> or the value * <code>false</code>. * @param b A boolean. * @return this * @throws JSONException */ public JSONWriter value(boolean b) throws JSONException { return this.append(b ? "true" : "false"); } /** * Append a double value. * @param d A double. * @return this * @throws JSONException If the number is not finite. */ public JSONWriter value(double d) throws JSONException { return this.value(new Double(d)); } /** * Append a long value. * @param l A long. * @return this * @throws JSONException */ public JSONWriter value(long l) throws JSONException { return this.append(Long.toString(l)); } /** * Append an object value. * @param object The object to append. It can be null, or a Boolean, Number, * String, JSONObject, or JSONArray, or an object that implements JSONString. * @return this * @throws JSONException If the value is out of sequence. */ public JSONWriter value(Object object) throws JSONException { return this.append(JSONObject.valueToString(object)); } }
12085952-sageandroid
commandline/src/org/json/JSONWriter.java
Java
gpl3
10,677
package org.json; /* Copyright (c) 2002 JSON.org 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 shall be used for Good, not Evil. 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. */ import java.io.IOException; import java.io.Writer; import java.lang.reflect.Array; import java.util.ArrayList; import java.util.Collection; import java.util.Iterator; import java.util.Map; /** * A JSONArray is an ordered sequence of values. Its external text form is a * string wrapped in square brackets with commas separating the values. The * internal form is an object having <code>get</code> and <code>opt</code> * methods for accessing the values by index, and <code>put</code> methods for * adding or replacing values. The values can be any of these types: * <code>Boolean</code>, <code>JSONArray</code>, <code>JSONObject</code>, * <code>Number</code>, <code>String</code>, or the * <code>JSONObject.NULL object</code>. * <p> * The constructor can convert a JSON text into a Java object. The * <code>toString</code> method converts to JSON text. * <p> * A <code>get</code> method returns a value if one can be found, and throws an * exception if one cannot be found. An <code>opt</code> method returns a * default value instead of throwing an exception, and so is useful for * obtaining optional values. * <p> * The generic <code>get()</code> and <code>opt()</code> methods return an * object which you can cast or query for type. There are also typed * <code>get</code> and <code>opt</code> methods that do type checking and type * coercion for you. * <p> * The texts produced by the <code>toString</code> methods strictly conform to * JSON syntax rules. The constructors are more forgiving in the texts they will * accept: * <ul> * <li>An extra <code>,</code>&nbsp;<small>(comma)</small> may appear just * before the closing bracket.</li> * <li>The <code>null</code> value will be inserted when there * is <code>,</code>&nbsp;<small>(comma)</small> elision.</li> * <li>Strings may be quoted with <code>'</code>&nbsp;<small>(single * quote)</small>.</li> * <li>Strings do not need to be quoted at all if they do not begin with a quote * or single quote, and if they do not contain leading or trailing spaces, * and if they do not contain any of these characters: * <code>{ } [ ] / \ : , = ; #</code> and if they do not look like numbers * and if they are not the reserved words <code>true</code>, * <code>false</code>, or <code>null</code>.</li> * <li>Values can be separated by <code>;</code> <small>(semicolon)</small> as * well as by <code>,</code> <small>(comma)</small>.</li> * </ul> * @author JSON.org * @version 2011-11-24 */ public class JSONArray { /** * The arrayList where the JSONArray's properties are kept. */ private final ArrayList myArrayList; /** * Construct an empty JSONArray. */ public JSONArray() { this.myArrayList = new ArrayList(); } /** * Construct a JSONArray from a JSONTokener. * @param x A JSONTokener * @throws JSONException If there is a syntax error. */ public JSONArray(JSONTokener x) throws JSONException { this(); if (x.nextClean() != '[') { throw x.syntaxError("A JSONArray text must start with '['"); } if (x.nextClean() != ']') { x.back(); for (;;) { if (x.nextClean() == ',') { x.back(); this.myArrayList.add(JSONObject.NULL); } else { x.back(); this.myArrayList.add(x.nextValue()); } switch (x.nextClean()) { case ';': case ',': if (x.nextClean() == ']') { return; } x.back(); break; case ']': return; default: throw x.syntaxError("Expected a ',' or ']'"); } } } } /** * Construct a JSONArray from a source JSON text. * @param source A string that begins with * <code>[</code>&nbsp;<small>(left bracket)</small> * and ends with <code>]</code>&nbsp;<small>(right bracket)</small>. * @throws JSONException If there is a syntax error. */ public JSONArray(String source) throws JSONException { this(new JSONTokener(source)); } /** * Construct a JSONArray from a Collection. * @param collection A Collection. */ public JSONArray(Collection collection) { this.myArrayList = new ArrayList(); if (collection != null) { Iterator iter = collection.iterator(); while (iter.hasNext()) { this.myArrayList.add(JSONObject.wrap(iter.next())); } } } /** * Construct a JSONArray from an array * @throws JSONException If not an array. */ public JSONArray(Object array) throws JSONException { this(); if (array.getClass().isArray()) { int length = Array.getLength(array); for (int i = 0; i < length; i += 1) { this.put(JSONObject.wrap(Array.get(array, i))); } } else { throw new JSONException( "JSONArray initial value should be a string or collection or array."); } } /** * Get the object value associated with an index. * @param index * The index must be between 0 and length() - 1. * @return An object value. * @throws JSONException If there is no value for the index. */ public Object get(int index) throws JSONException { Object object = this.opt(index); if (object == null) { throw new JSONException("JSONArray[" + index + "] not found."); } return object; } /** * Get the boolean value associated with an index. * The string values "true" and "false" are converted to boolean. * * @param index The index must be between 0 and length() - 1. * @return The truth. * @throws JSONException If there is no value for the index or if the * value is not convertible to boolean. */ public boolean getBoolean(int index) throws JSONException { Object object = this.get(index); if (object.equals(Boolean.FALSE) || (object instanceof String && ((String)object).equalsIgnoreCase("false"))) { return false; } else if (object.equals(Boolean.TRUE) || (object instanceof String && ((String)object).equalsIgnoreCase("true"))) { return true; } throw new JSONException("JSONArray[" + index + "] is not a boolean."); } /** * Get the double value associated with an index. * * @param index The index must be between 0 and length() - 1. * @return The value. * @throws JSONException If the key is not found or if the value cannot * be converted to a number. */ public double getDouble(int index) throws JSONException { Object object = this.get(index); try { return object instanceof Number ? ((Number)object).doubleValue() : Double.parseDouble((String)object); } catch (Exception e) { throw new JSONException("JSONArray[" + index + "] is not a number."); } } /** * Get the int value associated with an index. * * @param index The index must be between 0 and length() - 1. * @return The value. * @throws JSONException If the key is not found or if the value is not a number. */ public int getInt(int index) throws JSONException { Object object = this.get(index); try { return object instanceof Number ? ((Number)object).intValue() : Integer.parseInt((String)object); } catch (Exception e) { throw new JSONException("JSONArray[" + index + "] is not a number."); } } /** * Get the JSONArray associated with an index. * @param index The index must be between 0 and length() - 1. * @return A JSONArray value. * @throws JSONException If there is no value for the index. or if the * value is not a JSONArray */ public JSONArray getJSONArray(int index) throws JSONException { Object object = this.get(index); if (object instanceof JSONArray) { return (JSONArray)object; } throw new JSONException("JSONArray[" + index + "] is not a JSONArray."); } /** * Get the JSONObject associated with an index. * @param index subscript * @return A JSONObject value. * @throws JSONException If there is no value for the index or if the * value is not a JSONObject */ public JSONObject getJSONObject(int index) throws JSONException { Object object = this.get(index); if (object instanceof JSONObject) { return (JSONObject)object; } throw new JSONException("JSONArray[" + index + "] is not a JSONObject."); } /** * Get the long value associated with an index. * * @param index The index must be between 0 and length() - 1. * @return The value. * @throws JSONException If the key is not found or if the value cannot * be converted to a number. */ public long getLong(int index) throws JSONException { Object object = this.get(index); try { return object instanceof Number ? ((Number)object).longValue() : Long.parseLong((String)object); } catch (Exception e) { throw new JSONException("JSONArray[" + index + "] is not a number."); } } /** * Get the string associated with an index. * @param index The index must be between 0 and length() - 1. * @return A string value. * @throws JSONException If there is no string value for the index. */ public String getString(int index) throws JSONException { Object object = this.get(index); if (object instanceof String) { return (String)object; } throw new JSONException("JSONArray[" + index + "] not a string."); } /** * Determine if the value is null. * @param index The index must be between 0 and length() - 1. * @return true if the value at the index is null, or if there is no value. */ public boolean isNull(int index) { return JSONObject.NULL.equals(this.opt(index)); } /** * Make a string from the contents of this JSONArray. The * <code>separator</code> string is inserted between each element. * Warning: This method assumes that the data structure is acyclical. * @param separator A string that will be inserted between the elements. * @return a string. * @throws JSONException If the array contains an invalid number. */ public String join(String separator) throws JSONException { int len = this.length(); StringBuffer sb = new StringBuffer(); for (int i = 0; i < len; i += 1) { if (i > 0) { sb.append(separator); } sb.append(JSONObject.valueToString(this.myArrayList.get(i))); } return sb.toString(); } /** * Get the number of elements in the JSONArray, included nulls. * * @return The length (or size). */ public int length() { return this.myArrayList.size(); } /** * Get the optional object value associated with an index. * @param index The index must be between 0 and length() - 1. * @return An object value, or null if there is no * object at that index. */ public Object opt(int index) { return (index < 0 || index >= this.length()) ? null : this.myArrayList.get(index); } /** * Get the optional boolean value associated with an index. * It returns false if there is no value at that index, * or if the value is not Boolean.TRUE or the String "true". * * @param index The index must be between 0 and length() - 1. * @return The truth. */ public boolean optBoolean(int index) { return this.optBoolean(index, false); } /** * Get the optional boolean value associated with an index. * It returns the defaultValue if there is no value at that index or if * it is not a Boolean or the String "true" or "false" (case insensitive). * * @param index The index must be between 0 and length() - 1. * @param defaultValue A boolean default. * @return The truth. */ public boolean optBoolean(int index, boolean defaultValue) { try { return this.getBoolean(index); } catch (Exception e) { return defaultValue; } } /** * Get the optional double value associated with an index. * NaN is returned if there is no value for the index, * or if the value is not a number and cannot be converted to a number. * * @param index The index must be between 0 and length() - 1. * @return The value. */ public double optDouble(int index) { return this.optDouble(index, Double.NaN); } /** * Get the optional double value associated with an index. * The defaultValue is returned if there is no value for the index, * or if the value is not a number and cannot be converted to a number. * * @param index subscript * @param defaultValue The default value. * @return The value. */ public double optDouble(int index, double defaultValue) { try { return this.getDouble(index); } catch (Exception e) { return defaultValue; } } /** * Get the optional int value associated with an index. * Zero is returned if there is no value for the index, * or if the value is not a number and cannot be converted to a number. * * @param index The index must be between 0 and length() - 1. * @return The value. */ public int optInt(int index) { return this.optInt(index, 0); } /** * Get the optional int value associated with an index. * The defaultValue is returned if there is no value for the index, * or if the value is not a number and cannot be converted to a number. * @param index The index must be between 0 and length() - 1. * @param defaultValue The default value. * @return The value. */ public int optInt(int index, int defaultValue) { try { return this.getInt(index); } catch (Exception e) { return defaultValue; } } /** * Get the optional JSONArray associated with an index. * @param index subscript * @return A JSONArray value, or null if the index has no value, * or if the value is not a JSONArray. */ public JSONArray optJSONArray(int index) { Object o = this.opt(index); return o instanceof JSONArray ? (JSONArray)o : null; } /** * Get the optional JSONObject associated with an index. * Null is returned if the key is not found, or null if the index has * no value, or if the value is not a JSONObject. * * @param index The index must be between 0 and length() - 1. * @return A JSONObject value. */ public JSONObject optJSONObject(int index) { Object o = this.opt(index); return o instanceof JSONObject ? (JSONObject)o : null; } /** * Get the optional long value associated with an index. * Zero is returned if there is no value for the index, * or if the value is not a number and cannot be converted to a number. * * @param index The index must be between 0 and length() - 1. * @return The value. */ public long optLong(int index) { return this.optLong(index, 0); } /** * Get the optional long value associated with an index. * The defaultValue is returned if there is no value for the index, * or if the value is not a number and cannot be converted to a number. * @param index The index must be between 0 and length() - 1. * @param defaultValue The default value. * @return The value. */ public long optLong(int index, long defaultValue) { try { return this.getLong(index); } catch (Exception e) { return defaultValue; } } /** * Get the optional string value associated with an index. It returns an * empty string if there is no value at that index. If the value * is not a string and is not null, then it is coverted to a string. * * @param index The index must be between 0 and length() - 1. * @return A String value. */ public String optString(int index) { return this.optString(index, ""); } /** * Get the optional string associated with an index. * The defaultValue is returned if the key is not found. * * @param index The index must be between 0 and length() - 1. * @param defaultValue The default value. * @return A String value. */ public String optString(int index, String defaultValue) { Object object = this.opt(index); return JSONObject.NULL.equals(object) ? object.toString() : defaultValue; } /** * Append a boolean value. This increases the array's length by one. * * @param value A boolean value. * @return this. */ public JSONArray put(boolean value) { this.put(value ? Boolean.TRUE : Boolean.FALSE); return this; } /** * Put a value in the JSONArray, where the value will be a * JSONArray which is produced from a Collection. * @param value A Collection value. * @return this. */ public JSONArray put(Collection value) { this.put(new JSONArray(value)); return this; } /** * Append a double value. This increases the array's length by one. * * @param value A double value. * @throws JSONException if the value is not finite. * @return this. */ public JSONArray put(double value) throws JSONException { Double d = new Double(value); JSONObject.testValidity(d); this.put(d); return this; } /** * Append an int value. This increases the array's length by one. * * @param value An int value. * @return this. */ public JSONArray put(int value) { this.put(new Integer(value)); return this; } /** * Append an long value. This increases the array's length by one. * * @param value A long value. * @return this. */ public JSONArray put(long value) { this.put(new Long(value)); return this; } /** * Put a value in the JSONArray, where the value will be a * JSONObject which is produced from a Map. * @param value A Map value. * @return this. */ public JSONArray put(Map value) { this.put(new JSONObject(value)); return this; } /** * Append an object value. This increases the array's length by one. * @param value An object value. The value should be a * Boolean, Double, Integer, JSONArray, JSONObject, Long, or String, or the * JSONObject.NULL object. * @return this. */ public JSONArray put(Object value) { this.myArrayList.add(value); return this; } /** * Put or replace a boolean value in the JSONArray. If the index is greater * than the length of the JSONArray, then null elements will be added as * necessary to pad it out. * @param index The subscript. * @param value A boolean value. * @return this. * @throws JSONException If the index is negative. */ public JSONArray put(int index, boolean value) throws JSONException { this.put(index, value ? Boolean.TRUE : Boolean.FALSE); return this; } /** * Put a value in the JSONArray, where the value will be a * JSONArray which is produced from a Collection. * @param index The subscript. * @param value A Collection value. * @return this. * @throws JSONException If the index is negative or if the value is * not finite. */ public JSONArray put(int index, Collection value) throws JSONException { this.put(index, new JSONArray(value)); return this; } /** * Put or replace a double value. If the index is greater than the length of * the JSONArray, then null elements will be added as necessary to pad * it out. * @param index The subscript. * @param value A double value. * @return this. * @throws JSONException If the index is negative or if the value is * not finite. */ public JSONArray put(int index, double value) throws JSONException { this.put(index, new Double(value)); return this; } /** * Put or replace an int value. If the index is greater than the length of * the JSONArray, then null elements will be added as necessary to pad * it out. * @param index The subscript. * @param value An int value. * @return this. * @throws JSONException If the index is negative. */ public JSONArray put(int index, int value) throws JSONException { this.put(index, new Integer(value)); return this; } /** * Put or replace a long value. If the index is greater than the length of * the JSONArray, then null elements will be added as necessary to pad * it out. * @param index The subscript. * @param value A long value. * @return this. * @throws JSONException If the index is negative. */ public JSONArray put(int index, long value) throws JSONException { this.put(index, new Long(value)); return this; } /** * Put a value in the JSONArray, where the value will be a * JSONObject that is produced from a Map. * @param index The subscript. * @param value The Map value. * @return this. * @throws JSONException If the index is negative or if the the value is * an invalid number. */ public JSONArray put(int index, Map value) throws JSONException { this.put(index, new JSONObject(value)); return this; } /** * Put or replace an object value in the JSONArray. If the index is greater * than the length of the JSONArray, then null elements will be added as * necessary to pad it out. * @param index The subscript. * @param value The value to put into the array. The value should be a * Boolean, Double, Integer, JSONArray, JSONObject, Long, or String, or the * JSONObject.NULL object. * @return this. * @throws JSONException If the index is negative or if the the value is * an invalid number. */ public JSONArray put(int index, Object value) throws JSONException { JSONObject.testValidity(value); if (index < 0) { throw new JSONException("JSONArray[" + index + "] not found."); } if (index < this.length()) { this.myArrayList.set(index, value); } else { while (index != this.length()) { this.put(JSONObject.NULL); } this.put(value); } return this; } /** * Remove an index and close the hole. * @param index The index of the element to be removed. * @return The value that was associated with the index, * or null if there was no value. */ public Object remove(int index) { Object o = this.opt(index); this.myArrayList.remove(index); return o; } /** * Produce a JSONObject by combining a JSONArray of names with the values * of this JSONArray. * @param names A JSONArray containing a list of key strings. These will be * paired with the values. * @return A JSONObject, or null if there are no names or if this JSONArray * has no values. * @throws JSONException If any of the names are null. */ public JSONObject toJSONObject(JSONArray names) throws JSONException { if (names == null || names.length() == 0 || this.length() == 0) { return null; } JSONObject jo = new JSONObject(); for (int i = 0; i < names.length(); i += 1) { jo.put(names.getString(i), this.opt(i)); } return jo; } /** * Make a JSON text of this JSONArray. For compactness, no * unnecessary whitespace is added. If it is not possible to produce a * syntactically correct JSON text then null will be returned instead. This * could occur if the array contains an invalid number. * <p> * Warning: This method assumes that the data structure is acyclical. * * @return a printable, displayable, transmittable * representation of the array. */ public String toString() { try { return '[' + this.join(",") + ']'; } catch (Exception e) { return null; } } /** * Make a prettyprinted JSON text of this JSONArray. * Warning: This method assumes that the data structure is acyclical. * @param indentFactor The number of spaces to add to each level of * indentation. * @return a printable, displayable, transmittable * representation of the object, beginning * with <code>[</code>&nbsp;<small>(left bracket)</small> and ending * with <code>]</code>&nbsp;<small>(right bracket)</small>. * @throws JSONException */ public String toString(int indentFactor) throws JSONException { return this.toString(indentFactor, 0); } /** * Make a prettyprinted JSON text of this JSONArray. * Warning: This method assumes that the data structure is acyclical. * @param indentFactor The number of spaces to add to each level of * indentation. * @param indent The indention of the top level. * @return a printable, displayable, transmittable * representation of the array. * @throws JSONException */ String toString(int indentFactor, int indent) throws JSONException { int len = this.length(); if (len == 0) { return "[]"; } int i; StringBuffer sb = new StringBuffer("["); if (len == 1) { sb.append(JSONObject.valueToString(this.myArrayList.get(0), indentFactor, indent)); } else { int newindent = indent + indentFactor; sb.append('\n'); for (i = 0; i < len; i += 1) { if (i > 0) { sb.append(",\n"); } for (int j = 0; j < newindent; j += 1) { sb.append(' '); } sb.append(JSONObject.valueToString(this.myArrayList.get(i), indentFactor, newindent)); } sb.append('\n'); for (i = 0; i < indent; i += 1) { sb.append(' '); } } sb.append(']'); return sb.toString(); } /** * Write the contents of the JSONArray as JSON text to a writer. * For compactness, no whitespace is added. * <p> * Warning: This method assumes that the data structure is acyclical. * * @return The writer. * @throws JSONException */ public Writer write(Writer writer) throws JSONException { try { boolean b = false; int len = this.length(); writer.write('['); for (int i = 0; i < len; i += 1) { if (b) { writer.write(','); } Object v = this.myArrayList.get(i); if (v instanceof JSONObject) { ((JSONObject)v).write(writer); } else if (v instanceof JSONArray) { ((JSONArray)v).write(writer); } else { writer.write(JSONObject.valueToString(v)); } b = true; } writer.write(']'); return writer; } catch (IOException e) { throw new JSONException(e); } } }
12085952-sageandroid
commandline/src/org/json/JSONArray.java
Java
gpl3
29,953
package org.sagemath.singlecellserver; import java.io.BufferedReader; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import java.net.URISyntaxException; import java.text.DateFormat; import java.util.LinkedList; import java.util.ListIterator; import java.util.Timer; import java.util.UUID; import org.apache.http.HttpEntity; import org.apache.http.HttpResponse; import org.apache.http.HttpStatus; import org.apache.http.StatusLine; import org.apache.http.client.ClientProtocolException; import org.apache.http.client.methods.HttpPost; import org.apache.http.entity.mime.HttpMultipartMode; import org.apache.http.entity.mime.MultipartEntity; import org.json.JSONArray; import org.json.JSONException; import org.json.JSONObject; import org.sagemath.singlecellserver.SageSingleCell.SageInterruptedException; import android.text.format.Time; import android.util.Log; public class CommandRequest extends Command { private static final String TAG = "CommandRequest"; long time = System.currentTimeMillis(); private int SLEEP_BEFORE_TRY = 20; private boolean error = false; public CommandRequest() { super(); } public CommandRequest(UUID session) { super(session); } public JSONObject toJSON() throws JSONException { JSONObject header = new JSONObject(); header.put("session", session.toString()); header.put("msg_id", msg_id.toString()); JSONObject result = new JSONObject(); result.put("header", header); return result; } protected void sendRequest(SageSingleCell.ServerTask server) { CommandReply reply; try { HttpResponse httpResponse = server.postEval(toJSON()); processInitialReply(httpResponse); return; } catch (JSONException e) { reply = new HttpError(this, e.getLocalizedMessage()); } catch (ClientProtocolException e) { reply = new HttpError(this, e.getLocalizedMessage()); } catch (IOException e) { reply = new HttpError(this, e.getLocalizedMessage()); } catch (SageInterruptedException e) { reply = new HttpError(this, "Interrupted on user request"); } error = true; server.addReply(reply); } public StatusLine processInitialReply(HttpResponse response) throws IllegalStateException, IOException, JSONException { InputStream outputStream = response.getEntity().getContent(); String output = SageSingleCell.streamToString(outputStream); outputStream.close(); System.out.println("output = " + output); JSONObject outputJSON = new JSONObject(output); if (outputJSON.has("session_id")) session = UUID.fromString(outputJSON.getString("session_id")); return response.getStatusLine(); } public void receiveReply(SageSingleCell.ServerTask server) { sendRequest(server); if (error) return; long timeEnd = System.currentTimeMillis() + server.timeout(); int count = 0; while (System.currentTimeMillis() < timeEnd) { count++; LinkedList<CommandReply> result = pollResult(server); // System.out.println("Poll got "+ result.size()); ListIterator<CommandReply> iter = result.listIterator(); while (iter.hasNext()) { CommandReply reply = iter.next(); timeEnd += reply.extendTimeOut(); server.addReply(reply); } if (error) return; if (!result.isEmpty() && (result.getLast().terminateServerConnection())) return; try { Thread.sleep(count*SLEEP_BEFORE_TRY); } catch (InterruptedException e) {} } error = true; server.addReply(new HttpError(this, "Timeout")); } private LinkedList<CommandReply> pollResult(SageSingleCell.ServerTask server) { LinkedList<CommandReply> result = new LinkedList<CommandReply>(); try { int sequence = server.result.size(); result.addAll(pollResult(server, sequence)); return result; } catch (JSONException e) { CommandReply reply = new HttpError(this, e.getLocalizedMessage()); result.add(reply); } catch (ClientProtocolException e) { CommandReply reply = new HttpError(this, e.getLocalizedMessage()); result.add(reply); } catch (IOException e) { CommandReply reply = new HttpError(this, e.getLocalizedMessage()); result.add(reply); } catch (URISyntaxException e) { CommandReply reply = new HttpError(this, e.getLocalizedMessage()); result.add(reply); } catch (SageInterruptedException e) { CommandReply reply = new HttpError(this, "Interrupted on user request"); result.add(reply); } error = true; return result; } private LinkedList<CommandReply> pollResult(SageSingleCell.ServerTask server, int sequence) throws JSONException, IOException, URISyntaxException, SageInterruptedException { LinkedList<CommandReply> result = new LinkedList<CommandReply>(); try { Thread.sleep(SLEEP_BEFORE_TRY); } catch (InterruptedException e) { Log.e(TAG, e.getLocalizedMessage()); return result; } HttpResponse response = server.pollOutput(this, sequence); error = (response.getStatusLine().getStatusCode() != HttpStatus.SC_OK); HttpEntity entity = response.getEntity(); InputStream outputStream = entity.getContent(); String output = SageSingleCell.streamToString(outputStream); outputStream.close(); //output = output.substring(7, output.length()-2); // strip out "jQuery("...")" System.out.println("output = " + output); JSONObject outputJSON = new JSONObject(output); if (!outputJSON.has("content")) return result; JSONArray content = outputJSON.getJSONArray("content"); for (int i=0; i<content.length(); i++) { JSONObject obj = content.getJSONObject(i); CommandReply command = CommandReply.parse(obj); result.add(command); if (command instanceof DataFile) { DataFile file = (DataFile)command; file.downloadFile(server); } else if (command instanceof HtmlFiles) { HtmlFiles file = (HtmlFiles)command; file.downloadFile(server); } } return result; } public String toLongString() { JSONObject json; try { json = toJSON(); } catch (JSONException e) { return e.getLocalizedMessage(); } JSONWriter writer = new JSONWriter(); // writer.write(json.toString()); try { json.write(writer); } catch (JSONException e) { return e.getLocalizedMessage(); } StringBuffer str = writer.getBuffer(); return str.toString(); } }
12085952-sageandroid
commandline/src/org/sagemath/singlecellserver/CommandRequest.java
Java
gpl3
6,402
package org.sagemath.singlecellserver; import org.json.JSONException; import org.json.JSONObject; /* * * jQuery({ * "content": [{ * "parent_header": { * "username": "", "msg_id": "749529bd-bcfe-43a7-b660-2cea20df3f32", * "session": "7af9a99a-2a0d-438f-8576-5e0bd853501a"}, * "msg_type": "extension", * "sequence": 0, * "output_block": null, * "content": { * "content": { * "interact_id": "8157151862156143292", * "layout": {"top_center": ["n"]}, * "update": {"n": ["n"]}, * "controls": { * "n": { * "ncols": null, * "control_type": "selector", * "raw": true, * "default": 0, * "label": null, * "nrows": null, * "subtype": "list", * "values": 10, "width": "", * "value_labels": ["0", "1", "2", "3", "4", "5", "6", "7", "8", "9"]}}}, * "msg_type": "interact_prepare"}, * "header": {"msg_id": "4744042977225053037"} * }, { * "parent_header": { * "username": "", * "msg_id": "749529bd-bcfe-43a7-b660-2cea20df3f32", * "session": "7af9a99a-2a0d-438f-8576-5e0bd853501a"}, * "msg_type": "stream", "sequence": 1, "output_block": "8157151862156143292", * "content": {"data": "0\n", "name": "stdout"}, "header": {"msg_id": "7423072463567901439"}}, {"parent_header": {"username": "", "msg_id": "749529bd-bcfe-43a7-b660-2cea20df3f32", "session": "7af9a99a-2a0d-438f-8576-5e0bd853501a"}, "msg_type": "execute_reply", "sequence": 2, "output_block": null, "content": {"status": "ok"}, "header": {"msg_id": "1900046197361249484"}}]}) * * */ public class Interact extends CommandOutput { private final static String TAG = "Interact"; private final String id; protected JSONObject controls, layout; protected Interact(JSONObject json) throws JSONException { super(json); JSONObject content = json.getJSONObject("content").getJSONObject("content"); id = content.getString("interact_id"); controls = content.getJSONObject("controls"); layout = content.getJSONObject("layout"); } public long extendTimeOut() { return 60 * 1000; } public boolean isInteract() { return true; } public String getID() { return id; } public String toString() { return "Prepare interact id=" + getID(); } public JSONObject getControls() { return controls; } public JSONObject getLayout() { return layout; } } /* HTTP/1.1 200 OK Server: nginx/1.0.11 Date: Tue, 10 Jan 2012 21:03:24 GMT Content-Type: text/javascript; charset=utf-8 Connection: keep-alive Content-Length: 1225 jQuery150664064213167876_1326208736019({"content": [{ "parent_header": {"username": "", "msg_id": "f0826b78-7aaf-4eea-a5ce-0b10d24c5888", "session": "184c2fb0-1a8d-4c07-aee6-df85183d9ac2"}, "msg_type": "extension", "sequence": 0, "output_block": null, "content": {"content": {"interact_id": "5455242645056671226", "layout": {"top_center": ["n"]}, "update": {"n": ["n"]}, "controls": {"n": {"control_type": "slider", "raw": true, "default": 0.0, "step": 0.40000000000000002, "label": null, "subtype": "continuous", "range": [0.0, 100.0], "display_value": true}}}, "msg_type": "interact_prepare"}, "header": {"msg_id": "8880643058896313398"}}, { "parent_header": {"username": "", "msg_id": "f0826b78-7aaf-4eea-a5ce-0b10d24c5888", "session": "184c2fb0-1a8d-4c07-aee6-df85183d9ac2"}, "msg_type": "stream", "sequence": 1, "output_block": "5455242645056671226", "content": {"data": "0\n", "name": "stdout"}, "header": {"msg_id": "8823336185428654730"}}, {"parent_header": {"username": "", "msg_id": "f0826b78-7aaf-4eea-a5ce-0b10d24c5888", "session": "184c2fb0-1a8d-4c07-aee6-df85183d9ac2"}, "msg_type": "execute_reply", "sequence": 2, "output_block": null, "content": {"status": "ok"}, "header": {"msg_id": "1224514542068124881"}}]}) POST /eval?callback=jQuery150664064213167876_1326208736022 HTTP/1.1 Host: sagemath.org:5467 Connection: keep-alive Content-Length: 368 Origin: http://sagemath.org:5467 x-requested-with: XMLHttpRequest User-Agent: Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/535.7 (KHTML, like Gecko) Chrome/16.0.912.63 Safari/535.7 content-type: application/x-www-form-urlencoded accept: text/javascript, application/javascript, q=0.01 Referer: http://sagemath.org:5467/ Accept-Encoding: gzip,deflate,sdch Accept-Language: en-US,en;q=0.8,fr;q=0.6,de;q=0.4,ja;q=0.2 Accept-Charset: ISO-8859-1,utf-8;q=0.7,;q=0.3 Cookie: __utma=1.260350506.1306546516.1306612711.1306855420.3; HstCfa1579950=1313082432530; HstCmu1579950=1313082432530; c_ref_1579950=http:%2F%2Fboxen.math.washington.edu%2F; HstCla1579950=1314023965352; HstPn1579950=4; HstPt1579950=6; HstCnv1579950=2; HstCns1579950=2; __utma=138969649.2037720324.1307556884.1314205520.1326143310.11; __utmz=138969649.1314205520.10.6.utmcsr=en.wikipedia.org|utmccn=(referral)|utmcmd=referral|utmcct=/wiki/Sage_(mathematics_software) message={"parent_header":{},"header":{"msg_id":"45724d5f-01f8-4d9c-9eb0-d877a8880db8","session":"184c2fb0-1a8d-4c07-aee6-df85183d9ac2"},"msg_type":"execute_request","content":{"code":"_update_interact('5455242645056671226',control_vals=dict(n=23.6,))","sage_mode":true}} GET /output_poll?callback=jQuery150664064213167876_1326208736025&computation_id=184c2fb0-1a8d-4c07-aee6-df85183d9ac2&sequence=3&_=1326229408735 HTTP/1.1 Host: sagemath.org:5467 Connection: keep-alive x-requested-with: XMLHttpRequest User-Agent: Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/535.7 (KHTML, like Gecko) Chrome/16.0.912.63 Safari/535.7 accept: text/javascript, application/javascript,; q=0.01 Referer: http://sagemath.org:5467/ Accept-Encoding: gzip,deflate,sdch Accept-Language: en-US,en;q=0.8,fr;q=0.6,de;q=0.4,ja;q=0.2 Accept-Charset: ISO-8859-1,utf-8;q=0.7,*;q=0.3 Cookie: __utma=1.260350506.1306546516.1306612711.1306855420.3; HstCfa1579950=1313082432530; HstCmu1579950=1313082432530; c_ref_1579950=http%3A%2F%2Fboxen.math.washington.edu%2F; HstCla1579950=1314023965352; HstPn1579950=4; HstPt1579950=6; HstCnv1579950=2; HstCns1579950=2; __utma=138969649.2037720324.1307556884.1314205520.1326143310.11; __utmz=138969649.1314205520.10.6.utmcsr=en.wikipedia.org|utmccn=(referral)|utmcmd=referral|utmcct=/wiki/Sage_(mathematics_software) HTTP/1.1 200 OK Server: nginx/1.0.11 Date: Tue, 10 Jan 2012 21:03:29 GMT Content-Type: text/javascript; charset=utf-8 Connection: keep-alive Content-Length: 618 jQuery150664064213167876_1326208736025({"content": [{"parent_header": {"session": "184c2fb0-1a8d-4c07-aee6-df85183d9ac2", "msg_id": "45724d5f-01f8-4d9c-9eb0-d877a8880db8"}, "msg_type": "stream", "sequence": 3, "output_block": "5455242645056671226", "content": {"data": "23.6000000000000\n", "name": "stdout"}, "header": {"msg_id": "514409474887099253"}}, {"parent_header": {"session": "184c2fb0-1a8d-4c07-aee6-df85183d9ac2", "msg_id": "45724d5f-01f8-4d9c-9eb0-d877a8880db8"}, "msg_type": "execute_reply", "sequence": 4, "output_block": null, "content": {"status": "ok"}, "header": {"msg_id": "7283788905623826736"}}]}) */
12085952-sageandroid
commandline/src/org/sagemath/singlecellserver/Interact.java
Java
gpl3
7,079
package org.sagemath.singlecellserver; import java.util.UUID; import junit.framework.Assert; import org.json.JSONException; import org.json.JSONObject; import android.util.Log; /** * The base class for a server reply * * @author vbraun * */ public class CommandReply extends Command { private final static String TAG = "CommandReply"; private JSONObject json; protected CommandReply(JSONObject json) throws JSONException { this.json = json; JSONObject parent_header = json.getJSONObject("parent_header"); session = UUID.fromString(parent_header.getString("session")); msg_id = UUID.fromString(parent_header.getString("msg_id")); } protected CommandReply(CommandRequest request) { session = request.session; msg_id = request.msg_id; } public String toString() { return "Command reply base class"; } public void prettyPrint() { prettyPrint(json); } /** * Extend the HTTP timetout receive timeout. This is for interacts to extend the timeout. * @return milliseconds */ public long extendTimeOut() { return 0; } public boolean isInteract() { return false; } /** * Whether to keep polling for more results after receiving this message * @return */ public boolean terminateServerConnection() { return false; } /** * Turn a received JSONObject into the corresponding Command object * * @return a new CommandReply or derived class */ protected static CommandReply parse(JSONObject json) throws JSONException { String msg_type = json.getString("msg_type"); JSONObject content = json.getJSONObject("content"); // Log.d(TAG, "content = "+content.toString()); // prettyPrint(json); if (msg_type.equals("pyout")) return new PythonOutput(json); else if (msg_type.equals("display_data")) { JSONObject data = json.getJSONObject("content").getJSONObject("data"); if (data.has("text/filename")) return new DataFile(json); else return new DisplayData(json); } else if (msg_type.equals("stream")) return new ResultStream(json); else if (msg_type.equals("execute_reply")) { if (content.has("traceback")) return new Traceback(json); else return new ExecuteReply(json); } else if (msg_type.equals("extension")) { String ext_msg_type = content.getString("msg_type"); if (ext_msg_type.equals("session_end")) return new SessionEnd(json); if (ext_msg_type.equals("files")) return new HtmlFiles(json); if (ext_msg_type.equals("interact_prepare")) return new Interact(json); } throw new JSONException("Unknown msg_type"); } public String toLongString() { if (json == null) return "null"; JSONWriter writer = new JSONWriter(); // writer.write(json.toString()); try { json.write(writer); } catch (JSONException e) { return e.getLocalizedMessage(); } StringBuffer str = writer.getBuffer(); return str.toString(); } /** * Whether the reply is a reply to the given request * @param request * @return boolean */ public boolean isReplyTo(CommandRequest request) { System.out.println("msg_id = "+msg_id.toString()+ " "+request.msg_id.toString()); System.out.println("session = "+session.toString()+ " "+request.session.toString()); return (request != null) && session.equals(request.session); } }
12085952-sageandroid
commandline/src/org/sagemath/singlecellserver/CommandReply.java
Java
gpl3
3,296
package org.sagemath.singlecellserver; import java.util.UUID; import junit.framework.Assert; import org.json.JSONException; import org.json.JSONObject; import android.util.Log; /** * The base class for server communication. All derived classes should * derive from CommandRequest and CommandReply, but not from Command * directly. * * @author vbraun * */ public class Command { private final static String TAG = "Command"; protected UUID session; protected UUID msg_id; protected Command() { this.session = UUID.randomUUID(); msg_id = UUID.randomUUID(); } protected Command(UUID session) { if (session == null) this.session = UUID.randomUUID(); else this.session = session; msg_id = UUID.randomUUID(); } public String toShortString() { return toString(); } public String toLongString() { return toString(); } public String toString() { return "Command base class @" + Integer.toHexString(System.identityHashCode(this)); } /** * Whether or not the command contains data that is supposed to be shown to the user * @return boolean */ public boolean containsOutput() { return false; } protected static void prettyPrint(JSONObject json) { if (json == null) { System.out.println("null"); return; } JSONWriter writer = new JSONWriter(); writer.write(json.toString()); // try { // json.write(writer); // } catch (JSONException e) { // e.printStackTrace(); // } StringBuffer str = writer.getBuffer(); System.out.println(str); } }
12085952-sageandroid
commandline/src/org/sagemath/singlecellserver/Command.java
Java
gpl3
1,530
package org.sagemath.singlecellserver; import org.json.JSONException; import org.json.JSONObject; public class ExecuteReply extends CommandOutput { private final static String TAG = "ExecuteReply"; private String status; protected ExecuteReply(JSONObject json) throws JSONException { super(json); JSONObject content = json.getJSONObject("content"); status = content.getString("status"); } public String toString() { return "Execute reply status = "+status; } public String getStatus() { return status; } }
12085952-sageandroid
commandline/src/org/sagemath/singlecellserver/ExecuteReply.java
Java
gpl3
534
package org.sagemath.singlecellserver; import java.io.IOException; import java.net.URI; import java.net.URISyntaxException; import java.util.LinkedList; import org.json.JSONArray; import org.json.JSONException; import org.json.JSONObject; public class HtmlFiles extends CommandOutput { private final static String TAG = "HtmlFiles"; protected JSONArray files; protected LinkedList<URI> uriList = new LinkedList<URI>(); protected HtmlFiles(JSONObject json) throws JSONException { super(json); files = json.getJSONObject("content").getJSONObject("content").getJSONArray("files"); } public String toString() { if (uriList.isEmpty()) return "Html files (empty list)"; else return "Html files, number = "+uriList.size()+" first = "+getFirstURI().toString(); } public URI getFirstURI() { return uriList.getFirst(); } public void downloadFile(SageSingleCell.ServerTask server) throws IOException, URISyntaxException, JSONException { for (int i=0; i<files.length(); i++) { URI uri = server.downloadFileURI(this, files.get(i).toString()); uriList.add(uri); } } }
12085952-sageandroid
commandline/src/org/sagemath/singlecellserver/HtmlFiles.java
Java
gpl3
1,111
package org.sagemath.singlecellserver; import org.json.JSONException; import org.json.JSONObject; /** * Roughly, a CommandOutput is any JSON object that has a "output_block" field. These are intended * to be displayed on the screen. * * @author vbraun * */ public class CommandOutput extends CommandReply { private final static String TAG = "CommandOutput"; private String output_block; protected CommandOutput(JSONObject json) throws JSONException { super(json); output_block = json.get("output_block").toString(); // prettyPrint(); // System.out.println("block = " + output_block); } public boolean containsOutput() { return true; } public String outputBlock() { return output_block; } }
12085952-sageandroid
commandline/src/org/sagemath/singlecellserver/CommandOutput.java
Java
gpl3
729
package org.sagemath.singlecellserver; import junit.framework.Assert; import org.json.JSONException; import org.json.JSONObject; public class DisplayData extends CommandOutput { private final static String TAG = "DisplayData"; private JSONObject data; protected String value, mime; protected DisplayData(JSONObject json) throws JSONException { super(json); data = json.getJSONObject("content").getJSONObject("data"); mime = data.keys().next().toString(); value = data.getString(mime); // prettyPrint(json); } public String toString() { return "Display data "+value; } public String getData() { return value; } public String getMime() { return mime; } public String toHTML() { if (mime.equals("text/html")) return value; if (mime.equals("text/plain")) return "<pre>"+value+"</pre>"; return null; } }
12085952-sageandroid
commandline/src/org/sagemath/singlecellserver/DisplayData.java
Java
gpl3
853
package org.sagemath.singlecellserver; import java.io.BufferedInputStream; import java.io.ByteArrayOutputStream; import java.io.DataInputStream; import java.io.IOException; import java.io.InputStream; import java.net.URI; import java.net.URISyntaxException; import java.nio.Buffer; import org.apache.http.HttpEntity; import org.apache.http.HttpResponse; import org.apache.http.HttpStatus; import org.json.JSONException; import org.json.JSONObject; import org.sagemath.singlecellserver.SageSingleCell.SageInterruptedException; public class DataFile extends DisplayData { private final static String TAG = "DataFile"; protected DataFile(JSONObject json) throws JSONException { super(json); } public String toString() { if (data == null) return "Data file "+uri.toString(); else return "Data file "+value+" ("+data.length+" bytes)"; } public String mime() { String name = value.toLowerCase(); if (name.endsWith(".png")) return "image/png"; if (name.endsWith(".jpg")) return "image/png"; if (name.endsWith(".jpeg")) return "image/png"; if (name.endsWith(".svg")) return "image/svg"; return null; } protected byte[] data; protected URI uri; public URI getURI() { return uri; } public void downloadFile(SageSingleCell.ServerTask server) throws IOException, URISyntaxException, SageInterruptedException { uri = server.downloadFileURI(this, this.value); if (server.downloadDataFiles()) download(server, uri); } private void download(SageSingleCell.ServerTask server, URI uri) throws IOException, SageInterruptedException { HttpResponse response = server.downloadFile(uri); boolean error = (response.getStatusLine().getStatusCode() != HttpStatus.SC_OK); HttpEntity entity = response.getEntity(); InputStream stream = entity.getContent(); byte[] buffer = new byte[4096]; ByteArrayOutputStream buf = new ByteArrayOutputStream(); try { for (int n; (n = stream.read(buffer)) != -1; ) buf.write(buffer, 0, n); } finally { stream.close(); buf.close(); } data = buf.toByteArray(); } }
12085952-sageandroid
commandline/src/org/sagemath/singlecellserver/DataFile.java
Java
gpl3
2,176
package org.sagemath.singlecellserver; import org.json.JSONException; import org.json.JSONObject; /** * <h1>Streams (stdout, stderr, etc)</h1> * <p> * <pre><code> * Message type: ``stream``:: * content = { * # The name of the stream is one of 'stdin', 'stdout', 'stderr' * 'name' : str, * * # The data is an arbitrary string to be written to that stream * 'data' : str, * } * </code></pre> * When a kernel receives a raw_input call, it should also broadcast it on the pub * socket with the names 'stdin' and 'stdin_reply'. This will allow other clients * to monitor/display kernel interactions and possibly replay them to their user * or otherwise expose them. * * @author vbraun * */ public class ResultStream extends CommandOutput { private final static String TAG = "ResultStream"; protected JSONObject content; protected String data; protected ResultStream(JSONObject json) throws JSONException { super(json); content = json.getJSONObject("content"); data = content.getString("data"); } public String toString() { return "Result: stream = >>>"+data+"<<<"; } public String toShortString() { return "Stream output"; } public String get() { return data; } }
12085952-sageandroid
commandline/src/org/sagemath/singlecellserver/ResultStream.java
Java
gpl3
1,255
package org.sagemath.singlecellserver; public class HttpError extends CommandReply { private final static String TAG = "HttpError"; protected String message; protected HttpError(CommandRequest request, String message) { super(request); this.message = message; } public String toString() { return "HTTP error "+message; } @Override public boolean terminateServerConnection() { return true; } }
12085952-sageandroid
commandline/src/org/sagemath/singlecellserver/HttpError.java
Java
gpl3
424
package org.sagemath.singlecellserver; import java.util.LinkedList; import java.util.UUID; import org.json.JSONArray; import org.json.JSONException; import org.json.JSONObject; public class ExecuteRequest extends CommandRequest { private final static String TAG = "ExecuteRequest"; String input; boolean sage; public ExecuteRequest(String input, boolean sage, UUID session) { super(session); this.input = input; this.sage = sage; } public ExecuteRequest(String input) { super(); this.input = input; sage = true; } public String toString() { return "Request to execute >"+input+"<"; } public String toShortString() { return "Request to execute"; } public JSONObject toJSON() throws JSONException { JSONObject result = super.toJSON(); result.put("parent_header", new JSONArray()); result.put("msg_type", "execute_request"); JSONObject content = new JSONObject(); content.put("code", input); content.put("sage_mode", sage); result.put("content", content); return result; } // {"parent_header":{}, // "header":{ // "msg_id":"1ec1b4b4-722e-42c7-997d-e4a9605f5056", // "session":"c11a0761-910e-4c8c-b94e-803a13e5859a"}, // "msg_type":"execute_request", // "content":{"code":"code to execute", // "sage_mode":true}} }
12085952-sageandroid
commandline/src/org/sagemath/singlecellserver/ExecuteRequest.java
Java
gpl3
1,336
package org.sagemath.singlecellserver; import java.io.BufferedReader; import java.io.File; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import java.net.URI; import java.net.URISyntaxException; import java.util.LinkedList; import java.util.ListIterator; import java.util.UUID; import javax.net.ssl.HandshakeCompletedListener; import junit.framework.Assert; import org.apache.http.HttpEntity; import org.apache.http.HttpResponse; import org.apache.http.HttpStatus; import org.apache.http.HttpVersion; import org.apache.http.StatusLine; import org.apache.http.client.ClientProtocolException; import org.apache.http.client.ResponseHandler; import org.apache.http.client.methods.HttpGet; import org.apache.http.client.methods.HttpPost; import org.apache.http.entity.mime.HttpMultipartMode; import org.apache.http.entity.mime.MultipartEntity; import org.apache.http.entity.mime.content.StringBody; import org.apache.http.impl.client.DefaultHttpClient; import org.apache.http.params.BasicHttpParams; import org.apache.http.params.CoreProtocolPNames; import org.apache.http.params.HttpParams; import org.apache.http.util.EntityUtils; import org.json.JSONArray; import org.json.JSONException; import org.json.JSONObject; import android.util.Log; import android.text.format.Time; /** * Interface with the Sage single cell server * * @author vbraun * */ public class SageSingleCell { private final static String TAG = "SageSingleCell"; private long timeout = 30*1000; // private String server = "http://localhost:8001"; private String server = "http://sagemath.org:5467"; private String server_path_eval = "/eval"; private String server_path_output_poll = "/output_poll"; private String server_path_files = "/files"; protected boolean downloadDataFiles = true; /** * Whether to immediately download data files or only save their URI * * @param value Download immediately if true */ public void setDownloadDataFiles(boolean value) { downloadDataFiles = value; } /** * Set the server * * @param server The server, for example "http://sagemath.org:5467" * @param eval The path on the server for the eval post, for example "/eval" * @param poll The path on the server for the output polling, for example "/output_poll" */ public void setServer(String server, String eval, String poll, String files) { this.server = server; this.server_path_eval = eval; this.server_path_output_poll = poll; this.server_path_files = files; } public interface OnSageListener { /** * Output in a new block or an existing block where all current entries are supposed to be erased * @param output */ public void onSageOutputListener(CommandOutput output); /** * Output to add to an existing output block * @param output */ public void onSageAdditionalOutputListener(CommandOutput output); /** * Callback for an interact_prepare message * @param interact The interact */ public void onSageInteractListener(Interact interact); /** * The Sage session has been closed * @param reason A SessionEnd message or a HttpError */ public void onSageFinishedListener(CommandReply reason); } private OnSageListener listener; /** * Set the result callback, see {@link #query(String)} * * @param listener */ public void setOnSageListener(OnSageListener listener) { this.listener = listener; } public SageSingleCell() { logging(); } public void logging() { // You also have to // adb shell setprop log.tag.httpclient.wire.header VERBOSE // adb shell setprop log.tag.httpclient.wire.content VERBOSE java.util.logging.Logger apacheWireLog = java.util.logging.Logger.getLogger("org.apache.http.wire"); apacheWireLog.setLevel(java.util.logging.Level.FINEST); } protected static String streamToString(InputStream is) { BufferedReader reader = new BufferedReader(new InputStreamReader(is)); StringBuilder sb = new StringBuilder(); String line = null; try { while ((line = reader.readLine()) != null) { sb.append(line + "\n"); } } catch (IOException e) { e.printStackTrace(); } finally { try { is.close(); } catch (IOException e) { e.printStackTrace(); } } return sb.toString(); } public static class SageInterruptedException extends Exception { private static final long serialVersionUID = -5638564842011063160L; } LinkedList<ServerTask> threads = new LinkedList<ServerTask>(); private void addThread(ServerTask thread) { synchronized (threads) { threads.add(thread); } } private void removeThread(ServerTask thread) { synchronized (threads) { threads.remove(thread); } } public enum LogLevel { NONE, BRIEF, VERBOSE }; private LogLevel logLevel = LogLevel.NONE; public void setLogLevel(LogLevel logLevel) { this.logLevel = logLevel; } public class ServerTask extends Thread { private final static String TAG = "ServerTask"; private final UUID session; private final String sageInput; private boolean sendOnly = false; private final boolean sageMode = true; private boolean interrupt = false; private DefaultHttpClient httpClient; private Interact interact; private CommandRequest request, currentRequest; private LinkedList<String> outputBlocks = new LinkedList<String>(); private long initialTime = System.currentTimeMillis(); protected LinkedList<CommandReply> result = new LinkedList<CommandReply>(); protected void log(Command command) { if (logLevel.equals(LogLevel.NONE)) return; String s; if (command instanceof CommandReply) s = ">> "; else if (command instanceof CommandRequest) s = "<< "; else s = "== "; long t = System.currentTimeMillis() - initialTime; s += "(" + String.valueOf(t) + "ms) "; s += command.toShortString(); if (logLevel.equals(LogLevel.VERBOSE)) { s += " "; s += command.toLongString(); s += "\n"; } System.out.println(s); System.out.flush(); } /** * Whether to only send or also receive the replies * @param sendOnly */ protected void setSendOnly(boolean sendOnly) { this.sendOnly = sendOnly; } protected void addReply(CommandReply reply) { log(reply); result.add(reply); System.out.println(reply.containsOutput()); System.out.println(reply.isReplyTo(currentRequest)); if (reply.isInteract()) { interact = (Interact) reply; listener.onSageInteractListener(interact); } else if (reply.containsOutput() && reply.isReplyTo(currentRequest)) { CommandOutput output = (CommandOutput) reply; if (outputBlocks.contains(output.outputBlock())) listener.onSageAdditionalOutputListener(output); else { outputBlocks.add(output.outputBlock()); listener.onSageOutputListener(output); } } } /** * The timeout for the http request * @return timeout in milliseconds */ public long timeout() { return timeout; } private void init() { HttpParams params = new BasicHttpParams(); params.setParameter(CoreProtocolPNames.PROTOCOL_VERSION, HttpVersion.HTTP_1_1); httpClient = new DefaultHttpClient(params); addThread(this); currentRequest = request = new ExecuteRequest(sageInput, sageMode, session); } public ServerTask() { this.sageInput = null; this.session = null; init(); } public ServerTask(String sageInput) { this.sageInput = sageInput; this.session = null; init(); } public ServerTask(String sageInput, UUID session) { this.sageInput = sageInput; this.session = session; init(); } public void interrupt() { interrupt = true; } public boolean isInterrupted() { return interrupt; } protected HttpResponse postEval(JSONObject request) throws ClientProtocolException, IOException, SageInterruptedException, JSONException { if (interrupt) throw new SageInterruptedException(); HttpPost httpPost = new HttpPost(server + server_path_eval); MultipartEntity multipartEntity = new MultipartEntity(HttpMultipartMode.BROWSER_COMPATIBLE); if (request.has("content")) multipartEntity.addPart("message", new StringBody(request.toString())); else { JSONObject content = request.getJSONObject("content"); JSONObject header = request.getJSONObject("header"); multipartEntity.addPart("commands", new StringBody(JSONObject.quote(content.getString("code")))); multipartEntity.addPart("msg_id", new StringBody(header.getString("msg_id"))); multipartEntity.addPart("sage_mode", new StringBody("on")); } httpPost.setEntity(multipartEntity); HttpResponse httpResponse = httpClient.execute(httpPost); return httpResponse; } protected HttpResponse pollOutput(CommandRequest request, int sequence) throws ClientProtocolException, IOException, SageInterruptedException { if (interrupt) throw new SageInterruptedException(); Time time = new Time(); StringBuilder query = new StringBuilder(); time.setToNow(); // query.append("?callback=jQuery"); query.append("?computation_id=" + request.session.toString()); query.append("&sequence=" + sequence); query.append("&rand=" + time.toMillis(true)); HttpGet httpGet = new HttpGet(server + server_path_output_poll + query); return httpClient.execute(httpGet); } // protected void callSageOutputListener(CommandOutput output) { // listener.onSageOutputListener(output); // } // // protected void callSageReplaceOutputListener(CommandOutput output) { // listener.onSageReplaceOutputListener(output); // } // // protected void callSageInteractListener(Interact interact) { // listener.onSageInteractListener(interact); // } protected URI downloadFileURI(CommandReply reply, String filename) throws URISyntaxException { StringBuilder query = new StringBuilder(); query.append("/"+reply.session.toString()); query.append("/"+filename); return new URI(server + server_path_files + query); } protected HttpResponse downloadFile(URI uri) throws ClientProtocolException, IOException, SageInterruptedException { if (interrupt) throw new SageInterruptedException(); HttpGet httpGet = new HttpGet(uri); return httpClient.execute(httpGet); } protected boolean downloadDataFiles() { return SageSingleCell.this.downloadDataFiles; } @Override public void run() { super.run(); log(request); if (sendOnly) { request.sendRequest(this); removeThread(this); return; } request.receiveReply(this); removeThread(this); listener.onSageFinishedListener(result.getLast()); } } /** * Start an asynchronous query on the Sage server * The result will be handled by the callback set by {@link #setOnSageListener(OnSageListener)} * @param sageInput */ public void query(String sageInput) { ServerTask task = new ServerTask(sageInput); task.start(); } /** * Update an interactive element * @param interact The interact_prepare message we got from the server as we set up the interact * @param name The name of the variable in the interact function declaration * @param value The new value */ public void interact(Interact interact, String name, Object value) { String sageInput = "_update_interact('" + interact.getID() + "',control_vals=dict(" + name + "=" + value.toString() + ",))"; ServerTask task = new ServerTask(sageInput, interact.session); synchronized (threads) { for (ServerTask thread: threads) if (thread.interact == interact) { thread.currentRequest = task.request; thread.outputBlocks.clear(); } } task.setSendOnly(true); task.start(); } /** * Interrupt all pending Sage server transactions */ public void interrupt() { synchronized (threads) { for (ServerTask thread: threads) thread.interrupt(); } } /** * Whether a computation is currently running * * @return */ public boolean isRunning() { synchronized (threads) { for (ServerTask thread: threads) if (!thread.isInterrupted()) return true; } return false; } } /* === Send request === POST /eval HTTP/1.1 Host: localhost:8001 Connection: keep-alive Content-Length: 506 Cache-Control: max-age=0 Origin: http://localhost:8001 User-Agent: Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/535.2 (KHTML, like Gecko) Chrome/15.0.874.121 Safari/535.2 Content-Type: multipart/form-data; boundary=----WebKitFormBoundaryh9NcFTBy2FksKYpN Accept: text/html,application/xhtml+xml,application/xml;q=0.9,* / *;q=0.8 Referer: http://localhost:8001/ Accept-Encoding: gzip,deflate,sdch Accept-Language: en-US,en;q=0.8,de;q=0.6,ja;q=0.4,fr-FR;q=0.2,he;q=0.2,ga;q=0.2,ko;q=0.2 Accept-Charset: ISO-8859-1,utf-8;q=0.7,*;q=0.3 Cookie: DWd8c32a438995fbf98bd158172221d77e=dmJyYXVu%7C1%7CWHhzTnc5M0NXZDZyekQzcjlVL1lNZz09; DOKU_PREFS=sizeCtl%23679px ------WebKitFormBoundaryh9NcFTBy2FksKYpN Content-Disposition: form-data; name="commands" "1+1" ------WebKitFormBoundaryh9NcFTBy2FksKYpN Content-Disposition: form-data; name="session_id" 87013257-7c34-4c83-b7ed-2ec7e7480935 ------WebKitFormBoundaryh9NcFTBy2FksKYpN Content-Disposition: form-data; name="msg_id" 489696dc-ed8d-4cb6-a140-4282a43eda95 ------WebKitFormBoundaryh9NcFTBy2FksKYpN Content-Disposition: form-data; name="sage_mode" True ------WebKitFormBoundaryh9NcFTBy2FksKYpN-- HTTP/1.1 200 OK Server: nginx/1.0.4 Date: Mon, 12 Dec 2011 19:12:14 GMT Content-Type: text/html; charset=utf-8 Connection: keep-alive Content-Length: 0 === Poll for reply (unsuccessfully, try again) === GET /output_poll?callback=jQuery15015045171417295933_1323715011672&computation_id=25508880-6a6a-4353-9439-689468ec679e&sequence=0&_=1323718075839 HTTP/1.1 Host: localhost:8001 Connection: keep-alive x-requested-with: XMLHttpRequest User-Agent: Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/535.2 (KHTML, like Gecko) Chrome/15.0.874.121 Safari/535.2 accept: text/javascript, application/javascript, * / *; q=0.01 Referer: http://localhost:8001/ Accept-Encoding: gzip,deflate,sdch Accept-Language: en-US,en;q=0.8,de;q=0.6,ja;q=0.4,fr-FR;q=0.2,he;q=0.2,ga;q=0.2,ko;q=0.2 Accept-Charset: ISO-8859-1,utf-8;q=0.7,*;q=0.3 Cookie: DWd8c32a438995fbf98bd158172221d77e=dmJyYXVu%7C1%7CWHhzTnc5M0NXZDZyekQzcjlVL1lNZz09; DOKU_PREFS=sizeCtl%23679px HTTP/1.1 200 OK Server: nginx/1.0.4 Date: Mon, 12 Dec 2011 19:27:55 GMT Content-Type: text/javascript; charset=utf-8 Connection: keep-alive Content-Length: 44 jQuery15015045171417295933_1323715011672({}) === Poll for reply (success) === GET /output_poll?callback=jQuery15015045171417295933_1323715011662&computation_id=87013257-7c34-4c83-b7ed-2ec7e7480935&sequence=0&_=1323717134406 HTTP/1.1 Host: localhost:8001 Connection: keep-alive x-requested-with: XMLHttpRequest User-Agent: Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/535.2 (KHTML, like Gecko) Chrome/15.0.874.121 Safari/535.2 accept: text/javascript, application/javascript, * / *; q=0.01 Referer: http://localhost:8001/ Accept-Encoding: gzip,deflate,sdch Accept-Language: en-US,en;q=0.8,de;q=0.6,ja;q=0.4,fr-FR;q=0.2,he;q=0.2,ga;q=0.2,ko;q=0.2 Accept-Charset: ISO-8859-1,utf-8;q=0.7,*;q=0.3 Cookie: DWd8c32a438995fbf98bd158172221d77e=dmJyYXVu%7C1%7CWHhzTnc5M0NXZDZyekQzcjlVL1lNZz09; DOKU_PREFS=sizeCtl%23679px === Reply with result from server === HTTP/1.1 200 OK Server: nginx/1.0.4 Date: Mon, 12 Dec 2011 19:12:14 GMT Content-Type: text/javascript; charset=utf-8 Connection: keep-alive Content-Length: 830 jQuery15015045171417295933_1323715011662( {"content": [{ "parent_header": { "username": "", "msg_id": "489696dc-ed8d-4cb6-a140-4282a43eda95", "session": "87013257-7c34-4c83-b7ed-2ec7e7480935"}, "msg_type": "pyout", "sequence": 0, "output_block": null, "content": { "data": {"text/plain": "2"}}, "header": {"msg_id": "1620524024608841996"}}, { "parent_header": { "username": "", "msg_id": "489696dc-ed8d-4cb6-a140-4282a43eda95", "session": "87013257-7c34-4c83-b7ed-2ec7e7480935"}, "msg_type": "execute_reply", "sequence": 1, "output_block": null, "content": {"status": "ok"}, "header": {"msg_id": "1501182239947896697"}}, { "parent_header": {"session": "87013257-7c34-4c83-b7ed-2ec7e7480935"}, "msg_type": "extension", "sequence": 2, "content": {"msg_type": "session_end"}, "header": {"msg_id": "1e6db71f-61a0-47f9-9607-f2054243bb67"} }]}) === Reply with Syntax Erorr === GET /output_poll?callback=jQuery15015045171417295933_1323715011664&computation_id=9b3ed6bb-01e8-4a6e-9076-14c71324daf6&sequence=0&_=1323717902557 HTTP/1.1 Host: localhost:8001 Connection: keep-alive x-requested-with: XMLHttpRequest User-Agent: Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/535.2 (KHTML, like Gecko) Chrome/15.0.874.121 Safari/535.2 accept: text/javascript, application/javascript, * / *; q=0.01 Referer: http://localhost:8001/ Accept-Encoding: gzip,deflate,sdch Accept-Language: en-US,en;q=0.8,de;q=0.6,ja;q=0.4,fr-FR;q=0.2,he;q=0.2,ga;q=0.2,ko;q=0.2 Accept-Charset: ISO-8859-1,utf-8;q=0.7,*;q=0.3 Cookie: DWd8c32a438995fbf98bd158172221d77e=dmJyYXVu%7C1%7CWHhzTnc5M0NXZDZyekQzcjlVL1lNZz09; DOKU_PREFS=sizeCtl%23679px HTTP/1.1 200 OK Server: nginx/1.0.4 Date: Mon, 12 Dec 2011 19:25:02 GMT Content-Type: text/javascript; charset=utf-8 Connection: keep-alive Content-Length: 673 jQuery15015045171417295933_1323715011664({"content": [{"parent_header": {"username": "", "msg_id": "df56f48a-d47f-4267-b228-77f051d7d834", "session": "9b3ed6bb-01e8-4a6e-9076-14c71324daf6"}, "msg_type": "execute_reply", "sequence": 0, "output_block": null, "content": {"status": "error", "ename": "SyntaxError", "evalue": "invalid syntax", "traceback": ["\u001b[1;31m---------------------------------------------------------------------------\u001b[0m\n\u001b[1;31mSyntaxError\u001b[0m Traceback (most recent call last)", "\u001b[1;31mSyntaxError\u001b[0m: invalid syntax (<string>, line 39)"]}, "header": {"msg_id": "2853508955959610959"}}]})GET /output_poll?callback=jQuery15015045171417295933_1323715011665&computation_id=9b3ed6bb-01e8-4a6e-9076-14c71324daf6&sequence=1&_=1323717904769 HTTP/1.1 Host: localhost:8001 Connection: keep-alive x-requested-with: XMLHttpRequest User-Agent: Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/535.2 (KHTML, like Gecko) Chrome/15.0.874.121 Safari/535.2 accept: text/javascript, application/javascript, * / *; q=0.01 Referer: http://localhost:8001/ Accept-Encoding: gzip,deflate,sdch Accept-Language: en-US,en;q=0.8,de;q=0.6,ja;q=0.4,fr-FR;q=0.2,he;q=0.2,ga;q=0.2,ko;q=0.2 Accept-Charset: ISO-8859-1,utf-8;q=0.7,*;q=0.3 Cookie: DWd8c32a438995fbf98bd158172221d77e=dmJyYXVu%7C1%7CWHhzTnc5M0NXZDZyekQzcjlVL1lNZz09; DOKU_PREFS=sizeCtl%23679px HTTP/1.1 200 OK Server: nginx/1.0.4 Date: Mon, 12 Dec 2011 19:25:04 GMT Content-Type: text/javascript; charset=utf-8 Connection: keep-alive Content-Length: 269 jQuery15015045171417295933_1323715011665({"content": [{"parent_header": {"session": "9b3ed6bb-01e8-4a6e-9076-14c71324daf6"}, "msg_type": "extension", "sequence": 1, "content": {"msg_type": "session_end"}, "header": {"msg_id": "e01180d4-934c-4f12-858c-72d52e0330cd"}}]}) */
12085952-sageandroid
commandline/src/org/sagemath/singlecellserver/SageSingleCell.java
Java
gpl3
19,545
package org.sagemath.singlecellserver; import org.json.JSONException; import org.json.JSONObject; public class SessionEnd extends CommandReply { public final static String TAG = "SessionEnd"; protected SessionEnd(JSONObject json) throws JSONException { super(json); } public String toString() { return "End of Sage session marker"; } @Override public boolean terminateServerConnection() { return true; } }
12085952-sageandroid
commandline/src/org/sagemath/singlecellserver/SessionEnd.java
Java
gpl3
429
package org.sagemath.singlecellserver; import java.io.StringWriter; /** * * @author Elad Tabak * @since 28-Nov-2011 * @version 0.1 * */ public class JSONWriter extends StringWriter { private int indent = 0; @Override public void write(int c) { if (((char)c) == '[' || ((char)c) == '{') { super.write(c); super.write('\n'); indent++; writeIndentation(); } else if (((char)c) == ',') { super.write(c); super.write('\n'); writeIndentation(); } else if (((char)c) == ']' || ((char)c) == '}') { super.write('\n'); indent--; writeIndentation(); super.write(c); } else { super.write(c); } } private void writeIndentation() { for (int i = 0; i < indent; i++) { super.write(" "); } } }
12085952-sageandroid
commandline/src/org/sagemath/singlecellserver/JSONWriter.java
Java
gpl3
921
package org.sagemath.singlecellserver; import java.util.Iterator; import org.json.JSONException; import org.json.JSONObject; /** * <h1>Python output</h1> * <p> * When Python produces output from code that has been compiled in with the * 'single' flag to :func:`compile`, any expression that produces a value (such as * ``1+1``) is passed to ``sys.displayhook``, which is a callable that can do with * this value whatever it wants. The default behavior of ``sys.displayhook`` in * the Python interactive prompt is to print to ``sys.stdout`` the :func:`repr` of * the value as long as it is not ``None`` (which isn't printed at all). In our * case, the kernel instantiates as ``sys.displayhook`` an object which has * similar behavior, but which instead of printing to stdout, broadcasts these * values as ``pyout`` messages for clients to display appropriately. * <p> * IPython's displayhook can handle multiple simultaneous formats depending on its * configuration. The default pretty-printed repr text is always given with the * ``data`` entry in this message. Any other formats are provided in the * ``extra_formats`` list. Frontends are free to display any or all of these * according to its capabilities. ``extra_formats`` list contains 3-tuples of an ID * string, a type string, and the data. The ID is unique to the formatter * implementation that created the data. Frontends will typically ignore the ID * unless if it has requested a particular formatter. The type string tells the * frontend how to interpret the data. It is often, but not always a MIME type. * Frontends should ignore types that it does not understand. The data itself is * any JSON object and depends on the format. It is often, but not always a string. * <p> * Message type: ``pyout``:: * <p> * <pre><code> * content = { * # The counter for this execution is also provided so that clients can * # display it, since IPython automatically creates variables called _N * # (for prompt N). * 'execution_count' : int, * * # The data dict contains key/value pairs, where the kids are MIME * # types and the values are the raw data of the representation in that * # format. The data dict must minimally contain the ``text/plain`` * # MIME type which is used as a backup representation. * 'data' : dict, * } * </code></pre> * * @author vbraun */ public class PythonOutput extends CommandOutput { private final static String TAG = "PythonOutput"; protected JSONObject content, data; protected String text; protected PythonOutput(JSONObject json) throws JSONException { super(json); content = json.getJSONObject("content"); data = content.getJSONObject("data"); text = data.getString("text/plain"); } public String toString() { return "Python output: "+text; } public String toShortString() { return "Python output"; } /** * Get an iterator for the possible encodings. * * @return */ public Iterator<?> getEncodings() { return data.keys(); } /** * Get the output * * @param encoding Which of possibly multiple representations to return * @return The output in the chosen representation * @throws JSONException */ public String get(String encoding) throws JSONException { return data.getString(encoding); } /** * Return a textual representation of the output * * @return Text representation of the output; */ public String get() { return text; } }
12085952-sageandroid
commandline/src/org/sagemath/singlecellserver/PythonOutput.java
Java
gpl3
3,522
package org.sagemath.singlecellserver; import java.util.LinkedList; import java.util.ListIterator; public class Transaction { protected final SageSingleCell server; protected final CommandRequest request; protected final LinkedList<CommandReply> reply; public static class Factory { public Transaction newTransaction(SageSingleCell server, CommandRequest request, LinkedList<CommandReply> reply) { return new Transaction(server, request, reply); } } protected Transaction(SageSingleCell server, CommandRequest request, LinkedList<CommandReply> reply) { this.server = server; this.request = request; this.reply = reply; } public DataFile getDataFile() { for (CommandReply r: reply) if (r instanceof DataFile) return (DataFile)r; return null; } public HtmlFiles getHtmlFiles() { for (CommandReply r: reply) if (r instanceof HtmlFiles) return (HtmlFiles)r; return null; } public DisplayData getDisplayData() { for (CommandReply r: reply) if (r instanceof DisplayData) return (DisplayData)r; return null; } public ResultStream getResultStream() { for (CommandReply r: reply) if (r instanceof ResultStream) return (ResultStream)r; return null; } public PythonOutput getPythonOutput() { for (CommandReply r: reply) if (r instanceof PythonOutput) return (PythonOutput)r; return null; } public Traceback getTraceback() { for (CommandReply r: reply) if (r instanceof Traceback) return (Traceback)r; return null; } public HttpError getHttpError() { for (CommandReply r: reply) if (r instanceof HttpError) return (HttpError)r; return null; } public ExecuteReply getExecuteReply() { for (CommandReply r: reply) if (r instanceof ExecuteReply) return (ExecuteReply)r; return null; } public String toString() { StringBuilder s = new StringBuilder(); s.append(request); if (reply.isEmpty()) s.append("no reply"); else s.append("\n"); ListIterator<CommandReply> iter = reply.listIterator(); while (iter.hasNext()) { s.append(iter.next()); if (iter.hasNext()) s.append("\n"); } return s.toString(); } }
12085952-sageandroid
commandline/src/org/sagemath/singlecellserver/Transaction.java
Java
gpl3
2,152
package org.sagemath.commandline; import java.util.LinkedList; import org.sagemath.singlecellserver.CommandOutput; import org.sagemath.singlecellserver.CommandReply; import org.sagemath.singlecellserver.Interact; import org.sagemath.singlecellserver.SageSingleCell; import org.sagemath.singlecellserver.SageSingleCell.OnSageListener; public class Testcase implements OnSageListener { SageSingleCell server; String command; boolean finished = false; public static class Interaction { String control; Object value; } LinkedList<Interaction> interacts = new LinkedList<Interaction>(); public Testcase(SageSingleCell server, String command) { this.server = server; this.command = command; } public Testcase addInteract(String control, Object value) { Interaction i = new Interaction(); i.control = control; i.value = value; interacts.add(i); return this; } public void run() { server.query(command); while (!finished) { try { Thread.sleep(200 * 1000); } catch (InterruptedException e) { System.out.println("Testcase interrupted: "+e.getLocalizedMessage()); } } } Interact interact; @Override public void onSageOutputListener(CommandOutput output) { System.out.println("SageOutput"); System.out.println(output.toLongString()); System.out.println("\n"); System.out.flush(); if (interact == null || interacts.isEmpty()) return; Interaction i = interacts.pop(); server.interact(interact, i.control, i.value); if (interact == null || interacts.isEmpty()) return; i = interacts.pop(); server.interact(interact, i.control, i.value); } @Override public void onSageAdditionalOutputListener(CommandOutput output) { System.out.println("SageAdditionalOutput"); System.out.println(output.toLongString()); System.out.println("\n"); System.out.flush(); } @Override public void onSageInteractListener(Interact interact) { this.interact = interact; System.out.println("SageInteract"); System.out.println(interact.toLongString()); System.out.println("\n"); System.out.flush(); } @Override public void onSageFinishedListener(CommandReply reason) { System.out.println("SageFinished"); System.out.println(reason.toLongString()); System.out.println("\n"); System.out.flush(); finished = true; } }
12085952-sageandroid
commandline/src/org/sagemath/commandline/Testcase.java
Java
gpl3
2,308
package org.sagemath.commandline; import java.io.Console; import junit.framework.Assert; public class Client { private static final String TAG = "Client"; private Console console; public Client() { console = System.console(); } public static void main(String[] args) { Client client = new Client(); if (client == null) return; client.loop(); } private void loop() { Assert.assertNotNull(console); String line; while (true) { line = console.readLine("%s", "args"); console.printf("%s", line); } } }
12085952-sageandroid
commandline/src/org/sagemath/commandline/Client.java
Java
gpl3
540
package org.sagemath.commandline; import java.util.LinkedList; import org.sagemath.singlecellserver.CommandReply; import org.sagemath.singlecellserver.CommandRequest; import org.sagemath.singlecellserver.SageSingleCell; import org.sagemath.singlecellserver.Transaction; public class MyTransaction extends Transaction { public static class Factory extends Transaction.Factory { @Override public Transaction newTransaction(SageSingleCell server, CommandRequest request, LinkedList<CommandReply> reply) { return new MyTransaction(server, request, reply); } } protected MyTransaction(SageSingleCell server, CommandRequest request, LinkedList<CommandReply> reply) { super(server, request, reply); } public void print() { System.out.println(this.toString()); } }
12085952-sageandroid
commandline/src/org/sagemath/commandline/MyTransaction.java
Java
gpl3
794
package org.sagemath.commandline; import java.io.Console; import java.util.LinkedList; import java.util.ListIterator; import javax.swing.SingleSelectionModel; import org.sagemath.singlecellserver.CommandOutput; import org.sagemath.singlecellserver.CommandReply; import org.sagemath.singlecellserver.ExecuteRequest; import org.sagemath.singlecellserver.Interact; import org.sagemath.singlecellserver.SageSingleCell; import org.sagemath.singlecellserver.SageSingleCell.LogLevel; import org.sagemath.singlecellserver.SageSingleCell.ServerTask; import junit.framework.Assert; public class Test { private static final String TAG = "Client"; private SageSingleCell server = new SageSingleCell(); public Test() { // server.setServer("http://sagemath.org:5467", "/eval", "/output_poll", "/files"); server.setServer("http://aleph.sagemath.org", "/eval", "/output_poll", "/files"); server.setDownloadDataFiles(false); server.setLogLevel(LogLevel.BRIEF); } public static void main(String[] args) { Test test = new Test(); test.run(); } private void run() { //test("plot(sin(x),x,0,1)").run(); if (false) test("1+1").run(); if (false) test("@interact\n" + "def f(n=Selector(values=[\"Option1\",\"Option2\"])):\n" + " print n") .addInteract("n", 1) .run(); if (false) test("@interact\n" + "def f(n=DiscreteSlider(values=[2,3,5,7,11,13])):\n" + " print n*n") .addInteract("n", 2) .run(); if (false) test("@interact\n" + "def f(n=(1..10)):\n" + " print n*n") .addInteract("n", 7) .run(); if (false) test("1+1").run(); // if (false) test("@interact\n" + "def f(n = ContinuousSlider()):\n" + " html(n)\n" + " print n\n" + " plot(sin(x), x, 0, 2*pi).show()") .addInteract("n", 42) .addInteract("n", 13) .run(); // run("help(plot)"); // run("1+1"); // run("sin(0.5)"); // run("a + b"); // run("html(1/2)"); // run("plot(sin(x),x,0,1)"); } private Testcase test(String command) { Testcase testcase = new Testcase(server, command); server.setOnSageListener(testcase); return testcase; } // private void run(String command) { // runSerial(command); // } // private void runSerial(String command) { // ExecuteRequest request = new ExecuteRequest(command); // System.out.println(request); // LinkedList<CommandReply> reply = request.receiveReply(server.new ServerTask()); // ListIterator<CommandReply> iter = reply.listIterator(); // while (iter.hasNext()) // System.out.println(iter.next()); // System.out.println(); // } // // private void runParallel(String command) { // System.out.println("\nRunning "+command); // server.query(command); // } // // // @Override // public void onSageOutputListener(CommandOutput output) { // System.out.println("SageOutput"); // output.prettyPrint(); // } // // @Override // public void onSageReplaceOutputListener(CommandOutput output) { // System.out.println("SageReplaceOutput"); // output.prettyPrint(); // } // // static int interactChanges = 2; // // @Override // public void onSageInteractListener(Interact interact) { // // interact.prettyPrint(); // if (interactChanges-- <= 0) return; // System.out.println("changing interact"); // server.interact(interact, "n", 42); // } }
12085952-sageandroid
commandline/src/org/sagemath/commandline/Test.java
Java
gpl3
3,345
/* Javadoc style sheet */ /* Overall document style */ body { background-color:#ffffff; color:#353833; font-family:Arial, Helvetica, sans-serif; font-size:76%; margin:0; } a:link, a:visited { text-decoration:none; color:#4c6b87; } a:hover, a:focus { text-decoration:none; color:#bb7a2a; } a:active { text-decoration:none; color:#4c6b87; } a[name] { color:#353833; } a[name]:hover { text-decoration:none; color:#353833; } pre { font-size:1.3em; } h1 { font-size:1.8em; } h2 { font-size:1.5em; } h3 { font-size:1.4em; } h4 { font-size:1.3em; } h5 { font-size:1.2em; } h6 { font-size:1.1em; } ul { list-style-type:disc; } code, tt { font-size:1.2em; } dt code { font-size:1.2em; } table tr td dt code { font-size:1.2em; vertical-align:top; } sup { font-size:.6em; } /* Document title and Copyright styles */ .clear { clear:both; height:0px; overflow:hidden; } .aboutLanguage { float:right; padding:0px 21px; font-size:.8em; z-index:200; margin-top:-7px; } .legalCopy { margin-left:.5em; } .bar a, .bar a:link, .bar a:visited, .bar a:active { color:#FFFFFF; text-decoration:none; } .bar a:hover, .bar a:focus { color:#bb7a2a; } .tab { background-color:#0066FF; background-image:url(resources/titlebar.gif); background-position:left top; background-repeat:no-repeat; color:#ffffff; padding:8px; width:5em; font-weight:bold; } /* Navigation bar styles */ .bar { background-image:url(resources/background.gif); background-repeat:repeat-x; color:#FFFFFF; padding:.8em .5em .4em .8em; height:auto;/*height:1.8em;*/ font-size:1em; margin:0; } .topNav { background-image:url(resources/background.gif); background-repeat:repeat-x; color:#FFFFFF; float:left; padding:0; width:100%; clear:right; height:2.8em; padding-top:10px; overflow:hidden; } .bottomNav { margin-top:10px; background-image:url(resources/background.gif); background-repeat:repeat-x; color:#FFFFFF; float:left; padding:0; width:100%; clear:right; height:2.8em; padding-top:10px; overflow:hidden; } .subNav { background-color:#dee3e9; border-bottom:1px solid #9eadc0; float:left; width:100%; overflow:hidden; } .subNav div { clear:left; float:left; padding:0 0 5px 6px; } ul.navList, ul.subNavList { float:left; margin:0 25px 0 0; padding:0; } ul.navList li{ list-style:none; float:left; padding:3px 6px; } ul.subNavList li{ list-style:none; float:left; font-size:90%; } .topNav a:link, .topNav a:active, .topNav a:visited, .bottomNav a:link, .bottomNav a:active, .bottomNav a:visited { color:#FFFFFF; text-decoration:none; } .topNav a:hover, .bottomNav a:hover { text-decoration:none; color:#bb7a2a; } .navBarCell1Rev { background-image:url(resources/tab.gif); background-color:#a88834; color:#FFFFFF; margin: auto 5px; border:1px solid #c9aa44; } /* Page header and footer styles */ .header, .footer { clear:both; margin:0 20px; padding:5px 0 0 0; } .indexHeader { margin:10px; position:relative; } .indexHeader h1 { font-size:1.3em; } .title { color:#2c4557; margin:10px 0; } .subTitle { margin:5px 0 0 0; } .header ul { margin:0 0 25px 0; padding:0; } .footer ul { margin:20px 0 5px 0; } .header ul li, .footer ul li { list-style:none; font-size:1.2em; } /* Heading styles */ div.details ul.blockList ul.blockList ul.blockList li.blockList h4, div.details ul.blockList ul.blockList ul.blockListLast li.blockList h4 { background-color:#dee3e9; border-top:1px solid #9eadc0; border-bottom:1px solid #9eadc0; margin:0 0 6px -8px; padding:2px 5px; } ul.blockList ul.blockList ul.blockList li.blockList h3 { background-color:#dee3e9; border-top:1px solid #9eadc0; border-bottom:1px solid #9eadc0; margin:0 0 6px -8px; padding:2px 5px; } ul.blockList ul.blockList li.blockList h3 { padding:0; margin:15px 0; } ul.blockList li.blockList h2 { padding:0px 0 20px 0; } /* Page layout container styles */ .contentContainer, .sourceContainer, .classUseContainer, .serializedFormContainer, .constantValuesContainer { clear:both; padding:10px 20px; position:relative; } .indexContainer { margin:10px; position:relative; font-size:1.0em; } .indexContainer h2 { font-size:1.1em; padding:0 0 3px 0; } .indexContainer ul { margin:0; padding:0; } .indexContainer ul li { list-style:none; } .contentContainer .description dl dt, .contentContainer .details dl dt, .serializedFormContainer dl dt { font-size:1.1em; font-weight:bold; margin:10px 0 0 0; color:#4E4E4E; } .contentContainer .description dl dd, .contentContainer .details dl dd, .serializedFormContainer dl dd { margin:10px 0 10px 20px; } .serializedFormContainer dl.nameValue dt { margin-left:1px; font-size:1.1em; display:inline; font-weight:bold; } .serializedFormContainer dl.nameValue dd { margin:0 0 0 1px; font-size:1.1em; display:inline; } /* List styles */ ul.horizontal li { display:inline; font-size:0.9em; } ul.inheritance { margin:0; padding:0; } ul.inheritance li { display:inline; list-style:none; } ul.inheritance li ul.inheritance { margin-left:15px; padding-left:15px; padding-top:1px; } ul.blockList, ul.blockListLast { margin:10px 0 10px 0; padding:0; } ul.blockList li.blockList, ul.blockListLast li.blockList { list-style:none; margin-bottom:25px; } ul.blockList ul.blockList li.blockList, ul.blockList ul.blockListLast li.blockList { padding:0px 20px 5px 10px; border:1px solid #9eadc0; background-color:#f9f9f9; } ul.blockList ul.blockList ul.blockList li.blockList, ul.blockList ul.blockList ul.blockListLast li.blockList { padding:0 0 5px 8px; background-color:#ffffff; border:1px solid #9eadc0; border-top:none; } ul.blockList ul.blockList ul.blockList ul.blockList li.blockList { margin-left:0; padding-left:0; padding-bottom:15px; border:none; border-bottom:1px solid #9eadc0; } ul.blockList ul.blockList ul.blockList ul.blockList li.blockListLast { list-style:none; border-bottom:none; padding-bottom:0; } table tr td dl, table tr td dl dt, table tr td dl dd { margin-top:0; margin-bottom:1px; } /* Table styles */ .contentContainer table, .classUseContainer table, .constantValuesContainer table { border-bottom:1px solid #9eadc0; width:100%; } .contentContainer ul li table, .classUseContainer ul li table, .constantValuesContainer ul li table { width:100%; } .contentContainer .description table, .contentContainer .details table { border-bottom:none; } .contentContainer ul li table th.colOne, .contentContainer ul li table th.colFirst, .contentContainer ul li table th.colLast, .classUseContainer ul li table th, .constantValuesContainer ul li table th, .contentContainer ul li table td.colOne, .contentContainer ul li table td.colFirst, .contentContainer ul li table td.colLast, .classUseContainer ul li table td, .constantValuesContainer ul li table td{ vertical-align:top; padding-right:20px; } .contentContainer ul li table th.colLast, .classUseContainer ul li table th.colLast,.constantValuesContainer ul li table th.colLast, .contentContainer ul li table td.colLast, .classUseContainer ul li table td.colLast,.constantValuesContainer ul li table td.colLast, .contentContainer ul li table th.colOne, .classUseContainer ul li table th.colOne, .contentContainer ul li table td.colOne, .classUseContainer ul li table td.colOne { padding-right:3px; } .overviewSummary caption, .packageSummary caption, .contentContainer ul.blockList li.blockList caption, .summary caption, .classUseContainer caption, .constantValuesContainer caption { position:relative; text-align:left; background-repeat:no-repeat; color:#FFFFFF; font-weight:bold; clear:none; overflow:hidden; padding:0px; margin:0px; } caption a:link, caption a:hover, caption a:active, caption a:visited { color:#FFFFFF; } .overviewSummary caption span, .packageSummary caption span, .contentContainer ul.blockList li.blockList caption span, .summary caption span, .classUseContainer caption span, .constantValuesContainer caption span { white-space:nowrap; padding-top:8px; padding-left:8px; display:block; float:left; background-image:url(resources/titlebar.gif); height:18px; } .overviewSummary .tabEnd, .packageSummary .tabEnd, .contentContainer ul.blockList li.blockList .tabEnd, .summary .tabEnd, .classUseContainer .tabEnd, .constantValuesContainer .tabEnd { width:10px; background-image:url(resources/titlebar_end.gif); background-repeat:no-repeat; background-position:top right; position:relative; float:left; } ul.blockList ul.blockList li.blockList table { margin:0 0 12px 0px; width:100%; } .tableSubHeadingColor { background-color: #EEEEFF; } .altColor { background-color:#eeeeef; } .rowColor { background-color:#ffffff; } .overviewSummary td, .packageSummary td, .contentContainer ul.blockList li.blockList td, .summary td, .classUseContainer td, .constantValuesContainer td { text-align:left; padding:3px 3px 3px 7px; } th.colFirst, th.colLast, th.colOne, .constantValuesContainer th { background:#dee3e9; border-top:1px solid #9eadc0; border-bottom:1px solid #9eadc0; text-align:left; padding:3px 3px 3px 7px; } td.colOne a:link, td.colOne a:active, td.colOne a:visited, td.colOne a:hover, td.colFirst a:link, td.colFirst a:active, td.colFirst a:visited, td.colFirst a:hover, td.colLast a:link, td.colLast a:active, td.colLast a:visited, td.colLast a:hover, .constantValuesContainer td a:link, .constantValuesContainer td a:active, .constantValuesContainer td a:visited, .constantValuesContainer td a:hover { font-weight:bold; } td.colFirst, th.colFirst { border-left:1px solid #9eadc0; white-space:nowrap; } td.colLast, th.colLast { border-right:1px solid #9eadc0; } td.colOne, th.colOne { border-right:1px solid #9eadc0; border-left:1px solid #9eadc0; } table.overviewSummary { padding:0px; margin-left:0px; } table.overviewSummary td.colFirst, table.overviewSummary th.colFirst, table.overviewSummary td.colOne, table.overviewSummary th.colOne { width:25%; vertical-align:middle; } table.packageSummary td.colFirst, table.overviewSummary th.colFirst { width:25%; vertical-align:middle; } /* Content styles */ .description pre { margin-top:0; } .deprecatedContent { margin:0; padding:10px 0; } .docSummary { padding:0; } /* Formatting effect styles */ .sourceLineNo { color:green; padding:0 30px 0 0; } h1.hidden { visibility:hidden; overflow:hidden; font-size:.9em; } .block { display:block; margin:3px 0 0 0; } .strong { font-weight:bold; }
12085952-sageandroid
commandline/doc/stylesheet.css
CSS
gpl3
11,139
/* * HTML5 Boilerplate * * What follows is the result of much research on cross-browser styling. * Credit left inline and big thanks to Nicolas Gallagher, Jonathan Neal, * Kroc Camen, and the H5BP dev community and team. * * Detailed information about this CSS: h5bp.com/css * * ==|== normalize ========================================================== */ /* ============================================================================= HTML5 display definitions ========================================================================== */ article, aside, details, figcaption, figure, footer, header, hgroup, nav, section { display: block; } audio, canvas, video { display: inline-block; *display: inline; *zoom: 1; } audio:not([controls]) { display: none; } [hidden] { display: none; } /* ============================================================================= Base ========================================================================== */ /* * 1. Correct text resizing oddly in IE6/7 when body font-size is set using em units * 2. Prevent iOS text size adjust on device orientation change, without disabling user zoom: h5bp.com/g */ html { font-size: 100%; -webkit-text-size-adjust: 100%; -ms-text-size-adjust: 100%; } html, button, input, select, textarea { font-family: sans-serif; color: #222; } body { margin: 0; font-size: 1em; line-height: 1.4; } /* * Remove text-shadow in selection highlight: h5bp.com/i * These selection declarations have to be separate * Also: hot pink! (or customize the background color to match your design) */ ::-moz-selection { background: #fe57a1; color: #fff; text-shadow: none; } ::selection { color: #fff; text-shadow: none; background-color: #00AEEF;} /* ============================================================================= Links ========================================================================== */ a { color: #fff; text-decoration: none; } a:hover { /*color: #222222;*/ text-decoration: none; } a:visited { } a:focus { /*outline: thin dotted;*/ } /* Improve readability when focused and hovered in all browsers: h5bp.com/h */ a:hover, a:active { outline: 0; } /* ============================================================================= Typography ========================================================================== */ abbr[title] { border-bottom: 1px dotted; } b, strong { font-weight: bold; } blockquote { margin: 1em 40px; } dfn { font-style: italic; } hr { display: block; height: 1px; border: 0; border-top: 1px solid #ccc; margin: 1em 0; padding: 0; } ins { background: #ff9; color: #000; text-decoration: none; } mark { background: #ff0; color: #000; font-style: italic; font-weight: bold; } /* Redeclare monospace font family: h5bp.com/j */ pre, code, kbd, samp { font-family: monospace, serif; _font-family: 'courier new', monospace; font-size: 1em; } /* Improve readability of pre-formatted text in all browsers */ pre { white-space: pre; white-space: pre-wrap; word-wrap: break-word; } q { quotes: none; } q:before, q:after { content: ""; content: none; } small { font-size: 85%; } /* Position subscript and superscript content without affecting line-height: h5bp.com/k */ sub, sup { font-size: 75%; line-height: 0; position: relative; vertical-align: baseline; } sup { top: -0.5em; } sub { bottom: -0.25em; } /* ============================================================================= Lists ========================================================================== */ ul, ol { margin: 1em 0; padding: 0 0 0 40px; } dd { margin: 0 0 0 40px; } nav ul, nav ol { list-style: none; list-style-image: none; margin: 0; padding: 0; } /* ============================================================================= Embedded content ========================================================================== */ /* * 1. Improve image quality when scaled in IE7: h5bp.com/d * 2. Remove the gap between images and borders on image containers: h5bp.com/i/440 */ img { border: 0; -ms-interpolation-mode: bicubic; vertical-align: middle; } /* * Correct overflow not hidden in IE9 */ svg:not(:root) { overflow: hidden; } /* ============================================================================= Figures ========================================================================== */ figure { margin: 0; } /* ============================================================================= Forms ========================================================================== */ form { margin: 0; } fieldset { border: 0; margin: 0; padding: 0; } /* Indicate that 'label' will shift focus to the associated form element */ label { cursor: pointer; } /* * 1. Correct color not inheriting in IE6/7/8/9 * 2. Correct alignment displayed oddly in IE6/7 */ legend { border: 0; *margin-left: -7px; padding: 0; white-space: normal; } /* * 1. Correct font-size not inheriting in all browsers * 2. Remove margins in FF3/4 S5 Chrome * 3. Define consistent vertical alignment display in all browsers */ button, input, select, textarea { font-size: 100%; margin: 0; vertical-align: baseline; *vertical-align: middle; } /* * 1. Define line-height as normal to match FF3/4 (set using !important in the UA stylesheet) */ button, input { line-height: normal; } /* * 1. Display hand cursor for clickable form elements * 2. Allow styling of clickable form elements in iOS * 3. Correct inner spacing displayed oddly in IE7 (doesn't effect IE6) */ button, input[type="button"], input[type="reset"], input[type="submit"] { cursor: pointer; -webkit-appearance: button; *overflow: visible; } /* * Re-set default cursor for disabled elements */ button[disabled], input[disabled] { cursor: default; } /* * Consistent box sizing and appearance */ input[type="checkbox"], input[type="radio"] { box-sizing: border-box; padding: 0; *width: 13px; *height: 13px; } input[type="search"] { -webkit-appearance: textfield; -moz-box-sizing: content-box; -webkit-box-sizing: content-box; box-sizing: content-box; } input[type="search"]::-webkit-search-decoration, input[type="search"]::-webkit-search-cancel-button { -webkit-appearance: none; } /* * Remove inner padding and border in FF3/4: h5bp.com/l */ button::-moz-focus-inner, input::-moz-focus-inner { border: 0; padding: 0; } /* * 1. Remove default vertical scrollbar in IE6/7/8/9 * 2. Allow only vertical resizing */ textarea { overflow: auto; vertical-align: top; resize: vertical; } /* Colors for form validity */ input:valid, textarea:valid { } input:invalid, textarea:invalid { background-color: #f0dddd; } /* ============================================================================= Tables ========================================================================== */ table { border-collapse: collapse; border-spacing: 0; } td { vertical-align: top; } /* ============================================================================= Chrome Frame Prompt ========================================================================== */ .chromeframe { margin: 0.2em 0; background: #ccc; color: black; padding: 0.2em 0; } /* ==|== primary styles ===================================================== Author: ========================================================================== */ *{margin: 0;padding: 0} .fr{ float: right; } .fl{ float: left; } body { font-size: 14px; color: #333; font-family: Helvetica, sans-serif; margin: 0; padding: 0; -webkit-text-size-adjust: 100%; -ms-text-size-adjust: 100%; text-rendering: optimizeLegibility; -webkit-font-smoothing: antialiased; } /* ==|== media queries ====================================================== EXAMPLE Media Query for Responsive Design. This example overrides the primary ('mobile first') styles Modify as content requires. ========================================================================== */ @media only screen and (min-width: 35em) { /* Style adjustments for viewports that meet the condition */ } /* ==|== non-semantic helper classes ======================================== Please define your styles before this section. ========================================================================== */ /* For image replacement */ .ir { display: block; border: 0; text-indent: -999em; overflow: hidden; background-color: transparent; background-repeat: no-repeat; text-align: left; direction: ltr; *line-height: 0; } .ir br { display: none; } /* Hide from both screenreaders and browsers: h5bp.com/u */ .hidden { display: none !important; visibility: hidden; } /* Hide only visually, but have it available for screenreaders: h5bp.com/v */ .visuallyhidden { border: 0; clip: rect(0 0 0 0); height: 1px; margin: -1px; overflow: hidden; padding: 0; position: absolute; width: 1px; } /* Extends the .visuallyhidden class to allow the element to be focusable when navigated to via the keyboard: h5bp.com/p */ .visuallyhidden.focusable:active, .visuallyhidden.focusable:focus { clip: auto; height: auto; margin: 0; overflow: visible; position: static; width: auto; } /* Hide visually and from screenreaders, but maintain layout */ .invisible { visibility: hidden; } /* Contain floats: h5bp.com/q */ .clearfix:before, .clearfix:after { content: ""; display: table; } .clearfix:after { clear: both; } .clearfix { *zoom: 1; } /* ==|== print styles ======================================================= Print styles. Inlined to avoid required HTTP connection: h5bp.com/r ========================================================================== */ @media print { * { background: transparent !important; color: black !important; box-shadow:none !important; text-shadow: none !important; filter:none !important; -ms-filter: none !important; } /* Black prints faster: h5bp.com/s */ a, a:visited { text-decoration: underline; } a[href]:after { content: " (" attr(href) ")"; } abbr[title]:after { content: " (" attr(title) ")"; } .ir a:after, a[href^="javascript:"]:after, a[href^="#"]:after { content: ""; } /* Don't show links for images, or javascript/internal links */ pre, blockquote { border: 1px solid #999; page-break-inside: avoid; } thead { display: table-header-group; } /* h5bp.com/t */ tr, img { page-break-inside: avoid; } img { max-width: 100% !important; } @page { margin: 0.5cm; } p, h2, h3 { orphans: 3; widows: 3; } h2, h3 { page-break-after: avoid; } } /* the CSS */ body{ background-color: #f5f5f5; } body ul{ list-style: none; } #the-wrapper{ width: 980px; margin: 0 auto; background: url(img/bg.png); border-left: 1px solid #74d1f6; border-right: 1px solid #74d1f6; min-height: 1000px; } #login{ width: 260px; border: 1px solid #00aeef; border-radius: 3px; background-color: #fff; top: 200px; position: relative; margin: 0 auto; } #login-form input[type="text"], #login-form input[type="password"]{ height: 27px; width: 200px; margin: 0px 0px 18px 0px; border-radius: 3px; border: 1px solid #bbb; padding: 0px 0px 0px 15px; color: #333; outline: none; } #login-form input[type="text"]:focus, #login-form input[type="password"]:focus{ border: 1px solid #00aeef; box-shadow: 0px 0px 5px #00aeef; } #login-form input[type="submit"]{ height: 32px; padding: 0px 20px 0px 20px; background: url(img/button-bg.png); border: 1px solid #00aeef; border-radius: 3px; box-shadow: 0px 1px 1px #979797; color: #fff; text-shadow: 0px 1px #0076a3; } #login-header{ background: url(img/header-login-bg.png); border-bottom: 1px solid #00aeef; font-size: 18px; color: #fff; text-shadow: 0px 1px #0076a3; line-height: 10px; padding: 20px; } #login-contain{ padding: 20px; } #login-form input[type="submit"]:active { box-shadow: 0px -1px 1px #ddd; text-shadow: 0px -1px 1px #0076a3; } #result-contain{ margin-top: 20px; } /*index.php*/ /*header*/ #header{ position: relative; } #header-bg{ background: url(img/header-bg.png); border-bottom: 1px solid #16a4dd; height: 250px; } .avatar{ background-color: #fff; border-radius: 50%; text-align: center; border: 1px solid #04afef; box-shadow: 0px 1px 2px #005b7f; } .avatar img{ /* border-radius: 50%;*/ overflow: hidden; } #big-avatar{ padding: 4px; background-color: #fff; height: 150px; width: 150px; border-radius: 50%; text-align: center; position: absolute; border: 1px solid #04afef; top: 170px; left: 50px; box-shadow: 0px 1px 2px #005b7f; } .round{ width: 100%; height: 100%; border-radius: 50%; overflow: hidden; } #big-avatar img{ width: 150px; } #username-status{ font-size: 20px; text-shadow: 0px 1px #005B7F; color: #fff; position: absolute; top: 215px; left: 235px; } #username-status span{ display: block; height: 28px; width: 28px; } .online{ background: url(img/online.png) center no-repeat; } .offline{ background: url(img/offline.png) center no-repeat; } #header-menu-containner{ height: 33px; line-height: 33px; width: 100%; background-color: #36bef4; border-top: 1px solid #fff; color: #fff; text-shadow: 0px 1px #005B7F; border-bottom: 1px solid #16a4dd; } #header-menu-containner a{ color: #fff; text-shadow: 0px 1px #005B7F; } #header-menu{ margin: 0px; margin-left: 180px; } #header-menu li{ display: inline; padding-left: 25px; margin: 0px 15px 0 15px; } #header li.notification{ background: url("img/notification.png") left center no-repeat; } #header li.chat{ background: url("img/chat.png") left center no-repeat; } #header li.edit{ background: url("img/edit.png") left center no-repeat; } #small-avatar{ } #friend-list-containner{ height: 62px; position: absolute; right: 30px; top: 175px; } #friend-list-containner ul li{ display: inline; float: left; margin: 0px 4px 0px 4px; } #friend-list-containner ul li a div#dots{ background: url(img/dots.png) no-repeat left 35px; width: 62px; height: 62px; } #small-avatar{ width: 55px; height: 55px; padding: 2px; } #small-avatar img{ width: 55px; height: 55px; } #friend-list-containner ul li a { display: block; } #friend-list{ margin: 0px; } /*main*/ /*right-bar*/ #right-bar a{ color: #5ba1bc; } #right-bar{ color: #5ba1bc; height: 100%; background-color: #d7f1f7; } #online-list { margin: 0px; border-left: 1px solid #16a4dd; width: 230px; padding: 0px; } #online-list li { width: 230px; border-bottom: 1px solid #8bd6e7; } #user-status { width: 30px; height: 18px; } #user-info { width: 200px; } #user-online { padding: 10px 0px 10px 0px; } .username { font-weight: bold; color: #0076a3; } #main { } #user-online { padding: 10px 0px 10px 0px; } .username { font-weight: bold; color: #0076a3; } /*left main contain*/ #left-main-contain{ padding: 80px 60px 0px 50px; } .post{ border: 1px solid #00bff3; background-color: #fff; width: 600px; margin-bottom: 20px; } .post textarea{ outline: none; resize: none; border: none; width: 560px; padding: 10px 20px 10px 20px; } .post input[type="submit"]{ border: none; background-color: transparent; color: #005b7f; line-height: 35px; } .post #write-post{ position: relative; border-bottom: 1px solid #33ACDD; } .post .control{ padding: 0px 20px 0px 20px; height: 35px; background-color: #72d0f6; line-height: 35px; } .post .control-button{ display: block; height: 35px; width: 16px; margin-right: 20px; line-height: 35px; } .control-button#upload-img{ background: url(img/picture.png) no-repeat center; } .control-button#upload-file{ background: url(img/upload.png) no-repeat center; } .post-contain{ padding: 10px 20px 10px 20px; border-bottom: 1px solid #33ACDD; } .comment textarea{ } .syntaxhighlighter { background-color: white !important; } .syntaxhighlighter .line.alt1 { background-color: white !important; } .syntaxhighlighter .line.alt2 { background-color: white !important; } .syntaxhighlighter .line.highlighted.alt1, .syntaxhighlighter .line.highlighted.alt2 { background-color: #e0e0e0 !important; } .syntaxhighlighter .line.highlighted.number { color: black !important; } .syntaxhighlighter table caption { color: black !important; } .syntaxhighlighter .gutter { color: #afafaf !important; } .syntaxhighlighter .gutter .line { border-right: 3px solid #6ce26c !important; } .syntaxhighlighter .gutter .line.highlighted { background-color: #6ce26c !important; color: white !important; } .syntaxhighlighter.printing .line .content { border: none !important; } .syntaxhighlighter.collapsed { overflow: visible !important; } .syntaxhighlighter.collapsed .toolbar { color: blue !important; background: white !important; border: 1px solid #6ce26c !important; } .syntaxhighlighter.collapsed .toolbar a { color: blue !important; } .syntaxhighlighter.collapsed .toolbar a:hover { color: red !important; } .syntaxhighlighter .toolbar { color: white !important; background: #6ce26c !important; border: none !important; } .syntaxhighlighter .toolbar a { color: white !important; } .syntaxhighlighter .toolbar a:hover { color: black !important; } .syntaxhighlighter .plain, .syntaxhighlighter .plain a { color: black !important; } .syntaxhighlighter .comments, .syntaxhighlighter .comments a { color: #008200 !important; } .syntaxhighlighter .string, .syntaxhighlighter .string a { color: blue !important; } .syntaxhighlighter .keyword { color: #006699 !important; } .syntaxhighlighter .preprocessor { color: gray !important; } .syntaxhighlighter .variable { color: #aa7700 !important; } .syntaxhighlighter .value { color: #009900 !important; } .syntaxhighlighter .functions { color: #ff1493 !important; } .syntaxhighlighter .constants { color: #0066cc !important; } .syntaxhighlighter .script { font-weight: bold !important; color: #006699 !important; background-color: none !important; } .syntaxhighlighter .color1, .syntaxhighlighter .color1 a { color: gray !important; } .syntaxhighlighter .color2, .syntaxhighlighter .color2 a { color: #ff1493 !important; } .syntaxhighlighter .color3, .syntaxhighlighter .color3 a { color: red !important; } .syntaxhighlighter .keyword { font-weight: bold !important; } .code-view { max-height: 300px; position: relative; } /*! fancyBox v2.1.0 fancyapps.com | fancyapps.com/fancybox/#license */ .fancybox-wrap, .fancybox-skin, .fancybox-outer, .fancybox-inner, .fancybox-image, .fancybox-wrap iframe, .fancybox-wrap object, .fancybox-nav, .fancybox-nav span, .fancybox-tmp { padding: 0; margin: 0; border: 0; outline: none; vertical-align: top; } .fancybox-wrap { position: absolute; top: 0; left: 0; z-index: 8020; } .fancybox-skin { position: relative; background: #fff; color: #444; text-shadow: none; -webkit-border-radius: 1px; -moz-border-radius: 1px; border-radius: 1px; } .fancybox-opened { z-index: 8030; } .fancybox-opened .fancybox-skin { -webkit-box-shadow: 0 0px 5px #999898; -moz-box-shadow: 0 0px 5px #999898; box-shadow: 0 0px 5px #999898; } .fancybox-outer, .fancybox-inner { position: relative; } .fancybox-inner { overflow: hidden; } .fancybox-type-iframe .fancybox-inner { -webkit-overflow-scrolling: touch; } .fancybox-error { color: #444; font: 14px/20px "Helvetica Neue",Helvetica,Arial,sans-serif; margin: 0; padding: 15px; white-space: nowrap; } .fancybox-image, .fancybox-iframe { display: block; width: 100%; height: 100%; } .fancybox-image { max-width: 100%; max-height: 100%; } #fancybox-loading, .fancybox-close, .fancybox-prev span, .fancybox-next span { background-image: url('fancybox_sprite.png'); } #fancybox-loading { position: fixed; top: 50%; left: 50%; margin-top: -22px; margin-left: -22px; background-position: 0 -108px; opacity: 0.8; cursor: pointer; z-index: 8060; } #fancybox-loading div { width: 44px; height: 44px; background: url('fancybox_loading.gif') center center no-repeat; } .fancybox-close { position: absolute; top: -18px; right: -18px; width: 36px; height: 36px; cursor: pointer; z-index: 8040; } .fancybox-nav { position: absolute; top: 0; width: 40%; height: 100%; cursor: pointer; text-decoration: none; background: transparent url('blank.gif'); /* helps IE */ -webkit-tap-highlight-color: rgba(0,0,0,0); z-index: 8040; } .fancybox-prev { left: 0; } .fancybox-next { right: 0; } .fancybox-nav span { position: absolute; top: 50%; width: 36px; height: 34px; margin-top: -18px; cursor: pointer; z-index: 8040; visibility: hidden; } .fancybox-prev span { left: 10px; background-position: 0 -36px; } .fancybox-next span { right: 10px; background-position: 0 -72px; } .fancybox-nav:hover span { visibility: visible; } .fancybox-tmp { position: absolute; top: -9999px; left: -9999px; visibility: hidden; } /* Overlay helper */ .fancybox-lock { overflow: hidden; } .fancybox-overlay { position: absolute; top: 0; left: 0; overflow: hidden; display: none; z-index: 8010; background: url('../img/fancy-bg.png'); } .fancybox-overlay-fixed { position: fixed; bottom: 0; right: 0; } .fancybox-lock .fancybox-overlay { overflow: auto; overflow-y: scroll; } /* Title helper */ .fancybox-title { visibility: hidden; font: normal 13px/20px "Helvetica Neue",Helvetica,Arial,sans-serif; position: relative; text-shadow: none; z-index: 8050; } .fancybox-opened .fancybox-title { visibility: visible; } .fancybox-title-float-wrap { position: absolute; bottom: 0; right: 50%; margin-bottom: -35px; z-index: 8050; text-align: center; } .fancybox-title-float-wrap .child { display: inline-block; margin-right: -100%; padding: 2px 20px; background: transparent; /* Fallback for web browsers that doesn't support RGBa */ background: rgba(0, 0, 0, 0.8); -webkit-border-radius: 15px; -moz-border-radius: 15px; border-radius: 15px; text-shadow: 0 1px 2px #222; color: #FFF; font-weight: bold; line-height: 24px; white-space: nowrap; } .fancybox-title-outside-wrap { position: relative; margin-top: 10px; color: #fff; } .fancybox-title-inside-wrap { padding-top: 10px; } .fancybox-title-over-wrap { position: absolute; bottom: 0; left: 0; color: #fff; padding: 10px; background: #000; background: rgba(0, 0, 0, .8); } .fancybox-item.fancybox-close { background: url(./img/fancy-close.png) no-repeat center; }
11hca1-java-web
trunk/web/style.css
CSS
gpl3
22,629
<%-- Document : index Created on : Sep 7, 2012, 11:49:06 AM Author : 4pril --%> <%@page contentType="text/html" pageEncoding="UTF-8"%> <%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core"%> <!doctype html> <!-- paulirish.com/2008/conditional-stylesheets-vs-css-hacks-answer-neither/ --> <!--[if lt IE 7]> <html class="no-js lt-ie9 lt-ie8 lt-ie7" lang="en"> <![endif]--> <!--[if IE 7]> <html class="no-js lt-ie9 lt-ie8" lang="en"> <![endif]--> <!--[if IE 8]> <html class="no-js lt-ie9" lang="en"> <![endif]--> <!-- Consider adding a manifest.appcache: h5bp.com/d/Offline --> <!--[if gt IE 8]><!--> <html class="no-js" lang="en"> <!--<![endif]--> <head> <meta charset="utf-8"> <!-- Use the .htaccess and remove these lines to avoid edge case issues. More info: h5bp.com/i/378 --> <meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1"> <title><c:out value="${sessionScope.currentUser.getUsername()}" /></title> <meta name="description" content=""> <!-- Mobile viewport optimized: h5bp.com/viewport --> <meta name="viewport" content="width=device-width"> <!-- Place favicon.ico and apple-touch-icon.png in the root directory: mathiasbynens.be/notes/touch-icons --> <!-- <link rel="stylesheet" type="text/css" href="http://fonts.googleapis.com/css?family=Helvetica World"> --> <link rel="stylesheet" href="style.css"> <!-- More ideas for your <head> here: h5bp.com/d/head-Tips --> <!-- All JavaScript at the bottom, except this Modernizr build. Modernizr enables HTML5 elements & feature detects for optimal performance. Create your own custom Modernizr build: www.modernizr.com/download/ --> <script src="js/libs/modernizr-2.5.3.min.js"></script> </head> <body> <!-- Prompt IE 6 users to install Chrome Frame. Remove this if you support IE 6. chromium.org/developers/how-tos/chrome-frame-getting-started --> <!--[if lt IE 7]><p class=chromeframe>Your browser is <em>ancient!</em> <a href="http://browsehappy.com/">Upgrade to a different browser</a> or <a href="http://www.google.com/chromeframe/?redirect=true">install Google Chrome Frame</a> to experience this site.</p><![endif]--> <!-- Begin wrapper --> <div id="the-wrapper"> <!-- Begin header --> <div id="header"> <!-- Begin header-bg --> <div id="header-bg"> <!-- Begin friend-list-containner --> <div id="friend-list-containner"> <ul id="friend-list" class="clearfix"> <li><a href="#"> <div id="small-avatar" class="avatar"> <div class="round"> <img src="img/small-avatar-1.png" alt=""> </div> </div> </a></li> <li><a href="#"> <div id="small-avatar" class="avatar"> <div class="round"> <img src="img/small-avatar-2.png" alt=""> </div> </div> </a></li> <li><a href="#"> <div id="small-avatar" class="avatar"> <div class="round"> <img src="img/small-avatar-3.png" alt=""> </div> </div> </a></li> <li><a href="#"> <div id="small-avatar" class="avatar"> <div class="round"> <img src="img/small-avatar-4.png" alt=""> </div> </div> </a></li> <li><a href="#"> <div id="dots"></div> </a></li> </ul> </div> <!-- End friend-list-containner --> <!-- Begin big-avatar --> <div id="big-avatar" class="avatar"> <div class="round"> <!-- <a href="#"><img src="img/big-avatar-img.png" alt="" /></a> --> <a href="#"><img src="img/photo.jpg" alt="" /></a> </div> </div> <!-- End big-avatar --> <!-- Begin username and status --> <div id="username-status" class="clearfix"> <a href="#"><p class="fl"><c:out value="${sessionScope.currentUser.getUserRealName()}" /></p></a> <span class="online fr"></span> </div> <!-- End username status --> </div> <!-- End header-bg --> <!-- Begin header-menu-containner --> <div id="header-menu-containner"> <ul id="header-menu"> <a href="#"><li class="notification">27</li></a> <a href="#"><li class="chat">4</li></a> <a href="#"><li class="edit">90</li></a> </ul> </div> <!-- End header-menu-containner --> </div> <!-- End header --> <!-- Begin main --> <div id="main" class="clearfix"> <div id="right-bar" class="fr"> <!-- ul#online-list>a[href='']*3>li>div#user-online.clearfix[user-id='']>div#user-status.fl --> <!-- Begin online-list --> <ul id="online-list"> <a href="#"> <li> <div id="user-online" class="clearfix" user-id=""> <div id="user-status" class="fl online"></div> <div id="user-info" class="fr"> <p class="username">Đặng Tài</p> <p class="last-post">Đang làm bài</p> </div> </div> </li> </a> <a href="#"> <li> <div id="user-online" class="clearfix" user-id=""> <div id="user-status" class="fl online"></div> <div id="user-info" class="fr"> <p class="username">Hoàng Thùy</p> <p class="last-post">Đang bực đấy</p> </div> </div> </li> </a> <a href="#"> <li> <div id="user-online" class="clearfix" user-id=""> <div id="user-status" class="fl offline"></div> <div id="user-info" class="fr"> <p class="username">Ngọc Hân</p> <p class="last-post">Miss...</p> </div> </div> </li> </a> </ul> <!-- End online-list --> </div> <!-- End right-bar --> <!-- Begin left-main-contain --> <div id="left-main-contain" class="fl"> <!-- Begin post --> <div class="post"> <form action=""> <!-- Begin write-post --> <div id="write-post"> <textarea rows="3"></textarea> </div> <!-- End write-post --> <div class="control clearfix"> <a href="#" class="control-button fl" id="upload-img"></a> <a href="#" class="control-button fl" id="upload-file"></a> <input type="submit" value="Đăng" class="fr" /> </div> </form> </div> <!-- End post --> <!-- Begin post --> <div class="post"> <form action=""> <!-- Begin post-contain --> <div class="post-contain" post-id=""> <p class="username">Triệu Khang</p> <!-- begin post code --> <div class="code-view"> <script type="syntaxhighlighter" class="brush: java;"><![CDATA[ <p>Sai gì nhỉ</p> </div> <!-- End post-contain --> <!-- Begin post-contain --> <div class="post-contain" post-id=""> <p class="username">Triệu Khang</p> <p>abc</p> </div> ]]></script> </div> <!-- end post code --> <p>Sai gì nhỉ</p> </div> <!-- End post-contain --> <!-- Begin post-contain --> <div class="post-contain" post-id=""> <p class="username">Triệu Khang</p> <p>abc</p> </div> <!-- End post-contain --> <!-- Begin post-contain --> <div class="post-contain" post-id=""> <p class="username">Triệu Khang</p> <p>abc</p> </div> <!-- End post-contain --> <!-- Begin write-post --> <!-- <div id="write-post" class="comment"> <textarea></textarea> </div> --> <!-- End write-post --> <div class="control clearfix"> <!-- <a href="#" class="control-button fl" id="upload-img"></a> <a href="#" class="control-button fl" id="upload-file"></a> --> <input type="submit" value="Bình luận" class="fr" /> </div> </form> </div> <!-- End post --> <!-- Begin post --> <div class="post"> <form action=""> <!-- Begin post-contain --> <div class="post-contain" post-id=""> <p class="username">Triệu Khang</p> <!-- begin post code --> <div class="code-view"> <script type="syntaxhighlighter" class="brush: java;"><![CDATA[ <p>Sai gì nhỉ</p> </div> <!-- End post-contain --> <!-- Begin post-contain --> <div class="post-contain" post-id=""> <p class="username">Triệu Khang</p> <p>abc</p> </div> ]]></script> </div> <!-- end post code --> <p>Sai gì nhỉ</p> </div> <!-- End post-contain --> <!-- Begin post-contain --> <div class="post-contain" post-id=""> <p class="username">Triệu Khang</p> <p>abc</p> </div> <!-- End post-contain --> <!-- Begin post-contain --> <div class="post-contain" post-id=""> <p class="username">Triệu Khang</p> <p>abc</p> </div> <!-- End post-contain --> <!-- Begin write-post --> <!-- <div id="write-post" class="comment"> <textarea></textarea> </div> --> <!-- End write-post --> <div class="control clearfix"> <!-- <a href="#" class="control-button fl" id="upload-img"></a> <a href="#" class="control-button fl" id="upload-file"></a> --> <input type="submit" value="Bình luận" class="fr" /> </div> </form> </div> <!-- End post --> </div> <!-- End left-main-contain --> </div> <!-- End main --> </div> <!-- End wrapper --> <!-- JavaScript at the bottom for fast page loading --> <!-- Grab Google CDN's jQuery, with a protocol relative URL; fall back to local if offline --> <!--<script src="//ajax.googleapis.com/ajax/libs/jquery/1.7.1/jquery.min.js"></script>--> <script>window.jQuery || document.write('<script src="js/libs/jquery-1.7.1.min.js"><\/script>')</script> <!-- install SyntaxHighlighter --> <script type="text/javascript" src="js/libs/sh/XRegExp.js"></script> <!-- XRegExp is bundled with the final shCore.js during build --> <script type="text/javascript" src="js/libs/sh/shCore.js"></script> <script type="text/javascript" src="js/libs/sh/shBrushJScript.js"></script> <script type="text/javascript" src="js/libs/sh/shBrushJava.js"></script> <link type="text/css" rel="stylesheet" href="css/shCore.css"/> <link type="text/css" rel="Stylesheet" href="css/shThemeDefault.css" /> <script type="text/javascript">SyntaxHighlighter.all();</script> <!-- end SyntaxHighlighter --> <!-- Add fancyBox main JS and CSS files --> <!-- end scripts --> <!-- Asynchronous Google Analytics snippet. Change UA-XXXXX-X to be your site's ID. mathiasbynens.be/notes/async-analytics-snippet --> <script> // var _gaq=[['_setAccount','UA-33896517-1'],['_trackPageview']]; // (function(d,t){var g=d.createElement(t),s=d.getElementsByTagName(t)[0]; // g.src=('https:'==location.protocol?'//ssl':'//www')+'.google-analytics.com/ga.js'; // s.parentNode.insertBefore(g,s)}(document,'script')); </script> </body> </html>
11hca1-java-web
trunk/web/index.jsp
Java Server Pages
gpl3
12,508
// usage: log('inside coolFunc', this, arguments); // paulirish.com/2009/log-a-lightweight-wrapper-for-consolelog/ window.log = function f(){ log.history = log.history || []; log.history.push(arguments); if(this.console) { var args = arguments, newarr; args.callee = args.callee.caller; newarr = [].slice.call(args); if (typeof console.log === 'object') log.apply.call(console.log, console, newarr); else console.log.apply(console, newarr);}}; // make it safe to use console.log always (function(a){function b(){}for(var c="assert,count,debug,dir,dirxml,error,exception,group,groupCollapsed,groupEnd,info,log,markTimeline,profile,profileEnd,time,timeEnd,trace,warn".split(","),d;!!(d=c.pop());){a[d]=a[d]||b;}}) (function(){try{console.log();return window.console;}catch(a){return (window.console={});}}()); // place any jQuery/helper plugins in here, instead of separate, slower script files.
11hca1-java-web
trunk/web/js/plugins.js
JavaScript
gpl3
898
/* * To change this template, choose Tools | Templates * and open the template in the editor. */ /* * Function from : * http://trentgardner.net/jquery/serialize-json-with-jquery/ */ (function( $ ){ $.fn.serializeJSON=function() { var json = {}; jQuery.map($(this).serializeArray(), function(n, i){ json[n['name']] = n['value']; }); return json; }; })( jQuery ); $(function(){ $("input[type='password']").focus(function(){ $(this).val(''); }) $("input[type='text']").focus(function(){ $(this).val(''); }) function checkUser(){ //lay gia tri var username = $("input[name=username]").val(); var password = $("input[name=password]").val(); if( username == "" || password == "" ){ $("#result").html("").append("<p>ID và password không hợp lệ.</p>"); $("#result p").fadeOut(3000); return false; } return true; } $("input[name='login-button']").click(function(){ //chan su kien submit event.preventDefault(); $("#result").append('<div style="width:100%; text-align:center"><img src="img/loading.gif" /></div>'); // console.log($("#result")); if(!checkUser()){ return; } data = {data : JSON.stringify($("form").serializeJSON())}; console.log(data); if(data){ $.post('ajax_login', data, function(response) { //console.log(data); console.log(response); // response = jQuery.parseJSON(response); //console.log(response); //neu chuoi tra ve la true if( response.result == true){ $("form").fadeOut(500,function(){ //$("div#login").append("<h2 style='color:#454545;text-shadow: 0px 1px 1px #f5f5f5;'>Chào bạn " + response["user"] + "</h2>"); //redirect window.location.replace(response["url"]); }); }else{ $("#result").html("").append("<p>Người dùng không tồn tại hoặc sai mật khẩu.</p>"); $("#result p").fadeOut(3000); } console.log(result); }); } }); $("input[name='register-button']").bind('click', function(){ //chan su kien submit event.preventDefault(); if(!checkUser()){ return; } $("#result").append('<div style="width:100%; text-align:center"><img src="img/loading.gif" /></div>'); data = {data : JSON.stringify($("form").serializeJSON())}; //console.log(data); if(data){ $.post('ajax_register', data, function(response) { console.log(response); //response = jQuery.parseJSON(response); console.log(response); //neu chuoi tra ve la true if( response.result == true){ $("#result").html("").append("<p>Đăng ký thành công.</p>"); $("#result p").fadeOut(3000); }else{ $("#result").html("").append("<p>Người dùng đã tồn tại.</p>"); $("#result p").fadeOut(3000); } }); } }); }); $(function(){ $('.fancybox').fancybox({ 'onComplete': function() { $(".fancybox-wrap").css({'top':'20px', 'bottom':'auto'}); } }); })
11hca1-java-web
trunk/web/js/myScript.js
JavaScript
gpl3
4,120
// XRegExp 1.5.1 // (c) 2007-2012 Steven Levithan // MIT License // <http://xregexp.com> // Provides an augmented, extensible, cross-browser implementation of regular expressions, // including support for additional syntax, flags, and methods var XRegExp; if (XRegExp) { // Avoid running twice, since that would break references to native globals throw Error("can't load XRegExp twice in the same frame"); } // Run within an anonymous function to protect variables and avoid new globals (function (undefined) { //--------------------------------- // Constructor //--------------------------------- // Accepts a pattern and flags; returns a new, extended `RegExp` object. Differs from a native // regular expression in that additional syntax and flags are supported and cross-browser // syntax inconsistencies are ameliorated. `XRegExp(/regex/)` clones an existing regex and // converts to type XRegExp XRegExp = function (pattern, flags) { var output = [], currScope = XRegExp.OUTSIDE_CLASS, pos = 0, context, tokenResult, match, chr, regex; if (XRegExp.isRegExp(pattern)) { if (flags !== undefined) throw TypeError("can't supply flags when constructing one RegExp from another"); return clone(pattern); } // Tokens become part of the regex construction process, so protect against infinite // recursion when an XRegExp is constructed within a token handler or trigger if (isInsideConstructor) throw Error("can't call the XRegExp constructor within token definition functions"); flags = flags || ""; context = { // `this` object for custom tokens hasNamedCapture: false, captureNames: [], hasFlag: function (flag) {return flags.indexOf(flag) > -1;}, setFlag: function (flag) {flags += flag;} }; while (pos < pattern.length) { // Check for custom tokens at the current position tokenResult = runTokens(pattern, pos, currScope, context); if (tokenResult) { output.push(tokenResult.output); pos += (tokenResult.match[0].length || 1); } else { // Check for native multicharacter metasequences (excluding character classes) at // the current position if (match = nativ.exec.call(nativeTokens[currScope], pattern.slice(pos))) { output.push(match[0]); pos += match[0].length; } else { chr = pattern.charAt(pos); if (chr === "[") currScope = XRegExp.INSIDE_CLASS; else if (chr === "]") currScope = XRegExp.OUTSIDE_CLASS; // Advance position one character output.push(chr); pos++; } } } regex = RegExp(output.join(""), nativ.replace.call(flags, flagClip, "")); regex._xregexp = { source: pattern, captureNames: context.hasNamedCapture ? context.captureNames : null }; return regex; }; //--------------------------------- // Public properties //--------------------------------- XRegExp.version = "1.5.1"; // Token scope bitflags XRegExp.INSIDE_CLASS = 1; XRegExp.OUTSIDE_CLASS = 2; //--------------------------------- // Private variables //--------------------------------- var replacementToken = /\$(?:(\d\d?|[$&`'])|{([$\w]+)})/g, flagClip = /[^gimy]+|([\s\S])(?=[\s\S]*\1)/g, // Nonnative and duplicate flags quantifier = /^(?:[?*+]|{\d+(?:,\d*)?})\??/, isInsideConstructor = false, tokens = [], // Copy native globals for reference ("native" is an ES3 reserved keyword) nativ = { exec: RegExp.prototype.exec, test: RegExp.prototype.test, match: String.prototype.match, replace: String.prototype.replace, split: String.prototype.split }, compliantExecNpcg = nativ.exec.call(/()??/, "")[1] === undefined, // check `exec` handling of nonparticipating capturing groups compliantLastIndexIncrement = function () { var x = /^/g; nativ.test.call(x, ""); return !x.lastIndex; }(), hasNativeY = RegExp.prototype.sticky !== undefined, nativeTokens = {}; // `nativeTokens` match native multicharacter metasequences only (including deprecated octals, // excluding character classes) nativeTokens[XRegExp.INSIDE_CLASS] = /^(?:\\(?:[0-3][0-7]{0,2}|[4-7][0-7]?|x[\dA-Fa-f]{2}|u[\dA-Fa-f]{4}|c[A-Za-z]|[\s\S]))/; nativeTokens[XRegExp.OUTSIDE_CLASS] = /^(?:\\(?:0(?:[0-3][0-7]{0,2}|[4-7][0-7]?)?|[1-9]\d*|x[\dA-Fa-f]{2}|u[\dA-Fa-f]{4}|c[A-Za-z]|[\s\S])|\(\?[:=!]|[?*+]\?|{\d+(?:,\d*)?}\??)/; //--------------------------------- // Public methods //--------------------------------- // Lets you extend or change XRegExp syntax and create custom flags. This is used internally by // the XRegExp library and can be used to create XRegExp plugins. This function is intended for // users with advanced knowledge of JavaScript's regular expression syntax and behavior. It can // be disabled by `XRegExp.freezeTokens` XRegExp.addToken = function (regex, handler, scope, trigger) { tokens.push({ pattern: clone(regex, "g" + (hasNativeY ? "y" : "")), handler: handler, scope: scope || XRegExp.OUTSIDE_CLASS, trigger: trigger || null }); }; // Accepts a pattern and flags; returns an extended `RegExp` object. If the pattern and flag // combination has previously been cached, the cached copy is returned; otherwise the newly // created regex is cached XRegExp.cache = function (pattern, flags) { var key = pattern + "/" + (flags || ""); return XRegExp.cache[key] || (XRegExp.cache[key] = XRegExp(pattern, flags)); }; // Accepts a `RegExp` instance; returns a copy with the `/g` flag set. The copy has a fresh // `lastIndex` (set to zero). If you want to copy a regex without forcing the `global` // property, use `XRegExp(regex)`. Do not use `RegExp(regex)` because it will not preserve // special properties required for named capture XRegExp.copyAsGlobal = function (regex) { return clone(regex, "g"); }; // Accepts a string; returns the string with regex metacharacters escaped. The returned string // can safely be used at any point within a regex to match the provided literal string. Escaped // characters are [ ] { } ( ) * + ? - . , \ ^ $ | # and whitespace XRegExp.escape = function (str) { return str.replace(/[-[\]{}()*+?.,\\^$|#\s]/g, "\\$&"); }; // Accepts a string to search, regex to search with, position to start the search within the // string (default: 0), and an optional Boolean indicating whether matches must start at-or- // after the position or at the specified position only. This function ignores the `lastIndex` // of the provided regex in its own handling, but updates the property for compatibility XRegExp.execAt = function (str, regex, pos, anchored) { var r2 = clone(regex, "g" + ((anchored && hasNativeY) ? "y" : "")), match; r2.lastIndex = pos = pos || 0; match = r2.exec(str); // Run the altered `exec` (required for `lastIndex` fix, etc.) if (anchored && match && match.index !== pos) match = null; if (regex.global) regex.lastIndex = match ? r2.lastIndex : 0; return match; }; // Breaks the unrestorable link to XRegExp's private list of tokens, thereby preventing // syntax and flag changes. Should be run after XRegExp and any plugins are loaded XRegExp.freezeTokens = function () { XRegExp.addToken = function () { throw Error("can't run addToken after freezeTokens"); }; }; // Accepts any value; returns a Boolean indicating whether the argument is a `RegExp` object. // Note that this is also `true` for regex literals and regexes created by the `XRegExp` // constructor. This works correctly for variables created in another frame, when `instanceof` // and `constructor` checks would fail to work as intended XRegExp.isRegExp = function (o) { return Object.prototype.toString.call(o) === "[object RegExp]"; }; // Executes `callback` once per match within `str`. Provides a simpler and cleaner way to // iterate over regex matches compared to the traditional approaches of subverting // `String.prototype.replace` or repeatedly calling `exec` within a `while` loop XRegExp.iterate = function (str, regex, callback, context) { var r2 = clone(regex, "g"), i = -1, match; while (match = r2.exec(str)) { // Run the altered `exec` (required for `lastIndex` fix, etc.) if (regex.global) regex.lastIndex = r2.lastIndex; // Doing this to follow expectations if `lastIndex` is checked within `callback` callback.call(context, match, ++i, str, regex); if (r2.lastIndex === match.index) r2.lastIndex++; } if (regex.global) regex.lastIndex = 0; }; // Accepts a string and an array of regexes; returns the result of using each successive regex // to search within the matches of the previous regex. The array of regexes can also contain // objects with `regex` and `backref` properties, in which case the named or numbered back- // references specified are passed forward to the next regex or returned. E.g.: // var xregexpImgFileNames = XRegExp.matchChain(html, [ // {regex: /<img\b([^>]+)>/i, backref: 1}, // <img> tag attributes // {regex: XRegExp('(?ix) \\s src=" (?<src> [^"]+ )'), backref: "src"}, // src attribute values // {regex: XRegExp("^http://xregexp\\.com(/[^#?]+)", "i"), backref: 1}, // xregexp.com paths // /[^\/]+$/ // filenames (strip directory paths) // ]); XRegExp.matchChain = function (str, chain) { return function recurseChain (values, level) { var item = chain[level].regex ? chain[level] : {regex: chain[level]}, regex = clone(item.regex, "g"), matches = [], i; for (i = 0; i < values.length; i++) { XRegExp.iterate(values[i], regex, function (match) { matches.push(item.backref ? (match[item.backref] || "") : match[0]); }); } return ((level === chain.length - 1) || !matches.length) ? matches : recurseChain(matches, level + 1); }([str], 0); }; //--------------------------------- // New RegExp prototype methods //--------------------------------- // Accepts a context object and arguments array; returns the result of calling `exec` with the // first value in the arguments array. the context is ignored but is accepted for congruity // with `Function.prototype.apply` RegExp.prototype.apply = function (context, args) { return this.exec(args[0]); }; // Accepts a context object and string; returns the result of calling `exec` with the provided // string. the context is ignored but is accepted for congruity with `Function.prototype.call` RegExp.prototype.call = function (context, str) { return this.exec(str); }; //--------------------------------- // Overriden native methods //--------------------------------- // Adds named capture support (with backreferences returned as `result.name`), and fixes two // cross-browser issues per ES3: // - Captured values for nonparticipating capturing groups should be returned as `undefined`, // rather than the empty string. // - `lastIndex` should not be incremented after zero-length matches. RegExp.prototype.exec = function (str) { var match, name, r2, origLastIndex; if (!this.global) origLastIndex = this.lastIndex; match = nativ.exec.apply(this, arguments); if (match) { // Fix browsers whose `exec` methods don't consistently return `undefined` for // nonparticipating capturing groups if (!compliantExecNpcg && match.length > 1 && indexOf(match, "") > -1) { r2 = RegExp(this.source, nativ.replace.call(getNativeFlags(this), "g", "")); // Using `str.slice(match.index)` rather than `match[0]` in case lookahead allowed // matching due to characters outside the match nativ.replace.call((str + "").slice(match.index), r2, function () { for (var i = 1; i < arguments.length - 2; i++) { if (arguments[i] === undefined) match[i] = undefined; } }); } // Attach named capture properties if (this._xregexp && this._xregexp.captureNames) { for (var i = 1; i < match.length; i++) { name = this._xregexp.captureNames[i - 1]; if (name) match[name] = match[i]; } } // Fix browsers that increment `lastIndex` after zero-length matches if (!compliantLastIndexIncrement && this.global && !match[0].length && (this.lastIndex > match.index)) this.lastIndex--; } if (!this.global) this.lastIndex = origLastIndex; // Fix IE, Opera bug (last tested IE 9.0.5, Opera 11.61 on Windows) return match; }; // Fix browser bugs in native method RegExp.prototype.test = function (str) { // Use the native `exec` to skip some processing overhead, even though the altered // `exec` would take care of the `lastIndex` fixes var match, origLastIndex; if (!this.global) origLastIndex = this.lastIndex; match = nativ.exec.call(this, str); // Fix browsers that increment `lastIndex` after zero-length matches if (match && !compliantLastIndexIncrement && this.global && !match[0].length && (this.lastIndex > match.index)) this.lastIndex--; if (!this.global) this.lastIndex = origLastIndex; // Fix IE, Opera bug (last tested IE 9.0.5, Opera 11.61 on Windows) return !!match; }; // Adds named capture support and fixes browser bugs in native method String.prototype.match = function (regex) { if (!XRegExp.isRegExp(regex)) regex = RegExp(regex); // Native `RegExp` if (regex.global) { var result = nativ.match.apply(this, arguments); regex.lastIndex = 0; // Fix IE bug return result; } return regex.exec(this); // Run the altered `exec` }; // Adds support for `${n}` tokens for named and numbered backreferences in replacement text, // and provides named backreferences to replacement functions as `arguments[0].name`. Also // fixes cross-browser differences in replacement text syntax when performing a replacement // using a nonregex search value, and the value of replacement regexes' `lastIndex` property // during replacement iterations. Note that this doesn't support SpiderMonkey's proprietary // third (`flags`) parameter String.prototype.replace = function (search, replacement) { var isRegex = XRegExp.isRegExp(search), captureNames, result, str, origLastIndex; // There are too many combinations of search/replacement types/values and browser bugs that // preclude passing to native `replace`, so don't try //if (...) // return nativ.replace.apply(this, arguments); if (isRegex) { if (search._xregexp) captureNames = search._xregexp.captureNames; // Array or `null` if (!search.global) origLastIndex = search.lastIndex; } else { search = search + ""; // Type conversion } if (Object.prototype.toString.call(replacement) === "[object Function]") { result = nativ.replace.call(this + "", search, function () { if (captureNames) { // Change the `arguments[0]` string primitive to a String object which can store properties arguments[0] = new String(arguments[0]); // Store named backreferences on `arguments[0]` for (var i = 0; i < captureNames.length; i++) { if (captureNames[i]) arguments[0][captureNames[i]] = arguments[i + 1]; } } // Update `lastIndex` before calling `replacement` (fix browsers) if (isRegex && search.global) search.lastIndex = arguments[arguments.length - 2] + arguments[0].length; return replacement.apply(null, arguments); }); } else { str = this + ""; // Type conversion, so `args[args.length - 1]` will be a string (given nonstring `this`) result = nativ.replace.call(str, search, function () { var args = arguments; // Keep this function's `arguments` available through closure return nativ.replace.call(replacement + "", replacementToken, function ($0, $1, $2) { // Numbered backreference (without delimiters) or special variable if ($1) { switch ($1) { case "$": return "$"; case "&": return args[0]; case "`": return args[args.length - 1].slice(0, args[args.length - 2]); case "'": return args[args.length - 1].slice(args[args.length - 2] + args[0].length); // Numbered backreference default: // What does "$10" mean? // - Backreference 10, if 10 or more capturing groups exist // - Backreference 1 followed by "0", if 1-9 capturing groups exist // - Otherwise, it's the string "$10" // Also note: // - Backreferences cannot be more than two digits (enforced by `replacementToken`) // - "$01" is equivalent to "$1" if a capturing group exists, otherwise it's the string "$01" // - There is no "$0" token ("$&" is the entire match) var literalNumbers = ""; $1 = +$1; // Type conversion; drop leading zero if (!$1) // `$1` was "0" or "00" return $0; while ($1 > args.length - 3) { literalNumbers = String.prototype.slice.call($1, -1) + literalNumbers; $1 = Math.floor($1 / 10); // Drop the last digit } return ($1 ? args[$1] || "" : "$") + literalNumbers; } // Named backreference or delimited numbered backreference } else { // What does "${n}" mean? // - Backreference to numbered capture n. Two differences from "$n": // - n can be more than two digits // - Backreference 0 is allowed, and is the entire match // - Backreference to named capture n, if it exists and is not a number overridden by numbered capture // - Otherwise, it's the string "${n}" var n = +$2; // Type conversion; drop leading zeros if (n <= args.length - 3) return args[n]; n = captureNames ? indexOf(captureNames, $2) : -1; return n > -1 ? args[n + 1] : $0; } }); }); } if (isRegex) { if (search.global) search.lastIndex = 0; // Fix IE, Safari bug (last tested IE 9.0.5, Safari 5.1.2 on Windows) else search.lastIndex = origLastIndex; // Fix IE, Opera bug (last tested IE 9.0.5, Opera 11.61 on Windows) } return result; }; // A consistent cross-browser, ES3 compliant `split` String.prototype.split = function (s /* separator */, limit) { // If separator `s` is not a regex, use the native `split` if (!XRegExp.isRegExp(s)) return nativ.split.apply(this, arguments); var str = this + "", // Type conversion output = [], lastLastIndex = 0, match, lastLength; // Behavior for `limit`: if it's... // - `undefined`: No limit // - `NaN` or zero: Return an empty array // - A positive number: Use `Math.floor(limit)` // - A negative number: No limit // - Other: Type-convert, then use the above rules if (limit === undefined || +limit < 0) { limit = Infinity; } else { limit = Math.floor(+limit); if (!limit) return []; } // This is required if not `s.global`, and it avoids needing to set `s.lastIndex` to zero // and restore it to its original value when we're done using the regex s = XRegExp.copyAsGlobal(s); while (match = s.exec(str)) { // Run the altered `exec` (required for `lastIndex` fix, etc.) if (s.lastIndex > lastLastIndex) { output.push(str.slice(lastLastIndex, match.index)); if (match.length > 1 && match.index < str.length) Array.prototype.push.apply(output, match.slice(1)); lastLength = match[0].length; lastLastIndex = s.lastIndex; if (output.length >= limit) break; } if (s.lastIndex === match.index) s.lastIndex++; } if (lastLastIndex === str.length) { if (!nativ.test.call(s, "") || lastLength) output.push(""); } else { output.push(str.slice(lastLastIndex)); } return output.length > limit ? output.slice(0, limit) : output; }; //--------------------------------- // Private helper functions //--------------------------------- // Supporting function for `XRegExp`, `XRegExp.copyAsGlobal`, etc. Returns a copy of a `RegExp` // instance with a fresh `lastIndex` (set to zero), preserving properties required for named // capture. Also allows adding new flags in the process of copying the regex function clone (regex, additionalFlags) { if (!XRegExp.isRegExp(regex)) throw TypeError("type RegExp expected"); var x = regex._xregexp; regex = XRegExp(regex.source, getNativeFlags(regex) + (additionalFlags || "")); if (x) { regex._xregexp = { source: x.source, captureNames: x.captureNames ? x.captureNames.slice(0) : null }; } return regex; } function getNativeFlags (regex) { return (regex.global ? "g" : "") + (regex.ignoreCase ? "i" : "") + (regex.multiline ? "m" : "") + (regex.extended ? "x" : "") + // Proposed for ES4; included in AS3 (regex.sticky ? "y" : ""); } function runTokens (pattern, index, scope, context) { var i = tokens.length, result, match, t; // Protect against constructing XRegExps within token handler and trigger functions isInsideConstructor = true; // Must reset `isInsideConstructor`, even if a `trigger` or `handler` throws try { while (i--) { // Run in reverse order t = tokens[i]; if ((scope & t.scope) && (!t.trigger || t.trigger.call(context))) { t.pattern.lastIndex = index; match = t.pattern.exec(pattern); // Running the altered `exec` here allows use of named backreferences, etc. if (match && match.index === index) { result = { output: t.handler.call(context, match, scope), match: match }; break; } } } } catch (err) { throw err; } finally { isInsideConstructor = false; } return result; } function indexOf (array, item, from) { if (Array.prototype.indexOf) // Use the native array method if available return array.indexOf(item, from); for (var i = from || 0; i < array.length; i++) { if (array[i] === item) return i; } return -1; } //--------------------------------- // Built-in tokens //--------------------------------- // Augment XRegExp's regular expression syntax and flags. Note that when adding tokens, the // third (`scope`) argument defaults to `XRegExp.OUTSIDE_CLASS` // Comment pattern: (?# ) XRegExp.addToken( /\(\?#[^)]*\)/, function (match) { // Keep tokens separated unless the following token is a quantifier return nativ.test.call(quantifier, match.input.slice(match.index + match[0].length)) ? "" : "(?:)"; } ); // Capturing group (match the opening parenthesis only). // Required for support of named capturing groups XRegExp.addToken( /\((?!\?)/, function () { this.captureNames.push(null); return "("; } ); // Named capturing group (match the opening delimiter only): (?<name> XRegExp.addToken( /\(\?<([$\w]+)>/, function (match) { this.captureNames.push(match[1]); this.hasNamedCapture = true; return "("; } ); // Named backreference: \k<name> XRegExp.addToken( /\\k<([\w$]+)>/, function (match) { var index = indexOf(this.captureNames, match[1]); // Keep backreferences separate from subsequent literal numbers. Preserve back- // references to named groups that are undefined at this point as literal strings return index > -1 ? "\\" + (index + 1) + (isNaN(match.input.charAt(match.index + match[0].length)) ? "" : "(?:)") : match[0]; } ); // Empty character class: [] or [^] XRegExp.addToken( /\[\^?]/, function (match) { // For cross-browser compatibility with ES3, convert [] to \b\B and [^] to [\s\S]. // (?!) should work like \b\B, but is unreliable in Firefox return match[0] === "[]" ? "\\b\\B" : "[\\s\\S]"; } ); // Mode modifier at the start of the pattern only, with any combination of flags imsx: (?imsx) // Does not support x(?i), (?-i), (?i-m), (?i: ), (?i)(?m), etc. XRegExp.addToken( /^\(\?([imsx]+)\)/, function (match) { this.setFlag(match[1]); return ""; } ); // Whitespace and comments, in free-spacing (aka extended) mode only XRegExp.addToken( /(?:\s+|#.*)+/, function (match) { // Keep tokens separated unless the following token is a quantifier return nativ.test.call(quantifier, match.input.slice(match.index + match[0].length)) ? "" : "(?:)"; }, XRegExp.OUTSIDE_CLASS, function () {return this.hasFlag("x");} ); // Dot, in dotall (aka singleline) mode only XRegExp.addToken( /\./, function () {return "[\\s\\S]";}, XRegExp.OUTSIDE_CLASS, function () {return this.hasFlag("s");} ); //--------------------------------- // Backward compatibility //--------------------------------- // Uncomment the following block for compatibility with XRegExp 1.0-1.2: /* XRegExp.matchWithinChain = XRegExp.matchChain; RegExp.prototype.addFlags = function (s) {return clone(this, s);}; RegExp.prototype.execAll = function (s) {var r = []; XRegExp.iterate(s, this, function (m) {r.push(m);}); return r;}; RegExp.prototype.forEachExec = function (s, f, c) {return XRegExp.iterate(s, this, f, c);}; RegExp.prototype.validate = function (s) {var r = RegExp("^(?:" + this.source + ")$(?!\\s)", getNativeFlags(this)); if (this.global) this.lastIndex = 0; return s.search(r) === 0;}; */ })();
11hca1-java-web
trunk/web/js/libs/sh/XRegExp.js
JavaScript
gpl3
29,440
(function() { var sh = SyntaxHighlighter; /** * Provides functionality to dynamically load only the brushes that a needed to render the current page. * * There are two syntaxes that autoload understands. For example: * * SyntaxHighlighter.autoloader( * [ 'applescript', 'Scripts/shBrushAppleScript.js' ], * [ 'actionscript3', 'as3', 'Scripts/shBrushAS3.js' ] * ); * * or a more easily comprehendable one: * * SyntaxHighlighter.autoloader( * 'applescript Scripts/shBrushAppleScript.js', * 'actionscript3 as3 Scripts/shBrushAS3.js' * ); */ sh.autoloader = function() { var list = arguments, elements = sh.findElements(), brushes = {}, scripts = {}, all = SyntaxHighlighter.all, allCalled = false, allParams = null, i ; SyntaxHighlighter.all = function(params) { allParams = params; allCalled = true; }; function addBrush(aliases, url) { for (var i = 0; i < aliases.length; i++) brushes[aliases[i]] = url; }; function getAliases(item) { return item.pop ? item : item.split(/\s+/) ; } // create table of aliases and script urls for (i = 0; i < list.length; i++) { var aliases = getAliases(list[i]), url = aliases.pop() ; addBrush(aliases, url); } // dynamically add <script /> tags to the document body for (i = 0; i < elements.length; i++) { var url = brushes[elements[i].params.brush]; if (!url) continue; scripts[url] = false; loadScript(url); } function loadScript(url) { var script = document.createElement('script'), done = false ; script.src = url; script.type = 'text/javascript'; script.language = 'javascript'; script.onload = script.onreadystatechange = function() { if (!done && (!this.readyState || this.readyState == 'loaded' || this.readyState == 'complete')) { done = true; scripts[url] = true; checkAll(); // Handle memory leak in IE script.onload = script.onreadystatechange = null; script.parentNode.removeChild(script); } }; // sync way of adding script tags to the page document.body.appendChild(script); }; function checkAll() { for(var url in scripts) if (scripts[url] == false) return; if (allCalled) SyntaxHighlighter.highlight(allParams); }; }; })();
11hca1-java-web
trunk/web/js/libs/sh/shAutoloader.js
JavaScript
gpl3
2,315
/*! Copyright (c) 2011 Brandon Aaron (http://brandonaaron.net) * Licensed under the MIT License (LICENSE.txt). * * Thanks to: http://adomas.org/javascript-mouse-wheel/ for some pointers. * Thanks to: Mathias Bank(http://www.mathias-bank.de) for a scope bug fix. * Thanks to: Seamus Leahy for adding deltaX and deltaY * * Version: 3.0.6 * * Requires: 1.2.2+ */ (function(d){function e(a){var b=a||window.event,c=[].slice.call(arguments,1),f=0,e=0,g=0,a=d.event.fix(b);a.type="mousewheel";b.wheelDelta&&(f=b.wheelDelta/120);b.detail&&(f=-b.detail/3);g=f;b.axis!==void 0&&b.axis===b.HORIZONTAL_AXIS&&(g=0,e=-1*f);b.wheelDeltaY!==void 0&&(g=b.wheelDeltaY/120);b.wheelDeltaX!==void 0&&(e=-1*b.wheelDeltaX/120);c.unshift(a,f,e,g);return(d.event.dispatch||d.event.handle).apply(this,c)}var c=["DOMMouseScroll","mousewheel"];if(d.event.fixHooks)for(var h=c.length;h;)d.event.fixHooks[c[--h]]= d.event.mouseHooks;d.event.special.mousewheel={setup:function(){if(this.addEventListener)for(var a=c.length;a;)this.addEventListener(c[--a],e,false);else this.onmousewheel=e},teardown:function(){if(this.removeEventListener)for(var a=c.length;a;)this.removeEventListener(c[--a],e,false);else this.onmousewheel=null}};d.fn.extend({mousewheel:function(a){return a?this.bind("mousewheel",a):this.trigger("mousewheel")},unmousewheel:function(a){return this.unbind("mousewheel",a)}})})(jQuery);
11hca1-java-web
trunk/web/js/libs/jquery.mousewheel-3.0.6.pack.js
JavaScript
gpl3
1,384
<%-- Document : login_page Created on : Sep 12, 2012, 10:47:34 AM Author : 4pril --%> <%@page contentType="text/html" pageEncoding="UTF-8"%> <%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core"%> <!doctype html> <!-- paulirish.com/2008/conditional-stylesheets-vs-css-hacks-answer-neither/ --> <!--[if lt IE 7]> <html class="no-js lt-ie9 lt-ie8 lt-ie7" lang="en"> <![endif]--> <!--[if IE 7]> <html class="no-js lt-ie9 lt-ie8" lang="en"> <![endif]--> <!--[if IE 8]> <html class="no-js lt-ie9" lang="en"> <![endif]--> <!-- Consider adding a manifest.appcache: h5bp.com/d/Offline --> <!--[if gt IE 8]><!--> <html class="no-js" lang="en"> <!--<![endif]--> <head> <meta charset="utf-8"> <!-- Use the .htaccess and remove these lines to avoid edge case issues. More info: h5bp.com/i/378 --> <meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1"> <title><c:out value="" /></title> <meta name="description" content=""> <!-- Mobile viewport optimized: h5bp.com/viewport --> <meta name="viewport" content="width=device-width"> <!-- Place favicon.ico and apple-touch-icon.png in the root directory: mathiasbynens.be/notes/touch-icons --> <!-- <link rel="stylesheet" type="text/css" href="http://fonts.googleapis.com/css?family=Helvetica World"> --> <link rel="stylesheet" href="style.css"> <!-- More ideas for your <head> here: h5bp.com/d/head-Tips --> <!-- All JavaScript at the bottom, except this Modernizr build. Modernizr enables HTML5 elements & feature detects for optimal performance. Create your own custom Modernizr build: www.modernizr.com/download/ --> <script src="js/libs/modernizr-2.5.3.min.js"></script> </head> <body> <!-- Prompt IE 6 users to install Chrome Frame. Remove this if you support IE 6. chromium.org/developers/how-tos/chrome-frame-getting-started --> <!--[if lt IE 7]><p class=chromeframe>Your browser is <em>ancient!</em> <a href="http://browsehappy.com/">Upgrade to a different browser</a> or <a href="http://www.google.com/chromeframe/?redirect=true">install Google Chrome Frame</a> to experience this site.</p><![endif]--> <!-- Begin wrapper --> <div id="the-wrapper"> <!-- Begin login form --> <div id="login"> <div id="login-header">ĐĂNG NHẬP</div> <div id="login-contain"> <form id="login-form" action="" method="post" accept-charset="utf-8" class="clearfix"> <p><input type="text" class="fl" name="username" value="Tên đăng nhập"></p> <p><input type="password" class="fl" name="password" value="Mật khẩu" ></p> <input type="submit" name="register-button" class="fl" value="Đăng ký" > <input type="submit" name="login-button" class="fr" value="Đăng nhập" > <form> <div class="clearfix"></div> <div id="result-contain"> <p id="result"> <!-- <h3>Đăng nhập thành công. <a href="aa.txt" class="fancybox fancybox.ajax">link</a></h3>--> </p> </div> </div> </div> <!-- End login forn --> </div> <!-- End wrapper --> <!-- JavaScript at the bottom for fast page loading --> <!-- Grab Google CDN's jQuery, with a protocol relative URL; fall back to local if offline --> <!--<script src="//ajax.googleapis.com/ajax/libs/jquery/1.7.1/jquery.min.js"></script>--> <script>window.jQuery || document.write('<script src="js/libs/jquery-1.7.1.min.js"><\/script>')</script> <!-- Add fancyBox main JS and CSS files --> <!-- Add mousewheel plugin (this is optional) --> <script type="text/javascript" src="js/libs/jquery.mousewheel-3.0.6.pack.js"></script> <!-- Add fancyBox main JS and CSS files --> <script type="text/javascript" src="js/libs/fancybox/jquery.fancybox.js?v=2.1.0"></script> <link rel="stylesheet" type="text/css" href="css/jquery.fancybox.css?v=2.1.0" media="screen" /> <!-- add myScript --> <script type="text/javascript" src="js/myScript.js"></script> <!-- end scripts --> <!-- Asynchronous Google Analytics snippet. Change UA-XXXXX-X to be your site's ID. mathiasbynens.be/notes/async-analytics-snippet --> <script> // var _gaq=[['_setAccount','UA-33896517-1'],['_trackPageview']]; // (function(d,t){var g=d.createElement(t),s=d.getElementsByTagName(t)[0]; // g.src=('https:'==location.protocol?'//ssl':'//www')+'.google-analytics.com/ga.js'; // s.parentNode.insertBefore(g,s)}(document,'script')); </script> </body> </html>
11hca1-java-web
trunk/web/login_page.jsp
Java Server Pages
gpl3
4,529
.syntaxhighlighter a, .syntaxhighlighter div, .syntaxhighlighter code, .syntaxhighlighter table, .syntaxhighlighter table td, .syntaxhighlighter table tr, .syntaxhighlighter table tbody, .syntaxhighlighter table thead, .syntaxhighlighter table caption, .syntaxhighlighter textarea { -moz-border-radius: 0 0 0 0 !important; -webkit-border-radius: 0 0 0 0 !important; background: none !important; border: 0 !important; bottom: auto !important; float: none !important; height: auto !important; left: auto !important; line-height: 1.1em !important; margin: 0 !important; outline: 0 !important; overflow: visible !important; padding: 0 !important; position: static !important; right: auto !important; text-align: left !important; top: auto !important; vertical-align: baseline !important; width: auto !important; box-sizing: content-box !important; font-family: "Consolas", "Bitstream Vera Sans Mono", "Courier New", Courier, monospace !important; font-weight: normal !important; font-style: normal !important; font-size: 1em !important; min-height: inherit !important; min-height: auto !important; } .syntaxhighlighter { width: 100% !important; margin: 1em 0 1em 0 !important; position: relative !important; overflow: auto !important; font-size: 1em !important; } .syntaxhighlighter.source { overflow: hidden !important; } .syntaxhighlighter .bold { font-weight: bold !important; } .syntaxhighlighter .italic { font-style: italic !important; } .syntaxhighlighter .line { white-space: pre !important; } .syntaxhighlighter table { width: 100% !important; } .syntaxhighlighter table caption { text-align: left !important; padding: .5em 0 0.5em 1em !important; } .syntaxhighlighter table td.code { width: 100% !important; } .syntaxhighlighter table td.code .container { position: relative !important; } .syntaxhighlighter table td.code .container textarea { box-sizing: border-box !important; position: absolute !important; left: 0 !important; top: 0 !important; width: 100% !important; height: 100% !important; border: none !important; background: white !important; padding-left: 1em !important; overflow: hidden !important; white-space: pre !important; } .syntaxhighlighter table td.gutter .line { text-align: right !important; padding: 0 0.5em 0 1em !important; } .syntaxhighlighter table td.code .line { padding: 0 1em !important; } .syntaxhighlighter.nogutter td.code .container textarea, .syntaxhighlighter.nogutter td.code .line { padding-left: 0em !important; } .syntaxhighlighter.show { display: block !important; } .syntaxhighlighter.collapsed table { display: none !important; } .syntaxhighlighter.collapsed .toolbar { padding: 0.1em 0.8em 0em 0.8em !important; font-size: 1em !important; position: static !important; width: auto !important; height: auto !important; } .syntaxhighlighter.collapsed .toolbar span { display: inline !important; margin-right: 1em !important; } .syntaxhighlighter.collapsed .toolbar span a { padding: 0 !important; display: none !important; } .syntaxhighlighter.collapsed .toolbar span a.expandSource { display: inline !important; } .syntaxhighlighter .toolbar { position: absolute !important; right: 1px !important; top: 1px !important; width: 11px !important; height: 11px !important; font-size: 10px !important; z-index: 10 !important; } .syntaxhighlighter .toolbar span.title { display: inline !important; } .syntaxhighlighter .toolbar a { display: block !important; text-align: center !important; text-decoration: none !important; padding-top: 1px !important; } .syntaxhighlighter .toolbar a.expandSource { display: none !important; } .syntaxhighlighter.ie { font-size: .9em !important; padding: 1px 0 1px 0 !important; } .syntaxhighlighter.ie .toolbar { line-height: 8px !important; } .syntaxhighlighter.ie .toolbar a { padding-top: 0px !important; } .syntaxhighlighter.printing .line.alt1 .content, .syntaxhighlighter.printing .line.alt2 .content, .syntaxhighlighter.printing .line.highlighted .number, .syntaxhighlighter.printing .line.highlighted.alt1 .content, .syntaxhighlighter.printing .line.highlighted.alt2 .content { background: none !important; } .syntaxhighlighter.printing .line .number { color: #bbbbbb !important; } .syntaxhighlighter.printing .line .content { color: black !important; } .syntaxhighlighter.printing .toolbar { display: none !important; } .syntaxhighlighter.printing a { text-decoration: none !important; } .syntaxhighlighter.printing .plain, .syntaxhighlighter.printing .plain a { color: black !important; } .syntaxhighlighter.printing .comments, .syntaxhighlighter.printing .comments a { color: #008200 !important; } .syntaxhighlighter.printing .string, .syntaxhighlighter.printing .string a { color: blue !important; } .syntaxhighlighter.printing .keyword { color: #006699 !important; font-weight: bold !important; } .syntaxhighlighter.printing .preprocessor { color: gray !important; } .syntaxhighlighter.printing .variable { color: #aa7700 !important; } .syntaxhighlighter.printing .value { color: #009900 !important; } .syntaxhighlighter.printing .functions { color: #ff1493 !important; } .syntaxhighlighter.printing .constants { color: #0066cc !important; } .syntaxhighlighter.printing .script { font-weight: bold !important; } .syntaxhighlighter.printing .color1, .syntaxhighlighter.printing .color1 a { color: gray !important; } .syntaxhighlighter.printing .color2, .syntaxhighlighter.printing .color2 a { color: #ff1493 !important; } .syntaxhighlighter.printing .color3, .syntaxhighlighter.printing .color3 a { color: red !important; } .syntaxhighlighter.printing .break, .syntaxhighlighter.printing .break a { color: black !important; }
11hca1-java-web
trunk/web/css/shCore.css
CSS
gpl3
5,826
.syntaxhighlighter { background-color: white !important; } .syntaxhighlighter .line.alt1 { background-color: white !important; } .syntaxhighlighter .line.alt2 { background-color: white !important; } .syntaxhighlighter .line.highlighted.alt1, .syntaxhighlighter .line.highlighted.alt2 { background-color: #e0e0e0 !important; } .syntaxhighlighter .line.highlighted.number { color: black !important; } .syntaxhighlighter table caption { color: black !important; } .syntaxhighlighter .gutter { color: #afafaf !important; } .syntaxhighlighter .gutter .line { border-right: 3px solid #6ce26c !important; } .syntaxhighlighter .gutter .line.highlighted { background-color: #6ce26c !important; color: white !important; } .syntaxhighlighter.printing .line .content { border: none !important; } .syntaxhighlighter.collapsed { overflow: visible !important; } .syntaxhighlighter.collapsed .toolbar { color: blue !important; background: white !important; border: 1px solid #6ce26c !important; } .syntaxhighlighter.collapsed .toolbar a { color: blue !important; } .syntaxhighlighter.collapsed .toolbar a:hover { color: red !important; } .syntaxhighlighter .toolbar { color: white !important; background: #6ce26c !important; border: none !important; } .syntaxhighlighter .toolbar a { color: white !important; } .syntaxhighlighter .toolbar a:hover { color: black !important; } .syntaxhighlighter .plain, .syntaxhighlighter .plain a { color: black !important; } .syntaxhighlighter .comments, .syntaxhighlighter .comments a { color: #008200 !important; } .syntaxhighlighter .string, .syntaxhighlighter .string a { color: blue !important; } .syntaxhighlighter .keyword { color: #006699 !important; } .syntaxhighlighter .preprocessor { color: gray !important; } .syntaxhighlighter .variable { color: #aa7700 !important; } .syntaxhighlighter .value { color: #009900 !important; } .syntaxhighlighter .functions { color: #ff1493 !important; } .syntaxhighlighter .constants { color: #0066cc !important; } .syntaxhighlighter .script { font-weight: bold !important; color: #006699 !important; background-color: none !important; } .syntaxhighlighter .color1, .syntaxhighlighter .color1 a { color: gray !important; } .syntaxhighlighter .color2, .syntaxhighlighter .color2 a { color: #ff1493 !important; } .syntaxhighlighter .color3, .syntaxhighlighter .color3 a { color: red !important; } .syntaxhighlighter .keyword { font-weight: bold !important; }
11hca1-java-web
trunk/web/css/shThemeDefault.css
CSS
gpl3
2,499
/* * To change this template, choose Tools | Templates * and open the template in the editor. */ package dao; import java.util.List; import pojo.User; /** * * @author 4pril */ public class UserDAO extends MyQuery{ @Override protected Class getPOJOClass() { return this.getClass(); } public static User getUser(int user_id){ return (User) getObject( User.class, user_id); } public static boolean addUser(User user){ return addObject(user); } public static List<User> getListUser(String hql){ return (List<User>) (List<?>) getList(hql); } public static boolean login(User user){ //get list userMyQuery List<User> ds = getListUser("from User"); //duyet tim thang trung for (int i = 0; i < ds.size(); i++) { if(ds.get(i).getUsername().equals(user.getUsername()) && ds.get(i).getPassword().equals(user.getPassword())){ return true; } } return false; } public static User getLoginUser(User user){ User ur = null; //get list userMyQuery List<User> ds = getListUser("from User"); //duyet tim thang trung for (int i = 0; i < ds.size(); i++) { if(ds.get(i).getUsername().equals(user.getUsername()) && ds.get(i).getPassword().equals(user.getPassword())){ ur = ds.get(i); } } return ur; } public static boolean checkExists(User user){ List<User> ds = getListUser("from User"); //duyet tim thang trung for (int i = 0; i < ds.size(); i++) { if(ds.get(i).getUsername().equals(user.getUsername())){ return true; } } return false; } }
11hca1-java-web
trunk/src/java/dao/UserDAO.java
Java
gpl3
2,033
/* * To change this template, choose Tools | Templates * and open the template in the editor. */ package dao; import java.util.List; import org.hibernate.Hibernate; import org.hibernate.HibernateException; import org.hibernate.Session; import org.hibernate.Transaction; import util.HibernateUtil; /** * * @author 4pril */ public abstract class MyQuery { protected abstract Class getPOJOClass(); /* * Thuc thi cau truy van va tra ra List * * @param string hql * @return List<Object> */ protected static List<Object> getList(String hql) throws HibernateException{ //mo ket noi Session session = HibernateUtil.getSessionFactory().openSession(); //tao cau truy van org.hibernate.Query query = session.createQuery(hql); //thuc thi cau truy van List<Object> ds = query.list(); session.close(); return ds; } /* * Thuc thi cau truy van va tra ra doi tuong * * @param Class c * int id * @return Object obj */ protected static Object getObject(Class c, int id){ //mo ket noi Session session = HibernateUtil.getSessionFactory().openSession(); //thuc thi cau truy van Object obj = session.get(c, id); session.close(); return obj; } /* * Them 1 doi tuong vao csdl * * @params Object obj * @return boolean result */ protected static boolean addObject(Object obj) throws HibernateException{ //mo ket noi csdl Session session = HibernateUtil.getSessionFactory().openSession(); //tao transaction Transaction tran = null; // try{ tran = session.beginTransaction(); session.save(obj); tran.commit(); // }catch(HibernateException ex){ // tran.rollback(); // session.close(); // return false; // } session.close(); return true; } /* * Xoa 1 doi tuong khoi csdl * thuc te la update Deleted = 1 */ protected static boolean removeObject(Object obj) throws HibernateException{ //mo ket noi csdl Session session = HibernateUtil.getSessionFactory().openSession(); //tao transaction Transaction tran = null; // try{ tran = session.beginTransaction(); session.update(obj); tran.commit(); // }catch(HibernateException ex){ // tran.rollback(); // session.close(); // return false; // } session.close(); return true; } /* * Xoa 1 doi tuong khoi csdl * thuc te la update Deleted = 1 */ protected static boolean removeObject(Object obj, boolean realDelete) throws HibernateException{ if(realDelete == true){ //mo ket noi csdl Session session = HibernateUtil.getSessionFactory().openSession(); //tao transaction Transaction tran = null; // try{ tran = session.beginTransaction(); session.delete(obj); tran.commit(); // }catch(HibernateException ex){ // tran.rollback(); // session.close(); // return false; // } session.close(); return true; } return false; } /* * Update obj * * @params Object obj * @return boolean ketqua */ protected static boolean updateObject(Object obj) throws HibernateException{ //mo ket noi csdl Session session = HibernateUtil.getSessionFactory().openSession(); //tao transaction Transaction tran = null; // try{ tran = session.beginTransaction(); session.update(obj); tran.commit(); // }catch(HibernateException ex){ // tran.rollback(); // session.close(); // return false; // } session.close(); return true; } }
11hca1-java-web
trunk/src/java/dao/MyQuery.java
Java
gpl3
4,490
/* * To change this template, choose Tools | Templates * and open the template in the editor. */ package dao; import java.util.List; import pojo.ObjType; /** * * @author 4pril */ public class ObjectTypeDAO extends MyQuery{ public static ObjType getObjectTypeByName(String obj_name){ String hql = "from ObjType where objType.objName = '" + obj_name + "'"; return (ObjType) getList(hql).get(0); } public static List<ObjType> getListPost(String hql){ return (List<ObjType>) (List<?>) getList(hql); } @Override protected Class getPOJOClass() { return this.getClass(); } }
11hca1-java-web
trunk/src/java/dao/ObjectTypeDAO.java
Java
gpl3
683
/* * To change this template, choose Tools | Templates * and open the template in the editor. */ package dao; import pojo.Object; /** * * @author 4pril */ public class ObjectDAO extends MyQuery{ @Override protected Class getPOJOClass() { return this.getClass(); } protected static Object getObject(int obj_id){ return (Object) getObject(obj_id); } }
11hca1-java-web
trunk/src/java/dao/ObjectDAO.java
Java
gpl3
429