code stringlengths 3 1.18M | language stringclasses 1 value |
|---|---|
/*
* 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();
}
}
}
}
}
| Java |
/*
* 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);
}
}
| Java |
/*
* 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);
}
}
| Java |
/** Automatically generated file. DO NOT MODIFY */
package org.sagemath.droid;
public final class BuildConfig {
public final static boolean DEBUG = true;
} | Java |
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());
}
}
| Java |
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);
}
}
| Java |
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;
}
}
| Java |
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>
* & <small>(ampersand)</small> is replaced by &amp;
* < <small>(less than)</small> is replaced by &lt;
* > <small>(greater than)</small> is replaced by &gt;
* " <small>(double quote)</small> is replaced by &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("&");
break;
case '<':
sb.append("<");
break;
case '>':
sb.append(">");
break;
case '"':
sb.append(""");
break;
case '\'':
sb.append("'");
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><[ [ ]]></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 + ">";
}
}
}
} | Java |
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><[ [ ]]></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><[ [ ]]></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><[ [ ]]></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><[ [ ]]></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();
}
} | Java |
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();
}
}
| Java |
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();
}
}
| Java |
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> <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();
}
}
| Java |
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();
}
}
}
| Java |
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> <small>(comma)</small> may appear just
* before the closing brace.</li>
* <li>Strings may be quoted with <code>'</code> <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> <small>(left brace)</small> and ending
* with <code>}</code> <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> <small>(left brace)</small> and ending
* with <code>}</code> <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> <small>(left brace)</small> and ending
* with <code>}</code> <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> <small>(left brace)</small> and ending
* with <code>}</code> <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> <small>(left brace)</small> and ending
* with <code>}</code> <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> <small>(left brace)</small> and ending
* with <code>}</code> <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);
}
}
} | Java |
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;
}
}
| Java |
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>]]></code>.
* @throws JSONException If the <code>]]></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>& ' > < "</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;
}
}
}
}
| Java |
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> <small>(double quote)</small> or
* <code>'</code> <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 + "]";
}
} | Java |
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();
}
}
| Java |
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();
}
| Java |
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>'</quotes><quotes>"</quotes><slashes>///</slashes><ei><quotes>"'</quotes></ei><eo><b>don't</b><a>"quoted"</a></eo><closetag></script></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 "fine".</foo><foo>so <fine>.</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<content><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<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>!<two> "2" </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=\" "2" \" one=\"1\"><five/>First \t<content><five/>This is "content".<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<are><supported>!</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>&"toot"&toot;A</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;A\",\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>&"toot"&toot;&#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>'+search+'<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>'+search+'</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><escape></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();
}
}
} | Java |
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));
}
}
| Java |
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> <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> <small>(comma)</small> elision.</li>
* <li>Strings may be quoted with <code>'</code> <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> <small>(left bracket)</small>
* and ends with <code>]</code> <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> <small>(left bracket)</small> and ending
* with <code>]</code> <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);
}
}
} | Java |
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();
}
}
| Java |
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"}}]})
*/ | Java |
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);
}
}
| Java |
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);
}
}
| Java |
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;
}
}
| Java |
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);
}
}
}
| Java |
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;
}
}
| Java |
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;
}
} | Java |
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();
}
}
| Java |
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;
}
}
| Java |
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;
}
}
| Java |
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}}
}
| Java |
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"}}]})
*/ | Java |
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;
}
}
| Java |
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(" ");
}
}
}
| Java |
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;
}
}
| Java |
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();
}
}
| Java |
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;
}
}
| Java |
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);
}
}
}
| Java |
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());
}
}
| Java |
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);
// }
}
| Java |
/*
* 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;
}
}
| Java |
/*
* 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;
}
}
| Java |
/*
* 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();
}
}
| Java |
/*
* 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);
}
}
| Java |
/*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
package dao;
import java.util.List;
import myClass.Post;
import pojo.User;
/**
*
* @author 4pril
*/
public class PostDAO extends ObjectDAO{
public static List<Post> getListPost(User u_id){
String hql = "from MyObject p where p.onUser = " + u_id + " and p.ObjType.ObjName = 'post'";
return (List<Post>) (List<?>) getList(hql);
}
}
| Java |
/*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
package system;
/**
*
* @author 4pril
*/
public class System {
private static String login_url = "login";
private static String home_url = "index";
/**
* @return the login_url
*/
public static String getLogin_url() {
return login_url;
}
/**
* @param aLogin_url the login_url to set
*/
public static void setLogin_url(String aLogin_url) {
login_url = aLogin_url;
}
/**
* @return the home_url
*/
public static String getHome_url() {
return home_url;
}
/**
* @param aHome_url the home_url to set
*/
public static void setHome_url(String aHome_url) {
home_url = aHome_url;
}
}
| Java |
/*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
package myClass;
import dao.ObjectTypeDAO;
/**
*
* @author 4pril
*/
public class Post extends pojo.Object{
public Post(){
this.setObjType( ObjectTypeDAO.getObjectTypeByName("post"));
}
}
| Java |
/*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
package controller;
import dao.MyQuery;
import dao.UserDAO;
import java.io.IOException;
import java.io.PrintWriter;
import java.net.URLDecoder;
import java.util.List;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.json.simple.JSONObject;
import org.json.simple.parser.JSONParser;
import org.json.simple.parser.ParseException;
import pojo.User;
/**
*
* @author TrieuKhang
*/
@WebServlet(name = "ajax_register", urlPatterns = {"/ajax_register"})
public class ajax_register extends HttpServlet {
/**
* Processes requests for both HTTP
* <code>GET</code> and
* <code>POST</code> methods.
*
* @param request servlet request
* @param response servlet response
* @throws ServletException if a servlet-specific error occurs
* @throws IOException if an I/O error occurs
*/
protected void processRequest(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
PrintWriter out = response.getWriter();
try {
/*
* TODO output your page here. You may use following sample code.
*/
//init json obj response
JSONObject jObj_response = new JSONObject();
//init json parser
JSONParser jsonPaser = new JSONParser();
JSONObject jsonObj = new JSONObject();
try {
jsonObj = (JSONObject) jsonPaser.parse(request.getParameter("data"));
} catch (ParseException ex) {
Logger.getLogger(ajax_register.class.getName()).log(Level.SEVERE, null, ex);
}
response.setContentType("text/x-json; charset=UTF-8");
request.setCharacterEncoding("UTF-8");
String username = (String) jsonObj.get("username");
String pass = (String) jsonObj.get("password");
User user = new User();
user.setUsername(username);
user.setPassword(pass);
//get list user
boolean result = UserDAO.checkExists(user);
//có nghĩa là chưa có ai sử dụng username đó
if(result == false) {
UserDAO.addUser(user);
}
boolean register_result = !result;
jObj_response.put("result", register_result);
//tra json ra
out.println(jObj_response);
} finally {
out.close();
}
}
// <editor-fold defaultstate="collapsed" desc="HttpServlet methods. Click on the + sign on the left to edit the code.">
/**
* Handles the HTTP
* <code>GET</code> method.
*
* @param request servlet request
* @param response servlet response
* @throws ServletException if a servlet-specific error occurs
* @throws IOException if an I/O error occurs
*/
@Override
protected void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
processRequest(request, response);
}
/**
* Handles the HTTP
* <code>POST</code> method.
*
* @param request servlet request
* @param response servlet response
* @throws ServletException if a servlet-specific error occurs
* @throws IOException if an I/O error occurs
*/
@Override
protected void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
processRequest(request, response);
}
/**
* Returns a short description of the servlet.
*
* @return a String containing servlet description
*/
@Override
public String getServletInfo() {
return "Short description";
}// </editor-fold>
}
| Java |
/*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
package controller;
import dao.MyQuery;
import dao.UserDAO;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.List;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import pojo.User;
/**
*
* @author 4pril
*/
@WebServlet(name = "test", urlPatterns = {"/test"})
public class test extends HttpServlet {
/**
* Processes requests for both HTTP
* <code>GET</code> and
* <code>POST</code> methods.
*
* @param request servlet request
* @param response servlet response
* @throws ServletException if a servlet-specific error occurs
* @throws IOException if an I/O error occurs
*/
protected void processRequest(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
response.setContentType("text/html;charset=UTF-8");
PrintWriter out = response.getWriter();
try {
/*
* TODO output your page here. You may use following sample code.
*/
out.println("fck");
List<User> ds = null;
try {
ds = (List<User>) (List<?>) UserDAO.getListUser("from User");
} catch (Exception e) {
out.println(e.toString());
}
//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;
// }
out.println(ds.get(i).getUsername());
}
User user = new User();
user.setUsername("trieukhang");
user.setPassword("123");
boolean result = UserDAO.login(user);
if(result)
out.println(result);
else
out.println("fck");
} finally {
out.close();
}
}
// <editor-fold defaultstate="collapsed" desc="HttpServlet methods. Click on the + sign on the left to edit the code.">
/**
* Handles the HTTP
* <code>GET</code> method.
*
* @param request servlet request
* @param response servlet response
* @throws ServletException if a servlet-specific error occurs
* @throws IOException if an I/O error occurs
*/
@Override
protected void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
processRequest(request, response);
}
/**
* Handles the HTTP
* <code>POST</code> method.
*
* @param request servlet request
* @param response servlet response
* @throws ServletException if a servlet-specific error occurs
* @throws IOException if an I/O error occurs
*/
@Override
protected void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
processRequest(request, response);
}
/**
* Returns a short description of the servlet.
*
* @return a String containing servlet description
*/
@Override
public String getServletInfo() {
return "Short description";
}// </editor-fold>
}
| Java |
/*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
package controller;
import dao.MyQuery;
import dao.UserDAO;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.OutputStreamWriter;
import java.io.PrintWriter;
import java.lang.reflect.Array;
import java.net.URLDecoder;
import java.util.ArrayList;
import java.util.List;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import org.json.simple.JSONArray;
import pojo.User;
import org.json.simple.JSONObject;
import org.json.simple.JSONValue;
import org.json.simple.parser.JSONParser;
import org.json.simple.parser.ParseException;
/**
*
* @author TrieuKhang
*/
@WebServlet(name = "ajax_login", urlPatterns = {"/ajax_login"})
public class ajax_login extends HttpServlet {
/**
* Processes requests for both HTTP
* <code>GET</code> and
* <code>POST</code> methods.
*
* @param request servlet request
* @param response servlet response
* @throws ServletException if a servlet-specific error occurs
* @throws IOException if an I/O error occurs
*/
protected void processRequest(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
PrintWriter out = response.getWriter();
try {
/*
* TODO output your page here. You may use following sample code.
*/
JSONParser jP = new JSONParser();
JSONObject jO = new JSONObject();
try {
jO = (JSONObject) jP.parse(request.getParameter("data"));
//out.println("false");
} catch (ParseException ex) {
//Logger.getLogger(ajax_login.class.getName()).log(Level.SEVERE, null, ex);
out.println(ex.toString());
//return;
}
request.setCharacterEncoding("UTF-8");
response.setCharacterEncoding("UTF-8");
response.setContentType("text/x-json; charset=UTF-8");
String username = (String) jO.get("username");
String pass = (String) jO.get("password");
User user = new User();
user.setUsername(username);
user.setPassword(pass);
boolean result = false;
HttpSession session = request.getSession();
String redirectUrl = "";
result = UserDAO.login(user);
if(result){
session.setAttribute("isLogin", true);
session.setAttribute("currentUser", UserDAO.getLoginUser(user));
//redirect
redirectUrl = "index.jsp";
}
//init JSON
JSONObject new_jo = new JSONObject();
new_jo.put("result", result);
new_jo.put("user", user.getUsername());
new_jo.put("url", redirectUrl);
//new_jo.put("abc", username);
out.println(new_jo);
//neu ko co thi in ra false
//out.println("false");
}catch( Exception e){
out.println("lỗi " + e.toString());
}finally {
out.close();
}
}
// <editor-fold defaultstate="collapsed" desc="HttpServlet methods. Click on the + sign on the left to edit the code.">
/**
* Handles the HTTP
* <code>GET</code> method.
*
* @param request servlet request
* @param response servlet response
* @throws ServletException if a servlet-specific error occurs
* @throws IOException if an I/O error occurs
*/
@Override
protected void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
processRequest(request, response);
}
/**
* Handles the HTTP
* <code>POST</code> method.
*
* @param request servlet request
* @param response servlet response
* @throws ServletException if a servlet-specific error occurs
* @throws IOException if an I/O error occurs
*/
@Override
protected void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
processRequest(request, response);
}
/**
* Returns a short description of the servlet.
*
* @return a String containing servlet description
*/
@Override
public String getServletInfo() {
return "Short description";
}// </editor-fold>
private void splitat(char c) {
throw new UnsupportedOperationException("Not yet implemented");
}
}
| Java |
/*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
package controller;
import system.System;
import java.io.IOException;
import java.io.PrintWriter;
import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import org.hibernate.dialect.RDMSOS2200Dialect;
/**
*
* @author 4pril
*/
@WebServlet(name = "index", urlPatterns = {"/index"})
public class index extends HttpServlet {
/**
* Processes requests for both HTTP
* <code>GET</code> and
* <code>POST</code> methods.
*
* @param request servlet request
* @param response servlet response
* @throws ServletException if a servlet-specific error occurs
* @throws IOException if an I/O error occurs
*/
protected void processRequest(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
response.setContentType("text/html;charset=UTF-8");
PrintWriter out = response.getWriter();
try {
/*
* TODO output your page here. You may use following sample code.
*/
HttpSession session = request.getSession();
out.println(System.getLogin_url());
//out.println(session.getAttribute("isLogin"));
//get isLogin
if(session.getAttribute("isLogin") == null){
RequestDispatcher rd = request.getRequestDispatcher(System.getLogin_url());
rd.forward(request, response);
}
//da login
session.getAttribute("currentUser");
RequestDispatcher toHomePage = request.getRequestDispatcher("index.jsp");
toHomePage.forward(request, response);
} finally {
out.close();
}
}
// <editor-fold defaultstate="collapsed" desc="HttpServlet methods. Click on the + sign on the left to edit the code.">
/**
* Handles the HTTP
* <code>GET</code> method.
*
* @param request servlet request
* @param response servlet response
* @throws ServletException if a servlet-specific error occurs
* @throws IOException if an I/O error occurs
*/
@Override
protected void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
processRequest(request, response);
}
/**
* Handles the HTTP
* <code>POST</code> method.
*
* @param request servlet request
* @param response servlet response
* @throws ServletException if a servlet-specific error occurs
* @throws IOException if an I/O error occurs
*/
@Override
protected void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
processRequest(request, response);
}
/**
* Returns a short description of the servlet.
*
* @return a String containing servlet description
*/
@Override
public String getServletInfo() {
return "Short description";
}// </editor-fold>
}
| Java |
/*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
package controller;
import system.System;
import java.io.IOException;
import java.io.PrintWriter;
import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
/**
*
* @author 4pril
*/
@WebServlet(name = "login", urlPatterns = {"/login"})
public class login extends HttpServlet {
/**
* Processes requests for both HTTP
* <code>GET</code> and
* <code>POST</code> methods.
*
* @param request servlet request
* @param response servlet response
* @throws ServletException if a servlet-specific error occurs
* @throws IOException if an I/O error occurs
*/
protected void processRequest(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
response.setContentType("text/html;charset=UTF-8");
PrintWriter out = response.getWriter();
try {
/*
* TODO output your page here. You may use following sample code.
*/
HttpSession session = request.getSession();
if(session.getAttribute("isLogin") != null){
// RequestDispatcher rd = request.getRequestDispatcher("index.jsp");
// rd.forward(request, response);
response.sendRedirect("index.jsp");
return;
}
RequestDispatcher rd = request.getRequestDispatcher("login_page.jsp");
rd.forward(request, response);
} finally {
out.close();
}
}
// <editor-fold defaultstate="collapsed" desc="HttpServlet methods. Click on the + sign on the left to edit the code.">
/**
* Handles the HTTP
* <code>GET</code> method.
*
* @param request servlet request
* @param response servlet response
* @throws ServletException if a servlet-specific error occurs
* @throws IOException if an I/O error occurs
*/
@Override
protected void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
processRequest(request, response);
}
/**
* Handles the HTTP
* <code>POST</code> method.
*
* @param request servlet request
* @param response servlet response
* @throws ServletException if a servlet-specific error occurs
* @throws IOException if an I/O error occurs
*/
@Override
protected void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
processRequest(request, response);
}
/**
* Returns a short description of the servlet.
*
* @return a String containing servlet description
*/
@Override
public String getServletInfo() {
return "Short description";
}// </editor-fold>
}
| Java |
/*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
package util;
import org.hibernate.cfg.AnnotationConfiguration;
import org.hibernate.SessionFactory;
/**
* Hibernate Utility class with a convenient method to get Session Factory
* object.
*
* @author 4pril
*/
public class HibernateUtil {
private static final SessionFactory sessionFactory;
static {
try {
// Create the SessionFactory from standard (hibernate.cfg.xml)
// config file.
sessionFactory = new AnnotationConfiguration().configure().buildSessionFactory();
} catch (Throwable ex) {
// Log the exception.
System.err.println("Initial SessionFactory creation failed." + ex);
throw new ExceptionInInitializerError(ex);
}
}
public static SessionFactory getSessionFactory() {
return sessionFactory;
}
}
| Java |
package controller;
import java.awt.Graphics2D;
import java.awt.image.BufferedImage;
import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import javax.imageio.ImageIO;
import model.Food;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.servlet.ModelAndView;
import dao.FoodDAO;
@Controller
public class FoodController {
private static final int IMG_WIDTH = 100;
private static final int IMG_HEIGHT = 100;
String url = "";
String rootPath = System.getProperty("user.dir");
@Autowired
private FoodDAO dao;
@RequestMapping(value = "/foodlist", method = RequestMethod.GET)
public ModelAndView foodList() {
List<Food> list = dao.getList();
Map<String, Object> model = new HashMap<String, Object>();
url = "foodlist";
model.put("list", list);
model.put("url", url);
return new ModelAndView("../../Homepage", model);
}
@RequestMapping(value = "/addfood", method = RequestMethod.POST)
public ModelAndView addFood(@ModelAttribute Food food) {
Map<String, Object> model = new HashMap<String, Object>();
url = "foodinfo";
if (food.getId()==0) {
String name = food.getName();
File dir = new File(rootPath + File.separator + "workspace"
+ File.separator + "CNPM" + File.separator + "WebContent"
+ File.separator + "resources" + File.separator + "image");
Food.makeQR(name, dir.getAbsolutePath() + File.separator + "qr" + name
+ ".jpg");
String filePath = "/resources/image/qr" + name + ".jpg";
food.setQr(filePath);
}
dao.saveOrUpdate(food);
model.put("url", url);
return new ModelAndView("../../Homepage", model);
}
@RequestMapping(value = "/displayaddfood", method = RequestMethod.GET)
public ModelAndView displayAddFood() {
Map<String, Object> model = new HashMap<String, Object>();
url = "displayaddfood";
model.put("url", url);
model.put("food", new Food());
return new ModelAndView("../../Homepage", model);
}
@RequestMapping(value = "/displayupload", method = RequestMethod.GET)
public String displayUpload() {
return "Upload";
}
@RequestMapping(value = "/upload", method = RequestMethod.POST)
public ModelAndView upload(@RequestParam("file") MultipartFile file) {
Map<String, Object> model = new HashMap<String, Object>();
String message = "";
if (!file.isEmpty()) {
try {
byte[] bytes = file.getBytes();
File dir = new File(rootPath + File.separator + "workspace"
+ File.separator + "CNPM" + File.separator
+ "WebContent" + File.separator + "resources"
+ File.separator + "image");
if (!dir.exists())
dir.mkdirs();
Calendar cal = Calendar.getInstance();
SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMddHHmmss");
String name = sdf.format(cal.getTime());
File serverFile = new File(dir.getAbsolutePath()
+ File.separator + "img" + name + ".jpg");
BufferedOutputStream stream = new BufferedOutputStream(
new FileOutputStream(serverFile));
stream.write(bytes);
stream.close();
resizeIMG(serverFile);
String filePath = "/resources/image/img" + name + ".jpg";
model.put("filepath", filePath);
message = "You successfully uploaded file";
} catch (Exception e) {
message = "You failed to upload => " + e.getMessage();
}
} else {
message = "You failed to upload because the file was empty.";
}
model.put("message", message);
return new ModelAndView("Upload", model);
}
public static void resizeIMG(File file) {
try {
BufferedImage originalImage = ImageIO.read(file);
int type = originalImage.getType() == 0 ? BufferedImage.TYPE_INT_ARGB
: originalImage.getType();
BufferedImage resizeImageJpg = resizeImage(originalImage, type);
ImageIO.write(resizeImageJpg, "jpg",
new File(file.getAbsolutePath()));
} catch (IOException e) {
e.printStackTrace();
}
}
private static BufferedImage resizeImage(BufferedImage originalImage,
int type) {
BufferedImage resizedImage = new BufferedImage(IMG_WIDTH, IMG_HEIGHT,
type);
Graphics2D g = resizedImage.createGraphics();
g.drawImage(originalImage, 0, 0, IMG_WIDTH, IMG_HEIGHT, null);
g.dispose();
return resizedImage;
}
}
| Java |
package info.tAIR.tAIRApp;
import android.app.Activity;
import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
public class ContributorActivity extends Activity {
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.contributors);
final Button button01 = (Button)
findViewById(R.id.Button01);
button01.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
//Perform action on click
Uri uri = Uri.parse("http://www.tAIIC.com");
Intent intent = new Intent(Intent.ACTION_VIEW, uri);
startActivity(intent);
}
});
final Button button02 = (Button)
findViewById(R.id.Button02);
button02.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
//Perform action on click
Uri uri = Uri.parse("http://sites.jsoft.com/rm/home");
Intent intent = new Intent(Intent.ACTION_VIEW, uri);
startActivity(intent);
}
});
final Button button03 = (Button)
findViewById(R.id.Button03);
button03.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
//Perform action on click
Uri uri = Uri.parse("http://www.suavestudio.com/");
Intent intent = new Intent(Intent.ACTION_VIEW, uri);
startActivity(intent);
}
});
final Button button04 = (Button)
findViewById(R.id.Button04);
button04.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
//Perform action on click
finish();
}
});
}
}
| Java |
package info.tAIR.tAIRApp;
import android.app.Activity;
import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
public class AndDevActivity extends Activity {
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.anddevtab);
final Button button01 = (Button)
findViewById(R.id.Button01);
button01.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
//Perform action on click
Uri uri = Uri.parse("http://developer.android.com/sdk/index.html");
Intent intent = new Intent(Intent.ACTION_VIEW, uri);
startActivity(intent);
}
});
final Button button02 = (Button)
findViewById(R.id.Button02);
button02.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
// //Perform action on click
Uri uri = Uri.parse("http://developer.android.com/guide/index.html");
Intent intent = new Intent(Intent.ACTION_VIEW, uri);
startActivity(intent);
}
});
//
final Button button03 = (Button)
findViewById(R.id.Button03);
button03.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
// //Perform action on click
Uri uri = Uri.parse("http://developer.android.com/reference/packages.html");
Intent intent = new Intent(Intent.ACTION_VIEW, uri);
startActivity(intent);
}
});
//
final Button button04 = (Button)
findViewById(R.id.Button04);
button04.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
// //Perform action on click
Uri uri = Uri.parse("http://developer.android.com/resources/index.html");
Intent intent = new Intent(Intent.ACTION_VIEW, uri);
startActivity(intent);
}
});
final Button button05 = (Button)
findViewById(R.id.Button05);
button05.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
//Perform action on click
Uri uri = Uri.parse("https://groups.google.com/forum/#!forum/android-developers");
Intent intent = new Intent(Intent.ACTION_VIEW, uri);
startActivity(intent);
}
});
final Button button06 = (Button)
findViewById(R.id.Button06);
button06.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
//Perform action on click
Uri uri = Uri.parse("mailto:android-developers@googlegroups.com?body=\n\n\n\n\nSent from tAIR Companion App");
Intent intent = new Intent(Intent.ACTION_VIEW, uri);
startActivity(intent);
}
});
}
}
| Java |
package info.tAIR.tAIRApp;
import android.app.Activity;
import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
public class GroupActivity extends Activity {
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.grouptab);
final Button button01 = (Button)
findViewById(R.id.Button01);
button01.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
//Perform action on click
Uri uri = Uri.parse("http://groups.google.com/group/theairepository/about");
Intent intent = new Intent(Intent.ACTION_VIEW, uri);
startActivity(intent);
}
});
final Button button02 = (Button)
findViewById(R.id.Button02);
button02.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
// //Perform action on click
Uri uri = Uri.parse("https://groups.google.com/group/theairepository/");
Intent intent = new Intent(Intent.ACTION_VIEW, uri);
startActivity(intent);
}
});
final Button button03 = (Button)
findViewById(R.id.Button03);
button03.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
// //Perform action on click
Uri uri = Uri.parse("mailto:theairepository@googlegroups.com?body=\n\n\n\n\nSent from tAIR Companion App");
Intent intent = new Intent(Intent.ACTION_VIEW, uri);
startActivity(intent);
}
});
final Button button04 = (Button)
findViewById(R.id.Button04);
button04.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
// //Perform action on click
Uri uri = Uri.parse("https://groups.google.com/forum/?hl=en#!members/theairepository");
Intent intent = new Intent(Intent.ACTION_VIEW, uri);
startActivity(intent);
}
});
}
}
| Java |
package info.tAIR.tAIRApp;
import android.app.TabActivity;
import android.content.Intent;
import android.content.res.Resources;
import android.os.Bundle;
import android.widget.TabHost;
public class tAIRTabWidget extends TabActivity {
/** Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
Resources res = getResources(); // Resource object to get Drawables
TabHost tabHost = getTabHost(); // The activity TabHost
TabHost.TabSpec spec; // Resusable TabSpec for each tab
Intent intent; // Reusable Intent for each tab
// Create an Intent to launch an Activity for the tab (to be reused)
intent = new Intent().setClass(this, tAIRActivity.class);
// Initialize a TabSpec for each tab and add it to the TabHost
spec = tabHost.newTabSpec("tair").setIndicator("tAIR",
res.getDrawable(R.drawable.ic_tab_tair))
.setContent(intent);
tabHost.addTab(spec);
// Do the same for the other tabs
intent = new Intent().setClass(this, GroupActivity.class);
spec = tabHost.newTabSpec("group").setIndicator("Discuss",
res.getDrawable(R.drawable.ic_tab_group))
.setContent(intent);
tabHost.addTab(spec);
intent = new Intent().setClass(this, CodeActivity.class);
spec = tabHost.newTabSpec("code").setIndicator("Code",
res.getDrawable(R.drawable.ic_tab_code))
.setContent(intent);
tabHost.addTab(spec);
intent = new Intent().setClass(this, AIActivity.class);
spec = tabHost.newTabSpec("aiforum").setIndicator("AI Forums",
res.getDrawable(R.drawable.ic_tab_ai))
.setContent(intent);
tabHost.addTab(spec);
intent = new Intent().setClass(this, AndDevActivity.class);
spec = tabHost.newTabSpec("anddev").setIndicator("Android Developer",
res.getDrawable(R.drawable.ic_tab_anddev))
.setContent(intent);
tabHost.addTab(spec);
tabHost.setCurrentTab(0);
}
} | Java |
package info.tAIR.tAIRApp;
import android.app.Activity;
import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.Toast;
public class CodeActivity extends Activity {
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.codetab);
final Button button01 = (Button)
findViewById(R.id.Button01);
button01.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
//Perform action on click
Uri uri = Uri.parse("http://code.google.com/p/the-ai-repository");
Intent intent = new Intent(Intent.ACTION_VIEW, uri);
startActivity(intent);
}
});
final Button button02 = (Button)
findViewById(R.id.Button02);
button02.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
//Perform action on click
Uri uri = Uri.parse("http://code.google.com/p/the-ai-repository/downloads/list");
Intent intent = new Intent(Intent.ACTION_VIEW, uri);
startActivity(intent);
}
});
final Button button03 = (Button)
findViewById(R.id.Button03);
button03.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
//Perform action on click
Uri uri = Uri.parse("http://code.google.com/p/the-ai-repository/source/browse/");
Intent intent = new Intent(Intent.ACTION_VIEW, uri);
startActivity(intent);
}
});
final Button button04 = (Button)
findViewById(R.id.Button04);
button04.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
//Perform action on contributors click
Intent contribIntent = new Intent();
contribIntent.setClassName("info.tAIR.tAIRApp", "info.tAIR.tAIRApp.ContributorActivity");
startActivity(contribIntent);
}
});
final Button button05 = (Button)
findViewById(R.id.Button05);
button05.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
//Perform action on click
Toast.makeText(CodeActivity.this, "tAIR Companion App v2.0\n\n Copyright @ 2010-2011\n\n http://www.tAIR.info", Toast.LENGTH_LONG).show();
}
});
}
}
| Java |
package info.tAIR.tAIRApp;
import android.app.Activity;
import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
public class AIActivity extends Activity {
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.aitab);
final Button button01 = (Button)
findViewById(R.id.Button01);
button01.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
//Perform action on click
Uri uri = Uri.parse("http://appinventor.googlelabs.com/forum");
Intent intent = new Intent(Intent.ACTION_VIEW, uri);
startActivity(intent);
}
});
final Button button02 = (Button)
findViewById(R.id.Button02);
button02.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
//Perform action on click
Uri uri = Uri.parse("mailto:getting-started-with-app-inventor@googlegroups.com?body=\n\n\n\n\nSent from tAIR Companion App");
Intent intent = new Intent(Intent.ACTION_VIEW, uri);
startActivity(intent);
}
});
final Button button03 = (Button)
findViewById(R.id.Button03);
button03.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
//Perform action on click
Uri uri = Uri.parse("mailto:app-inventor-instructors@googlegroups.com?body=\n\n\n\n\nSent from tAIR Companion App");
Intent intent = new Intent(Intent.ACTION_VIEW, uri);
startActivity(intent);
}
});
final Button button04 = (Button)
findViewById(R.id.Button04);
button04.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
//Perform action on click
Uri uri = Uri.parse("mailto:programming-with-app-inventor@googlegroups.com?body=\n\n\n\n\nSent from tAIR Companion App");
Intent intent = new Intent(Intent.ACTION_VIEW, uri);
startActivity(intent);
}
});
final Button button05 = (Button)
findViewById(R.id.Button05);
button05.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
//Perform action on click
Uri uri = Uri.parse("mailto:appinventor@googlegroups.com?body=\n\n\n\n\nSent from tAIR Companion App");
Intent intent = new Intent(Intent.ACTION_VIEW, uri);
startActivity(intent);
}
});
}
}
| Java |
package info.tAIR.tAIRApp;
import android.app.Activity;
import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
public class tAIRActivity extends Activity {
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.tairtab);
final Button button01 = (Button)
findViewById(R.id.Button01);
button01.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
//Perform action on click
Uri uri = Uri.parse("http://www.tair.info/messages");
Intent intent = new Intent(Intent.ACTION_VIEW, uri);
startActivity(intent);
}
});
final Button button02 = (Button)
findViewById(R.id.Button02);
button02.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
// //Perform action on click
Uri uri = Uri.parse("http://www.tair.info/block-images");
Intent intent = new Intent(Intent.ACTION_VIEW, uri);
startActivity(intent);
}
});
//
final Button button03 = (Button)
findViewById(R.id.Button03);
button03.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
// //Perform action on click
Uri uri = Uri.parse("http://www.tair.info/source-code");
Intent intent = new Intent(Intent.ACTION_VIEW, uri);
startActivity(intent);
}
});
//
final Button button04 = (Button)
findViewById(R.id.Button04);
button04.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
// //Perform action on click
Uri uri = Uri.parse("http://www.tair.info/tutorials");
Intent intent = new Intent(Intent.ACTION_VIEW, uri);
startActivity(intent);
}
});
final Button button05 = (Button)
findViewById(R.id.Button05);
button05.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
//Perform action on click
Uri uri = Uri.parse("http://www.tair.info/other-resources");
Intent intent = new Intent(Intent.ACTION_VIEW, uri);
startActivity(intent);
}
});
final Button button06 = (Button)
findViewById(R.id.Button06);
button06.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
//Perform action on click
Uri uri = Uri.parse("http://www.tair.info/android-sdk-1");
Intent intent = new Intent(Intent.ACTION_VIEW, uri);
startActivity(intent);
}
});
final Button button07 = (Button)
findViewById(R.id.Button07);
button07.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
//Perform action on click
Uri uri = Uri.parse("http://www.tair.info/contact-us");
Intent intent = new Intent(Intent.ACTION_VIEW, uri);
startActivity(intent);
}
});
}
}
| Java |
package fracPackage;
import java.awt.*;
public class ColorScheme
{
public Color[] colorArr;
public ColorScheme()
{
}
public Color color(int nIter)
{
int red = (int)Math.round(-120*Math.cos(nIter/6.) + 120);
int green = (int)Math.round(-120*Math.cos(nIter/6. + 1.04) + 120);
int blue = (int)Math.round(-120*Math.cos(nIter/6. + 2.08) + 120);
return new Color(red, green, blue);
}
}
| Java |
package fracPackage;
import java.awt.*;
public class FractalPoint extends pObject
{
private double x, y;
private int nIter;
private Iteration pIter;
public FractalPoint(int i0, int j0, double x0, double y0, Iteration iter)
{
super(x0, y0);
x = x0;
y = y0;
nIter = 0;
pIter = iter;
}
public int nIter()
{
return nIter;
}
public boolean isOut()
{
return super.isOut(pIter, x, y);
}
public void iterate(int n)
{
int i = 0;
while (i < n && !isOut())
{
i++;
super.iterate(pIter, x, y);
}
nIter += i;
}
public Color color(ColorScheme cSchm)
{
if (isOut()) return cSchm.color(nIter);
return Color.black;
}
}
| Java |
package fracPackage;
public class pObject{
private double re, im;
public pObject(double x, double y)
{
re = 0; im = 0;
}
public void iterate (Iteration iter, double x, double y)
{
double oldRe = re;
re = re*re - im*im + x;
im = 2*im*oldRe + y;
}
public boolean isOut (Iteration iter, double x, double y)
{
return re*re + im*im > 4;
}
} | Java |
package fracPackage;
import java.awt.*;
public class ColorScheme
{
public Color[] colorArr;
public double alpha = 0;
public double betta = 0;
public double gamma = 0;
public ColorScheme()
{
}
public ColorScheme(double phi)
{
if(phi<10){
this.alpha = phi*0.628;
} else if(phi<20){
this.betta = phi*0.628;
} else {
this.gamma = phi*0.628;
}
}
public Color color(int nIter)
{
int red = (int)Math.round(-125*(Math.cos(nIter/6.+ alpha + 2* betta)) + 125);
int green = (int)Math.round(-125*(Math.cos(nIter/6. + 1.04 + 2* alpha + gamma)) + 125);
int blue = (int)Math.round(-125*(Math.cos(nIter/6. + 2.08 + betta +2*gamma)) + 125);
return new Color(red, green, blue);
}
}
| Java |
/*package fracPackage;
import javax.swing.*;
import java.awt.*;
import java.awt.image.*;
import java.awt.event.*;
public class rawDraw extends JFrame implements KeyListener
{
UserMenu usrMenu;
public rawDraw()
{
super("RawMandelbrot");
addKeyListener(this);
usrMenu = new UserMenu(this);
SwingComponent swComp = new SwingComponent(usrMenu);
setDefaultCloseOperation(EXIT_ON_CLOSE);
getContentPane().add(swComp);
setSize(600, 600);
setVisible(true);
}
class SwingComponent extends JComponent
{
UserMenu scFrac;
public SwingComponent(UserMenu frac)
{
scFrac = frac;
}
public void paintComponent(Graphics g)
{
FractalObserver frObs = new FractalObserver();
super.paintComponent(g);
g.drawImage(scFrac.getImage(),0,0, 600, 600, frObs);
}
}
public static void main(String[] args)
{
new rawDraw();
}
class FractalObserver implements ImageObserver
{
public boolean imageUpdate(Image img, int infoflags, int x, int y, int width, int heigth)
{
return true;
}
}
public void keyPressed(KeyEvent ke)
{
int key = ke.getKeyCode();
switch(key)
{
case KeyEvent.VK_LEFT:
usrMenu.moveLeft();
break;
case KeyEvent.VK_RIGHT:
usrMenu.moveRight();
break;
case KeyEvent.VK_UP:
usrMenu.moveUp();
break;
case KeyEvent.VK_DOWN:
usrMenu.moveDown();
break;
case KeyEvent.VK_Z:
usrMenu.enlarge();
break;
case KeyEvent.VK_X:
usrMenu.ensmall();
break;
}
}
public void keyReleased(KeyEvent kEv)
{
}
public void keyTyped(KeyEvent kEv)
{
}
}*/ | Java |
package fracPackage;
import polishNotation.Iteration;
public class Message
{
public int type;
public int dx;
public int dy;
public double chSize;
public FractalPoint fPoint;
public int i;
public int j;
public double xLeft;
public double xRight;
public double yLow;
public double yHigh;
public int nX;
public int nY;
public int nIter;
public Iteration iter;
public ColorScheme cschm;
public double a, b;
public double ceiling;
}
| Java |
package fracPackage;
import polishNotation.Iteration;
import java.awt.*;
public class FractalPoint extends pObject
{
private double x, y;
private int nIter;
public FractalPoint(double x0, double y0, Iteration iter, double ceiling)
{
super(x0, y0, iter, ceiling);
x = x0;
y = y0;
nIter = 0;
}
public FractalPoint(double x0, double y0, double a, double b, Iteration iter, double ceiling)
{
super(x0, y0, a, b, iter, ceiling);
x = x0;
y = y0;
nIter = 0;
}
public FractalPoint(FractalPoint fp)
{
super(0, 0, null, 5);
if(fp!= null)
{
x = fp.x;
y = fp.y;
nIter = fp.nIter;
}
}
public double x()
{
return x;
}
public double y()
{
return y;
}
public int nIter()
{
return nIter;
}
public boolean isOut()
{
return super.isOut(x, y);
}
public void iterate(int n)
{
int i = 0;
while (i < n && !isOut())
{
i++;
super.iterate();
}
nIter += i;
}
public Color color(ColorScheme cSchm)
{
if (isOut()) return cSchm.color(nIter);
return Color.black;
}
public String toString()
{
return "x: " + x + " y: " + y + " nIter: " + nIter;
}
} | Java |
package fracPackage;
import java.awt.*;
import polishNotation.Iteration;
import polishNotation.PolishNotation;
import java.awt.image.*;
//---
public class Fractal implements Runnable
{
Thread computation;
static double xLeftDefault = -2;
static double xRightDefault = 2;
static double yLowDefault = -2;
static double yHighDefault = 2;
static double aDefault = 0.35;
static double bDefault = 0.1;
static double ceilingDefault = 2;
static int nXDefault = 600;
static int nYDefault = 600;
static int nIterDefault = 100;
static String iterDefault = "z^2 + c";
private SynchrMenu synchr;
private double xLeft;
private double xRight;
private double yLow;
private double yHigh;
private int nX;
private int nY;
private int nIter;
private ColorScheme cSchm;
private Iteration iter;
protected double ceiling;
protected double a;
protected double b;
private FractalPoint[][] field;
private int nIterCurrent;
private BufferedImage img;
private Component comp;
private AbleToDraw mainWindow;
/*---------------------------------------------------------------------------------------------------------------------------------------*/
public Fractal(SynchrMenu Synchr, Component Graph, AbleToDraw mWindow)
{
computation = new Thread(this, "computation");
xLeft = xLeftDefault; xRight = xRightDefault;
yLow = yLowDefault; yHigh = yHighDefault;
nX = nXDefault; nY = nYDefault;
nIterCurrent = 0; cSchm = new ColorScheme();
PolishNotation pnot = new PolishNotation(iterDefault);
pnot.polish();
iter = new Iteration(pnot.outline);
nIter = nIterDefault;
ceiling = ceilingDefault;
synchr = Synchr;
mainWindow = mWindow;
comp = Graph;
newFracField();
img = new BufferedImage(nX, nY, BufferedImage.TYPE_INT_RGB);
computation.start();
}
/*--------------------------------------------------------------------------------------------------------------*/
public void newFracField()
{
field = new FractalPoint[nX][nY];
for(int i = 0; i < nX; i++)
{
double xi = ItoX(i, nX, xLeft, xRight);
for(int j = 0; j < nY; j++)
{
double yj = JtoY(j, nY, yLow, yHigh);
field[i][j] = makeField(xi, yj, iter);
}
}
}
public FractalPoint makeField(double xi, double yj, Iteration iter)
{
return new FractalPoint(xi, yj, iter, ceiling);
}
public void makeNewFractal()
{
newFracField();
iterateAndDraw();
}
public void changeScale (double chSizeParam )
{
double xl = xLeft; double xr = xRight;
double yl = yLow; double yh = yHigh;
xLeft = (xl + xr)/2 - (xr - xl)/2 * chSizeParam;
xRight = (xl + xr)/2 + (xr - xl)/2 * chSizeParam;
yLow = (yl + yh)/2 - (yh - yl)/2 * chSizeParam;
yHigh = (yl + yh)/2 + (yh - yl)/2 * chSizeParam;
makeNewFractal();
}
/*--------------------------------------------------------------------------------------------------------------*/
public void iterate(int n)
{
for(int i = 0; i < nX; i++)
for(int j = 0; j < nY; j++)
field[i][j].iterate(n);
nIterCurrent += n;
}
public void iterateAndDraw()
{
for(int j = 0; j < nY; j++)
{
if(synchr.watchMessage()) return;
for(int i = 0; i < nX; i++)
{
field[i][j].iterate(nIter);
}
if(j % (nY/6 + 1) == 0 || j == nY - 1) draw(j + 1);
}
nIterCurrent = nIter;
}
/*--------------------------------------------------------------------------------------------------------------*/
public FractalPoint pointXY(double x, double y)
{
int i, j;
i = XtoI(x, nX, xLeft, xRight);
j = YtoJ(y, nY, yLow , yHigh );
return field[i][j];
}
/*--------------------------------------------------------------------------------------------------------------*/
public void draw()
{
draw(nY);
}
public void draw(int height)
{
img = new BufferedImage(nX, nY, BufferedImage.TYPE_INT_RGB);
Graphics2D graph = img.createGraphics();
for(int i = 0; i < nX; i ++)
for(int j = 0; j < height; j++)
{
graph.setColor(field[i][j].color(cSchm));
graph.drawLine(i,j,i,j);
}
graph.setColor(Color.LIGHT_GRAY);
graph.fillRect(0, height, nX, nY - height);
comp.repaint();
}
public void moveX(int dnX)
{
int i, j;
if(dnX == 0) return;
else if(dnX < 0)
{
for(i = nX - 1; i >= -dnX; i--)
for(j = 0; j < nY; j++)
field[i][j] = field[i + dnX][j];
for(i = 0; i < -dnX; i++)
for(j = 0; j < nY; j++)
{
double x,y;
x = ItoX(i + dnX, nX, xLeft, xRight);
y = JtoY(j, nY, yLow, yHigh);
field[i][j] = makeField(x,y, iter);
field[i][j].iterate(nIter);
}
}
else
{
for(i = 0; i < nX - dnX; i++)
for(j = 0; j < nY; j++)
field[i][j] = field[i + dnX][j];
for(i = nX - dnX; i < nX; i++)
for(j = 0; j < nY; j++)
{
double x,y;
x = ItoX(i + dnX, nX, xLeft, xRight);
y = JtoY(j, nY, yLow, yHigh);
field[i][j] = makeField(x,y, iter);
field[i][j].iterate(nIter);
}
}
double xLeftOld = xLeft;
xLeft = ItoX(0 + dnX, nX, xLeftOld, xRight);
xRight = ItoX(nX + dnX, nX, xLeftOld, xRight);
draw(nY);
}
public void moveY(int dnY)
{
int i, j;
if(dnY == 0) return;
else if(dnY > 0)
{
for(i = 0; i < nX; i++)
for(j = nY - 1; j >= dnY; j--)
field[i][j] = field[i][j - dnY];
for(i = 0; i < nX; i++)
for(j = 0; j < dnY; j++)
{
double x,y;
x = ItoX(i , nX, xLeft, xRight);
y = JtoY(j - dnY, nY, yLow, yHigh);
field[i][j] = makeField(x,y, iter);
field[i][j].iterate(nIter);
}
}
else
{
for(i = 0; i < nX; i++)
for(j = 0; j < nY + dnY; j++)
field[i][j] = field[i][j - dnY];
for(i = 0; i < nX; i++)
for(j = nY + dnY; j < nY; j++)
{
double x,y;
x = ItoX(i , nX, xLeft, xRight);
y = JtoY(j - dnY, nY, yLow, yHigh);
field[i][j] = makeField(x,y, iter);
field[i][j].iterate(nIter);
}
}
double yLowOld = yLow;
yLow = JtoY(nY - dnY, nY, yLowOld, yHigh);
yHigh = JtoY(0 - dnY, nY, yLowOld, yHigh);
draw(nY);
}
public BufferedImage getImage()
{
return img;
}
/*----------------------------------------------------------------------------------------------------------------------------------*/
public double getxLeft()
{
return xLeft;
}
public double getxRight()
{
return xRight;
}
public double getyLow()
{
return yLow;
}
public double getyHigh()
{
return yHigh;
}
/*-------------------------------------------------------------------------------------------------------------------------
*-------------------------------------------------------------------------------------------------------------------------
*/
public static double ItoX(int i, int NX, double xleft, double xright)
{
return (xleft*(NX - i) + xright*i)/NX;
}
public static double JtoY(int j, int NY, double ylow, double yhigh)
{
return (yhigh*(NY - j) + ylow*j)/NY;
}
public static int XtoI(double x, int NX, double xleft, double xright)
{
return (int)Math.round( (x - xleft)/(xright - xleft)*NX );
}
public static int YtoJ(double y, int NY, double ylow, double yhigh)
{
return (int)Math.round( (yhigh - y)/(yhigh - ylow )*NY );
}
/*--------------------------------------------------------------------------------------------------------------*/
/*--------------------------------------------------------------------------------------------------------------*/
public void run()
{
Message message;
while( true )
{
message = synchr.getMessage();
switch(message.type)
{
case SynchrMenu.MAKENEWFRACTAL:
xLeft = message.xLeft;
xRight = message.xRight;
yLow = message.yLow;
yHigh = message.yHigh;
nX = message.nX;
nY = message.nY;
cSchm = message.cschm;
iter = message.iter;
nIter = message.nIter;
ceiling= message.ceiling;
a = message.a;
b = message.b;
makeNewFractal();
break;
case SynchrMenu.MOVEX:
moveX(message.dx);
break;
case SynchrMenu.MOVEY:
moveY(message.dy);
break;
case SynchrMenu.CHANGESCALE:
changeScale(message.chSize);
break;
case SynchrMenu.CHANGECOLOR:
cSchm = message.cschm;
draw();
break;
case SynchrMenu.DRAW:
draw();
break;
case SynchrMenu.GETPOINT:
FractalPoint fp = new FractalPoint( field[message.i][message.j] );
mainWindow.putIterXYdata(fp.x(), fp.y(), fp.nIter());
break;
}
}
}
} | Java |
package fracPackage;
import polishNotation.Iteration;
import polishNotation.PolishNotation;
import java.util.*;
public class SynchrMenu
{
public static final int NOTHING = -1;
public static final int MAKENEWFRACTAL = 0;
public static final int CHANGESCALE = 1;
public static final int MOVEX = 2;
public static final int MOVEY = 3;
public static final int CHANGEDATA = 4;
public static final int CHANGEITER = 5;
public static final int CHANGECOLOR = 6;
public static final int DRAW = 7;
public static final int GETPOINT = 8;
public static final int RENEWDATA = 9;
public static final int CHANGEAB = 10;
private LinkedList<Message> MessageQueue;
private int dx;
private int dy;
private double chSize;
private FractalPoint fPoint;
private int i;
private int j;
private double xLeft;
private double xRight;
private double yLow;
private double yHigh;
private int nX;
private int nY;
private int nIter;
private Iteration iter;
private ColorScheme cschm;
private double a, b;
private double ceiling;
private int gorizontal;
private int vertical;
boolean isMessage;
boolean isBusy;
public SynchrMenu()
{
xLeft = Fractal.xLeftDefault; xRight = Fractal.xRightDefault;
yLow = Fractal.yLowDefault; yHigh = Fractal.yHighDefault;
nX = Fractal.nXDefault; nY = Fractal.nYDefault;
gorizontal = 600;
vertical = 600;
a = Fractal.aDefault;
b = Fractal.bDefault;
ceiling = Fractal.ceilingDefault;
nIter = Fractal.nIterDefault;
PolishNotation pont = new PolishNotation(Fractal.iterDefault);
pont.polish();
iter = new Iteration(pont.outline);
cschm = new ColorScheme(0);
MessageQueue = new LinkedList<Message>();
isMessage = false;
}
public void makeNewFractal()
{
putMessage(MAKENEWFRACTAL);
}
synchronized private void putMessage(int MessageType)
{
Message mess = new Message();
mess.type = MessageType;
mess.a = a;
mess.b = b;
mess.i = i;
mess.j = j;
mess.xLeft = xLeft;
mess.xRight = xRight;
mess.yLow = yLow;
mess.yHigh = yHigh;
mess.nX = nX;
mess.nY = nY;
mess.iter = iter;
mess.nIter = nIter;
mess.cschm = cschm;
mess.dx = dx;
mess.dy = dy;
mess.chSize = chSize;
mess.ceiling = ceiling;
MessageQueue.offer(mess);
notify();
}
synchronized public Message getMessage()
{
if(MessageQueue.isEmpty())
try { wait(); }
catch(InterruptedException e) { }
return MessageQueue.poll();
}
synchronized public boolean watchMessage()
{
for( Message msg : MessageQueue )
{
if(msg.type == MAKENEWFRACTAL || msg.type == CHANGESCALE) return true;
}
return false;
}
//===============================BEFORE, IT WAS USERMENU=================================================================
public int setIter(String input)
{
PolishNotation pnot = new PolishNotation(input);
pnot.polish();
iter = new Iteration(pnot.outline);
return 0;
}
public void setColor(double param)
{
cschm = new ColorScheme(param);
putMessage(CHANGECOLOR);
}
public void setAB(double A, double B)
{
a = A;
b = B;
}
public void changeScale (double chSizeParam )
{
chSize = chSizeParam;
double xl = xLeft; double xr = xRight;
double yl = yLow; double yh = yHigh;
xLeft = (xl + xr)/2 - (xr - xl)/2 * chSizeParam;
xRight = (xl + xr)/2 + (xr - xl)/2 * chSizeParam;
yLow = (yl + yh)/2 - (yh - yl)/2 * chSizeParam;
yHigh = (yl + yh)/2 + (yh - yl)/2 * chSizeParam;
putMessage(CHANGESCALE);
}
public void enlarge ()
{
changeScale(0.6);
}
public void ensmall ()
{
changeScale(1/0.6);
}
public void moveX(int dX)
{
dx = dX;
double xLeftOld = xLeft;
xLeft = Fractal.ItoX(0 + dx, nX, xLeftOld, xRight);
xRight = Fractal.ItoX(nX + dx, nX, xLeftOld, xRight);
putMessage(MOVEX);
}
public void moveY(int dY)
{
dy = dY;
double yLowOld = yLow;
yLow = Fractal.JtoY(nY - dy, nY, yLowOld, yHigh);
yHigh = Fractal.JtoY(0 - dy, nY, yLowOld, yHigh);
putMessage(MOVEY);
}
public FractalPoint getFPoint(int p, int q)
{
if(p < 0 || p > gorizontal || q < 0 || q > gorizontal) return null;
i = nX*p/gorizontal;
j = nY*q/vertical;
putMessage(GETPOINT);
return fPoint;
}
public void setDimension(int Size)
{
gorizontal = vertical = Size;
}
public int setProperties(String X, String Y, String Size, String nXY, String NIter, String Ceiling)
{
double x, y, size, ceil;
int nxy, niter;
try {
x = Double .parseDouble(X);
y = Double .parseDouble(Y);
size = Double .parseDouble(Size);
nxy = Integer.parseInt(nXY);
niter = Integer.parseInt(NIter);
ceil = Double .parseDouble(Ceiling);
} catch (NumberFormatException e) { return -1; }
if(size <= 2.0E-14 ||
nxy <= 0 ||
ceil < 2 ||
ceil > 1000) return -1;
xLeft = x;
xRight = x + size;
yLow = y - size;
yHigh = y;
nX = nxy;
nY = nxy;
nIter = niter;
ceiling = ceil;
return 0;
}
public void setDefaultProperties()
{
xLeft = Fractal.xLeftDefault; xRight = Fractal.xRightDefault;
yLow = Fractal.yLowDefault; yHigh = Fractal.yHighDefault;
nX = Fractal.nXDefault; nY = Fractal.nYDefault;
ceiling = Fractal.ceilingDefault;
nIter = Fractal.nIterDefault;
}
public void moveLeft()
{
moveX(-nX/15 - 1);
}
public void moveRight()
{
moveX( nX/15 + 1);
}
public void moveUp()
{
moveY( nY/15 + 1);
}
public void moveDown()
{
moveY(-nY/15 - 1);
}
public double xLeft()
{
return xLeft;
}
public double xRight()
{
return xRight;
}
public double yLow()
{
return yLow;
}
public double yHigh()
{
return yHigh;
}
public int nX()
{
return nX;
}
public int nY()
{
return nY;
}
public int nIter()
{
return nIter;
}
public Iteration iter()
{
return iter;
}
public ColorScheme cschm()
{
return cschm;
}
public int dx()
{
return dx;
}
public int dy()
{
return dy;
}
public double chSize()
{
return chSize;
}
public double a()
{
return a;
}
public double b()
{
return b;
}
public double ceiling()
{
return ceiling;
}
} | Java |
package fracPackage;
import polishNotation.Complex;
import polishNotation.Iteration;
public class pObject
{
Iteration iter;
private Complex z;
private Complex c;
private double ceiling;
public pObject(double x, double y, Iteration Iter, double Ceiling) // MANDELBROT
{
z = new Complex(0,0); c = new Complex(x,y);
iter = Iter;
ceiling = Ceiling;
}
public pObject(double x, double y, double a, double b, Iteration Iter, double Ceiling)
{
z = new Complex(x,y); c = new Complex(a,b); // JULIA
iter = Iter;
ceiling = Ceiling;
}
public void iterate ()
{
iter.setZ(z);
iter.setC(c);
z = new Complex(iter.iterate());
}
public boolean isOut (double x, double y)
{
return z.mod() > ceiling;
}
} | Java |
package fracPackage;
public interface AbleToDraw
{
public void putIterXYdata(double x, double y, int nIter);
}
| Java |
package fracPackage;
import java.awt.Component;
import polishNotation.Iteration;
public class JuliaFractal extends Fractal
{
public JuliaFractal(SynchrMenu synchr, Component Graph, AbleToDraw Window)
{
super(synchr, Graph, Window);
a = synchr.a();
b = synchr.b();
}
public FractalPoint makeField(double xi, double yj, Iteration iter)
{
return new FractalPoint(xi, yj, a, b, iter, ceiling);
}
} | Java |
package polishNotation;
public class OperObject extends Operand{
private boolean isOperand;
private boolean isOperator;
private Operand operand;
private char operator;
OperObject(boolean nd, boolean tor, Operand o, char c){ //constructors
this.isOperand = nd;
this.isOperator = tor;
this.operand = new Operand(o);
this.operator = c;
}
OperObject(Operand o){ //constructors
this.isOperand = true;
this.isOperator = false;
this.operand = new Operand(o);
}
OperObject(char c){ //constructors
this.isOperand = false;
this.isOperator = true;
this.operator = c;
}
public boolean isOperand(){
return isOperand;
}
public boolean isOperator(){
return isOperator;
}
public void setOperand(Operand o){
operand.setOperand(o);
}
public void setOperator(char c){
this.operator = c;
}
public Operand getOperand(){
return operand;
}
public char getOperator(){
return operator;
}
public String toString(){
if(isOperand)
return operand.toString();
else if(isOperator)
return "operator " + operator;
else return "0";
}
} | Java |
package polishNotation;
import java.util.LinkedList;
public class PolishNotation{
public LinkedList<OperObject> outline; //fields
public LinkedList<OperObject> stack;
public String s;
public PolishNotation(){ //constructor
s = "";
outline = new LinkedList<OperObject>() ;
stack = new LinkedList<OperObject>() ;
}
public PolishNotation(String arg){ //constructor 2
s = arg;
outline = new LinkedList<OperObject>() ;
stack = new LinkedList<OperObject>() ;
}
static boolean isDelim(char c) {
return c == ' ';
}
static boolean isZ(char c) {
return (c == 'z')||(c == 'Z');
}
static boolean isC(char c) {
return (c == 'c')||(c == 'C');
}
static boolean isBiOperator(char c) {
return c == '+' || c == '-' || c == '*' || c == '/' || c == '^';
}
static boolean isUniOperator(char c) {
return c == 's' || c == 'o' || c == 't' || c == 'g' || c == 'e';
}
static int priority(char op) {
switch (op) {
case '(':
return 1;
case '+':
case '-':
return 2;
case '*':
case '/':
return 3;
case '^':
return 4;
case 's':
case 'o':
case 'g':
case 't':
case 'e':
return 5;
default:
return -1;
}
}
public int analyse(){
int count = 0;
int i = 0;
boolean biOperatorExpected = false;
boolean operandExpected = true;
boolean thereIsZ = false;
boolean thereIsC = false;
s = s.replace(" ", "");
s = s.replace("(-", "(0-");
s = s.replace("sin", "s");
s = s.replace("cos", "o");
s = s.replace("ctg", "g");
s = s.replace("tg", "t");
s = s.replace("exp", "e");
while(i < s.length()) {
char b = s.charAt(i);
if (! Character.isDigit(b) && !(b == '.')&& !(b == 'i') &&!isBiOperator(b) && !isUniOperator(b) && !(b == '(') && !( b== ')') && !(isZ(b)) && !(isC(b))){
return -1;
}
++i;
}
i = 0;
while(i < s.length()) {
char b = s.charAt(i);
if (Character.isDigit(b)){
if(operandExpected == false){
return -1;
}
while(i < s.length()-1 && (Character.isDigit(s.charAt(i+1)) || (s.charAt(i+1) == '.') )){
++i;
b = s.charAt(i);
}
biOperatorExpected = true;
operandExpected = false;
}
if (b == 'i'){
if(i<=1 || ! Character.isDigit(s.charAt(i-1))){
return -1;
}
}
if (isBiOperator(b)){
if(biOperatorExpected == false){
return -1;
}
biOperatorExpected = false;
operandExpected = true;
if (b == '^'){
int j = i+1;
char h = s.charAt(j);
if(h == '('){
int hCount = 1;
while( hCount >0 && !isZ(h) && !isC(h) &&!(h == '/')&& !(h == '.') && j < s.length() ) {
j++;
h = s.charAt(j);
if(h == '(') hCount++;
if(h == ')') hCount--;
System.out.println(h);
}
if (h == '.' || h == '/' || isZ(h) || isC(h)){
return -1;
}
} else {
while( !isZ(h) && !isC(h) && !(h == '.')&& !(h == '/') && !isBiOperator(h) && !isUniOperator(h) && j < s.length() ) {
j++;
h = s.charAt(j);
}
if (h == '.' ||h == '/' || isZ(h) || isC(h)){
return -1;
}
}
}
}
if (isUniOperator(b)){
if(operandExpected == false){
return -1;
}
}
if(b == '('){
++count;
if(biOperatorExpected == true){
return -1;
}
}
if( b== ')'){
--count;
if(operandExpected == true){
return -1;
}
}
if (isZ(b)) {
if(operandExpected == false){
return -1;
}
biOperatorExpected = true;
operandExpected = false;
thereIsZ = true;
}
if (isC(b)) {
if(biOperatorExpected == true){
return -1;
}
biOperatorExpected = true;
operandExpected = false;
thereIsC = true;
}
if(count<0){
return -1;
}
++i;
}
if (!thereIsZ || !thereIsC){
return -1;
}
if(count != 0){
return -1;
} else {
return 1;
}
}
public int polish() {
for (int i = 0; i < s.length(); i++) {
char b = s.charAt(i);
if(b== '('){
stack.add(new OperObject(b));
} else if( b== ')'){
while(!stack.isEmpty() && !(stack.getLast().getOperator() == '(')){
OperObject op = stack.removeLast();
if(!(op.getOperator() == '(')){
outline.add(op);
}
}
stack.removeLast();
} else if (isBiOperator(b)){
while(!stack.isEmpty() && (priority(stack.getLast().getOperator()) >= priority(b))){
OperObject op = stack.removeLast();
outline.add(op);
}
stack.add(new OperObject(b));
} else if (isUniOperator(b)){
while(!stack.isEmpty() && (priority(stack.getLast().getOperator()) >= priority(b))){
OperObject op = stack.removeLast();
outline.add(op);
}
stack.add(new OperObject(b));
} else if (isZ(b)) {
outline.add(new OperObject(new Operand('z')));
} else if (isC(b)) {
outline.add(new OperObject(new Operand('c')));
} else if(Character.isDigit(s.charAt(i))){
String number = "";
while (i < s.length() && (Character.isDigit(s.charAt(i)) || (s.charAt(i)== '.') || (s.charAt(i)== 'i')))
number += s.charAt(i++);
--i;
Complex a;
if(s.charAt(i)== 'i'){
number = number.replace("i", "");
a = new Complex(0,Double.parseDouble(number));
}else {
a = new Complex(Double.parseDouble(number));
}
Operand oper = new Operand(a);
OperObject toadd = new OperObject(oper);
outline.add(toadd);
}
}
while(!stack.isEmpty()){
OperObject sign = stack.removeLast();
if(! (sign.getOperator() == '(') && !(sign.getOperator() == ')')){
outline.add(sign);
}
}
return 1;
}
}
| Java |
package polishNotation;
public class Complex {
private static final double EPS = 1e-12; // accuracy
private double re, im;
public Complex(double re, double im) { // constructors
this.re = re; this.im = im;
}
public Complex(double re){
this(re, 0.0);
}
public Complex(){
this(0.0, 0.0);
}
public Complex(Complex z){
this(z.getRe(), z.getIm()) ;
}
// access
public double getRe(){
return re;
}
public double getIm(){
return im;
}
public Complex getZ(){
return this;
}
public void setRe(double re){this.re = re;}
public void setIm(double im){this.im = im;}
public void setZ(Complex z){re = z.getRe(); im = z.getIm();}
// mod and arg
public double mod(){
return Math.sqrt(re * re + im * im);
}
public double arg(){
return Math.atan2(im, re);
}
public boolean isReal(){
return Math.abs(im) < EPS;
}
// methods of class Object
public boolean equals(Complex z){
return Math.abs(re -z.re) < EPS &&
Math.abs(im - z.im) < EPS;
}
public String toString(){
return "Complex: " + re + " " + im;
}
public void mul(Complex z){ //*=
double t = re * z.re - im * z.im;
im = re * z.im + im * z.re;
re = t;
}
public Complex plus(Complex z){ // +
return new Complex(re + z.re, im + z.im);
}
public Complex minus(Complex z){ //-
return new Complex(re - z.re, im - z.im);
}
public Complex asterisk(Complex z){ // *
return new Complex(
re * z.re - im * z.im, re * z.im + im * z.re);
}
public Complex slash(Complex z){ // /
double m = z.mod();
return new Complex( (re * z.re + im * z.im) / m /m, (im * z.re - re * z.im) / m /m);
}
public Complex pow(double n){ // ^ in real power
if( ((int)n == n ) && n > 0){
Complex result = new Complex(this);
int i=1;
while(i < n){
result.mul(this);
++i;
}
return result;
}else{
return new Complex();
}
}
public Complex exp(){ // exponenta
return new Complex(Math.exp(re)* Math.cos(im) , Math.exp(re)* Math.sin(im));
}
public Complex cos(){ // cos
Complex a = new Complex(0.5);
Complex b = new Complex(-im, re);
Complex c = new Complex(im, -re);
if(((b.exp()).plus(c.exp())).asterisk(a).mod() <EPS ){
return new Complex();
} else return new Complex( ((b.exp()).plus(c.exp())).asterisk(a));
}
public Complex sin(){ // sin
Complex a = new Complex(0, -0.5);
Complex b = new Complex(-im, re);
Complex c = new Complex(im, -re);
if(((b.exp()).minus(c.exp())).asterisk(a).mod() <EPS ){
return new Complex();
} else return new Complex( ((b.exp()).minus(c.exp())).asterisk(a));
}
public Complex tan(){ // tan
return new Complex( this.sin().slash(this.cos()));
}
public Complex cotan(){ // cotan
return new Complex( this.cos().slash(this.sin()));
}
}
| Java |
package polishNotation;
public class Operand extends Complex{
private boolean isNumber;
private boolean isZ;
private boolean isC;
private Complex value;
Operand(){ //constructors
this.isNumber = true;
this.isZ = false;
this.isC = false;
this.value = new Complex();
}
public Operand(boolean n, boolean z, boolean c, Complex val){ //constructors
this.isNumber = n;
this.isZ = z;
this.isC = c;
this.value = new Complex(val);
}
public Operand(Operand op){ //constructors
this.isNumber = op.isNumber;
this.isZ = op.isZ;
this.isC = op.isC;
this.value = new Complex(op.value);
}
public Operand(double re, double im){ //constructors
this.isNumber = true;
this.isZ = false;
this.isC = false;
this.value.setRe(re);
this.value.setIm(im);
}
public Operand(Complex z){ //constructors
this.isNumber = true;
this.isZ = false;
this.isC = false;
this.value = new Complex(z);
}
public Operand(Complex z, Character c){
isNumber = false;
if(c == 'c' || c == 'C') {
isC = true;
isZ = false;
}
if(c == 'z' || c == 'Z') {
isZ = true;
isC = false;
}
value = new Complex(z);
}
public Operand(Character c){
this(new Complex(),c);
}
public boolean isZ(){
return isZ;
}
public boolean isC(){
return isC;
}
public boolean isNumber(){
return isNumber;
}
public void setValue(Complex a){
value.setZ(a);
}
public Complex getValue(){
return value;
}
public void setOperand(boolean n, boolean z, boolean c, Complex val){ //constructors
this.isNumber = n;
this.isZ = z;
this.isC = c;
this.value = new Complex(val);
}
public void setOperand(Operand o){ //constructors
this.setOperand(o.isNumber, o.isZ, o.isC, o.value);
}
// +, -, *, /, ^
public Operand plus(Operand z){ // +
return new Operand(this.value.plus(z.value));
}
public Operand minus(Operand z){ //-
return new Operand(this.value.minus(z.value));
}
public Operand asterisk(Operand z){ //*
return new Operand(this.value.asterisk(z.value));
}
public Operand slash(Operand z){ // *
return new Operand(this.value.slash(z.value));
}
public Operand pow(Operand z){ //-
return new Operand(this.value.pow(z.value.getRe()));
}
public Operand exp(){ // exponenta
return new Operand(this.value.exp());
}
public Operand cos(){ // cos
return new Operand(this.value.cos());
}
public Operand sin(){ // sin
return new Operand(this.value.sin());
}
public Operand tan(){ // tan
return new Operand(this.value.tan());
}
public Operand cotan(){ // cotan
return new Operand(this.value.cotan());
}
public String toString(){
if(isNumber) return value.toString();
else if(isZ) return "z";
else if(isC) return "c";
else return "" + isNumber + isZ + isC + value;
}
} | Java |
package polishNotation;
import java.util.LinkedList;
//import java.util.LinkedList;
public class Iteration{
public LinkedList<OperObject> outline;
public Complex z;
public Complex c;
public Iteration(){
z = new Complex();
c = new Complex();
this.outline = new LinkedList<OperObject>();
}
public Iteration(Complex z, Complex c){
this.z = new Complex(z);
this.c = new Complex(c);
this.outline = new LinkedList<OperObject>();
}
public Iteration(LinkedList<OperObject> iter, Complex z, Complex c){
this.z = new Complex(z);
this.c = new Complex(c);
this.outline = new LinkedList<OperObject>(iter);
}
public Iteration(Iteration a){
this.z = new Complex(a.z);
this.c = new Complex(a.c);
this.outline = new LinkedList<OperObject>(a.outline);
}
public Iteration(LinkedList<OperObject> iter){
this.z = new Complex();
this.c = new Complex();
this.outline = new LinkedList<OperObject>(iter);
}
public void setZ(Complex z){
this.z = new Complex(z);
}
public void setC(Complex c){
this.c = new Complex(c);
}
public Complex iterate(){
LinkedList<OperObject> line = new LinkedList<OperObject>(outline);
LinkedList<Operand> st = new LinkedList<Operand>();
while(!line.isEmpty()){
OperObject op = line.removeFirst();
if (op.isOperand()){
if (op.getOperand().isZ()){
op.getOperand().setOperand(false, true, false, z);
st.add(new Operand(op.getOperand().getValue()));
} else if (op.getOperand().isC()){
op.getOperand().setOperand(false, false, true, c);
st.add(new Operand(op.getOperand().getValue()));
} else st.add(op.getOperand());
}
if (op.isOperator()){
if (PolishNotation.isBiOperator(op.getOperator())){
Operand r = st.removeLast();
Operand l = st.removeLast();
switch (op.getOperator()) {
case '+':
st.add(l.plus(r));
break;
case '-':
st.add(l.minus(r));
break;
case '*':
st.add(l.asterisk(r));
break;
case '/':
st.add(l.slash(r));
break;
case '^':
st.add(l.pow(r));
break;
}
}
if (PolishNotation.isUniOperator(op.getOperator())){
Operand r = st.removeLast();
switch (op.getOperator()) {
case 's':
st.add(r.sin());
break;
case 'o':
st.add(r.cos());
break;
case 't':
st.add(r.tan());
break;
case 'g':
st.add(r.cotan());
break;
case 'e':
st.add(r.exp());
break;
}
}
}
}
Complex result = new Complex(st.removeLast().getValue());
return result;
}
} | Java |
package main_interface;
import java.awt.Image;
import java.awt.image.ImageObserver;
public class FractalObserver implements ImageObserver {
public boolean imageUpdate(Image img,int infoflags,int x,int y, int width, int heith){
return true;
}
}
| Java |
package main_interface;
import java.awt.BorderLayout;
import java.awt.Dimension;
import java.io.File;
import javax.swing.ImageIcon;
import javax.swing.JButton;
import javax.swing.JEditorPane;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JTabbedPane;
import javax.swing.JTextArea;
import javax.swing.JTextPane;
import javax.swing.ScrollPaneConstants;
public class helpWindow extends JFrame{
public JEditorPane editor;
public JEditorPane editor0;
public void MakeAll(JEditorPane e1, JEditorPane e2) {
JFrame frame = new JFrame();
frame.setName("Help");
frame.pack();
JPanel panel = new JPanel();
panel.setLayout(new BorderLayout());
JPanel icon = new JPanel();
icon.setLayout(new BorderLayout());
JLabel us = new JLabel(new ImageIcon("fill-color.png"));
us.setOpaque(false);
icon.setPreferredSize(new Dimension(400,50));
icon.add(us,BorderLayout.WEST);
JPanel other = new JPanel();
other.setLayout(new BorderLayout());
JTabbedPane tabPanel = new JTabbedPane(JTabbedPane.TOP, JTabbedPane.SCROLL_TAB_LAYOUT);
JPanel tab1 = new JPanel(new BorderLayout(0,0));
try{
File homePage0 = new File("programm.html");
String path0 = homePage0.getAbsolutePath();
e1 = new JEditorPane("file://"+path0);
} catch (Exception ex) {
}
e1.setContentType("text/html");
e1.setEditable(false);
tab1.add(e1);
tab1.setPreferredSize(new Dimension(400,650));
tabPanel.addTab("О программе",tab1);
JPanel tab2 = new JPanel(new BorderLayout(0,0));
try{
File homePage = new File("instuction.html");
String path = homePage.getAbsolutePath();
e2 = new JEditorPane("file://"+path);
} catch (Exception ex) {
}
e2.setContentType("text/html");
e2.setEditable(false);
JScrollPane scroll = new JScrollPane(e2);
tab2.add(scroll);
tabPanel.addTab("Инструкция",tab2);
other.add(tabPanel,BorderLayout.CENTER);
frame.add(icon, BorderLayout.NORTH);
frame.add(other,BorderLayout.CENTER);
frame.setSize(420,470);
frame.setTitle("Help");
//frame.setResizable(false);
frame.setLocationRelativeTo(null);
frame.setAlwaysOnTop(true);
frame.setVisible(true);
}
} | Java |
package main_interface;
import javax.swing.filechooser.FileFilter;
public class JpgFilesFilter extends FileFilter {
public boolean accept(java.io.File file) {
if ( file.isDirectory() )
return true;
return ( file.getName().endsWith("jpg")) ;
}
public String getDescription() {
return "Изображения (*.jpg)";
}
}
| Java |
package main_interface;
import javax.swing.filechooser.FileFilter;
public class PngFilesFilter extends FileFilter {
public boolean accept(java.io.File file) {
if ( file.isDirectory() )
return true;
return ( file.getName().endsWith("png")) ;
}
public String getDescription() {
return "Изображения (*.png)";
}
} | Java |
package main_interface;
import javax.swing.filechooser.FileFilter;
public class TextFilesFilter extends FileFilter {
public boolean accept(java.io.File file) {
if ( file.isDirectory() ) return true;
return ( file.getName().endsWith(".frac") );
}
public String getDescription() {
return "Фрактал (*.frac)";
}
}
| Java |
package main_interface;
import java.awt.BorderLayout;
import java.awt.Dimension;
import java.awt.GridLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.JTextArea;
import javax.swing.JTextField;
import fracPackage.SynchrMenu;
public class ParametersWin {
public JFrame frame;
public JPanel pane[];
public JTextField text[];
public void MakeParamWin(final SynchrMenu sm){
frame = new JFrame();
frame.setResizable(false);
frame.setSize(new Dimension(320,300));
frame.setAlwaysOnTop(true);
JPanel panel = new JPanel();
JPanel pane0 = new JPanel();
pane0.add(new JLabel("Задайте параметры:"));
panel.add(pane0);
final String label[] = {" Координата X "," Координата Y "," Размер "," Разрешение ","Число итераций", " Бесконечность "};
JLabel[] label0 = new JLabel[label.length];
pane = new JPanel[label.length];
text = new JTextField[label.length];
for (int i=0;i < label.length;++i ){
label0[i] = new JLabel();
label0[i].setText(label[i]);
pane[i] = new JPanel();
pane[i].add(label0[i]);
text[i] = new JTextField();
text[i].setColumns(6);
pane[i].add(text[i]);
panel.add(pane[i]);
}
text[0].setText(""+sm.xLeft());
text[1].setText(""+sm.yHigh());
text[2].setText(""+(sm.xRight() - sm.xLeft()));
text[3].setText(""+sm.nX());
text[4].setText(""+sm.nIter());
text[5].setText(""+sm.ceiling());
JButton confirm = new JButton("Применить");
confirm.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e){
if (sm.setProperties(text[0].getText(),text[1].getText(),text[2].getText(),text[3].getText(),text[4].getText(),text[5].getText()) < 0 ){
JOptionPane.showMessageDialog(frame,"Некорректно заполнены поля!", "Ошибка",JOptionPane.WARNING_MESSAGE);
return;
}
sm.makeNewFractal();
frame.dispose();
}
});
JButton asItWas = new JButton("По умолчанию");
asItWas.addActionListener(new ActionListener(){
public void actionPerformed( ActionEvent e){
sm.setDefaultProperties();
sm.makeNewFractal();
frame.dispose();
}
});
JPanel l = new JPanel();
JPanel l1 = new JPanel();
l.add(confirm);
l1.add(asItWas);
panel.add(l);
panel.add(l1);
frame.add(panel);
frame.setTitle("Parameters");
frame.setLocationRelativeTo(null);
frame.setVisible(true);
}
}
| Java |
package main_interface;
import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.Dimension;
import java.awt.Graphics;
import java.awt.Toolkit;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.File;
import java.io.IOException;
import javax.imageio.ImageIO;
import javax.swing.ImageIcon;
import javax.swing.JButton;
import javax.swing.JComponent;
import javax.swing.JFileChooser;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JMenu;
import javax.swing.JMenuBar;
import javax.swing.JMenuItem;
import javax.swing.JPanel;
import javax.swing.JTabbedPane;
import javax.swing.JToolBar;
import javax.swing.KeyStroke;
import polishNotation.PolishNotation;
import main_interface.MainFrame.swComponent;
import fracPackage.AbleToDraw;
import fracPackage.Fractal;
import fracPackage.JuliaFractal;
import fracPackage.SynchrMenu;
public class JuliaWindow implements AbleToDraw {
private JButton savePic;
private SynchrMenu synchrMenuJ;
JFrame frame= new JFrame();
private JFileChooser fcp;
private JpgFilesFilter jpg;
private PngFilesFilter png;
public JuliaFractal fractalJulia;
public JPanel graphJul;
private swComponent c;
public void MakeJuliaFrame(double a, double b,String s) {
final JFrame frame= new JFrame(); frame.setName("Julia");
JPanel panel = new JPanel();
panel.setLayout(new BorderLayout());
JMenuBar menuBar = new JMenuBar();
savePic = new JButton("Cохранить");
savePic.setFocusable(false);
savePic.setOpaque(false);
savePic.setContentAreaFilled(false);
savePic.setBorderPainted(false);
JButton param = new JButton("Параметры");
param.setFocusable(false);
param.setOpaque(false);
param.setContentAreaFilled(false);
param.setBorderPainted(false);
param.addActionListener(new ActionListener(){
public void actionPerformed(ActionEvent e){
ParametersWin w = new ParametersWin();
w.MakeParamWin(synchrMenuJ);
}
});
jpg = new JpgFilesFilter();
png = new PngFilesFilter();
fcp = new JFileChooser();
fcp.addChoosableFileFilter(jpg);
fcp.addChoosableFileFilter(png);
savePic.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
fcp.setDialogTitle("Сохранение файла");
fcp.setFileSelectionMode(JFileChooser.FILES_ONLY);
int res = fcp.showSaveDialog(frame);
if ( res == JFileChooser.APPROVE_OPTION ){
try{
if (fcp.getFileFilter() == jpg) {
ImageIO.write(fractalJulia.getImage(), "JPG", new File(fcp.getSelectedFile().getAbsolutePath()+".jpg"));
System.out.println(fcp.getSelectedFile().getAbsolutePath());
} else
if (fcp.getFileFilter() == png) {
ImageIO.write(fractalJulia.getImage(), "PNG", new File(fcp.getSelectedFile().getAbsolutePath()+".png"));
System.out.println(fcp.getSelectedFile().getAbsolutePath());
} else {
ImageIO.write(fractalJulia.getImage(), "JPG", new File(fcp.getSelectedFile().getAbsolutePath()+".jpg"));
}
} catch (IOException ie) {
ie.printStackTrace();
}
}
}
});
menuBar.add(savePic);
menuBar.add(param);
panel.add(menuBar,BorderLayout.NORTH);
JPanel picture = new JPanel();
c = new swComponent();
synchrMenuJ = new SynchrMenu();
fractalJulia = new JuliaFractal (synchrMenuJ, c, this);
synchrMenuJ.setAB(a,b);
PolishNotation pol = new PolishNotation(s);
synchrMenuJ.setIter(pol.s);
synchrMenuJ.makeNewFractal();
c.setPreferredSize(new Dimension(600, 600));
picture.add(c, BorderLayout.CENTER);
picture.add(new JLabel(" "), BorderLayout.NORTH);
picture.add(new JLabel(" "), BorderLayout.SOUTH);
picture.add(new JLabel(" "), BorderLayout.WEST);
picture.setOpaque(false);
picture.revalidate();
JToolBar toolbar = new JToolBar("Toolbar",JToolBar.VERTICAL);
toolbar.setOpaque(false);
toolbar.setFloatable(false);
String[] iconFiles = { "zoom-in.png", "zoom-out.png","arrow-left1.png","arrow-right1.png","arrow-up1.png","arrow-down1.png", "fill-color1.png" };
String[] newiconFiles = { "zoom-in2.png", "zoom-out2.png","arrow-left.png","arrow-right.png","arrow-up.png","arrow-down.png", "fill-color.png" };
String[] buttonLabels = { "����������", "��������", "�����","������","�����","����","����"};
ImageIcon[] icons = new ImageIcon[iconFiles.length];
JButton[] buttons = new JButton[buttonLabels.length];
for (int i = 0; i < iconFiles.length; ++i) {
icons[i] = new ImageIcon(iconFiles[i]);
buttons[i] = new JButton(icons[i]);
buttons[i].setFocusPainted(false);
buttons[i].setContentAreaFilled(false);
buttons[i].setToolTipText(buttonLabels[i]);
buttons[i].setOpaque(false);
buttons[i].setBorderPainted(false);
buttons[i].setRolloverIcon(new ImageIcon(newiconFiles[i]));
toolbar.add(buttons[i]);
}
buttons[1].addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
synchrMenuJ.ensmall();
c.repaint();
}
});
buttons[0].addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
synchrMenuJ.enlarge();
c.repaint();
}
});
buttons[2].addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
synchrMenuJ.moveLeft();
}
});
buttons[4].addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
synchrMenuJ.moveUp();
}
});
buttons[3].addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
synchrMenuJ.moveRight();
}
});
buttons[5].addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
synchrMenuJ.moveDown();;
}
});
buttons[6].addActionListener(new ActionListener(){
public void actionPerformed(ActionEvent e){
ColorWindow cw = new ColorWindow();
int position = cw.getPosition(1);
cw.MakeWindow(synchrMenuJ,position,1);
}
});
panel.add(toolbar,BorderLayout.EAST);
panel.add(picture, BorderLayout.CENTER);
frame.add(panel);
frame.setSize(650,658);
frame.setLocationRelativeTo(null);
frame.setResizable(false);
frame.setVisible(true);
}
public class swComponent extends JComponent {
public void paintComponent(Graphics g) {
FractalObserver fObs = new FractalObserver();
super.paintComponent(g);
g.drawImage(fractalJulia.getImage(),0,0, c.getHeight(), c.getHeight(),fObs);
}
}
public void putIterXYdata(double x, double y, int nIter)
{
}
}
| Java |
package main_interface;
import java.awt.BorderLayout;
import java.awt.Dimension;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.ImageIcon;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JSlider;
import fracPackage.SynchrMenu;
public class ColorWindow extends JFrame{
private static JSlider slider;
private static JFrame frame;
public static int result;
public static int result0;
public void MakeWindow(final SynchrMenu frac, int res,final int a) {
frame = new JFrame();
frame.setName("Color");
frame.pack();
JPanel panel = new JPanel();
JLabel shrift = new JLabel("Выберите цветовую гамму");
panel.add(new JLabel(" "));
panel.add(shrift);
JLabel bar = new JLabel(new ImageIcon("ColorBar.png"));
panel.add(bar);
slider = new JSlider(0, 30, 0);
slider.setMajorTickSpacing(500);
slider.setPaintTicks(true);
slider.setValue(res);
slider.setValue(res);
Dimension d = slider.getPreferredSize();
slider.setPreferredSize(new Dimension(d.width+117,d.height));
panel.add(slider);
JButton okey = new JButton("Применить");
okey.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
if (a == 0 ) {
result0 = slider.getValue();
frac.setColor(result0);
}
else {
result = slider.getValue();
frac.setColor(result);
}
frame.dispose();
}
});
panel.add(okey);
frame.add(panel);
frame.setSize(400,145);
frame.setLocationRelativeTo(null);
frame.setVisible(true);
}
public int getPosition(int a){
if (a == 0)
return result0;
else
return result;
}
}
| Java |
package main_interface;
import javax.imageio.ImageIO;
import javax.swing.*;
import javax.swing.border.*;
import java.awt.*;
import java.awt.event.*;
import java.awt.image.BufferedImage;
import java.awt.image.ImageObserver;
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
import javax.swing.filechooser.*;
import java.awt.AWTKeyStroke;
import java.awt.BorderLayout;
import java.awt.Container;
import java.awt.Dimension;
import java.awt.FlowLayout;
import java.awt.Graphics;
import java.awt.GridLayout;
import java.awt.Image;
import java.awt.KeyboardFocusManager;
import java.awt.LayoutManager;
import java.io.FileReader;
import java.util.HashSet;
import java.util.Locale;
import java.util.Scanner;
import javax.swing.border.*;
import polishNotation.PolishNotation;
import fracPackage.AbleToDraw;
import fracPackage.ColorScheme;
import fracPackage.Fractal;
import fracPackage.JuliaFractal;
import fracPackage.FractalPoint;
import fracPackage.SynchrMenu;
public class MainFrame extends JFrame implements AbleToDraw {
private DefaultListModel<String> list_model;
private DefaultListModel<String> list_model_favorite;
private JList<String> list2;
private JList<String> list1;
private JpgFilesFilter jpg;
private PngFilesFilter png;
private TextFilesFilter txt;
private JMenuItem delete;
private JMenuItem removeAll;
private JPopupMenu pm;
private JButton[] buttons;
public JPanel graph;
public JPanel picture;
private JFileChooser fc1;
private JFileChooser fcp;
private JMenuItem savePic;
public final JTextField t1,t2,t3;
private int i;
private JButton param;
private int ScreenWidth;
private int ScreenHeight;
public Fractal fractal;
public SynchrMenu synchrMenu;
public MainFrame() {
super("main_frame");
setDefaultCloseOperation(EXIT_ON_CLOSE);
pack();
// setContentPane(new JLabel(new ImageIcon("3.jpg")));
getScreenSize();
setSize((ScreenWidth*25/40),(ScreenHeight*35/40));
setTitle("Mandelbrot ABC");
setLocationRelativeTo(null);
JMenuBar menuBar = new JMenuBar();
JMenu file = new JMenu("Файл");
JMenuItem open = new JMenuItem("Открыть избранные");
//make hot key
open.setAccelerator(KeyStroke.getKeyStroke("ctrl O"));
JMenuItem saveObj = new JMenuItem("Cохранить избранные");
saveObj.setAccelerator(KeyStroke.getKeyStroke("ctrl S"));
savePic = new JMenuItem("Cохранить изображение");
savePic.setAccelerator(KeyStroke.getKeyStroke("ctrl P"));
file.add(open);
file.addSeparator();
file.add(saveObj);
file.add(savePic);
//the rigth order is important!
menuBar.add(file);
JButton help = new JButton("Справка");
help.setContentAreaFilled(false);
help.setOpaque(false);
help.setBorderPainted(false);
help.setFocusable(false);
help.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
helpWindow u = new helpWindow();
u.editor0 = new JEditorPane();
u.editor = new JEditorPane();
u.MakeAll(u.editor0, u.editor);
}
});
param = new JButton("Параметры");
param.setOpaque(false);
param.setContentAreaFilled(false);
param.setBorderPainted(false);
param.setEnabled(false);
param.setFocusable(false);
param.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
ParametersWin paramWin = new ParametersWin();
paramWin.MakeParamWin(synchrMenu);
}
});
menuBar.add(param);
menuBar.add(help);
setJMenuBar(menuBar);
final JTextField smallField;
smallField = new JTextField(13);
t1 = new JTextField(10);
t1.setToolTipText("Re(c)");
t2 = new JTextField(10);
t2.setToolTipText("Im(c)");
t3 = new JTextField(3);
t3.setToolTipText("n - количество итераций до бесконечности");
//табличное колво строк, столбцов, расстояния
JPanel grid = new JPanel(new GridLayout(1,1,0,0));
grid.setOpaque(false);
// добавляем компоненты
JPanel text_button = new JPanel(new FlowLayout(FlowLayout.LEFT));
text_button.setOpaque(false);
smallField.setToolTipText("Введите функцию");
text_button.add(new JLabel("f(z) = "));
text_button.add( smallField);
JButton draw = new JButton("ОК");
draw.setToolTipText("Нарисовать множество Мандельброта");
text_button.add(draw);
ImageIcon favImage = new ImageIcon("bookmarks2.png");
JButton fav = new JButton(favImage);
fav.setToolTipText("Добавить в избранное");
fav.setPreferredSize(new Dimension(22,22));
fav.setOpaque(false);
fav.setFocusPainted(false);
fav.setContentAreaFilled(false);
fav.setRolloverIcon(new ImageIcon("bookmarks.png"));
fav.setBorderPainted(false);
text_button.add(fav);
fav.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
check(smallField.getText(),list_model_favorite);
}
});
grid.add(text_button);
// JPanel har_button = new JPanel(new FlowLayout(FlowLayout.LEFT));
// har_button.setOpaque(false);
JPanel har = new JPanel(new FlowLayout(FlowLayout.CENTER ));
har.setToolTipText("Характеристики выбранной точки");
har.setOpaque(false);
har.add(t1);
har.add(t2);
har.add(t3);
text_button.add(har);
JButton Julia = new JButton("Жюлиа"); /////Julia
Julia.setToolTipText("Нарисовать для точки мн-во Жюлиа");
Julia.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
if ((t1.getText().length() > 0) & (t2.getText().length() > 0)) {
JuliaWindow julfr = new JuliaWindow();
julfr.MakeJuliaFrame(Double.parseDouble(t1.getText()), Double.parseDouble(t2.getText()),smallField.getText());
}
}
});
text_button.add(Julia);
// grid.add(har_button);
picture = new JPanel();
picture.setOpaque(false);
picture.setLayout(new BorderLayout());
graph = new JPanel();//// here we add picture of Mandelbrot made my Jenya
graph.setOpaque(false);
picture.add(graph);
/*-----------From Jenya--------------------------------------------------------------------------------------*/
synchrMenu = new SynchrMenu();
fractal = new Fractal(synchrMenu, graph, this);
/*-----------------------------------------------------------------------------------------------------------*/
graph.setLayout(new BorderLayout());
graph.addMouseListener(new MouseAdapter(){
public void mouseClicked(MouseEvent e){
if(e.getClickCount()==2)
{
synchrMenu.getFPoint(e.getX(), e.getY());
}
}
});
graph.setFocusable(true);
graph.addMouseListener(new MouseListener() {
@Override
public void mouseReleased(MouseEvent arg0) {
}
@Override
public void mousePressed(MouseEvent arg0) {
}
@Override
public void mouseExited(MouseEvent arg0) {
}
@Override
public void mouseEntered(MouseEvent arg0) {
}
@Override
public void mouseClicked(MouseEvent arg0) {
graph.grabFocus();
}
});
addKeyBindingLeft(graph);
addKeyBindingRight(graph);
addKeyBindingUp(graph);
addKeyBindingDown(graph);
draw.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
if ((smallField.getText()).length() > 0 ) {
PolishNotation input = new PolishNotation(smallField.getText());
if (input.analyse() < 0){
JOptionPane.showMessageDialog(MainFrame.this,
"Проверьте коректность функционального выражения", "Ошибка",
JOptionPane.WARNING_MESSAGE);
} else {
for (int i = 0; i < buttons.length; i++) {
buttons[i].setEnabled(true);
}
param.setEnabled(true);
synchrMenu.setDimension(graph.getHeight());
synchrMenu.setIter(input.s);
synchrMenu.makeNewFractal();
swComponent sw1 = new swComponent();
graph.add(sw1, BorderLayout.CENTER);
picture.revalidate();
}
} else
JOptionPane.showMessageDialog(MainFrame.this,
"Задайте функцию!", "Ошибка",
JOptionPane.WARNING_MESSAGE);
}});
fc1 = new JFileChooser();
fcp = new JFileChooser();
jpg = new JpgFilesFilter();
png = new PngFilesFilter();
txt = new TextFilesFilter();
fcp.addChoosableFileFilter(jpg);
fcp.addChoosableFileFilter(png);
savePic.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
fcp.setDialogTitle("Сохранение файла");
fcp.setFileSelectionMode(JFileChooser.FILES_ONLY);
int res = fcp.showSaveDialog(getContentPane());
if ( res == JFileChooser.APPROVE_OPTION ){
try{
if (fcp.getFileFilter() == jpg) {
ImageIO.write(fractal.getImage(), "JPG", new File(fcp.getSelectedFile().getAbsolutePath()+".jpg"));
System.out.println(fcp.getSelectedFile().getAbsolutePath());
} else
if (fcp.getFileFilter() == png) {
ImageIO.write(fractal.getImage(), "PNG", new File(fcp.getSelectedFile().getAbsolutePath()+".png"));
System.out.println(fcp.getSelectedFile().getAbsolutePath());
} else{
ImageIO.write(fractal.getImage(), "PNG", new File(fcp.getSelectedFile().getAbsolutePath()+".png"));
System.out.println(fcp.getSelectedFile().getAbsolutePath());
}
} catch (IOException ie) {
ie.printStackTrace();
}
}
}
});
fc1.addChoosableFileFilter(txt);
saveObj.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
fc1.setDialogTitle("Сохранение избранных");
fc1.setFileSelectionMode(JFileChooser.FILES_ONLY);
int res = fc1.showSaveDialog(getContentPane());
if ( res == JFileChooser.APPROVE_OPTION ){
if (list2.getModel().getSize() != 0 ) {
try {
if (fc1.getFileFilter() == txt ) {
FileWriter ryt = new FileWriter(fc1.getSelectedFile().getAbsolutePath()+ ".frac");
BufferedWriter out = new BufferedWriter(ryt);
for (int i=0; i < list2.getModel().getSize();i++) {
out.write((String)list_model_favorite.get(i));
out.newLine();
}
out.close();
} else {
FileWriter ryt = new FileWriter(fc1.getSelectedFile().getAbsolutePath());
BufferedWriter out = new BufferedWriter(ryt);
for (int i=0; i < list2.getModel().getSize();i++) {
out.write((String)list_model_favorite.get(i));
out.newLine();
}
out.close();
}
} catch (IOException ie) {
ie.printStackTrace();
}
}
}
}});
open.addActionListener(new ActionListener(){
public void actionPerformed(ActionEvent e) {
fc1.setDialogTitle("Открыть");
fc1.setFileSelectionMode(JFileChooser.FILES_ONLY);
int res = fc1.showOpenDialog(getContentPane());
if (res == JFileChooser.APPROVE_OPTION) {
File set_file = fc1.getSelectedFile();
try{
String selected_func;
FileReader selected_file = new FileReader(set_file);
BufferedReader reader = new BufferedReader(selected_file);
while ((selected_func = reader.readLine()) != null) {
check(selected_func,list_model_favorite);
}
}
catch (FileNotFoundException o) {
o.printStackTrace();
}
catch (IOException o) {
o.printStackTrace();
}
}
}});
smallField.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
if ((smallField.getText()).length() > 0 ) {
PolishNotation input = new PolishNotation(smallField.getText());
if (input.analyse() < 0){
JOptionPane.showMessageDialog(MainFrame.this,
"Проверьте коректность функционального выражения", "Ошибка",
JOptionPane.WARNING_MESSAGE);
} else {
synchrMenu.setDimension(graph.getHeight());
synchrMenu.setIter(input.s);
synchrMenu.makeNewFractal();
graph.add(new swComponent(), BorderLayout.CENTER);
picture.add(graph);
picture.revalidate();
}
}
}});
picture.add(new JLabel(" "), BorderLayout.WEST);
picture.add(new JLabel(" "), BorderLayout.SOUTH);
picture.add(new JLabel(" "), BorderLayout.NORTH);
//////////////////////////////////////////////TOOLBAR
JToolBar toolbar = new JToolBar("Toolbar",JToolBar.VERTICAL);
toolbar.setOpaque(false);
toolbar.setFloatable(false);
String[] iconFiles = { "zoom-in.png", "zoom-out.png","arrow-left1.png","arrow-right1.png","arrow-up1.png","arrow-down1.png", "fill-color1.png" };
String[] newiconFiles = { "zoom-in2.png", "zoom-out2.png","arrow-left.png","arrow-right.png","arrow-up.png","arrow-down.png", "fill-color.png" };
String[] buttonLabels = { "Приблизить", "Отдалить", "Влево","Вправо","Вверх","Вниз","Цвет"};
ImageIcon[] icons = new ImageIcon[iconFiles.length];
buttons = new JButton[buttonLabels.length];
for (i = 0; i < iconFiles.length; ++i) {
icons[i] = new ImageIcon(iconFiles[i]);
buttons[i] = new JButton(icons[i]);
buttons[i].setEnabled(false);
buttons[i].setFocusPainted(false);
buttons[i].setContentAreaFilled(false);
buttons[i].setToolTipText(buttonLabels[i]);
buttons[i].setOpaque(false);
buttons[i].setBorderPainted(false);
buttons[i].setRolloverIcon(new ImageIcon(newiconFiles[i]));
toolbar.add(buttons[i]);
}
buttons[0].addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
synchrMenu.enlarge();
graph.repaint();
}
});
buttons[1].addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
synchrMenu.ensmall();
graph.repaint();
}
});
buttons[2].addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
synchrMenu.moveLeft();
}
});
buttons[4].addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
synchrMenu.moveUp();
}
});
buttons[3].addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
synchrMenu.moveRight();
}
});
buttons[5].addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
synchrMenu.moveDown();;
}
});
buttons[6].addActionListener(new ActionListener(){
public void actionPerformed(ActionEvent e){
ColorWindow cw = new ColorWindow();
int position = cw.getPosition(0);
cw.MakeWindow(synchrMenu, position,0);
}
});
picture.add(toolbar, BorderLayout.EAST);
//////////////////////////////////////////////////
JPanel right = new JPanel(new BorderLayout());
right.setOpaque(false);
JPanel left = new JPanel(new GridLayout(2,1));
left.setOpaque(false);
list_model = new DefaultListModel<String>();
list_model.add(0,"z*(sin(z))^2 + c");
list_model.add(0,"z*tg(z) + c");
list_model.add(0,"z*(sin(z)-cos(z)) + c");
list_model.add(0,"z*(cos(z))^3 + c");
list_model.add(0,"exp(-z) + c");
list_model.add(0,"z*tg(z) + c");
list_model.add(0,"z*sin(z) + c");
list_model.add(0,"z^8 + z^3 + c");
list_model.add(0,"z^4 + c");
list_model.add(0,"z^3 + c");
list_model.add(0,"z^2 + c");
list_model.add(0,"z + c");
list1 = new JList<String>(list_model);
JScrollPane scroll_list1 = new JScrollPane(list1);
list1.setBorder(new CompoundBorder(new TitledBorder("Примеры"), new EmptyBorder(1, 1, 1, 1)));
scroll_list1.setOpaque(false);
scroll_list1.getViewport().setOpaque(false);
left.add(scroll_list1);
list_model_favorite = new DefaultListModel<String>();
list2 = new JList<String>(list_model_favorite);
pm = new JPopupMenu();
delete = new JMenuItem("Удалить");
removeAll = new JMenuItem("Очистить список");
pm.add(delete);
pm.add(removeAll);
list2.addMouseListener(new MouseAdapter() {
public void mouseClicked(MouseEvent me) {
if (SwingUtilities.isRightMouseButton(me) && !list2.isSelectionEmpty() && list2.locationToIndex(me.getPoint()) == list2.getSelectedIndex()) {
pm.show(list2, me.getX(), me.getY());
}
if(me.getClickCount()==2){
if (!list2.isSelectionEmpty() && list2.locationToIndex(me.getPoint()) == list1.getSelectedIndex()) {
smallField.setText((String) list_model_favorite.get(list2.getSelectedIndex()));
}
}
}
});
list1.addMouseListener(new MouseAdapter(){
public void mouseClicked(MouseEvent e){
if(e.getClickCount()==2){
if (!list1.isSelectionEmpty() && list1.locationToIndex(e.getPoint()) == list1.getSelectedIndex()) {
smallField.setText((String) list_model.get(list1.getSelectedIndex()));
}
}
}
});
list2.addMouseListener(new MouseAdapter(){
public void mouseClicked(MouseEvent e){
if(e.getClickCount()==2){
if (!list2.isSelectionEmpty() && list2.locationToIndex(e.getPoint()) == list2.getSelectedIndex()) {
smallField.setText((String) list_model_favorite.get(list2.getSelectedIndex()));
}
}
}
});
delete.addActionListener(new ActionListener(){
public void actionPerformed(ActionEvent e) {
System.out.println(list2.getSelectedIndex());
list_model_favorite.remove(list2.getSelectedIndex());
}
});
removeAll.addActionListener(new ActionListener(){
public void actionPerformed(ActionEvent e){
list_model_favorite.removeAllElements();
}
});
JScrollPane scroll_list2 = new JScrollPane(list2);
list2.setBorder(new CompoundBorder(new TitledBorder("Избранные"), new EmptyBorder(1, 1, 1, 1)));
scroll_list2.setOpaque(false);
scroll_list2.getViewport().setOpaque(false);
left.add(scroll_list2);
JSplitPane splitVertic = new JSplitPane(JSplitPane.VERTICAL_SPLIT);
splitVertic.setOpaque(false);
splitVertic.setDividerSize(6);
splitVertic.setResizeWeight(0.99);
splitVertic.setEnabled(false);
splitVertic.isContinuousLayout();
splitVertic.setTopComponent(picture);
splitVertic.setBottomComponent(grid);
JSplitPane splitHorizont = new JSplitPane();
splitHorizont.setOpaque(false);
splitHorizont.setEnabled(false);
//splitHorizont.setOneTouchExpandable(true);
splitHorizont.setDividerSize(8);
splitHorizont.isContinuousLayout();
splitHorizont.setDividerLocation(0.2);
splitHorizont.setResizeWeight(0.2);
splitHorizont.setLeftComponent(left);
splitHorizont.setRightComponent(right);
right.add(splitVertic);
getContentPane().setLayout(new BorderLayout());
getContentPane().add(splitHorizont, BorderLayout.CENTER);
///////////////////////////
setVisible(true);
}
void addKeyBindingLeft(JComponent jc) {
jc.getInputMap(JComponent.WHEN_FOCUSED).put(KeyStroke.getKeyStroke(KeyEvent.VK_LEFT, 0, false), "left pressed");
jc.getActionMap().put("left pressed", new AbstractAction() {
@Override
public void actionPerformed(ActionEvent ae) {
synchrMenu.moveLeft();
}
});
}
void addKeyBindingRight(JComponent jc) {
jc.getInputMap(JComponent.WHEN_FOCUSED).put(KeyStroke.getKeyStroke(KeyEvent.VK_RIGHT, 0, false), "right pressed");
jc.getActionMap().put("right pressed", new AbstractAction() {
@Override
public void actionPerformed(ActionEvent ae) {
synchrMenu.moveRight();
}
});
}
void addKeyBindingUp(JComponent jc) {
jc.getInputMap(JComponent.WHEN_FOCUSED).put(KeyStroke.getKeyStroke(KeyEvent.VK_UP, 0, false), "up pressed");
jc.getActionMap().put("up pressed", new AbstractAction() {
public void actionPerformed(ActionEvent ae) {
synchrMenu.moveUp();
}
});
}
void addKeyBindingDown(JComponent jc) {
jc.getInputMap(JComponent.WHEN_FOCUSED).put(KeyStroke.getKeyStroke(KeyEvent.VK_DOWN, 0, false), "down pressed");
jc.getActionMap().put("down pressed", new AbstractAction() {
@Override
public void actionPerformed(ActionEvent ae) {
synchrMenu.moveDown();
}
});
}
public SynchrMenu getFrac(){
return synchrMenu;
}
//====================================A FUNCTION GETTING THE SCREEN RESOLUTION===========================================
public void getScreenSize()
{
Dimension screenSize = Toolkit.getDefaultToolkit().getScreenSize();
ScreenWidth = screenSize.width;
ScreenHeight = screenSize.height;
}
//======================================================================================================================
public void putIterXYdata(double x, double y, int nIter)
{
t1.setText("" + x);
t2.setText("" + y);
t3.setText("" + nIter);
t1.setCaretPosition(0);
t2.setCaretPosition(0);
t3.setCaretPosition(0);
}
public void check(String a,DefaultListModel<String> list ) {
int i;
if ( a.length() > 0 ) {
int p = list2.getModel().getSize();
if (p == 0 )
list.add(0,a);
System.out.println(p);
for (i=0;i<p;++i){
if (a.equals((String) list.get(i))){
break;
}
}
if ((i == p) & (p!= 0)) list_model_favorite.add((p),a);
}
}
//=======================================================================================================================
public class swComponent extends JComponent {
public void paintComponent(Graphics g) {
FractalObserver fObs = new FractalObserver();
super.paintComponent(g);
g.drawImage(fractal.getImage(),0,0,graph.getSize().height,graph.getSize().height,fObs);
}
}
///////////////////////
public static void main(String[] args) {
Locale[] l = Locale.getAvailableLocales();
for (int i = 0; i < l.length; i++) {
if(l[i].toString().equals("ru")){
Locale.setDefault(l[i]);
break;
}
}
MainFrame win = new MainFrame();
win.setResizable(false);
}
}
| Java |
package fracPackage;
import java.awt.*;
public class FractalPoint extends pObject
{
private double x, y;
private int nIter;
private Iteration pIter;
public FractalPoint(int i0, int j0, double x0, double y0, Iteration iter)
{
super(x0, y0);
x = x0;
y = y0;
nIter = 0;
pIter = iter;
}
public int nIter()
{
return nIter;
}
public boolean isOut()
{
return super.isOut(pIter, x, y);
}
public void iterate(int n)
{
int i = 0;
while (i < n && !isOut())
{
i++;
super.iterate(pIter, x, y);
}
nIter += i;
}
public Color color(ColorScheme cSchm)
{
if (isOut()) return cSchm.color(nIter);
return Color.black;
}
}
| Java |
//package com.serial;
//
//import java.lang.reflect.Array;
//import java.util.Arrays;
//import java.util.HashMap;
//
//import android.os.Handler;
//import android.util.Log;
//
//import com.friendlyarm.AndroidSDK.HardwareControler;
//import com.mini6410.DataPackage;
//import com.mini6410.MainActivity;
//
//public class SerialServer {
// private static final String TAG = "SerialServer";
//
// public static final String SERIAL_COM_DEFAULT = "/dev/s3c2410_serial2";
// public static final String SERIAL_COM_0 = "/dev/s3c2410_serial0";
// public static final String SERIAL_COM_1 = "/dev/s3c2410_serial1";
// public static final String SERIAL_COM_2 = "/dev/s3c2410_serial2";
// public static final String SERIAL_COM_3 = "/dev/s3c2410_serial3";
// public static final String SERIAL_COM_4 = "/dev/s3c2410_serial4";
// public static final String SERIAL_COM_5 = "/dev/s3c2410_serial5";
//
// public static final long SERIAL_BAUD_RATE_DEFAULT = 115200;
// public static final long SERIAL_BAUD_RATE_110 = 110;
// public static final long SERIAL_BAUD_RATE_300 = 300;
// public static final long SERIAL_BAUD_RATE_600 = 600;
// public static final long SERIAL_BAUD_RATE_1200 = 1200;
// public static final long SERIAL_BAUD_RATE_2400 = 2400;
// public static final long SERIAL_BAUD_RATE_4800 = 4800; //COŨ��
// public static final long SERIAL_BAUD_RATE_9600 = 9600; //�¶Ⱥ�PHֵ
// public static final long SERIAL_BAUD_RATE_14400 = 14400;
// public static final long SERIAL_BAUD_RATE_19200 = 19200;
// public static final long SERIAL_BAUD_RATE_38400 = 38400;
// public static final long SERIAL_BAUD_RATE_56000 = 56000;
// public static final long SERIAL_BAUD_RATE_57600 = 57600;
// public static final long SERIAL_BAUD_RATE_115200 = 115200;
// public static final long SERIAL_BAUD_RATE_128000 = 128000;
// public static final long SERIAL_BAUD_RATE_256000 = 256000;
//
// public static final int SERIAL_DATA_BITS_DEFAULT = 8;
// public static final int SERIAL_DATA_BITS_5 = 5;
// public static final int SERIAL_DATA_BITS_6 = 6;
// public static final int SERIAL_DATA_BITS_7 = 7;
// public static final int SERIAL_DATA_BITS_8 = 8;
//
// public static final int SERIAL_STOP_BITS_DEFAULT = 1;
// public static final int SERIAL_STOP_BITS_1 = 1;
// public static final int SERIAL_STOP_BITS_2 = 2;
//
// public static final int SERIAL_DATA_SEND_PERIOD_DEFAULT = 500;
// public static final int SERIAL_DATA_SEND_PERIOD_500 = 500;
// public static final int SERIAL_DATA_SEND_PERIOD_1000 = 1000;
// public static final int SERIAL_DATA_SEND_PERIOD_1500 = 1500;
// public static final int SERIAL_DATA_SEND_PERIOD_2000 = 2000;
//
// public static final byte[] SERIAL_COMMAND_GET_VALUE_CO = {(byte) 0x3A, (byte) 0x30, (byte) 0x31, (byte) 0x30, (byte) 0x33, (byte) 0x30,(byte) 0x32,(byte) 0x30, (byte) 0x30, (byte) 0x30, (byte) 0x41,(byte) 0x30,(byte) 0x39, (byte) 0x0D, (byte) 0x0A};
// public static final byte[] SERIAL_COMMAND_GET_VALUE_PH_TEMPERATURE = {(byte) 0x02, (byte) 0x30, (byte) 0x31};
//
//
// public static final int SERIAL_TYPE_CO = 0;
// public static final int SERIAL_TYPE_PH_TEMPERATURE = 1;
//
//
// /* �������BUF�ij��� */
// public static final int SERIAL_BUF_LENGTH_DEFAULT = 20;
//
// /* CO����Ũ�ȷ������BUF�ij��� */
// public static final int SERIAL_BUF_LENGTH_CO = 16;
//
// /* PH���¶�ֵ �������BUF�ij��� */
// public static final int SERIAL_BUF_LENGTH_PH_TEMPERATURE = 11;
//
// private String mdevName;
// private long mbaud;
// private int mdataBits;
// private int mstopBits;
// private int mtype;
// private int mbuflength;
// private byte[] mcommand;
//
// private HashMap<Byte, Integer> mHashMap = null;
//
// private DataPackage mDataPackage = null;
// private serialServerThread mserialServerThread = null;
//
// Handler mHandler = null;
//
// public SerialServer(Handler mHandler){
// this.mHandler = mHandler;
//
// mdevName = SERIAL_COM_2;
// mbaud = SERIAL_BAUD_RATE_115200;
// mdataBits = SERIAL_DATA_BITS_8;
// mstopBits = SERIAL_STOP_BITS_1;
//
// mDataPackage = new DataPackage();
//
// buildHashMap();
// }
//
// public SerialServer(Handler mHandler,String devName, long baud, int dataBits, int stopBits){
// this.mHandler = mHandler;
//
// mdevName = devName;
// mbaud = baud;
// mdataBits = dataBits;
// mstopBits = stopBits;
//
// mDataPackage = new DataPackage();
//
// buildHashMap();
// }
//
// public void setSerialServerType(int type){
// mtype = type;
//
// switch (mtype) {
// case SERIAL_TYPE_CO:
// mbuflength = SERIAL_BUF_LENGTH_CO;
// mcommand = SERIAL_COMMAND_GET_VALUE_CO;
// break;
// case SERIAL_TYPE_PH_TEMPERATURE:
// mbuflength = SERIAL_BUF_LENGTH_PH_TEMPERATURE;
// mcommand = SERIAL_COMMAND_GET_VALUE_PH_TEMPERATURE;
// break;
// default:
// break;
// }
// }
//
// public int getSerialServerType(){
// return mtype;
// }
//
// public void buildHashMap(){
// mHashMap = new HashMap<Byte, Integer>();
//
// byte[] mkeys = {(byte)0x30,(byte)0x31,(byte)0x32,(byte)0x33,
// (byte)0x34,(byte)0x35,(byte)0x36,(byte)0x37,
// (byte)0x38,(byte)0x39,(byte)0x41,(byte)0x42,
// (byte)0x43,(byte)0x44,(byte)0x45,(byte)0x46};
// int[] mvalues = {(int)0x0,(int)0x1,(int)0x2,(int)0x3,
// (int)0x4,(int)0x5,(int)0x6,(int)0x7,
// (int)0x8,(int)0x9,(int)0xA,(int)0xB,
// (int)0xC,(int)0xD,(int)0xE,(int)0xF};
//
// for(int i = 0; i < mkeys.length;i++){
// mHashMap.put(mkeys[i], mvalues[i]);
//
// }
//}
//
//public int getValue(byte key){
// int value = 0;
// Log.i("~~~~~~~~~~~~~~~~", String.valueOf(value)+"~~~~~~~0000000000~~~~~~~~~"+String.valueOf(key));
//
// if (mHashMap != null) {
// value = (Integer) mHashMap.get(key);
// }
//
// Log.i("~~~~~~~~~~~~~~~~", String.valueOf(value)+"~~~~~~~~~111111111111~~~~~~~"+String.valueOf(key));
// return value;
//}
//
//public void start(){
// safeStop();
//
// mserialServerThread = new serialServerThread();
// mserialServerThread.start();
//}
//
//public void safeStop(){
// if(mserialServerThread != null && mserialServerThread.isAlive()){
// mserialServerThread.interrupt();
// mserialServerThread.stop = true;
// try {
// mserialServerThread.join();
// } catch (InterruptedException e) {
// e.printStackTrace();
// }
// }
// mserialServerThread = null;
//}
//
//
//public void analyzeData(byte[] buf){
// byte[] mbuf = buf;
// //byte[] mbuf ={(byte)0x3A,(byte)0x30,(byte)0x31 ,(byte)0x30 ,(byte)0x33 ,(byte)0x30 ,(byte)0x32 ,(byte)0x30 ,(byte)0x30 ,(byte)0x37 ,(byte)0x32 ,(byte)0x31 ,(byte)0x41 ,(byte)0x0D ,(byte)0x0A ,(byte)0xFF};
//
// Log.i("!!!!!!!!!!!!!!", String.valueOf(mbuf[7])+ " "+String.valueOf(mbuf[8])+ " "+String.valueOf(mbuf[9])+ " "+String.valueOf(mbuf[10]));
//
// switch (mtype) {
// case SERIAL_TYPE_CO:
// if(mbuf[0] == 0x3A && mbuf[1] == 0x30 && mbuf[2] == 0x31 &&
// mbuf[3] == 0x30 && mbuf[4] == 0x33 && mbuf[5] == 0x30 && mbuf[6] == 0x32){
// mDataPackage.mgas_concentration = (float) (getValue(mbuf[7])*Math.pow(16, 3)+ getValue(mbuf[8])*Math.pow(16, 2)+ getValue(mbuf[9])*Math.pow(16, 1)+ getValue(mbuf[10])*Math.pow(16, 0));
// }
//
// break;
// case SERIAL_TYPE_PH_TEMPERATURE:
// if(mbuf[0] == 0x32 && mbuf[1] == 0x30 && mbuf[2] == 0x31){
// mDataPackage.mph_value = (float) (getValue(mbuf[3])*10 + getValue(mbuf[4])+ getValue(mbuf[5])*0.1 + getValue(mbuf[6])*0.01);
// mDataPackage.mwater_temperature = (float) (getValue(mbuf[7])*10 + getValue(mbuf[8])+ getValue(mbuf[9])*0.1);
// }
//
// break;
// default:
// break;
// }
//}
//
//
//
//public void generateData(){
// float random = (float) Math.random();
// mDataPackage.mgas_concentration = random*10+0;
// mDataPackage.mwater_temperature = random*50+0;
// mDataPackage.mph_value = (int)(random*14+0);
//}
//
//public void sendData(){
// sendMessage(MainActivity.MSG_GET_DATA_SUCCESS,mtype,0, mDataPackage);
//}
//
//public void sendMessage(int what ){
// if(mHandler != null){
// mHandler.sendMessage(mHandler.obtainMessage(what));
// }
//}
//
//public void sendMessage(int what, Object obj ){
// if(mHandler != null){
// mHandler.sendMessage(mHandler.obtainMessage(what, obj));
// }
//}
//
//public void sendMessage(int what, int arg1,int arg2,Object obj ){
// if(mHandler != null){
// mHandler.sendMessage(mHandler.obtainMessage(what,arg1,arg2,obj));
// }
//}
//
//private class serialServerThread extends Thread{
// volatile boolean stop = false;
// private byte[] buf = new byte[mbuflength];
// private byte[] buf1 = new byte[8];
// private byte[] buf2 = new byte[8];
//
// private int fd = 0; //�������
// int size = 0;
// int ret = 0;
//
//
// @Override
// public void run() {
//
// fd = HardwareControler.openSerialPort(mdevName, mbaud, mdataBits, mstopBits);
//
// if(fd == -1)
// {
// Log.e(TAG, "Failed to open the serial port :" + mdevName);
//
// stop = true;
// }
//
//
// while(!stop){
//
// //Send Command To Get Data
// if(mcommand != null){
// HardwareControler.write(fd, mcommand);
// }
//
// //Check Whether The Serial Port Has Data
// ret = HardwareControler.select(fd, 2, 1000*1000);
// switch(ret){
// case -1:
// Log.e(TAG, "Error occurred when getting data!");
// break;
// case 0:
// Log.i(TAG, "There is No Data!");
// break;
// case 1:
// { Arrays.fill(buf,(byte)0);
// size = HardwareControler.read(fd, buf, buf.length);
//
// /*size = HardwareControler.read(fd, buf, buf.length);
// for(int i = 0; i < buf.length; i++)
// {
// size += HardwareControler.read(fd, p, 1);
// buf++;
// }*/
//
//
// Log.i("@@@@@@@@@@@", String.valueOf(size));
// if(size == buf.length)
// {
// //generateData();
// analyzeData(buf);
// sendData();
// }else if(size == 0){
// Log.i(TAG, "There is No Data!");
// }else if(size == -1){
// Log.e(TAG, "Error occurred when getting data!");
// }else{
// Log.e(TAG, "Error occurred when getting data!");
// }
// }
// break;
// default:
// break;
// }
//
// try {
// Thread.sleep( SERIAL_DATA_SEND_PERIOD_500 );
// } catch ( InterruptedException e ) {
// e.printStackTrace();
// }
//
// }
//
// if(fd != -1)
// {
// HardwareControler.close(fd);
// }
//
// }
//}
//}
| Java |
package com.mini6410.PWM;
import android.app.Activity;
import android.os.Bundle;
import android.text.Editable;
import android.text.TextWatcher;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.CompoundButton;
import android.widget.EditText;
import android.widget.ToggleButton;
import com.friendlyarm.AndroidSDK.HardwareControler;
import com.mini6410.R;
/**
*
* ClassName:PWMActivity
* Reason: PWM Demo
*
* @author snowdream
* @version
* @since Ver 1.1
* @Date 2011 2012-03-11 17:21
*
* @see
*/
public class PWMActivity extends Activity implements Button.OnClickListener,ToggleButton.OnCheckedChangeListener{
public static final String TAG = "PWMActivity";
/*PWM频率*/
public static final int PWM_FREQUENCY_1 = 1;
public static final int PWM_FREQUENCY_100 = 100;
public static final int PWM_FREQUENCY_200 = 200;
public static final int PWM_FREQUENCY_500 = 500;
public static final int PWM_FREQUENCY_1000 = 1000;
public static final int PWM_FREQUENCY_2000 = 2000;
public static final int PWM_FREQUENCY_5000 = 5000;
public static final int PWM_FREQUENCY_10000 = 10000;
/*PWM播放时长*/
public static final int PWM_PLAY_PERIOD_FOR_EVER = -1;
public static final int PWM_PLAY_PERIOD_100 = 100;
public static final int PWM_PLAY_PERIOD_200 = 200;
public static final int PWM_PLAY_PERIOD_300 = 300;
public static final int PWM_PLAY_PERIOD_500 = 500;
public static final int PWM_PLAY_PERIOD_1000 = 1000;
/*PWM播放间隔*/
public static final int PWM_WAIT_PERIOD_100 = 100;
public static final int PWM_WAIT_PERIOD_200 = 200;
public static final int PWM_WAIT_PERIOD_300 = 300;
public static final int PWM_WAIT_PERIOD_500 = 500;
public static final int PWM_WAIT_PERIOD_1000 = 1000;
/*播放频率*/
public int mfrequency = PWM_FREQUENCY_1000;
/*频率改变步长Step*/
public int mfrequencystep = 100;
/*播放时长*/
public int mplayperiod = PWM_PLAY_PERIOD_1000;
/*播放间隔*/
public int mwaitperiod = PWM_WAIT_PERIOD_1000;
/*播放次数*/
public int mplaynum = 20;
private boolean mStop = false;
private Button mButtonSub = null;
private Button mButtonAdd = null;
private ToggleButton mToggleButtonStartForEver= null;
private ToggleButton mToggleButtonStartForTimes = null;
private EditText mEditTextFrequency = null;
private EditText mEditTextPlayPeriod = null;
private EditText mTextViewWaitPeriod = null;
private EditText mEditTextPlayNum = null;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.pwmdemo);
initUI();
initData();
}
@Override
protected void onDestroy() {
mStop = true;
super.onDestroy();
}
/**
*
* initUI: 初始化UI
*
* @param
* @return
* @throws
*/
public void initUI(){
mButtonSub = (Button)findViewById(R.id.ButtonSUB);
mButtonAdd = (Button)findViewById(R.id.ButtonADD);
/*按钮监听器,具体实现参考下面的函数:onClick*/
mButtonSub.setOnClickListener(this);
mButtonAdd.setOnClickListener(this);
mToggleButtonStartForEver= (ToggleButton)findViewById(R.id.ToggleButtonStartForEver);
mToggleButtonStartForTimes = (ToggleButton)findViewById(R.id.ToggleButtonStartForTimes);
/*开关按钮监听器,具体实现参考下面的函数:onCheckedChanged*/
mToggleButtonStartForEver.setOnCheckedChangeListener(this);
mToggleButtonStartForTimes.setOnCheckedChangeListener(this);
mEditTextFrequency = (EditText)findViewById(R.id.EditTextFrequency);
mEditTextPlayPeriod = (EditText)findViewById(R.id.EditTextPlayPeriod);
mTextViewWaitPeriod = (EditText)findViewById(R.id.EditTextWaitPeriod);
mEditTextPlayNum = (EditText)findViewById(R.id.EditTextPlayNum);
/*EditText监听器,具体实现参考下面的函数:onTextChanged
* 主要用于获取更改后最新的数值,下同。
* */
mEditTextFrequency.addTextChangedListener(new TextWatcher() {
public void onTextChanged(CharSequence s, int start, int before, int count) {
// TODO Auto-generated method stub
try {
mfrequency = Integer.parseInt(mEditTextFrequency.getText().toString());
} catch (NumberFormatException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
public void beforeTextChanged(CharSequence s, int start, int count,
int after) {
// TODO Auto-generated method stub
}
public void afterTextChanged(Editable s) {
// TODO Auto-generated method stub
}
});
mEditTextPlayPeriod.addTextChangedListener(new TextWatcher() {
public void onTextChanged(CharSequence s, int start, int before, int count) {
// TODO Auto-generated method stub
try {
mplayperiod = Integer.parseInt(mEditTextPlayPeriod.getText().toString());
} catch (NumberFormatException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
public void beforeTextChanged(CharSequence s, int start, int count,
int after) {
// TODO Auto-generated method stub
}
public void afterTextChanged(Editable s) {
// TODO Auto-generated method stub
}
});
mTextViewWaitPeriod.addTextChangedListener(new TextWatcher() {
public void onTextChanged(CharSequence s, int start, int before, int count) {
// TODO Auto-generated method stub
try {
mwaitperiod = Integer.parseInt(mTextViewWaitPeriod.getText().toString());
} catch (NumberFormatException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
public void beforeTextChanged(CharSequence s, int start, int count,
int after) {
// TODO Auto-generated method stub
}
public void afterTextChanged(Editable s) {
// TODO Auto-generated method stub
}
});
mEditTextPlayNum.addTextChangedListener(new TextWatcher() {
public void onTextChanged(CharSequence s, int start, int before, int count) {
// TODO Auto-generated method stub
try {
mplaynum = Integer.parseInt(mEditTextPlayNum.getText().toString());
} catch (NumberFormatException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
public void beforeTextChanged(CharSequence s, int start, int count,
int after) {
// TODO Auto-generated method stub
}
public void afterTextChanged(Editable s) {
// TODO Auto-generated method stub
}
});
}
/**
*
* initData: 初始化各个控件的数值
*
* @param
* @return
* @throws
*/
public void initData(){
mEditTextFrequency.setText(String.valueOf(mfrequency));
mEditTextPlayPeriod.setText(String.valueOf(mplayperiod));
mTextViewWaitPeriod.setText(String.valueOf(mwaitperiod));
mEditTextPlayNum.setText(String.valueOf(mplaynum));
}
/**
*
* onCheckedChanged: 开关按钮监听器。当有开关按钮的状态改变时,响应点击。
*
* @param buttonView 改变状态的开关按钮对象;
* @param isChecked 该开关按钮是否被选中;
* @return
* @throws
*/
public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
ToggleButton mToggleButton = (ToggleButton)buttonView;
switch (mToggleButton.getId()) {
case R.id.ToggleButtonStartForEver:
if(isChecked){
PWMPlay(mfrequency);
}else{
mStop = true;
PWMStop();
}
break;
case R.id.ToggleButtonStartForTimes:
if(isChecked){
mStop = false;
PWMThread mPWMThread = new PWMThread();
mPWMThread.start();
}else{
mStop = true;
}
break;
default:
break;
}
}
/**
*
* onClick: 按钮监听器。当有按钮被点击时,响应点击。
*
* @param v 被点击的按钮对象;
* @return
* @throws
*/
public void onClick(View v) {
Button mButton = (Button)v;
switch (mButton.getId()) {
case R.id.ButtonSUB:
if(mfrequency <= 1)
mfrequency = PWM_FREQUENCY_1;
else if(mfrequency == PWM_FREQUENCY_100)
mfrequency = PWM_FREQUENCY_1;
else
mfrequency -= mfrequencystep;
mEditTextFrequency.setText(String.valueOf(mfrequency));
break;
case R.id.ButtonADD:
if(mfrequency <= 1)
mfrequency = PWM_FREQUENCY_100;
else
mfrequency += mfrequencystep;
mEditTextFrequency.setText(String.valueOf(mfrequency));
break;
default:
break;
}
}
/**
*
* PWMPlay: 启动蜂鸣器 ,并播放。
*
* @param frequency 播放频率
* @return true 表示播放成功;否则,表示播放失败。
* @throws
*/
public boolean PWMPlay(int frequency)
{
boolean ret = false;
int result = -1;
result = HardwareControler.PWMPlay(frequency);
if(result == 0)
ret = true;
else
ret = false;
return ret;
}
/**
*
* PWMStop: 停止并关闭蜂鸣器。
*
* @param
* @return true 表示停止成功;否则,表示停止失败。
* @throws
*/
public boolean PWMStop(){
boolean ret = false;
int result = -1;
result = HardwareControler.PWMStop();
if(result == 0)
ret = true;
else
ret = false;
return ret;
}
/**
*
* PWMThread: PWM播放线程
*
* @param
* @return
* @throws
*/
public class PWMThread extends Thread{
@Override
public void run() {
Log.i(TAG, "PWMThread Start");
for(int i = 0 ; i < mplaynum; i++ )
{
Log.i(TAG, String.valueOf(i));
if(mStop)
{
PWMStop();
break;
}
/*启动蜂鸣器,并使用频率 mfrequency 进行播放*/
PWMPlay(mfrequency);
/*等待播放时长 mplayperiod 结束*/
try {
sleep(mplayperiod);
} catch (InterruptedException e) {
e.printStackTrace();
}
/*停止蜂鸣器*/
PWMStop();
if(mStop)
break;
/*等待播放间隔 mwaitperiod 结束*/
try {
sleep(mwaitperiod);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
Log.i(TAG, "PWMThread Stop");
}
}
}
| Java |
package com.mini6410.EEPROM;
import android.os.Handler;
import android.util.Log;
import com.friendlyarm.AndroidSDK.HardwareControler;
public class ReadEEPROM{
private static final String TAG = "WriteEEPROM";
private static final int MAX_LENGTH = 256; //EEPROM最多可存储256个字节数据
Handler mHandler = null;
private ReadEEPROMThread mReadEEPROMThread = null;
public ReadEEPROM(Handler mHandler){
this.mHandler = mHandler;
}
public void ReadData(){
safeStop();
mReadEEPROMThread = new ReadEEPROMThread();
mReadEEPROMThread.start();
}
public void safeStop(){
if(mReadEEPROMThread != null && mReadEEPROMThread.isAlive()){
mReadEEPROMThread.interrupt();
mReadEEPROMThread.stop = true;
try {
mReadEEPROMThread.join();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
mReadEEPROMThread = null;
}
public void sendMessage(int what ){
if(mHandler != null){
mHandler.sendMessage(mHandler.obtainMessage(what));
}
}
public void sendMessage(int what, Object obj ){
if(mHandler != null){
mHandler.sendMessage(mHandler.obtainMessage(what, obj));
}
}
public void sendMessage(int what, int arg1,int arg2,Object obj ){
if(mHandler != null){
mHandler.sendMessage(mHandler.obtainMessage(what,arg1,arg2,obj));
}
}
public void sendMessage(int what, int arg1,int arg2 ){
if(mHandler != null){
mHandler.sendMessage(mHandler.obtainMessage(what,arg1,arg2));
}
}
private class ReadEEPROMThread extends Thread{
volatile boolean stop = false;
int fd = 0;
int length = 0;
int pos = 0;
byte data = 0;
@Override
public void run() {
fd = HardwareControler.openI2CDevice();
if(fd == -1)
{
Log.e(TAG, "Failed to open the I2CDevice !");
stop = true;
}
length = MAX_LENGTH;
while(!stop){
if (pos >= length) {
break;
}
data = (byte)HardwareControler.readByteDataFromI2C(fd, pos);
sendMessage(EEPROMActivity.MSG_GET_DATA, data);
sendMessage(EEPROMActivity.MSG_UPDATE_UI, pos,length);
Log.i(TAG, "readByteDataFromI2C pos: "+ pos);
pos++;
// try {
// Thread.sleep(10);
// } catch ( InterruptedException e ) {
// e.printStackTrace();
// }
}
if(fd != -1)
{
HardwareControler.close(fd);
}
}
}
}
| Java |
package com.mini6410.EEPROM;
import android.os.Handler;
import android.util.Log;
import com.friendlyarm.AndroidSDK.HardwareControler;
public class WriteEEPROM{
private static final String TAG = "WriteEEPROM";
private static final int MAX_LENGTH = 256; //EEPROM最多可存储256个字节数据
Handler mHandler = null;
byte[] mData = null;
private WriteEEPROMThread mWriteEEPROMThread = null;
public WriteEEPROM(Handler mHandler){
this.mHandler = mHandler;
}
public void WriteData(byte[] data){
mData = data;
safeStop();
mWriteEEPROMThread = new WriteEEPROMThread();
mWriteEEPROMThread.start();
}
public void safeStop(){
if(mWriteEEPROMThread != null && mWriteEEPROMThread.isAlive()){
mWriteEEPROMThread.interrupt();
mWriteEEPROMThread.stop = true;
try {
mWriteEEPROMThread.join();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
mWriteEEPROMThread = null;
}
public void sendMessage(int what ){
if(mHandler != null){
mHandler.sendMessage(mHandler.obtainMessage(what));
}
}
public void sendMessage(int what, Object obj ){
if(mHandler != null){
mHandler.sendMessage(mHandler.obtainMessage(what, obj));
}
}
public void sendMessage(int what, int arg1,int arg2,Object obj ){
if(mHandler != null){
mHandler.sendMessage(mHandler.obtainMessage(what,arg1,arg2,obj));
}
}
public void sendMessage(int what, int arg1,int arg2 ){
if(mHandler != null){
mHandler.sendMessage(mHandler.obtainMessage(what,arg1,arg2));
}
}
private class WriteEEPROMThread extends Thread{
volatile boolean stop = false;
int fd = 0;
int length = 0;
int pos = 0;
@Override
public void run() {
if(mData == null){
Log.e(TAG, "There is No Data!");
stop = true;
}
fd = HardwareControler.openI2CDevice();
if(fd == -1)
{
Log.e(TAG, "Failed to open the I2CDevice !");
stop = true;
}
length = mData.length;
if (length > MAX_LENGTH) {
length = MAX_LENGTH;
}
for(int i = 0 ; i < MAX_LENGTH; i++){
HardwareControler.writeByteDataToI2C(fd, i, (byte)'\0');
}
while(!stop){
if (pos >= length) {
break;
}
HardwareControler.writeByteDataToI2C(fd, pos, mData[pos]);
sendMessage(EEPROMActivity.MSG_UPDATE_UI, pos,length);
Log.i(TAG, "writeByteDataToI2C pos: "+ pos);
pos++;
// try {
// Thread.sleep(10);
// } catch ( InterruptedException e ) {
// e.printStackTrace();
// }
}
if(fd != -1)
{
HardwareControler.close(fd);
}
}
}
}
| Java |
package com.mini6410.EEPROM;
import android.app.Activity;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.text.Editable;
import android.view.View;
import android.view.Window;
import android.widget.Button;
import android.widget.EditText;
import com.mini6410.R;
public class EEPROMActivity extends Activity {
public static final int MSG_UPDATE_UI = 0;
public static final int MSG_GET_DATA = 1;
private Button mButtonWrite = null;
private Button mButtonRead = null;
private EditText mEditTextWrite = null;
private EditText mEditTextRead = null;
private Editable mEditable = null;
private WriteEEPROM mWriteEEPROM = null;
private ReadEEPROM mReadEEPROM = null;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
requestWindowFeature(Window.FEATURE_PROGRESS);
setContentView(R.layout.eepromdemo);
setProgressBarVisibility(true);
initUI();
initData();
}
public void initUI(){
mButtonWrite = (Button)findViewById(R.id.Button_write);
mButtonRead = (Button)findViewById(R.id.Button_read);
mButtonWrite.setOnClickListener(mClickListener);
mButtonRead.setOnClickListener(mClickListener);
mEditTextWrite = (EditText)findViewById(R.id.EditText_write);
mEditTextRead = (EditText)findViewById(R.id.EditText_read);
mEditable = mEditTextRead.getText();
}
public void initData(){
mWriteEEPROM = new WriteEEPROM(mHandler);
mReadEEPROM = new ReadEEPROM(mHandler);
}
private Handler mHandler = new Handler(){
@Override
public void handleMessage(Message msg) {
switch (msg.what) {
case MSG_UPDATE_UI:
int pos = (int)msg.arg1;
int length = (int)msg.arg2;
setProgress(pos*10000/(length -1));
break;
case MSG_GET_DATA:
Byte dataByte = (Byte)msg.obj;
mEditable.append((char)dataByte.byteValue());
mEditTextRead.setText(mEditable);
break;
default:
break;
}
}
};
private Button.OnClickListener mClickListener = new Button.OnClickListener(){
public void onClick(View v) {
Button mButton = (Button)v;
switch (mButton.getId()) {
case R.id.Button_read:
ReadDataIntoEEPROM();
break;
case R.id.Button_write:
WriteDataIntoEEPROM();
break;
default:
break;
}
}
};
public void WriteDataIntoEEPROM(){
byte[] data = mEditTextWrite.getText().toString().getBytes();
if(mWriteEEPROM != null)
mWriteEEPROM.WriteData(data);
}
public void ReadDataIntoEEPROM(){
mEditable.clear();
if(mReadEEPROM != null)
mReadEEPROM.ReadData();
}
@Override
protected void onDestroy() {
super.onDestroy();
}
}
| Java |
package com.mini6410.ADC;
import java.util.Timer;
import java.util.TimerTask;
import android.app.Activity;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.util.Log;
import android.widget.TextView;
import com.friendlyarm.AndroidSDK.HardwareControler;
import com.mini6410.R;
/**
*
* ClassName:ADCActivity
* Reason: ADC Demo
*
* @author snowdream
* @version
* @since Ver 1.1
* @Date 2011 2012-03-16 12:04
*
* @see
*/
public class ADCActivity extends Activity {
private static final String TAG = "ADCActivity";
/*刷新UI标记*/
public static final int Update_UI = 0;
/*计时器*/
private Timer mTimer = null;
private TimerTask mTimerTask = null;
/*用来显示ADC返回值的控件*/
private TextView mTextView_ADC = null;
/*读取ADC的返回值*/
private int result = 0;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.adcdemo);
initUI();
initData();
}
/**
*
* initUI: 初始化UI
*
* @param
* @return
* @throws
*/
private void initUI() {
mTextView_ADC = (TextView)findViewById(R.id.TextView_adcresult);
}
/**
*
* initData: 新建定时器,每隔500ms发出消息,通知Activity刷新UI一次。
*
* @param
* @return
* @throws
*/
private void initData() {
mTimer = new Timer();
mTimerTask = new TimerTask() {
@Override
public void run() {
/*调用底层库API读取ADC的值,正常情况下,返回ADC值,否则,出错,返回-1*/
result = HardwareControler.readADC();
if(-1 == result){
Log.e(TAG,"Read ADC Error!");
}else{
Log.i(TAG,"readADC result: "+ result);
mHandler.sendMessage(mHandler.obtainMessage(Update_UI));
}
}
};
mTimer.schedule(mTimerTask, 0, 500);
}
private Handler mHandler = new Handler(){
@Override
public void handleMessage(Message msg) {
int type = msg.what;
switch (type) {
case Update_UI:
mTextView_ADC.setText(String.valueOf(result));
break;
default:
break;
}
}
};
@Override
protected void onDestroy() {
if(mTimer != null){
mTimer.cancel();
mTimer = null;
}
super.onDestroy();
}
}
| Java |
package com.mini6410.HelloMini6410;
import com.mini6410.R;
import android.app.Activity;
import android.os.Bundle;
/**
*
* ClassName:HelloMini6410Activity
* Reason: Hello Mini6410 Demo
*
* @author snowdream
* @version
* @since Ver 1.1
* @Date 2011 2012-03-10 20:11
*
* @see
*/
public class HelloMini6410Activity extends Activity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.hellomini6410);
}
}
| Java |
package com.mini6410.LED;
import com.friendlyarm.AndroidSDK.HardwareControler;
import com.mini6410.R;
import android.app.Activity;
import android.os.Bundle;
import android.widget.CompoundButton;
import android.widget.ToggleButton;
/**
*
* ClassName:LEDActivity
* Reason: LED Demo
*
* @author snowdream
* @version
* @since Ver 1.1
* @Date 2011 2012-03-11 16:07
*
* @see
*/
public class LEDActivity extends Activity implements ToggleButton.OnCheckedChangeListener {
/*四个LED灯,编号ID依次为:LED 0,LED_1,LED_2,LED_3*/
public static final int LED_0 = 0;
public static final int LED_1 = 1;
public static final int LED_2 = 2;
public static final int LED_3 = 3;
/*LED灯的状态: ON 表示点亮, OFF表示熄灭*/
public static final int OFF = 0;
public static final int ON = 1;
private int mledID = LED_0;
private int mledState = OFF;
private boolean mStop = false;
/*LED编号数组*/
private int[] mleds = new int[]{LED_0,LED_1,LED_2,LED_3};
/*5个开关按钮*/
private ToggleButton mToggleButton_led0 = null;
private ToggleButton mToggleButton_led1 = null;
private ToggleButton mToggleButton_led2 = null;
private ToggleButton mToggleButton_led3 = null;
private ToggleButton mToggleButton_ledrandom = null;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.leddemo);
initUI();
}
@Override
protected void onDestroy() {
mStop = true;
super.onDestroy();
}
/**
*
* initUI: 初始化UI
*
* @param
* @return
* @throws
*/
public void initUI(){
mToggleButton_led0 = (ToggleButton)findViewById(R.id.button_led0);
mToggleButton_led1 = (ToggleButton)findViewById(R.id.button_led1);
mToggleButton_led2 = (ToggleButton)findViewById(R.id.button_led2);
mToggleButton_led3 = (ToggleButton)findViewById(R.id.button_led3);
mToggleButton_ledrandom = (ToggleButton)findViewById(R.id.button_ledrandom);
mToggleButton_led0.setOnCheckedChangeListener(this);
mToggleButton_led1.setOnCheckedChangeListener(this);
mToggleButton_led2.setOnCheckedChangeListener(this);
mToggleButton_led3.setOnCheckedChangeListener(this);
mToggleButton_ledrandom.setOnCheckedChangeListener(this);
}
/**
*
* onCheckedChanged: 开关按钮监听器
*
* @param buttonView 当前被按下的按钮对象;isChecked表示该按钮的开关状态
* @return
* @throws
*/
public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
ToggleButton mToggleButton = (ToggleButton)buttonView;
if(isChecked)
mledState = ON;
else
mledState = OFF;
switch (mToggleButton.getId()) {
case R.id.button_led0:
mledID = LED_0;
setLedState(mledID, mledState);
break;
case R.id.button_led1:
mledID = LED_1;
setLedState(mledID, mledState);
break;
case R.id.button_led2:
mledID = LED_2;
setLedState(mledID, mledState);
break;
case R.id.button_led3:
mledID = LED_3;
setLedState(mledID, mledState);
break;
case R.id.button_ledrandom:
if(isChecked){
mStop = false;
RandomLight();
}else{
mStop = true;
setALlLightsOff();
}
break;
default:
break;
}
}
/**
*
* setLedState: 设置LED灯的开关
*
* @param ledID LED灯编号;ledState LED灯的开关状态
* @return true,表示操作成功;否则返回 false。
* @throws
*/
public boolean setLedState(int ledID, int ledState){
boolean ret = false;
int result = -1;
result = HardwareControler.setLedState(ledID, ledState);
if(result == 0)
ret = true;
else
ret = false;
return ret;
}
/**
*
* RandomLight: 随机点亮LED灯
*
* @param
* @return
* @throws
*/
public void RandomLight(){
new Thread(){
int mledNum = mleds.length;
int mrandom = 0;
@Override
public void run() {
while(!mStop){
/*从0 1 2 3范围内产生一个整数随机数*/
mrandom = (int)(Math.random()*(mledNum));
/*随机点亮一盏LED灯,然后关闭其他的LED灯*/
for(int i = 0; i <mleds.length; i++){
if(i == mrandom){
setLedState(mleds[i], ON);
}else{
setLedState(mleds[i], OFF);
}
}
try {
sleep(200);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}}.start();
}
/**
*
* setALlLightsOff: 熄灭全部的LED灯
*
* @param
* @return
* @throws
*/
public void setALlLightsOff(){
for(int i = 0; i <mleds.length; i++){
setLedState(mleds[i], OFF);
}
}
/**
*
* setALlLightsOn: 点亮全部的LED灯
*
* @param
* @return
* @throws
*/
public void setALlLightsOn(){
for(int i = 0; i <mleds.length; i++){
setLedState(mleds[i], ON);
}
}
}
| Java |
package com.mini6410;
import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.ArrayAdapter;
import android.widget.ListView;
import android.widget.TextView;
import com.mini6410.ADC.ADCActivity;
import com.mini6410.EEPROM.EEPROMActivity;
import com.mini6410.HelloMini6410.HelloMini6410Activity;
import com.mini6410.LED.LEDActivity;
import com.mini6410.PWM.PWMActivity;
public class MainActivity extends Activity implements OnItemClickListener {
private static final String TAG = "MainActivity";
//ListView
ListView mListView = null;
//TextView
TextView mEmptyView = null;
public void onCreate(Bundle savedInstanceState) {
Log.i(TAG,"onCreate");
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
initUI();
initData();
}
/**
*
* initUI: 初始化UI
*
* @param
* @return
* @throws
*/
public void initUI(){
mEmptyView=(TextView)findViewById(R.id.empty);
mListView=(ListView)findViewById(R.id.listview);
mListView.setOnItemClickListener(this);
mListView.setEmptyView(mEmptyView);
}
/**
*
* initData: 初始化ListView的数据适配器
*
* @param
* @return
* @throws
*/
public void initData(){
ArrayAdapter<CharSequence> adapter = ArrayAdapter.createFromResource(
this, R.array.demos, android.R.layout.simple_list_item_1);
mListView.setAdapter(adapter);
}
/**
*
* onItemClick: 响应ListView的Item点击动作
*
* @param
* @return
* @throws
*/
public void onItemClick(AdapterView<?> parent, View v, int position, long id) {
Intent intent = new Intent();
switch (position) {
case 0:
intent.setClass(this, HelloMini6410Activity.class);
break;
case 1:
intent.setClass(this, LEDActivity.class);
break;
case 2:
intent.setClass(this, PWMActivity.class);
break;
case 3:
intent.setClass(this, ADCActivity.class);
break;
case 4:
intent.setClass(this, EEPROMActivity.class);
break;
}
startActivity(intent);
}
} | Java |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.