code stringlengths 3 1.18M | language stringclasses 1 value |
|---|---|
package main.activities;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import main.db.entities.FavoriteAdvert;
import main.db.entities.dao.FavoriteAdvertDAO;
import model.advertisers.Advertiser;
import model.advertisers.Leboncoin;
import model.advertisers.Vivastreet;
import model.domain.Advert;
import model.domain.Category;
import model.domain.Region;
import model.reference.Categories;
import model.reference.Regions;
import android.app.Activity;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.SharedPreferences.Editor;
import android.net.Uri;
import android.objects.LoaderImageView;
import android.os.Bundle;
import android.util.Log;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.ArrayAdapter;
import android.widget.CheckBox;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.LinearLayout.LayoutParams;
import android.widget.ListView;
import android.widget.SimpleAdapter;
import android.widget.Spinner;
import android.widget.TextView;
//TODO this class is too big.... really?
public class mainActivity extends Activity {
// TODO to change with a file saved
// elements caracterising the search
private List<Advertiser> listAdvertisers = new ArrayList<Advertiser>();
private Advertiser currentAdvertiser;
ArrayList<HashMap<String, String>> listItem;
private String category = Categories.ALL.getName();
private String region = Regions.ALL.getName();
private String keyWords;
private List<Advert> adverts;
private boolean isFinished = false;
// detail
private String urlMail;
// android entities
// main
private EditText editTextSearch;
private ListView myListView;
private TextView noResult;
// websites
private TextView advertiserTextView;
private CheckBox allAdvertisersCheckBox;
private CheckBox leboncoinCheckBox;
private CheckBox vivaSteetCheckBox;
// category and location
private TextView textViewCategories;
private TextView textViewLocations;
private Spinner spinnerCategories;
private Spinner spinnerLocations;
// Constant for preferences
private final String CATEGORY_PREF = "categoriesAnnonceCompare";
private final String LOCATION_PREF = "locationsAnnonceCompare";
//temp variables used for saving
private String tempHyperLinkDetail;
private String tempAdvertName;
/** Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
goToMain();
}
public void goToMain() {
setContentView(R.layout.main);
// main
editTextSearch = (EditText) findViewById(R.id.editTextSearch);
myListView = (ListView) findViewById(R.id.listviewperso);
noResult = (TextView) findViewById(R.id.noResult);
displayList();
//favorite adverts
//TODO to implement
FavoriteAdvertDAO favoriteAdvertDAO=new FavoriteAdvertDAO(this);
favoriteAdvertDAO.open();
List<FavoriteAdvert> listFavoriteAdverts=favoriteAdvertDAO.getFavoriteAdverts();
System.out.println();
favoriteAdvertDAO.close();
}
private void goToWebSite() {
// websites
setContentView(R.layout.websites);
allAdvertisersCheckBox = (CheckBox) findViewById(R.id.allAdvertisers);
leboncoinCheckBox = (CheckBox) findViewById(R.id.leboncoin);
vivaSteetCheckBox = (CheckBox) findViewById(R.id.vivastreet);
advertiserTextView = (TextView) findViewById(R.id.advertisers);
advertiserTextView.setTextSize(30);
}
public void saveWebsitesOnClick(View view) {
listAdvertisers.clear();
if (allAdvertisersCheckBox.isChecked()) {
choiceForAll();
} else {
if (leboncoinCheckBox.isChecked()) {
listAdvertisers.add(new Leboncoin());
}
if (vivaSteetCheckBox.isChecked()) {
listAdvertisers.add(new Vivastreet());
}
}
goToMain();
}
private void choiceForAll() {
listAdvertisers.add(new Vivastreet());
listAdvertisers.add(new Leboncoin());
}
public void saveCategoriesOnClick(View view) {
category = (String) spinnerCategories
.getItemAtPosition(spinnerCategories.getSelectedItemPosition());
Editor prefs = getPreferences(0).edit();
prefs.putString(CATEGORY_PREF, category);
prefs.commit();
goToMain();
}
public void saveLocationsOnClick(View view) {
region = (String) spinnerLocations.getItemAtPosition(spinnerLocations
.getSelectedItemPosition());
Editor prefs = getPreferences(0).edit();
prefs.putString(LOCATION_PREF, region);
prefs.commit();
goToMain();
}
public void launchSearchClickHandler(View view) {
if (editTextSearch.getText().toString() != null
&& !editTextSearch.getText().toString().equals("")) {
keyWords = (String) editTextSearch.getText().toString();
} else {
keyWords = "";
}
findAdverts();
}
// TODO put a loading there
public void findAdverts() {
listItem = new ArrayList<HashMap<String, String>>();
HashMap<String, String> map;
adverts = new ArrayList<Advert>();
long start = System.currentTimeMillis();
Log.i("listAdvertisers.size() ",
String.valueOf(listAdvertisers.size()));
if (listAdvertisers.size() == 0) {
choiceForAll();
}
for (int i = 0; i < listAdvertisers.size(); i++) {
Advertiser myAdvertiser = listAdvertisers.get(i);
Log.i("myAdvertiser ", myAdvertiser.toString());
myAdvertiser.setLocation(myAdvertiser.getAdvertiserReference()
.getLocalisation().get(region));
myAdvertiser.setKeyWord(keyWords);
myAdvertiser.setCategory(myAdvertiser.getAdvertiserReference()
.getCategories().get(category));
myAdvertiser.setKind("offres");
Log.i("URLsearch", myAdvertiser.getUrlResearch());
try {
adverts.addAll(myAdvertiser.findAdverts());
} catch (Exception e1) {
Log.i("findAdverts exception ", e1.getMessage());
e1.printStackTrace();
}
}
long end = System.currentTimeMillis();
long timeSpent = (start - end);
Log.d("Time to find all adverts: ", String.valueOf(timeSpent));
for (int i = 0; i < adverts.size(); i++) {
adverts.get(i).reparseAllAtributes();
map = new HashMap<String, String>();
if (adverts.get(i).getName() != null) {
map.put("description", adverts.get(i).getName());
}
if (adverts.get(i).getPrice() != null) {
map.put("price", adverts.get(i).getPrice());
}
if (adverts.get(i).getTown() != null) {
map.put("location", adverts.get(i).getTown());
}
if (adverts.get(i).getDate() != null) {
map.put("date", adverts.get(i).getDate());
}
map.put("id", String.valueOf(adverts.get(i).getId()));
listItem.add(map);
}
displayList();
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
new MenuInflater(getApplication()).inflate(R.menu.menu, menu);
return (super.onCreateOptionsMenu(menu));
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
if (item.getItemId() == R.id.websites) {
goToWebSite();
} else if (item.getItemId() == R.id.geographical) {
goToLocations();
} else if (item.getItemId() == R.id.categories) {
goToCategories();
}
return (super.onOptionsItemSelected(item));
}
private void goToCategories() {
setContentView(R.layout.categories);
SharedPreferences prefs = getPreferences(0);
String myCategory = (String) prefs.getAll().get(CATEGORY_PREF);
// categorie and location part
textViewCategories = (TextView) findViewById(R.id.categoriesMessage);
textViewCategories.setTextSize(30);
spinnerCategories = (Spinner) findViewById(R.id.spinnerCategories);
List<CharSequence> featuresList = new ArrayList<CharSequence>();
ArrayAdapter<CharSequence> featuresAdapter = new ArrayAdapter<CharSequence>(
this, android.R.layout.simple_spinner_item, featuresList);
featuresAdapter
.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
spinnerCategories = ((Spinner) mainActivity.this
.findViewById(R.id.spinnerCategories));
spinnerCategories.setAdapter(featuresAdapter);
List<Category> listCategories = Categories.CATEGORIES_LIST;
if (myCategory != null) {
for (int i = 0; i < listCategories.size(); i++) {
if (listCategories.get(i).isRoot()
&& listCategories.get(i).getName().equals(myCategory)) {
featuresAdapter.add(listCategories.get(i).getName());
}
}
}
for (int i = 0; i < listCategories.size(); i++) {
if (listCategories.get(i).isRoot()
&& (myCategory == null | !listCategories.get(i).getName()
.equals(myCategory))) {
featuresAdapter.add(listCategories.get(i).getName());
}
}
}
private void goToLocations() {
setContentView(R.layout.location);
textViewLocations = (TextView) findViewById(R.id.locations);
textViewLocations.setTextSize(30);
SharedPreferences prefs = getPreferences(0);
String myLocation = (String) prefs.getAll().get(LOCATION_PREF);
spinnerLocations = (Spinner) findViewById(R.id.spinnerLocations);
List<CharSequence> featuresListLocations = new ArrayList<CharSequence>();
ArrayAdapter<CharSequence> featuresAdapterLocations = new ArrayAdapter<CharSequence>(
this, android.R.layout.simple_spinner_item,
featuresListLocations);
featuresAdapterLocations
.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
spinnerLocations = ((Spinner) mainActivity.this
.findViewById(R.id.spinnerLocations));
spinnerLocations.setAdapter(featuresAdapterLocations);
List<Region> listLocations = Regions.REGION_LIST;
if (myLocation != null) {
for (int i = 0; i < listLocations.size(); i++) {
if (listLocations.get(i).getName().equals(myLocation)) {
featuresAdapterLocations
.add(listLocations.get(i).getName());
}
}
}
for (int i = 0; i < listLocations.size(); i++) {
if (myLocation == null
| !listLocations.get(i).getName().equals(myLocation)) {
featuresAdapterLocations.add(listLocations.get(i).getName());
}
}
}
public void displayList() {
if (listItem != null && listItem.size() == 0) {
noResult.setVisibility(View.VISIBLE);
}
if (listItem != null && listItem.size() > 0) {
SimpleAdapter mSchedule = new SimpleAdapter(this.getBaseContext(),
listItem, R.layout.advert, new String[] { "description",
"price", "location", "date" }, new int[] {
R.id.description, R.id.price, R.id.location,
R.id.date });
myListView.setAdapter(mSchedule);
myListView.setOnItemClickListener(new OnItemClickListener() {
@SuppressWarnings("unchecked")
public void onItemClick(AdapterView<?> a, View v, int position,
long id) {
HashMap<String, String> map = (HashMap<String, String>) myListView
.getItemAtPosition(position);
double idAvert = Double.valueOf(map.get("id"));
getDetail(idAvert);
}
});
}
}
public void getDetail(double id) {
setContentView(R.layout.advertdetail);
LinearLayout loaderImage = (LinearLayout) this
.findViewById(R.id.loaderImage);
LinearLayout loaderPhoneImg = (LinearLayout) this
.findViewById(R.id.loaderPhoneImg);
TextView price = (TextView) this.findViewById(R.id.price);
TextView location = (TextView) this.findViewById(R.id.location);
TextView date = (TextView) this.findViewById(R.id.date);
TextView detailDescription = (TextView) this
.findViewById(R.id.detailDescription);
TextView name = (TextView) this.findViewById(R.id.name);
Advert anAdvert = Advert.findById(adverts, id);
anAdvert.getMoreDetail();
name.setText(anAdvert.getName());
price.setText(anAdvert.getPrice());
location.setText(anAdvert.getTown());
date.setText(anAdvert.getDate());
detailDescription.setText(anAdvert.getDetail());
tempHyperLinkDetail = anAdvert.getHyperlinkDetail();
tempAdvertName=anAdvert.getName();
urlMail = anAdvert.getUrlContact();
try {
if (anAdvert.getHyperlinkPictureHD() != null
&& anAdvert.getHyperlinkPictureHD() != "") {
final LoaderImageView image = new LoaderImageView(this,
anAdvert.getHyperlinkPictureHD());
image.setLayoutParams(new LayoutParams(
LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT));
loaderImage.addView(image);
// TODO adapt this
// final LoaderImageView phoneImage = new LoaderImageView(this,
// anAdvert.getOwner().getPhoneNumber().toString());
// image.setLayoutParams(new LayoutParams(
// LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT));
//
// loaderPhoneImg.addView(phoneImage);
final TextView phoneTextView = (TextView) findViewById(R.id.phoneRecon);
String linkOrPhone = anAdvert.getOwner().getPhoneNumber()
.toString();
phoneTextView.setText(linkOrPhone);
}
} catch (Exception e) {
e.printStackTrace();
}
}
public void beforeDetailClickHandler(View view) {
goToMain();
}
public void saveAnnounceClickHandler(View view) {
// TODO to implement
FavoriteAdvertDAO aFavoriteAdvertDAO=new FavoriteAdvertDAO(this);
FavoriteAdvert aFavoriteAdvert=new FavoriteAdvert(this.tempAdvertName,this.tempHyperLinkDetail);
aFavoriteAdvertDAO.open();
aFavoriteAdvertDAO.insertFavoriteAdvert(aFavoriteAdvert);
aFavoriteAdvertDAO.close();
goToMain();
}
public void sendMailHandler(View view) {
Intent i = new Intent(Intent.ACTION_VIEW);
i.setData(Uri.parse(urlMail));
startActivity(i);
}
} | Java |
package main.db.entities;
public class FavoriteAdvert {
private int id;
private String advertName;
private String advertUrl;
public FavoriteAdvert(){}
public FavoriteAdvert(String advertNameString, String advertUrlString){
this.advertUrl = advertUrlString;
this.advertName=advertNameString;
}
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getadvertUrl() {
return advertUrl;
}
public void setadvertUrl(String advertUrl){
this.advertUrl=advertUrl;
}
public String getAdvertName() {
return advertName;
}
public void setAdvertName(String advertName) {
this.advertName = advertName;
}
public String toString(){
return "ID : "+id+"\n" +
"nom l'annonce : "+advertName+"\n"+
"url de l'annonce : "+advertUrl+"\n";
}
} | Java |
package main.helper;
import main.db.entities.dao.FavoriteAdvertDAO;
import android.content.Context;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteDatabase.CursorFactory;
import android.database.sqlite.SQLiteOpenHelper;
public class SqlHelper extends SQLiteOpenHelper {
public SqlHelper(Context context, String name, CursorFactory factory,
int version) {
super(context, name, factory, version);
}
@Override
public void onCreate(SQLiteDatabase db) {
// table creation from the request defined in the variable
// CREATE_BDD
db.execSQL(FavoriteAdvertDAO.CREATE_BDD);
}
@Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
// TODO
}
}
| Java |
/** Automatically generated file. DO NOT MODIFY */
package main.activities;
public final class BuildConfig {
public final static boolean DEBUG = true;
} | Java |
/*
* This file is part of AXS, Annotation-XPath for SAX.
*
* Copyright (c) 2013 Benjamin K. Stuhl
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies
* of the Software, and to permit persons to whom the Software is furnished to do
* so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in all
* copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
* SOFTWARE.
*/
package com.googlecode.axs;
import java.io.StringReader;
import java.util.Arrays;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Map;
import java.util.Set;
import java.util.Vector;
import java.util.regex.Pattern;
import java.util.regex.PatternSyntaxException;
import javax.annotation.processing.Messager;
import javax.lang.model.element.Element;
import javax.tools.Diagnostic.Kind;
import com.googlecode.axs.xpath.AndExpression;
import com.googlecode.axs.xpath.AttributeExpression;
import com.googlecode.axs.xpath.CaptureAttrsFunction;
import com.googlecode.axs.xpath.Expression;
import com.googlecode.axs.xpath.IntegerValue;
import com.googlecode.axs.xpath.NameValue;
import com.googlecode.axs.xpath.Node;
import com.googlecode.axs.xpath.NotExpression;
import com.googlecode.axs.xpath.NumericComparisonExpression;
import com.googlecode.axs.xpath.OrExpression;
import com.googlecode.axs.xpath.ParseException;
import com.googlecode.axs.xpath.Parser;
import com.googlecode.axs.xpath.ParserVisitor;
import com.googlecode.axs.xpath.PositionFunction;
import com.googlecode.axs.xpath.Predicate;
import com.googlecode.axs.xpath.SimpleNode;
import com.googlecode.axs.xpath.Slash;
import com.googlecode.axs.xpath.SlashSlash;
import com.googlecode.axs.xpath.Start;
import com.googlecode.axs.xpath.StepExpression;
import com.googlecode.axs.xpath.StringComparisonExpression;
import com.googlecode.axs.xpath.StringSearchFunction;
import com.googlecode.axs.xpath.StringValue;
/**
* This class performs the actual compilation of XPath expressions to generate
* the _AXSData needed at run time.
* @author Ben
*
*/
public class CompiledAXSData implements ParserVisitor {
private AnnotatedClass mClass;
private Messager mMessager;
public CompiledAXSData(AnnotatedClass ac, Messager messager) {
mClass = ac;
mMessager = messager;
mInstructions = new Vector<ShortVector>();
mLiterals = new Vector<String>();
mQNames = new Vector<QName>();
mLiteralIndices = new HashMap<String, Integer>();
mQNameIndices = new HashMap<QName, Integer>();
}
private int mMaxPredicateStackDepth = 0, mCurrentPredicateStackDepth = 0;
private Vector<ShortVector> mInstructions = null;
private Vector<String> mLiterals = null;
private Vector<QName> mQNames = null;
private HashMap<String, Integer> mLiteralIndices = null;
private HashMap<QName, Integer> mQNameIndices = null;
private HashMap<String, Vector<Integer>> mTriggerTags = new HashMap<String, Vector<Integer>>();
private HashSet<String> mAttributeCaptureTags = new HashSet<String>();
private HashSet<String> mPositionCaptureTags = new HashSet<String>();
public class Method {
private String mName;
private String mXPathExpression;
private int mIndex;
public Method(String name, String expression, int index) {
mName = name;
mXPathExpression = expression;
mIndex = index;
}
public String name() {
return mName;
}
public String expression() {
return mXPathExpression;
}
public int index() {
return mIndex;
}
}
private Vector<Method> mMethods = new Vector<Method>();
private int mNrXPathMethods = 0;
private int mNrXPathEndMethods = 0;
private int mNrXPathStartMethods = 0;
private Element mCurrentMethodElement = null;
private void errorMessage(String message) {
mMessager.printMessage(Kind.ERROR, message, mCurrentMethodElement);
}
/**
* Add @p literal to the literals table and return its index
* @param literal
* @return the index of the literal
*/
private short addLiteral(String literal) {
Integer index = mLiteralIndices.get(literal);
if (index != null)
return index.shortValue();
mLiterals.add(literal);
mLiteralIndices.put(literal, mLiterals.size() - 1);
return (short)(mLiterals.size() - 1);
}
private QName parseQName(String name, boolean isAttribute) {
int colonPosition = name.indexOf(':');
if (colonPosition > 0) {
String prefix = name.substring(0, colonPosition);
String localName = name.substring(colonPosition + 1);
String uri = mClass.prefixMap().get(prefix);
if (uri == null) {
errorMessage("No Namespace URI mapping specified for prefix \"" + prefix + "\"");
}
return new QName(uri, localName);
}
return new QName(isAttribute ? null : mClass.prefixMap().get(""), name);
}
/**
* Add @p qName to the QNames table and return its index
* @param qName
* @return the index of the QName
*/
private short addQName(QName qName) {
Integer index = mQNameIndices.get(qName);
if (index != null)
return index.shortValue();
mQNames.add(qName);
mQNameIndices.put(qName, mQNames.size() - 1);
return (short)(mQNames.size() - 1);
}
/**
* Add @p n to the stack size required for this expression.
* @param n
*/
private void requireStackDepth(int n) {
mCurrentPredicateStackDepth += n;
}
/**
* Start the process of tracking stack sizes needed for this predicate.
*/
private void startTrackingStackDepth() {
mCurrentPredicateStackDepth = 0;
}
private void finishTrackingStackDepth() {
if (mCurrentPredicateStackDepth > mMaxPredicateStackDepth)
mMaxPredicateStackDepth = mCurrentPredicateStackDepth;
}
@Override
public Object visit(SimpleNode node, ShortVector data) {
errorMessage("Got an unhandled #" + node.getClass().getSimpleName() + " node in the parse tree!");
return null;
}
@Override
public Object visit(Start node, ShortVector data) {
errorMessage("Got an unhandled #" + node.getClass().getSimpleName() + " node in the parse tree!");
return null;
}
@Override
public Object visit(Slash node, ShortVector data) {
errorMessage("Got an unhandled #" + node.getClass().getSimpleName() + " node in the parse tree!");
return null;
}
@Override
public Object visit(SlashSlash node, ShortVector data) {
errorMessage("Got an unhandled #" + node.getClass().getSimpleName() + " node in the parse tree!");
return null;
}
// Predicate nodes and all the expression types contained under them
// return a mask of capture type flags as an Integer; StepExpression
// nodes return the union of all the captures their Predicates require
private static final int CAPTURE_NONE = 0;
private static final int CAPTURE_ATTRIBUTES = 0x0001;
private static final int CAPTURE_POSITIONS = 0x0002;
/**
* Compile all the Predicates required by this node. Does _not_
* compile the axis step itself.
*/
@Override
public Object visit(StepExpression node, ShortVector instrs) {
errorMessage("Got an unhandled #" + node.getClass().getSimpleName() + " node in the parse tree!");
return null;
}
@Override
public Object visit(Predicate node, ShortVector instrs) {
int captures = CAPTURE_NONE;
startTrackingStackDepth();
if (node.jjtGetNumChildren() == 1 && node.jjtGetChild(0) instanceof IntegerValue) {
// it's an implicit position() predicate, e.g. bar/foo[3]
requireStackDepth(1);
instrs.push(XPathExpression.INSTR_POSITION);
node.jjtGetChild(0).jjtAccept(this, instrs);
instrs.push(XPathExpression.INSTR_EQ);
captures |= CAPTURE_POSITIONS;
} else {
for (int i = 0, children = node.jjtGetNumChildren(); i < children; i++) {
captures |= (Integer) node.jjtGetChild(i).jjtAccept(this, instrs);
}
}
finishTrackingStackDepth();
instrs.push(XPathExpression.INSTR_TEST_PREDICATE);
return captures;
}
@Override
public Object visit(OrExpression node, ShortVector instrs) {
int children = node.jjtGetNumChildren();
int captures = CAPTURE_NONE;
for (int i = 0; i < children; i++) {
captures |= (Integer) node.jjtGetChild(i).jjtAccept(this, instrs);
}
for (int i = 1; i < children; i++) {
instrs.push(XPathExpression.INSTR_OR);
}
return captures;
}
@Override
public Object visit(AndExpression node, ShortVector instrs) {
int children = node.jjtGetNumChildren();
int captures = CAPTURE_NONE;
for (int i = 0; i < children; i++) {
captures |= (Integer) node.jjtGetChild(i).jjtAccept(this, instrs);
}
for (int i = 1; i < children; i++) {
instrs.push(XPathExpression.INSTR_AND);
}
return captures;
}
@Override
public Object visit(NotExpression node, ShortVector instrs) {
if (node.jjtGetNumChildren() != 1)
errorMessage("Unexpectedly found " + node.jjtGetNumChildren() + " descendants of a not() expression");
int captures = (Integer) node.jjtGetChild(0).jjtAccept(this, instrs);
instrs.push(XPathExpression.INSTR_NOT);
return captures;
}
@Override
public Object visit(NumericComparisonExpression node, ShortVector instrs) {
if (node.jjtGetNumChildren() != 2)
errorMessage("Unexpectedly found " + node.jjtGetNumChildren() + " descendants of a numeric comparison expression");
int captures = CAPTURE_NONE;
for (int i = 0; i < 2; i++) {
captures |= (Integer) node.jjtGetChild(i).jjtAccept(this, instrs);
}
String op = (String) node.jjtGetValue();
if ("=".equals(op)) {
instrs.push(XPathExpression.INSTR_EQ);
} else if ("!=".equals(op)) {
instrs.push(XPathExpression.INSTR_NE);
} else if (">".equals(op)) {
instrs.push(XPathExpression.INSTR_GT);
} else if ("<".equals(op)) {
instrs.push(XPathExpression.INSTR_LT);
} else if (">=".equals(op)) {
instrs.push(XPathExpression.INSTR_GE);
} else if ("<=".equals(op)) {
instrs.push(XPathExpression.INSTR_LE);
} else {
errorMessage("Unknown binary operator \"" + op + "\"");
}
return captures;
}
@Override
public Object visit(StringComparisonExpression node, ShortVector instrs) {
if (node.jjtGetNumChildren() != 2)
errorMessage("Unexpectedly found " + node.jjtGetNumChildren() + " descendants of a string comparison expression");
int captures = CAPTURE_NONE;
for (int i = 0; i < 2; i++) {
captures |= (Integer) node.jjtGetChild(i).jjtAccept(this, instrs);
}
requireStackDepth(1);
String op = (String) node.jjtGetValue();
if ("=".equals(op)) {
instrs.push(XPathExpression.INSTR_EQ_STR);
} else if ("!=".equals(op)) {
instrs.push(XPathExpression.INSTR_EQ_STR);
instrs.push(XPathExpression.INSTR_NOT);
} else {
errorMessage("Unknown binary operator \"" + op + "\"");
}
return captures;
}
@Override
public Object visit(StringSearchFunction node, ShortVector instrs) {
if (node.jjtGetNumChildren() != 2)
errorMessage("Unexpectedly found " + node.jjtGetNumChildren() + " descendants of a string search function expression");
int captures = CAPTURE_NONE;
for (int i = 0; i < 2; i++) {
captures |= (Integer) node.jjtGetChild(i).jjtAccept(this, instrs);
}
String fnName = (String) node.jjtGetValue();
requireStackDepth(1);
if ("contains".equals(fnName)) {
instrs.push(XPathExpression.INSTR_CONTAINS);
} else if ("starts-with".equals(fnName)) {
instrs.push(XPathExpression.INSTR_STARTS_WITH);
} else if ("ends-with".equals(fnName)) {
instrs.push(XPathExpression.INSTR_ENDS_WITH);
} else if ("matches".equals(fnName)) {
String pattern = mLiterals.get(instrs.get(instrs.size() - 1));
// test-compile the expression so that malformed expressions are
// a compile-time error, not a runtime error
try {
Pattern.compile(pattern);
} catch (PatternSyntaxException e) {
errorMessage("Malformed regular expression: " + e);
}
instrs.push(XPathExpression.INSTR_MATCHES);
} else {
errorMessage("Unknown string comparison function \"" + fnName + "\"");
}
return captures;
}
@Override
public Object visit(IntegerValue node, ShortVector instrs) {
String ival = (String) node.jjtGetValue();
requireStackDepth(1);
instrs.push(XPathExpression.INSTR_ILITERAL);
instrs.push(Short.parseShort(ival));
return CAPTURE_NONE;
}
@Override
public Object visit(StringValue node, ShortVector instrs) {
String str = (String) node.jjtGetValue();
// the stored value includes the start and end quotes: strip them
// and unescape any quotation marks in the literal
char quote = str.charAt(0);
str = str.substring(1, str.length()-1);
str = str.replace(new String(new char[] { quote, quote }), new String(new char[] { quote }));
instrs.push(XPathExpression.INSTR_LITERAL);
instrs.push(addLiteral(str));
return CAPTURE_NONE;
}
@Override
public Object visit(AttributeExpression node, ShortVector instrs) {
String name = (String) node.jjtGetChild(0).jjtAccept(this, instrs);
if (name.startsWith("child::") || name.startsWith("descendant::")) {
errorMessage("Cannot use Element as a value in a predicate");
} else if (name.startsWith("attribute::")) {
name = name.substring(11);
}
QName qName = parseQName(name, true);
instrs.push(XPathExpression.INSTR_ATTRIBUTE);
instrs.push(addQName(qName));
return CAPTURE_ATTRIBUTES;
}
@Override
public Object visit(CaptureAttrsFunction node, ShortVector instrs) {
requireStackDepth(1);
instrs.push(XPathExpression.INSTR_ILITERAL);
instrs.push((short) 1);
return CAPTURE_ATTRIBUTES;
}
@Override
public Object visit(PositionFunction node, ShortVector instrs) {
requireStackDepth(1);
instrs.push(XPathExpression.INSTR_POSITION);
return CAPTURE_POSITIONS;
}
/**
* Returns the raw Name value
*/
@Override
public Object visit(NameValue node, ShortVector instrs) {
return node.jjtGetValue();
}
/**
* Do the work of compiling an Expression.
*
* @return the Local Name of the last tag in the expression
*/
@Override
public Object visit(Expression expressionNode, ShortVector instrs) {
// we compile steps from last to first as matches the tag stack
int totalSteps = expressionNode.jjtGetNumChildren();
if (totalSteps == 0) {
errorMessage("An XPath expression must have at least one element");
return "";
}
// we need to keep track of whether the step _after_ the current step
// was a descendant:: step, e.g. when compiling "a/b/descendant::c", we need
// to know that "c" was a descendant:: step when we compile "b"
boolean lastWasDescendant = false;
for (int step = totalSteps - 1; step >= 0; step -= 2) {
// determine the tag name for this step
Node axisStepNode = expressionNode.jjtGetChild(step);
String name = (String) axisStepNode.jjtGetChild(0).jjtAccept(this, instrs);
boolean isDescendant = lastWasDescendant;
lastWasDescendant = false;
if (name.startsWith("child::")) {
name = name.substring(7);
} else if (name.startsWith("descendant::")) {
name = name.substring(11);
lastWasDescendant = true;
} else if (name.startsWith("attribute::") || name.startsWith("@")) {
errorMessage("Cannot use an attribute name as an Axis Step");
}
// this is the real name for this step
QName qName = parseQName(name, false);
// add an instruction scroll up the stack to this node, if the following
// step was a '//'
if (step != totalSteps - 1) {
// we're not on the "b" of ...a/b
Node separatorNode = expressionNode.jjtGetChild(step + 1);
if (separatorNode instanceof SlashSlash) {
isDescendant = true;
}
}
int nonconsecutiveElementLabel = instrs.size();
if (isDescendant) {
// this tag is the "b" in "a/b//c" or "a/b/descendant::c":
// look up the stack until we find it
instrs.push(XPathExpression.INSTR_NONCONSECUTIVE_ELEMENT);
instrs.push(addQName(qName));
}
// now that we're at the correct tag, compile any Predicates for this step
int captureFlags = CAPTURE_NONE;
for (int i = 1, children = axisStepNode.jjtGetNumChildren(); i < children; i++) {
captureFlags |= (Integer) axisStepNode.jjtGetChild(i).jjtAccept(this, instrs);
if (isDescendant) {
// each Predicate ends with an INSTR_TEST_PREDICATE, patch it into an
// INSTR_SOFT_TEST_PREDICATE so that if the predicate fails the VM will
// branch back to retry the INSTR_NONCONSECUTIVE_ELEMENT up the tag stack
if (instrs.top() != XPathExpression.INSTR_TEST_PREDICATE)
errorMessage("Internal error: found a predicate that ended with instruction " + instrs.top());
int softTestLabel = instrs.size() - 1;
instrs.put(instrs.size() - 1, XPathExpression.INSTR_SOFT_TEST_PREDICATE);
instrs.push((short)(nonconsecutiveElementLabel - softTestLabel));
}
}
// then compile the step itself
instrs.push(XPathExpression.INSTR_ELEMENT);
instrs.push(addQName(qName));
if ((captureFlags & CAPTURE_ATTRIBUTES) != 0) {
mAttributeCaptureTags.add(qName.getLocalPart());
}
if ((captureFlags & CAPTURE_POSITIONS) != 0) {
if (step < 2) {
// this is the topmost node in the pattern: we can't capture positions for it
errorMessage("Cannot use position() predicates for the topmost node in a path");
}
mPositionCaptureTags.add(qName.getLocalPart());
}
}
// if the pattern starts with a Slash, mark it absolute
if (expressionNode.jjtGetChild(0) instanceof Slash) {
instrs.push(XPathExpression.INSTR_ROOT);
}
// return the local part of the innermost node in the pattern
String lastNodeName = (String) expressionNode.jjtGetChild(totalSteps - 1)
.jjtGetChild(0)
.jjtAccept(this, instrs);
return parseQName(lastNodeName, false).getLocalPart();
}
private String compileExpression(Node expressionNode, ShortVector instrVector) {
return (String) expressionNode.jjtAccept(this, instrVector);
}
/**
* Compile a single XPath expression.
* The token list is directly add()ed to mTokens and the literals and QNames
* to the global pools in mLiterals and mQNames. The resulting one or more
* Methods are added to mMethods and the appropriate triggers are addTrigger()ed.
* @param messager
* @param methodName the name of the annotated method
* @param xpathExpression the XPath annotation of the annotated method
*/
private void compileOneExpression(String methodName, String xpathExpression) {
mCurrentMethodElement = mClass.methodElements().get(methodName);
// invoke the JJTree/JavaCC parser in com.googlecode.axs.xpath.Parser
Parser parser = new Parser(new StringReader(xpathExpression));
Node rootNode;
try {
// attempt the parse
rootNode = parser.Start();
// the Start element has as direct children all the alternative expressions
for (int child = 0, nrChildren = rootNode.jjtGetNumChildren(); child < nrChildren; child++) {
ShortVector instructions = new ShortVector();
String trigger = compileExpression(rootNode.jjtGetChild(child), instructions);
// System.out.println("parsed \"" + xpathExpression + "\" to " + instructions);
// store the compiled method
mInstructions.add(instructions);
mMethods.add(new Method(methodName, xpathExpression, mInstructions.size() - 1));
addTrigger(trigger, mInstructions.size() - 1);
}
} catch (ParseException e) {
errorMessage("Syntax error in XPath expression:\n" + e.getMessage());
} catch (Exception e) {
errorMessage("Internal error parsing XPath expression \"" + xpathExpression + "\": " + e.toString());
e.printStackTrace();
}
}
/**
* Add @p xprIx to the list of triggers for @p tag
* @param tag
* @param xprIx
*/
private void addTrigger(String tag, int xprIx) {
Vector<Integer> triggers = mTriggerTags.get(tag);
if (triggers == null) {
triggers = new Vector<Integer>();
mTriggerTags.put(tag, triggers);
}
triggers.add(xprIx);
}
/**
* Compile the methods in one class of annotation and return the number of Methods generated.
* @param messager
* @param methodSet
* @return
*/
private int compileOneSet(Map<String, String> methodSet) {
int firstMethodIndex = mMethods.size() - 1;
String[] sortedMethods = methodSet.keySet().toArray(new String[0]);
Arrays.sort(sortedMethods);
for (String method : sortedMethods) {
String xpathExpression = methodSet.get(method);
compileOneExpression(method, xpathExpression);
}
return (mMethods.size() - 1) - firstMethodIndex;
}
/**
* Compile all the XPath expressions in the AnnotatedClass
* @param messager a Message for logging
*/
public void compile() {
mNrXPathMethods = compileOneSet(mClass.xPathMethods());
mNrXPathEndMethods = compileOneSet(mClass.xPathEndMethods());
mNrXPathStartMethods = compileOneSet(mClass.xPathStartMethods());
}
public Vector<ShortVector> instructions() {
return mInstructions;
}
public Vector<String> literals() {
return mLiterals;
}
public Vector<QName> qNames() {
return mQNames;
}
public Vector<Method> methods() {
return mMethods;
}
public int numberOfXPathMethods() {
return mNrXPathMethods;
}
public int numberOfXPathEndMethods() {
return mNrXPathEndMethods;
}
public int numberOfXPathStartMethods() {
return mNrXPathStartMethods;
}
public int maximumPredicateStackDepth() {
return mMaxPredicateStackDepth;
}
public Set<String> attributeCaptureTags() {
return mAttributeCaptureTags;
}
public Set<String> positionCaptureTags() {
return mPositionCaptureTags;
}
public Map<String, Vector<Integer>> triggers() {
return mTriggerTags;
}
public String packageName() {
String className = mClass.className().toString();
int lastDot = className.lastIndexOf('.');
String packageName = className.substring(0, lastDot);
return packageName;
}
public String className() {
return mClass.classElement().getSimpleName().toString();
}
}
| Java |
/*
* This file is part of AXS, Annotation-XPath for SAX.
*
* Copyright (c) 2013 Benjamin K. Stuhl
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies
* of the Software, and to permit persons to whom the Software is furnished to do
* so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in all
* copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
* SOFTWARE.
*/
package com.googlecode.axs;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.Writer;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.Vector;
/**
* This class provides the static method which supports the writing of
* _AXSData classes.
* @author Ben
*
*/
class AXSDataWriter {
private AXSDataWriter() {
}
private static boolean sWriteGeneratedAnnotation = true;
public static void setUseGeneratedAnnotation(boolean write) {
sWriteGeneratedAnnotation = write;
}
/**
* Write out the compiled _AXSData as Java source code to the given writer
* @param w the writer to which the code should be written.
* @param axsData the _AXSData to write
*/
public static void writeAXSData(Writer w, CompiledAXSData axsData) throws IOException {
// we make no attempt to reduce the number of times a given string
// is written out, since javac will unique-ify repeated string literals
// anyways
// we write out all the big arrays as delay-initialized to first use,
// to avoid having the dynamic initialization suck start-up time
int nrTexts = axsData.numberOfXPathMethods();
int nrEnds = axsData.numberOfXPathEndMethods();
int nrStarts = axsData.numberOfXPathStartMethods();
Vector<CompiledAXSData.Method> methods = axsData.methods();
writeHeader(w, axsData);
writeCallFunction(w, axsData.className(), "callXPathText", "String", methods.subList(0, nrTexts));
writeCallFunction(w, axsData.className(), "callXPathEnd", null, methods.subList(nrTexts, nrTexts+nrEnds));
writeCallFunction(w, axsData.className(), "callXPathStart", "Attributes", methods.subList(nrTexts+nrEnds, nrTexts+nrEnds+nrStarts));
writeInt(w, "getAXSDataVersion", AbstractAnnotatedHandler.AXSDATA_VERSION);
writeInt(w, "getNumberOfCapturingExpressions", nrTexts);
writeInt(w, "getNumberOfEndExpressions", nrEnds);
writeInt(w, "getMaximumPredicateStackDepth", axsData.maximumPredicateStackDepth());
writeTriggerTags(w, axsData.triggers());
writeSet(w, "AttributeCaptureTags", "getAttributeCaptureTags", axsData.attributeCaptureTags());
writeSet(w, "PositionCaptureTags", "getPositionCaptureTags", axsData.positionCaptureTags());
writeExpressions(w, methods, axsData.instructions(), axsData.literals(), axsData.qNames());
writeFooter(w);
}
/**
* Add a single import statement to the file.
* @param w
* @param className the fully-qualified class name
* @throws IOException
*/
private static void writeImport(Writer w, String className) throws IOException {
w.write("import ");
w.write(className);
w.write(";\n");
}
/**
* Indent by @p n spaces
* @param w
* @param n
* @throws IOException
*/
private static void indent(Writer w, int n) throws IOException {
while (n-- > 0)
w.write(' ');
}
/**
* Write the all-stars comment line of appropriate length for the license block
* @param w
* @param maxLineLength
*/
private static void writeLicenseStarLine(Writer w, int maxLineLength) throws IOException {
w.write("/* ");
for (int i = 0; i < maxLineLength + 1; i++)
w.write('*');
w.write("*/\n");
}
/**
* Writes the MIT license header as a nice block header.
* @param w
* @throws IOException
*/
private static void writeLicense(Writer w) throws IOException {
ClassLoader ourLoader = AXSDataWriter.class.getClassLoader();
InputStream licenseStream = ourLoader.getResourceAsStream("resources/LICENSE");
BufferedReader licenseReader = new BufferedReader(new InputStreamReader(licenseStream));
int maxLineLength = 0;
Vector<String> lines = new Vector<String>();
while (true) {
String line = licenseReader.readLine();
if (line == null)
break;
if (line.length() > maxLineLength)
maxLineLength = line.length();
lines.add(line);
}
writeLicenseStarLine(w, maxLineLength);
String lineFormat = "%-" + maxLineLength + "s";
for (String line : lines) {
w.write("/* ");
w.write(String.format(lineFormat, line));
w.write(" */\n");
}
writeLicenseStarLine(w, maxLineLength);
}
private static void writeHeader(Writer w, CompiledAXSData axsData) throws IOException {
w.write("/* This class is autogenerated by the AXS compiler. Do not edit! */\n\n");
writeLicense(w);
w.write("\npackage ");
w.write(axsData.packageName());
w.write(";\n\n");
writeImport(w, "java.util.HashMap");
writeImport(w, "java.util.HashSet");
writeImport(w, "java.util.Map");
writeImport(w, "java.util.Set");
if (sWriteGeneratedAnnotation) {
writeImport(w, "javax.annotation.Generated");
}
writeImport(w, "org.xml.sax.Attributes");
writeImport(w, "org.xml.sax.SAXException");
w.write("\n");
writeImport(w, "com.googlecode.axs.AXSData");
writeImport(w, "com.googlecode.axs.AbstractAnnotatedHandler");
writeImport(w, "com.googlecode.axs.HandlerCallError");
writeImport(w, "com.googlecode.axs.QName");
writeImport(w, "com.googlecode.axs.XPathExpression");
w.write("\n");
writeImport(w, axsData.packageName() + "." + axsData.className());
w.write("\n");
if (sWriteGeneratedAnnotation) {
w.write("\n@Generated(value = { \"com.googlecode.axs.AnnotationProcessor\", \"");
w.write(axsData.packageName() + "." + axsData.className() + "\"})\n");
}
w.write("public class "); w.write(axsData.className() + "_AXSData"); w.write(" implements AXSData {\n");
indent(w, 4); w.write("private static Object Lock = new Object();\n\n");
}
private static void writeCallFunction(Writer w, String className, String fnName,
String argType, List<CompiledAXSData.Method> methods) throws IOException {
indent(w, 4); w.write("@Override\n");
indent(w, 4); w.write("public void ");
w.write(fnName);
w.write("(AbstractAnnotatedHandler abstractHandler, int exprIx");
if (argType != null) {
w.write(", ");
w.write(argType);
w.write(" callbackArg");
}
w.write(") throws SAXException {\n");
indent(w, 8); w.write(className + " handler = (" + className + ") abstractHandler;\n\n");
indent(w, 8); w.write("switch (exprIx) {\n");
for (int i = 0, len = methods.size(); i < len; i++) {
indent(w, 8); w.write("case " + methods.get(i).index() + ": \n");
indent(w, 12); w.write("// \"" + methods.get(i).expression() + "\"\n");
indent(w, 12); w.write("handler." + methods.get(i).name() + "(");
if (argType != null)
w.write("callbackArg");
w.write(");\n");
indent(w, 12); w.write("break;\n");
}
indent(w, 8); w.write("default: throw new HandlerCallError(\"unhandled call #\" + exprIx);\n");
indent(w, 8); w.write("}\n");
indent(w, 4); w.write("}\n\n");
}
private static void writeInt(Writer w, String getterName, int value) throws IOException {
indent(w, 4); w.write("@Override\n");
indent(w, 4); w.write("public int " + getterName + "() {\n");
indent(w, 8); w.write("return " + value + ";\n");
indent(w, 4); w.write("}\n\n");
}
private static void writeTriggerTags(Writer w, Map<String, Vector<Integer>> triggers) throws IOException {
indent(w, 4); w.write("private static HashMap<String, int[]> Triggers = null;\n\n");
indent(w, 4); w.write("@Override\n");
indent(w, 4); w.write("public Map<String, int[]> getTriggerTags() {\n");
indent(w, 8); w.write("synchronized (Lock) {\n");
indent(w, 12); w.write("if (Triggers != null)\n");
indent(w, 16); w.write("return Triggers;\n");
indent(w, 12); w.write("Triggers = new HashMap<String, int[]>();\n");
for (Map.Entry<String, Vector<Integer>> trigger : triggers.entrySet()) {
indent(w, 12); w.write("Triggers.put(\"" + trigger.getKey());
w.write("\", \n");
indent(w, 20); w.write("new int[] { ");
for (int ix : trigger.getValue()) {
w.write(String.valueOf(ix));
w.write(", ");
}
w.write("});\n");
}
indent(w, 8); w.write("}\n");
indent(w, 8); w.write("return Triggers;\n");
indent(w, 4); w.write("}\n\n");
}
private static void writeSet(Writer w, String setName, String getterName, Set<String> set) throws IOException {
indent(w, 4); w.write("private static HashSet<String> " + setName + " = null;\n\n");
indent(w, 4); w.write("@Override\n");
indent(w, 4); w.write("public Set<String> " + getterName + "() {\n");
indent(w, 8); w.write("synchronized (Lock) {\n");
indent(w, 12); w.write("if (" + setName + " != null)\n");
indent(w, 16); w.write("return " + setName + ";\n\n");
indent(w, 12); w.write(setName + " = new HashSet<String>();\n");
for (String s : set) {
indent(w, 12); w.write(setName + ".add(\"" + s + "\");\n");
}
indent(w, 8); w.write("}\n");
indent(w, 8); w.write("return " + setName + ";\n");
indent(w, 4); w.write("}\n\n");
}
// these two arrays MUST match the encoding used in XPathExpression
// they are package-scope, since they're needed in CompiledAXSData as well
// how many instruction slots a given instruction occupies
static final int[] InstructionLengths = {
1,
1, 2, 1, 2, 2,
1, 1, 2, 1, 1,
1, 1, 1, 2, 1,
1, 1, 1, 1, 1,
1, 1, 2
};
// the XPathExpression.* names for each token value
static final String[] InstructionNames = {
"(zero)",
"INSTR_ROOT",
"INSTR_ELEMENT",
"INSTR_CONTAINS",
"INSTR_ATTRIBUTE",
"INSTR_LITERAL",
"INSTR_EQ_STR",
"INSTR_NOT",
"INSTR_ILITERAL",
"INSTR_AND",
"INSTR_OR",
"INSTR_TEST_PREDICATE",
"INSTR_ENDS_WITH",
"INSTR_STARTS_WITH",
"INSTR_NONCONSECUTIVE_ELEMENT",
"INSTR_POSITION",
"INSTR_LT",
"INSTR_GT",
"INSTR_EQ",
"INSTR_NE",
"INSTR_LE",
"INSTR_GE",
"INSTR_MATCHES",
"INSTR_SOFT_TEST_PREDICATE"
};
static final int NONE = 0;
static final int STRING = 1;
static final int QNAME = 2;
static final int INTEGER = 3;
static final int InstructionArguments[] = {
NONE,
NONE,
QNAME,
NONE,
QNAME,
STRING,
NONE,
NONE,
INTEGER,
NONE,
NONE,
NONE,
NONE,
NONE,
QNAME,
NONE,
NONE,
NONE,
NONE,
NONE,
NONE,
NONE,
NONE,
INTEGER
};
private static void writeInstructionArray(Writer w, int indentSpaces, ShortVector instrs) throws IOException {
final int in = indentSpaces;
w.write("new short[] {\n");
for (int i = 0, len = instrs.size(); i < len; i++) {
short instr = instrs.get(i);
indent(w, in+4); w.write("XPathExpression."); w.write(InstructionNames[instr]); w.write(",");
if (InstructionLengths[instr] == 2) {
i++;
w.write(" ");
w.write(String.valueOf(instrs.get(i)));
w.write(",");
}
w.write("\n");
}
indent(w, in); w.write("}");
}
private static void writeStringArray(Writer w, int indentSpaces, Vector<String> literals) throws IOException {
final int in = indentSpaces;
w.write("new String[] {\n");
for (int i = 0, len = literals.size(); i < len; i++) {
indent(w, in+4);
w.write('"');
w.write(literals.get(i).replace("\"", "\\\""));
w.write("\",\n");
}
indent(w, in); w.write("}");
}
private static void writeQNameArray(Writer w, int indentSpaces, Vector<QName> qNames) throws IOException {
final int in = indentSpaces;
w.write("new QName[] {\n");
for (int i = 0, len = qNames.size(); i < len; i++) {
QName qn = qNames.get(i);
indent(w, in+4);
w.write("new QName(\"");
w.write(qn.getNamespaceURI().replace("\"", "\\\""));
w.write("\", \"");
w.write(qn.getLocalPart().replace("\"", "\\\""));
w.write("\"),\n");
}
indent(w, in); w.write("}");
}
private static void writeExpressions(Writer w, Vector<CompiledAXSData.Method> methods, Vector<ShortVector> instructions, Vector<String> literals, Vector<QName> qNames) throws IOException {
indent(w, 4); w.write("private static String[] Literals = ");
writeStringArray(w, 4, literals);
w.write(";\n\n");
indent(w, 4); w.write("private static QName[] QNames = ");
writeQNameArray(w, 4, qNames);
w.write(";\n\n");
indent(w, 4); w.write("private static XPathExpression[] Expressions = new XPathExpression[] {\n");
for (int i = 0, len = instructions.size(); i < len; i++) {
indent(w, 8); w.write("new XPathExpression(");
w.write(" // \"");
w.write(methods.get(i).expression());
w.write("\"\n");
indent(w, 8); writeInstructionArray(w, 8, instructions.get(i));
w.write(", QNames, Literals),\n");
}
indent(w, 4); w.write("};\n\n");
indent(w, 4); w.write("public XPathExpression[] getXPathExpressions() {\n return Expressions;\n }\n");
}
private static void writeFooter(Writer w) throws IOException {
w.write("}\n");
}
}
| Java |
/*
* This file is part of AXS, Annotation-XPath for SAX.
*
* Copyright (c) 2013 Benjamin K. Stuhl
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies
* of the Software, and to permit persons to whom the Software is furnished to do
* so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in all
* copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
* SOFTWARE.
*/
package com.googlecode.axs;
import java.util.Arrays;
/**
* Internal support class which implements a Vector<short>
* @author Ben
*
*/
public class ShortVector {
private short[] buffer;
private int length = 0;
public ShortVector() {
buffer = new short[16];
}
public void push(short v) {
if (length == buffer.length) {
// reallocate
int newsz = length * 3 / 2;
short[] newBuffer = new short[newsz];
System.arraycopy(buffer, 0, newBuffer, 0, buffer.length);
buffer = newBuffer;
}
buffer[length++] = v;
}
public int size() {
return length;
}
public short top() {
if (length == 0)
throw new ArrayIndexOutOfBoundsException(0);
return buffer[length - 1];
}
public short get(int index) {
if (index >= length)
throw new ArrayIndexOutOfBoundsException(index);
return buffer[index];
}
public void put(int index, short v) {
if (index >= length)
throw new ArrayIndexOutOfBoundsException(index);
buffer[index] = v;
}
public short[] result() {
return Arrays.copyOf(buffer, length);
}
public String toString() {
StringBuffer sb = new StringBuffer("ShortVector(");
sb.append(length);
sb.append(", [");
for (int i = 0; i < length; i++) {
sb.append(buffer[i]);
if (i != length-1)
sb.append(", ");
}
sb.append("])");
return sb.toString();
}
}
| Java |
/*
* This file is part of AXS, Annotation-XPath for SAX.
*
* Copyright (c) 2013 Benjamin K. Stuhl
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies
* of the Software, and to permit persons to whom the Software is furnished to do
* so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in all
* copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
* SOFTWARE.
*/
package com.googlecode.axs;
import java.util.HashMap;
import java.util.Map;
import javax.annotation.processing.Messager;
import javax.lang.model.element.Element;
import javax.lang.model.element.Name;
import javax.lang.model.element.TypeElement;
import javax.tools.Diagnostic.Kind;
/**
* This class collects all the annotated methods found within a single subclass
* of AbstractAnnotatedHandler, so that they can be combined into a single _AXSData
* file.
* @author Ben
*
*/
class AnnotatedClass {
// the class that this object is annotating
private TypeElement mClassElement;
private Messager mMessager;
// maps of method names to XPath expressions
private HashMap<String, String> mXPathMethods = new HashMap<String, String>();
private HashMap<String, String> mXPathEndMethods = new HashMap<String, String>();
private HashMap<String, String> mXPathStartMethods = new HashMap<String, String>();
// maps of method names to Elements
private HashMap<String, Element> mMethodElements = new HashMap<String, Element>();
// map of prefixes to Namespace URIs
private HashMap<String, String> mPrefixMap = new HashMap<String, String>();
public AnnotatedClass(Messager messager, TypeElement clazz) {
mMessager = messager;
mClassElement = clazz;
mPrefixMap.put("", null);
}
public void addMethodAnnotation(Element methodElement, TypeElement annotationElement) {
final String aType = annotationElement.getSimpleName().toString();
final String method = methodElement.getSimpleName().toString();
mMethodElements.put(method, methodElement);
if ("XPath".equals(aType)) {
XPath xp = methodElement.getAnnotation(XPath.class);
mXPathMethods.put(method, xp.value());
} else if ("XPathStart".equals(aType)) {
XPathStart xp = methodElement.getAnnotation(XPathStart.class);
mXPathStartMethods.put(method, xp.value());
} else if ("XPathEnd".equals(aType)) {
XPathEnd xp = methodElement.getAnnotation(XPathEnd.class);
mXPathEndMethods.put(method, xp.value());
} else {
mMessager.printMessage(Kind.ERROR,
"Cannot apply annotation " + aType + " to element of type " + methodElement.getKind(), methodElement);
}
}
public void addClassAnnotation(TypeElement annotationElement) {
final String aType = annotationElement.getSimpleName().toString();
if (!"XPathNamespaces".equals(aType)) {
mMessager.printMessage(Kind.ERROR, "Cannot apply annotation " + aType, mClassElement);
return;
}
XPathNamespaces ns = mClassElement.getAnnotation(XPathNamespaces.class);
String[] prefixes = ns.value();
for (String p : prefixes) {
int eqPos = p.indexOf('=');
if (eqPos < 0) {
mMessager.printMessage(Kind.ERROR, "Namespaces must be of the form \"prefix=URI\"", mClassElement);
continue;
}
String prefix = p.substring(0, eqPos);
String uri = p.substring(eqPos+1);
mMessager.printMessage(Kind.NOTE, "Mapping namespace \"" + prefix + "\" to \"" + uri + "\" for class " + className());
mPrefixMap.put(prefix, uri);
}
}
public Name className() {
return mClassElement.getQualifiedName();
}
public TypeElement classElement() {
return mClassElement;
}
public Map<String, Element> methodElements() {
return mMethodElements;
}
public Map<String, String> xPathMethods() {
return mXPathMethods;
}
public Map<String, String> xPathEndMethods() {
return mXPathEndMethods;
}
public Map<String, String> xPathStartMethods() {
return mXPathStartMethods;
}
public Map<String, String> prefixMap() {
return mPrefixMap;
}
}
| Java |
/*
* This file is part of AXS, Annotation-XPath for SAX.
*
* Copyright (c) 2013 Benjamin K. Stuhl
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies
* of the Software, and to permit persons to whom the Software is furnished to do
* so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in all
* copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
* SOFTWARE.
*/
package com.googlecode.axs;
import java.io.BufferedWriter;
import java.io.IOException;
import java.util.HashMap;
import java.util.Set;
import javax.annotation.processing.AbstractProcessor;
import javax.annotation.processing.Filer;
import javax.annotation.processing.Messager;
import javax.annotation.processing.RoundEnvironment;
import javax.annotation.processing.SupportedAnnotationTypes;
import javax.annotation.processing.SupportedOptions;
import javax.annotation.processing.SupportedSourceVersion;
import javax.lang.model.SourceVersion;
import javax.lang.model.element.Element;
import javax.lang.model.element.ElementKind;
import javax.lang.model.element.TypeElement;
import javax.tools.Diagnostic.Kind;
import javax.tools.FileObject;
/**
* This class provides the compiler processing needed to support the
* annotations, specifically the generation of the _AXSData class
* containing the compiled XPath expressions needed for a given
* AbstractAnnotatedHandler subclass
* @author Ben
*
*/
@SupportedAnnotationTypes({
"com.googlecode.axs.XPath",
"com.googlecode.axs.XPathStart",
"com.googlecode.axs.XPathEnd",
"com.googlecode.axs.XPathNamespaces"
})
@SupportedSourceVersion(SourceVersion.RELEASE_6)
@SupportedOptions("axs.nogenerated")
public class AnnotationProcessor extends AbstractProcessor {
// accumulate all the classes we need to generate _AXSData classes for
private HashMap<TypeElement, AnnotatedClass> mClasses = new HashMap<TypeElement, AnnotatedClass>();
private int mAnnotatedMethods = 0;
public AnnotationProcessor() {
super();
}
private TypeElement enclosingClassOf(Element elem) {
while (true) {
if (elem.getKind() == ElementKind.CLASS)
return (TypeElement) elem;
elem = elem.getEnclosingElement();
}
}
@Override
public boolean process(Set<? extends TypeElement> elements,
RoundEnvironment env) {
final Filer filer = processingEnv.getFiler();
final Messager messager = processingEnv.getMessager();
// collect all the annotations for each user class into
// a coherent set
for (TypeElement annotationElement : elements) {
for (Element e : env.getElementsAnnotatedWith(annotationElement)) {
TypeElement classElement = enclosingClassOf(e);
AnnotatedClass ac = mClasses.get(classElement);
if (ac == null) {
ac = new AnnotatedClass(messager, classElement);
mClasses.put(classElement, ac);
}
if (e.getKind() == ElementKind.METHOD) {
ac.addMethodAnnotation(e, annotationElement);
mAnnotatedMethods += 1;
} else if (e.getKind() == ElementKind.CLASS) {
ac.addClassAnnotation(annotationElement);
} else {
messager.printMessage(Kind.ERROR, "Invalid location for annotation " + annotationElement.getSimpleName(), e);
}
}
}
// only write out the _AXSData classes on the final annotation processing round
if (!env.processingOver())
return true;
messager.printMessage(Kind.NOTE, "Found " + mClasses.size() +
(mClasses.size() > 1 ? " classes" : " class") +
" with XPath annotations on " + mAnnotatedMethods +
(mAnnotatedMethods == 1 ? " method" : " methods"));
// compile the XPath expressions for each class and write
// out the _AXSData for it
for (AnnotatedClass ac : mClasses.values()) {
CompiledAXSData axsData = new CompiledAXSData(ac, messager);
axsData.compile();
String filename = ac.className() + "_AXSData";
try {
FileObject axsDataFile = filer.createSourceFile(filename,
ac.classElement());
BufferedWriter writer = new BufferedWriter(axsDataFile.openWriter());
if (processingEnv.getOptions().containsKey("axs.nogenerated"))
AXSDataWriter.setUseGeneratedAnnotation(false);
AXSDataWriter.writeAXSData(writer, axsData);
writer.close();
} catch (IOException e) {
messager.printMessage(Kind.ERROR, "Error writing " + filename +
": " + e.toString());
}
}
return true;
}
}
| Java |
/*
* This file is part of AXS, Annotation-XPath for SAX.
*
* Copyright (c) 2013 Benjamin K. Stuhl
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies
* of the Software, and to permit persons to whom the Software is furnished to do
* so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in all
* copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
* SOFTWARE.
*/
package com.googlecode.axs.tests;
import java.io.File;
import java.io.IOException;
import java.util.Map;
import javax.xml.parsers.ParserConfigurationException;
import javax.xml.parsers.SAXParser;
import javax.xml.parsers.SAXParserFactory;
import org.xml.sax.SAXException;
import com.googlecode.axs.AbstractAnnotatedHandler;
import com.googlecode.axs.QName;
import com.googlecode.axs.XPath;
import com.googlecode.axs.XPathNamespaces;
public class RuntimeTest4 extends AbstractAnnotatedHandler {
@XPath("italic//bold")
public void testPredicateRetrial(String text) {
if (text.equals("Text 1 and text 2.")) {
System.out.println("[OK] Matched longest copy.");
} else if (text.equals("text 2")) {
System.out.println("[OK] Matched medium copy.");
} else if (text.equals("2")) {
System.out.println("[OK] Matched shortest copy.");
} else {
System.out.println("[FAIL] Got unexpected text \"" + text + "\"");
}
}
public static void main(String[] args) {
SAXParserFactory factory = SAXParserFactory.newInstance();
factory.setNamespaceAware(true);
if (! (new File(args[0] + "/testData4.xml")).exists()) {
System.out.println("Usage: RuntimeTest4 path/to/testData");
System.exit(1);
}
System.out.println("[INFO] Should get exactly 3 [OK]s.");
try {
SAXParser parser = factory.newSAXParser();
String testDataRoot = args[0];
RuntimeTest4 test1 = new RuntimeTest4();
parser.parse(testDataRoot + "/testData4.xml", test1);
} catch (SAXException e) {
System.out.println("[FAIL] Got a SAXException: "+ e);
} catch (IOException e) {
System.out.println("Usage: RuntimeTest3 path/to/testData");
} catch (ParserConfigurationException e) {
System.out.println("[FAIL] Got a ParserConfigurationException: " + e);
}
}
}
| Java |
/*
* This file is part of AXS, Annotation-XPath for SAX.
*
* Copyright (c) 2013 Benjamin K. Stuhl
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies
* of the Software, and to permit persons to whom the Software is furnished to do
* so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in all
* copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
* SOFTWARE.
*/
package com.googlecode.axs.tests;
import java.io.File;
import java.io.IOException;
import java.util.Map;
import javax.xml.parsers.ParserConfigurationException;
import javax.xml.parsers.SAXParser;
import javax.xml.parsers.SAXParserFactory;
import org.xml.sax.SAXException;
import com.googlecode.axs.AbstractAnnotatedHandler;
import com.googlecode.axs.QName;
import com.googlecode.axs.XPath;
import com.googlecode.axs.XPathNamespaces;
public class RuntimeTest3 extends AbstractAnnotatedHandler {
private void expect(String expectation, String value) {
if (expectation.equals(value)) {
System.out.println("[OK] expect \"" + expectation + "\"");
} else {
System.out.println("[FAIL] expect \"" + expectation + "\", got \"" + value + "\"");
}
}
@XPath("entry[@mod = 'moda'][@key = 'keyb']//value[@type='type2']")
public void testPredicateRetrial(String text) {
expect("Retrial1", text);
}
public static void main(String[] args) {
SAXParserFactory factory = SAXParserFactory.newInstance();
factory.setNamespaceAware(true);
if (! (new File(args[0] + "/testData3.xml")).exists()) {
System.out.println("Usage: RuntimeTest3 path/to/testData");
System.exit(1);
}
try {
SAXParser parser = factory.newSAXParser();
String testDataRoot = args[0];
RuntimeTest3 test1 = new RuntimeTest3();
parser.parse(testDataRoot + "/testData3.xml", test1);
} catch (SAXException e) {
System.out.println("[FAIL] Got a SAXException: "+ e);
} catch (IOException e) {
System.out.println("Usage: RuntimeTest3 path/to/testData");
} catch (ParserConfigurationException e) {
System.out.println("[FAIL] Got a ParserConfigurationException: " + e);
}
}
}
| Java |
/*
* This file is part of AXS, Annotation-XPath for SAX.
*
* Copyright (c) 2013 Benjamin K. Stuhl
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies
* of the Software, and to permit persons to whom the Software is furnished to do
* so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in all
* copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
* SOFTWARE.
*/
package com.googlecode.axs.tests;
import java.io.File;
import java.io.IOException;
import javax.xml.parsers.ParserConfigurationException;
import javax.xml.parsers.SAXParser;
import javax.xml.parsers.SAXParserFactory;
import org.xml.sax.Attributes;
import org.xml.sax.SAXException;
import com.googlecode.axs.AbstractAnnotatedHandler;
import com.googlecode.axs.XPath;
import com.googlecode.axs.XPathEnd;
import com.googlecode.axs.XPathNamespaces;
import com.googlecode.axs.XPathStart;
@XPathNamespaces({ "ns1=http://test.values/tests" })
public class RuntimeTest1 extends AbstractAnnotatedHandler {
private int mNrBElements = 0;
private int mNrDElements = 0;
private int mNrEElements = 0;
public int nrBElements() { return mNrBElements; }
public int nrDElements() { return mNrDElements; }
public int nrEElements() { return mNrEElements; }
@XPath("b")
public void bElement(String text) {
if (!text.equals("testing text ")) {
System.out.println("[FAIL] found a <b> element containing \"" + text + "\"");
}
mNrBElements++;
}
@XPathStart("d")
public void dElementStart(Attributes attrs) {
if (!"true".equals(attrs.getValue("attr3"))) {
System.out.println("[FAIL] <d> element does not have attr3=\"true\"");
} else {
System.out.println("[OK] <d> element has attr3=\"true\"");
}
mNrDElements++;
}
@XPathStart("e")
public void eElementStart(Attributes attrs) {
mNrEElements++;
}
@XPathEnd("e")
public void eElementEnd() {
mNrEElements++;
}
private void checkText(String text, int n) {
if (!text.equals("This is some testing text " + n + "!")) {
System.out.println("[FAIL] Looked for text " + n + ", got \"" + text + "\"");
} else {
System.out.println("[OK] Found testing text " + n);
}
}
@XPath("//tests/test[position() < 4]/a")
public void testAElement(String text) {
if (!text.startsWith("This is some testing text ")) {
System.out.println("[FAIL] Looked for text, got \"" + text + "\"");
}
}
@XPath("/tests/test[2]/a[@attr1 = 'value1' and attribute::value2 != 'value3'][1]")
public void testAElementAttrs2(String text) {
checkText(text, 2);
}
@XPath("//a[attribute::attr2 = 'value3' and not(@ns1:attrNotFound = 'foo''bar')]")
public void testAElementAttrs3(String text) {
checkText(text, 3);
}
@XPath("/tests/test[2]/a[starts-with(@attr1,'value') and attribute::attr2 = 'value2' and position() = 3]")
public void testAElementAttrs4(String text) {
checkText(text, 4);
}
/**
* @param args
*/
public static void main(String[] args) {
SAXParserFactory factory = SAXParserFactory.newInstance();
if (! (new File(args[0] + "/testData1.xml")).exists()) {
System.out.println("Usage: RuntimeTest1 path/to/testData");
System.exit(1);
}
try {
SAXParser parser = factory.newSAXParser();
String testDataRoot = args[0];
RuntimeTest1 test1 = new RuntimeTest1();
parser.parse(testDataRoot + "/testData1.xml", test1);
if (test1.nrBElements() == 6) {
System.out.println("[OK] Found 6 <b> elements");
} else {
System.out.println("[FAIL] Found " + test1.nrBElements() + " <b> elements?!");
}
if (test1.nrDElements() == 1) {
System.out.println("[OK] Found 1 <d> element");
} else {
System.out.println("[FAIL] Found " + test1.nrDElements() + " <d> elements?!");
}
if (test1.nrEElements() == 0) {
System.out.println("[OK] Found 0 <e> elements");
} else {
System.out.println("[FAIL] Found " + test1.nrEElements() + " <e> elements?!");
}
} catch (SAXException e) {
System.out.println("[FAIL] Got a SAXException: "+ e);
} catch (IOException e) {
System.out.println("Usage: RuntimeTest1 path/to/testData");
} catch (ParserConfigurationException e) {
System.out.println("[FAIL] Got a ParserConfigurationException: " + e);
}
}
}
| Java |
/*
* This file is part of AXS, Annotation-XPath for SAX.
*
* Copyright (c) 2013 Benjamin K. Stuhl
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies
* of the Software, and to permit persons to whom the Software is furnished to do
* so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in all
* copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
* SOFTWARE.
*/
package com.googlecode.axs.tests;
import java.io.File;
import java.io.IOException;
import java.util.Map;
import javax.xml.parsers.ParserConfigurationException;
import javax.xml.parsers.SAXParser;
import javax.xml.parsers.SAXParserFactory;
import org.xml.sax.SAXException;
import com.googlecode.axs.AbstractAnnotatedHandler;
import com.googlecode.axs.QName;
import com.googlecode.axs.XPath;
import com.googlecode.axs.XPathNamespaces;
@XPathNamespaces({ "ns1=http://test.values/ns1", "ns2=http://test.values/ns2", "=http://test.values/ns0" })
public class RuntimeTest2 extends AbstractAnnotatedHandler {
private void expect(String expectation, String value) {
if (expectation.equals(value)) {
System.out.println("[OK] expect \"" + expectation + "\"");
} else {
System.out.println("[FAIL] expect \"" + expectation + "\", got \"" + value + "\"");
}
}
@XPath("ns2:key[captureattrs()]/value " +
"| ns1:map/ns2:key[ends-with(@value, 'bb')]/value " +
"| ns2:key[contains(@value, 'bb')]/value")
void testAttributeStack(String text) {
Map<QName, String> attrs = attributesAtDepth(tagDepth() - 2);
String key = attrs.get(new QName("value"));
if (key.equals("abbb"))
expect("Value 10", text);
else if (key.equals("bbbb"))
expect("Value 11", text);
else
System.out.println("[FAIL] unexpected key \"" + key + "\"");
}
@XPath("ns1:map/ns2:key[ends-with(@value, 'c')] | ns1:map/ns2:key[starts-with(@value, 'c')]")
void neverHappen(String text) {
System.out.println("[FAIL] pattern matched that shouldn't");
}
@XPath("ns2:key[starts-with('bbbbbbbbb', @value)]")
void testStartsWith(String text) {
expect("Value 11", text);
}
@XPath("value[@label != '']")
void testEmpty(String text) {
expect("", text);
}
@XPath("ns2:key[matches(@value, 'ab*')]")
void testRegexp(String text) {
expect("Value 10", text);
}
public static void main(String[] args) {
SAXParserFactory factory = SAXParserFactory.newInstance();
factory.setNamespaceAware(true);
if (! (new File(args[0] + "/testData2.xml")).exists()) {
System.out.println("Usage: RuntimeTest2 path/to/testData");
System.exit(1);
}
try {
SAXParser parser = factory.newSAXParser();
String testDataRoot = args[0];
RuntimeTest2 test1 = new RuntimeTest2();
parser.parse(testDataRoot + "/testData2.xml", test1);
} catch (SAXException e) {
System.out.println("[FAIL] Got a SAXException: "+ e);
} catch (IOException e) {
System.out.println("Usage: RuntimeTest2 path/to/testData");
} catch (ParserConfigurationException e) {
System.out.println("[FAIL] Got a ParserConfigurationException: " + e);
}
}
}
| Java |
/*
* This file is part of AXS, Annotation-XPath for SAX.
*
* Copyright (c) 2013 Benjamin K. Stuhl
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies
* of the Software, and to permit persons to whom the Software is furnished to do
* so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in all
* copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
* SOFTWARE.
*/
package com.googlecode.axs.tests;
import org.xml.sax.Attributes;
import com.googlecode.axs.AbstractAnnotatedHandler;
import com.googlecode.axs.XPath;
import com.googlecode.axs.XPathEnd;
import com.googlecode.axs.XPathNamespaces;
import com.googlecode.axs.XPathStart;
@XPathNamespaces({
"=http://foo.bar/NS1",
"baz=http://baz.blah/NS2",
"grep=mailto:grep.is.not.awk"
})
public class CompilationTest extends AbstractAnnotatedHandler {
public CompilationTest() {
super();
}
@XPath("foo/ (: not baz :) bar")
public void barElement(String text) {
}
@XPath("/grep[captureattrs()]//foo[2]")
public void fooElement2(String text) {
}
@XPathStart("foo/baz/blah/blah")
public void blahElement2(Attributes attrs) {
}
@XPathStart("/baz//blah")
public void blahElement(Attributes attrs) {
}
@XPathEnd("grep[@is = 'awk']/not")
public void notElementEnd() {
}
@XPathEnd("/grep[@is != 'awk']//awk[2]")
public void awkElementEnd() {
}
public static void main(String[] args) {
CompilationTest t = new CompilationTest();
System.out.println("[OK] Instantiated a CompilationTest object\n");
}
}
| Java |
/*
* This file is part of AXS, Annotation-XPath for SAX.
*
* Copyright (c) 2013 Benjamin K. Stuhl
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies
* of the Software, and to permit persons to whom the Software is furnished to do
* so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in all
* copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
* SOFTWARE.
*/
package com.googlecode.axs;
/**
* This is thrown if a handler's autogenerated _AXSData extension is unable to find
* a call for a given id. It should never happen.
* @author Ben
*
*/
public class HandlerCallError extends Error {
private static final long serialVersionUID = 671966460457946905L;
public HandlerCallError() {
}
public HandlerCallError(String arg0) {
super(arg0);
}
public HandlerCallError(Throwable arg0) {
super(arg0);
}
public HandlerCallError(String arg0, Throwable arg1) {
super(arg0, arg1);
}
}
| Java |
/*
* This file is part of AXS, Annotation-XPath for SAX.
*
* Copyright (c) 2013 Benjamin K. Stuhl
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies
* of the Software, and to permit persons to whom the Software is furnished to do
* so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in all
* copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
* SOFTWARE.
*/
package com.googlecode.axs;
/**
* This is thrown if the XPath expression evaluator encounters an error. It should
* never happen.
* @author Ben
*
*/
public class XPathExecutionError extends Error {
private static final long serialVersionUID = 8766724750974708974L;
public XPathExecutionError() {
}
public XPathExecutionError(String message) {
super(message);
}
public XPathExecutionError(Throwable cause) {
super(cause);
}
public XPathExecutionError(String message, Throwable cause) {
super(message, cause);
}
}
| Java |
/*
* This file is part of AXS, Annotation-XPath for SAX.
*
* Copyright (c) 2013 Benjamin K. Stuhl
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies
* of the Software, and to permit persons to whom the Software is furnished to do
* so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in all
* copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
* SOFTWARE.
*/
package com.googlecode.axs;
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
@Target(ElementType.METHOD)
@Retention(RetentionPolicy.SOURCE)
public @interface XPathStart {
String value();
}
| Java |
/*
* This file is part of AXS, Annotation-XPath for SAX.
*
* Copyright (c) 2013 Benjamin K. Stuhl
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies
* of the Software, and to permit persons to whom the Software is furnished to do
* so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in all
* copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
* SOFTWARE.
*/
package com.googlecode.axs;
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
@Target(ElementType.METHOD)
@Retention(RetentionPolicy.SOURCE)
public @interface XPathEnd {
String value();
}
| Java |
/*
* This file is part of AXS, Annotation-XPath for SAX.
*
* Copyright (c) 2013 Benjamin K. Stuhl
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies
* of the Software, and to permit persons to whom the Software is furnished to do
* so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in all
* copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
* SOFTWARE.
*/
package com.googlecode.axs;
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
@Target(ElementType.METHOD)
@Retention(RetentionPolicy.SOURCE)
public @interface XPath {
String value();
}
| Java |
/*
* This file is part of AXS, Annotation-XPath for SAX.
*
* Copyright (c) 2013 Benjamin K. Stuhl
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies
* of the Software, and to permit persons to whom the Software is furnished to do
* so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in all
* copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
* SOFTWARE.
*/
package com.googlecode.axs;
import java.util.Map;
import java.util.Set;
import org.xml.sax.Attributes;
import org.xml.sax.SAXException;
/**
* This is the interface that the autogenerated _AXSData stubs implement to provide
* the compiled XPath queries and callbacks for a Handler. It is completely subject to
* change in a future version of this library.
* @author Ben
*
*/
public interface AXSData {
/**
* Report what version of the AXSData format this is.
* @return the version as 0xAAAABBBB where AAAA is the major version
* and BBBB is the minor version
*/
public abstract int getAXSDataVersion();
/**
* Call an {@literal @}XPathStart() function.
* @param handler the Handler to make the call on
* @param xpId the index of the XPath expression in the expression data
* @param attrs the SAX Attributes of the the node which triggered the call
*/
public abstract void callXPathStart(AbstractAnnotatedHandler handler, int xpId, Attributes attrs)
throws SAXException;
/**
* Call an {@literal @}XPathEnd() function.
* @param handler the Handler to make the call on
* @param xpId the index of the XPath expression in the expression data
*/
public abstract void callXPathEnd(AbstractAnnotatedHandler handler, int xpId)
throws SAXException;
/**
* Call an {@literal @}XPath() function.
* @param handler the Handler to make the call on
* @param xpId the index of the XPath expression in the expression data
* @param text the concatenated TEXT elements enclosed by this element
*/
public abstract void callXPathText(AbstractAnnotatedHandler handler, int xpId, String text)
throws SAXException;
/**
* Fetch the list of precompiled XPath expressions used by the Handler. The list must be
* sorted so that all the {@literal @}XPath() expressions (which require the engine to capture
* all the TEXT elements within the match range of the expression) are first, then all the
* {@literal @}XPathEnd() expressions, then the {@literal @}XPathStart() expressions
* @return the array of compiled XPath expressions
*/
public XPathExpression[] getXPathExpressions();
// FIXME: does it make sense to have a literals() and qNames() pointer per XPathExpression,
// or should there be getXPathLiterals() and getXPathQNames() functions?
/**
* Get the number of expressions which require the engine to capture TEXT elements. These
* expressions must be the first N elements of {@link getXPathExpressions()}.
* @return the number of expressions
*/
public int getNumberOfCapturingExpressions();
// FIXME: does it take more space to have multiple getNumber*() functions, or should there
// be just one getConstant(int constantName) function?
/**
* Get the number of {@literal @}XPathEnd() expressions
* @return the number of expressions
*/
public int getNumberOfEndExpressions();
/**
* Get the maximum stack depth required to evaluate any predicate in the expression array.
* @return the maximum stack depth required
*/
public int getMaximumPredicateStackDepth();
/**
* Get the map of which tags can trigger attempts to evaluate which XPath expressions.
* @return a map of tag Local Names to arrays of indices into the expression array
*/
public Map<String, int[]> getTriggerTags();
/**
* Get the set of tags whose attributes should be captured for later XPath expressions.
* @return a Set<String> of Local Names
*/
public Set<String> getAttributeCaptureTags();
/**
* Get the set of tags for which the engine should record the position() values for later
* XPath expression evaluations.
* @return a Set<String> of Local Names
*/
public Set<String> getPositionCaptureTags();
}
| Java |
/*
* This file is part of AXS, Annotation-XPath for SAX.
*
* Copyright (c) 2013 Benjamin K. Stuhl
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies
* of the Software, and to permit persons to whom the Software is furnished to do
* so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in all
* copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
* SOFTWARE.
*/
package com.googlecode.axs;
/**
* An XPathExpression is a precompiled form of an XPath expression. Its format
* is subject to change in future versions of this library; however, it is intended
* to keep backwards compatibility so that it is always safe to upgrade to the latest
* version of the runtime.
* @author Ben
*
*/
public final class XPathExpression {
// The list of valid Token[] values
public static final short INSTR_ROOT = 1;
public static final short INSTR_ELEMENT = 2; // the following value is the index into QNames[]
public static final short INSTR_CONTAINS = 3;
public static final short INSTR_ATTRIBUTE = 4; // the following value is the index into QNames[]
public static final short INSTR_LITERAL = 5; // the following value is the index into Literals[]
public static final short INSTR_EQ_STR = 6;
public static final short INSTR_NOT = 7;
public static final short INSTR_ILITERAL = 8; // the following value is the literal value
public static final short INSTR_AND = 9;
public static final short INSTR_OR = 10;
public static final short INSTR_TEST_PREDICATE = 11;
public static final short INSTR_ENDS_WITH = 12;
public static final short INSTR_STARTS_WITH = 13;
public static final short INSTR_NONCONSECUTIVE_ELEMENT = 14; // the following value is the index into QNames
public static final short INSTR_POSITION = 15; // the following value is the index into QNames
public static final short INSTR_LT = 16;
public static final short INSTR_GT = 17;
public static final short INSTR_EQ = 18;
public static final short INSTR_NE = 19;
public static final short INSTR_LE = 20;
public static final short INSTR_GE = 21;
public static final short INSTR_MATCHES = 22;
public static final short INSTR_SOFT_TEST_PREDICATE = 23; // the following value is a signed offset relative to this instruction
private short[] mInstructions = null;
private QName[] mQNames = null;
private String[] mLiterals = null;
public XPathExpression(short[] instrs, QName[] qNames, String[] literals) {
mInstructions = instrs;
mQNames = qNames;
mLiterals = literals;
}
public short[] instructions() {
return mInstructions;
}
public QName[] qNames() {
return mQNames;
}
public String[] literals() {
return mLiterals;
}
}
| Java |
/*
* This file is part of AXS, Annotation-XPath for SAX.
*
* Copyright (c) 2013 Benjamin K. Stuhl
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies
* of the Software, and to permit persons to whom the Software is furnished to do
* so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in all
* copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
* SOFTWARE.
*/
package com.googlecode.axs;
import javax.xml.XMLConstants;
/**
* This is a clone of javax.xml.namespace.QName,
* which we embed for compatibility with older versions of Android.
*/
public class QName {
private final String mNamespaceURI;
private final String mLocalPart;
public QName(String namespaceURI, String localPart) {
if (namespaceURI == null) {
mNamespaceURI = XMLConstants.NULL_NS_URI;
} else {
mNamespaceURI = namespaceURI;
}
mLocalPart = localPart;
}
public QName(String localPart) {
this(
XMLConstants.NULL_NS_URI,
localPart);
}
public String getNamespaceURI() {
return mNamespaceURI;
}
public String getLocalPart() {
return mLocalPart;
}
public boolean equals(Object other) {
if (other == this) {
return true;
}
if (other instanceof QName) {
QName qName = (QName) other;
return mLocalPart.equals(qName.mLocalPart) && mNamespaceURI.equals(qName.mNamespaceURI);
}
return false;
}
public final int hashCode() {
return mNamespaceURI.hashCode() ^ mLocalPart.hashCode();
}
public String toString() {
if (mNamespaceURI.length() == 0) {
return mLocalPart;
}
return "{" + mNamespaceURI +"}" + mLocalPart;
}
}
| Java |
/*
* This file is part of AXS, Annotation-XPath for SAX.
*
* Copyright (c) 2013 Benjamin K. Stuhl
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies
* of the Software, and to permit persons to whom the Software is furnished to do
* so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in all
* copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
* SOFTWARE.
*/
package com.googlecode.axs;
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
@Target(ElementType.TYPE)
@Retention(RetentionPolicy.SOURCE)
public @interface XPathNamespaces {
String[] value();
}
| Java |
/*
* This file is part of AXS, Annotation-XPath for SAX.
*
* Copyright (c) 2013 Benjamin K. Stuhl
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies
* of the Software, and to permit persons to whom the Software is furnished to do
* so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in all
* copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
* SOFTWARE.
*/
package com.googlecode.axs;
import java.util.HashMap;
import java.util.Map;
import java.util.Set;
import java.util.Stack;
import java.util.regex.Pattern;
import java.util.regex.PatternSyntaxException;
import org.xml.sax.Attributes;
import org.xml.sax.SAXException;
import org.xml.sax.helpers.DefaultHandler;
/**
* The AnnotatedHandlerBase provides the engine that powers any AXS handler class:
* all handlers must derive from it.
* @author Ben
*
*/
public class AbstractAnnotatedHandler extends DefaultHandler {
// the version of the _AXSData expressions generated by the library
public static final int AXSDATA_VERSION = 0x00010000; // v1.0
// a Stack of the current tag path
private Stack<QName> mTagStack = new Stack<QName>();
// a Stack of the attributes for the current tag path
// note: we only store attributes that may be needed to execute one of the
// XPath expressions in the handler; all tags whose attributes are never referenced
// have null stored here.
private Stack<HashMap<QName, String>> mAttributesStack = new Stack<HashMap<QName, String>>();
// a Stack of the active text captures
private Stack<StringBuilder> mTextCaptureStack = new Stack<StringBuilder>();
// how many text captures are active
private int mNrActiveTextCaptures = 0;
// according to some Googling, it is faster to store a mutable object in a Map
// and update it in-place than it is to do a fetch, update, store sequence
private final class Position {
private int mValue = 1;
public void increment() {
++mValue;
}
public int get() {
return mValue;
}
public String toString() {
return "Position(" + mValue + ")";
}
};
// a Stack of HashMap<QName, Position>s which store position capture information
// each Map stores the number of times that each QName has been seen under this parent
private Stack<HashMap<QName, Position>> mPositionCaptureStack = new Stack<HashMap<QName, Position>>();
// the evaluation stack for the predicate evaluator
private int[] mPredicateStack = null;
// the string stack for the predicate evaluator
private String[] mPredicateStringStack = new String[2];
// a cache so that we don't have to recompile patterns for matches()
// function calls
private HashMap<String, Pattern> mPatternCache = null;
// the compiled XPath expression data provider for our subclass
private AXSData mAXSData = null;
// cached values pulled from the AXSData
private XPathExpression[] mExpressions = null;
private int mNrCaptureExpressions = 0;
private int mNrEndExpressions = 0;
private Map<String, int[]> mTriggerTags = null;
private Set<String> mAttributeCaptureTags = null;
private Set<String> mPositionCaptureTags = null;
private boolean mCaptureAttributes = false;
private boolean mCapturePositions = false;
// cache a few objects to reduce GC churn for the common case that only one expression is active
// at a time
private StringBuilder mCachedStringBuilder = null;
private HashMap<QName, String> mCachedAttributesMap = null;
private HashMap<QName, Position> mCachedPositionMap = null;
private static final boolean TRACE_EXECUTION = false;
public AbstractAnnotatedHandler() {
super();
// runtime-load the _AXSData class that corresponds to our subclass
try {
ClassLoader loader = this.getClass().getClassLoader();
@SuppressWarnings("rawtypes")
Class axsDataClass = loader.loadClass(this.getClass().getName() + "_AXSData");
mAXSData = (AXSData) axsDataClass.newInstance();
} catch (ClassNotFoundException e) {
throw new XPathExecutionError("Unable to load _AXSData for class "+ this.getClass().getName());
} catch (IllegalAccessException e) {
throw new XPathExecutionError("Bug: got an IllegalAccessException while instantiating _AXSData" +
" for class "+ this.getClass().getName());
} catch (InstantiationException e) {
throw new XPathExecutionError("Bug: got an InstantiationException while instantiating _AXSData" +
" for class "+ this.getClass().getName());
}
}
// load and cache all the relevant data from the _AXSData
private void setup() {
mExpressions = mAXSData.getXPathExpressions();
mNrCaptureExpressions = mAXSData.getNumberOfCapturingExpressions();
mNrEndExpressions = mAXSData.getNumberOfEndExpressions();
mTriggerTags = mAXSData.getTriggerTags();
mAttributeCaptureTags = mAXSData.getAttributeCaptureTags();
mPositionCaptureTags = mAXSData.getPositionCaptureTags();
mCaptureAttributes = !mAttributeCaptureTags.isEmpty();
mCapturePositions = !mPositionCaptureTags.isEmpty();
mPredicateStack = new int[mAXSData.getMaximumPredicateStackDepth()];
}
// clear everything for a new document
private void reset() {
mTagStack.clear();
mAttributesStack.clear();
mTextCaptureStack.clear();
mNrActiveTextCaptures = 0;
}
@Override
public void startDocument() throws SAXException {
if (mExpressions == null)
setup();
reset();
}
private void instrOk() {
System.out.println("ok");
}
private void instrFail() {
System.out.println("fail");
}
/**
* Test an XPathExpression against the current tag.
* @param xpr the expression to test
* @return true if the expression matches, false otherwise
*/
private boolean testExpression(XPathExpression xpr)
{
final short[] instructions = xpr.instructions();
final String[] literals = xpr.literals();
final QName[] qNames = xpr.qNames();
final int[] evaluationStack = mPredicateStack;
int esp = 0;
int ip = 0, maxIp = instructions.length;
int tagp = mTagStack.size() - 1; // the current tag
String[] stringStack = mPredicateStringStack;
int ssp = 0;
if (TRACE_EXECUTION)
System.out.println("START TEST:");
// We implement predicates as a simple stack machine, while nodes are tested
// directly against the tag stack. The expression is compiled to a reverse-Polish
// form, where we test from the top of the tag stack back up towards the root.
while (ip < maxIp) {
final int instr = instructions[ip];
switch (instr) {
case XPathExpression.INSTR_ROOT:
// test if we've hit the document root
if (TRACE_EXECUTION)
System.out.print(" ROOT(tagp=" + tagp + "): ");
if (tagp != -1) {
if (TRACE_EXECUTION)
instrFail();
return false;
}
if (TRACE_EXECUTION)
instrOk();
break;
case XPathExpression.INSTR_ELEMENT:
{
final QName wantedTag = qNames[instructions[++ip]];
if (TRACE_EXECUTION)
System.out.print(" ELEMENT(" + wantedTag + "): ");
// test if the current node is a specific tag
if (tagp < 0) {
if (TRACE_EXECUTION)
instrFail();
return false;
}
final QName tag = mTagStack.get(tagp);
if (!wantedTag.equals(tag)) {
if (TRACE_EXECUTION)
instrFail();
return false;
}
if (TRACE_EXECUTION)
instrOk();
// consume this level in the tag stack
tagp--;
break;
}
case XPathExpression.INSTR_CONTAINS:
{
if (stringStack[0].contains(stringStack[1])) {
evaluationStack[esp++] = 1;
} else {
evaluationStack[esp++] = 0;
}
if (TRACE_EXECUTION)
System.out.println(" CONTAINS(\"" + stringStack[0] + "\", \"" +
stringStack[1] + "\"): " + evaluationStack[esp-1]);
ssp = 0;
break;
}
case XPathExpression.INSTR_ATTRIBUTE:
{
final QName attrName = qNames[instructions[++ip]];
if (TRACE_EXECUTION)
System.out.print(" ATTRIBUTE(" + attrName + "): ");
// push the value of an attribute onto the predicate string stack
if (tagp < 0) {
if (TRACE_EXECUTION)
instrFail();
return false;
}
final HashMap<QName, String> attrs = mAttributesStack.get(tagp);
if (attrs == null) {
// predicates are executed before the tag value is tested, so
// there is no guarantee that capture data is available if the tag
// test would eventually fail
if (TRACE_EXECUTION)
instrFail();
return false;
}
final String value = attrs.get(attrName);
stringStack[ssp++] = (value != null ? value : "");
if (TRACE_EXECUTION)
System.out.println(stringStack[ssp-1]);
break;
}
case XPathExpression.INSTR_LITERAL:
// push a literal onto the predicate string stack
stringStack[ssp++] = literals[instructions[++ip]];
if (TRACE_EXECUTION)
System.out.println(" LITERAL(\"" + stringStack[ssp-1] + "\")");
break;
case XPathExpression.INSTR_EQ_STR:
// compare the two strings on the string stack and push the result
// on the evaluation stack
if (stringStack[0].equals(stringStack[1])) {
evaluationStack[esp++] = 1;
} else {
evaluationStack[esp++] = 0;
}
ssp = 0;
if (TRACE_EXECUTION)
System.out.println(" EQ_STR: " + evaluationStack[esp-1]);
break;
case XPathExpression.INSTR_NOT:
// invert the sense of the top of the evaluation stack
if (evaluationStack[esp-1] == 0) {
evaluationStack[esp-1] = 1;
} else {
evaluationStack[esp-1] = 0;
}
if (TRACE_EXECUTION)
System.out.println(" NOT: " + evaluationStack[esp-1]);
break;
case XPathExpression.INSTR_ILITERAL:
// push a numeric value onto the evaluation stack
evaluationStack[esp++] = instructions[++ip];
if (TRACE_EXECUTION)
System.out.println(" ILITERAL(" + evaluationStack[esp-1] + ")");
break;
case XPathExpression.INSTR_AND:
{
// AND together the top two values on the evaluation stack
final int i1 = evaluationStack[--esp];
final int i2 = evaluationStack[esp-1];
evaluationStack[esp-1] = ((i1 != 0) && (i2 != 0) ? 1 : 0);
if (TRACE_EXECUTION)
System.out.println(" AND: " + evaluationStack[esp-1]);
break;
}
case XPathExpression.INSTR_OR:
{
// OR together the top two values on the evaluation stack
final int i1 = evaluationStack[--esp];
final int i2 = evaluationStack[esp-1];
evaluationStack[esp-1] = ((i1 != 0) || (i2 != 0) ? 1 : 0);
if (TRACE_EXECUTION)
System.out.println(" OR: " + evaluationStack[esp-1]);
break;
}
case XPathExpression.INSTR_TEST_PREDICATE:
// test whether the predicate matched
if (TRACE_EXECUTION)
System.out.print(" TEST_PREDICATE: ");
if (esp != 1 || evaluationStack[0] == 0) {
if (TRACE_EXECUTION)
instrFail();
return false;
}
esp = 0;
if (TRACE_EXECUTION)
instrOk();
break;
case XPathExpression.INSTR_ENDS_WITH:
{
if (stringStack[0].endsWith(stringStack[1])) {
evaluationStack[esp++] = 1;
} else {
evaluationStack[esp++] = 0;
}
ssp = 0;
if (TRACE_EXECUTION)
System.out.println(" ENDS_WITH(\"" + stringStack[0] + "\", \"" +
stringStack[1] + "\"): " + evaluationStack[esp-1]);
break;
}
case XPathExpression.INSTR_STARTS_WITH:
{
if (stringStack[0].startsWith(stringStack[1])) {
evaluationStack[esp++] = 1;
} else {
evaluationStack[esp++] = 0;
}
ssp = 0;
if (TRACE_EXECUTION)
System.out.println(" STARTS_WITH(\"" + stringStack[0] + "\", \"" +
stringStack[1] + "\"): " + evaluationStack[esp-1]);
break;
}
case XPathExpression.INSTR_NONCONSECUTIVE_ELEMENT:
// consumes any number of tags until the QName before the double slash is found
// but does not consume the tag
{
final QName targetTag = qNames[instructions[++ip]];
if (TRACE_EXECUTION)
System.out.print(" NONCONSECUTIVE_ELEMENT(" + targetTag + "): ");
while (tagp >= 0) {
if (mTagStack.get(tagp).equals(targetTag))
break;
tagp--;
}
if (tagp < 0) {
if (TRACE_EXECUTION)
instrFail();
return false;
}
if (TRACE_EXECUTION)
instrOk();
break;
}
case XPathExpression.INSTR_POSITION:
// push the position() of the current tag onto the evaluation stack
if (TRACE_EXECUTION)
System.out.print(" POSITION: ");
if (tagp <= 0) {
if (TRACE_EXECUTION)
instrFail();
return false;
}
// look up the current tag under its parent
final HashMap<QName, Position> posMap = mPositionCaptureStack.get(tagp-1);
if (posMap == null) {
// predicates are executed before the tag value is tested, so
// there is no guarantee that capture data is available if the tag
// test would eventually fail
if (TRACE_EXECUTION)
instrFail();
return false;
}
final int pos = posMap.get(mTagStack.get(tagp)).get();
evaluationStack[esp++] = pos;
if (TRACE_EXECUTION)
System.out.println(String.valueOf(evaluationStack[esp-1]));
break;
case XPathExpression.INSTR_LT:
{
// less-than operation
final int i1 = evaluationStack[--esp];
final int i2 = evaluationStack[esp-1];
evaluationStack[esp-1] = (i2 < i1 ? 1 : 0);
if (TRACE_EXECUTION)
System.out.println(" LT: " + evaluationStack[esp-1]);
break;
}
case XPathExpression.INSTR_GT:
{
// greater-than operation
final int i1 = evaluationStack[--esp];
final int i2 = evaluationStack[esp-1];
evaluationStack[esp-1] = (i2 > i1 ? 1 : 0);
if (TRACE_EXECUTION)
System.out.println(" GT: " + evaluationStack[esp-1]);
break;
}
case XPathExpression.INSTR_EQ:
{
// numeric equality operation
final int i1 = evaluationStack[--esp];
final int i2 = evaluationStack[esp-1];
evaluationStack[esp-1] = (i2 == i1 ? 1 : 0);
if (TRACE_EXECUTION)
System.out.println(" EQ: " + evaluationStack[esp-1]);
break;
}
case XPathExpression.INSTR_NE:
{
// numeric inequality operation
final int i1 = evaluationStack[--esp];
final int i2 = evaluationStack[esp-1];
evaluationStack[esp-1] = (i2 != i1 ? 1 : 0);
if (TRACE_EXECUTION)
System.out.println(" NE: " + evaluationStack[esp-1]);
break;
}
case XPathExpression.INSTR_LE:
{
// less-than-or-equal operation
final int i1 = evaluationStack[--esp];
final int i2 = evaluationStack[esp-1];
evaluationStack[esp-1] = (i2 <= i1 ? 1 : 0);
if (TRACE_EXECUTION)
System.out.println(" LE: " + evaluationStack[esp-1]);
break;
}
case XPathExpression.INSTR_GE:
{
// greater-than-or-equal operation
final int i1 = evaluationStack[--esp];
final int i2 = evaluationStack[esp-1];
evaluationStack[esp-1] = (i2 >= i1 ? 1 : 0);
if (TRACE_EXECUTION)
System.out.println(" GE: " + evaluationStack[esp-1]);
break;
}
case XPathExpression.INSTR_MATCHES:
{
final String target = stringStack[0];
final String patternString = stringStack[1];
if (TRACE_EXECUTION)
System.out.print(" MATCHES(\"" + target + "\", \"" + patternString + "\": ");
if (mPatternCache == null)
mPatternCache = new HashMap<String, Pattern>();
Pattern pattern = mPatternCache.get(patternString);
if (pattern == null) {
try {
pattern = Pattern.compile(patternString);
} catch (PatternSyntaxException e) {
if (TRACE_EXECUTION)
instrFail();
return false;
}
mPatternCache.put(patternString, pattern);
}
evaluationStack[esp++] = (pattern.matcher(target).matches() ? 1 : 0);
if (TRACE_EXECUTION)
System.out.println(String.valueOf(evaluationStack[esp-1]));
break;
}
case XPathExpression.INSTR_SOFT_TEST_PREDICATE:
// test whether the predicate matched
if (TRACE_EXECUTION)
System.out.print(" SOFT_TEST_PREDICATE: ");
if (esp != 1 || evaluationStack[0] == 0) {
// the predicate failed: pop the tag stack and branch
if (--tagp < 0) {
if (TRACE_EXECUTION)
instrFail();
return false;
}
if (TRACE_EXECUTION)
System.out.println("branch");
esp = 0;
ip += instructions[ip+1];
continue; // execute the branch immediately
}
esp = 0;
ip++;
if (TRACE_EXECUTION)
instrOk();
break;
default:
throw new XPathExecutionError("unexpected instruction value " + instr);
}
ip++;
}
return true;
}
/**
* Build a QName from the startElement()/endElement() parameters.
* @param uri
* @param localName
* @param qName
* @return a new QName
*/
private QName makeQName(String uri, String localName, String qName) {
if (! "".equals(uri))
return new QName(uri, localName);
return new QName(qName);
}
/**
* Capture all the attributes in @p attrs.
* @param attrs the attributes to capture to the attribute stack
*/
private void captureAttributes(Attributes attrs) {
HashMap<QName, String> map = null;
// try to hit the map cache
if (mCachedAttributesMap != null) {
map = mCachedAttributesMap;
mCachedAttributesMap = null;
map.clear();
} else {
map = new HashMap<QName, String>();
}
// store all the attributes into the map
for (int i = 0, len = attrs.getLength(); i < len; i++) {
final String uri = attrs.getURI(i);
final String localName = attrs.getLocalName(i);
final String value = attrs.getValue(i);
map.put(makeQName(uri, localName, localName), value);
}
// push the map onto the attributes stack
mAttributesStack.push(map);
}
/**
* Update the position record for a new tag. Assumes that the capture stack is still
* at the position for the tag's parent.
* @param qn the QName of the new tag
*/
private void capturePosition(QName qn) {
// there is only one root element, ever
if (mPositionCaptureStack.empty())
return;
HashMap<QName, Position> map = mPositionCaptureStack.pop();
if (map == null) {
if (mCachedPositionMap != null) {
map = mCachedPositionMap;
mCachedPositionMap = null;
map.clear();
} else {
map = new HashMap<QName, Position>();
}
}
Position p = map.get(qn);
if (p != null) {
p.increment();
} else {
map.put(qn, new Position());
}
mPositionCaptureStack.push(map);
}
/**
* Set up to start capturing all the text within this element.
*/
private void startTextCapture() {
StringBuilder sb = mTextCaptureStack.pop();
if (sb != null) {
mTextCaptureStack.push(sb);
return;
}
mNrActiveTextCaptures++;
if (mCachedStringBuilder != null) {
mCachedStringBuilder.setLength(0);
mTextCaptureStack.push(mCachedStringBuilder);
mCachedStringBuilder = null;
} else {
mTextCaptureStack.push(new StringBuilder());
}
}
/**
* The implementation of startElement() provides support for starting text captures for
* {@literal @}XPath() handlers and firing {@literal @}XPathStart() handlers. Make sure
* you call it via super if you override it in your handler subclass.
*/
@Override
public void startElement(String uri, String localName, String qName, Attributes attrs) throws SAXException {
// push this tag onto the stack
final QName qn = makeQName(uri, localName, qName);
mTagStack.push(qn);
if (TRACE_EXECUTION)
System.out.println("startElement: <" + qn + ">");
String normalizedLocalName = qn.getLocalPart();
// test whether to perform attribute capture
if (mCaptureAttributes) {
if (mAttributeCaptureTags.contains(normalizedLocalName)) {
captureAttributes(attrs);
if (TRACE_EXECUTION)
System.out.println("captureAttributes => " + mAttributesStack.peek());
} else {
mAttributesStack.push(null);
}
}
// test whether to perform position capture
if (mCapturePositions) {
if (mPositionCaptureTags.contains(normalizedLocalName)) {
if (TRACE_EXECUTION)
System.out.println("capturePosition => " + mPositionCaptureStack.peek());
// update the position marker in the parent tag's level in the stack
capturePosition(qn);
}
// push the position capture stack
mPositionCaptureStack.push(null);
}
// push the text capture stack
mTextCaptureStack.push(null);
// test whether we should start text capture for one or more expressions
// and test whether we have any expressions to fire
int[] triggeredExpressions = mTriggerTags.get(normalizedLocalName);
if (triggeredExpressions == null)
return;
for (final int exprIndex : triggeredExpressions) {
// skip @XPathEnd() expressions
if (exprIndex >= mNrCaptureExpressions && exprIndex < mNrCaptureExpressions+mNrEndExpressions)
continue;
if (!testExpression(mExpressions[exprIndex]))
continue;
// the expression matched: execute it
if (exprIndex < mNrCaptureExpressions) {
if (TRACE_EXECUTION)
System.out.println("CAPTURE for @XPath(" + exprIndex + ")");
// we've found the start of an @XPath() expression: start capturing TEXT elements
startTextCapture();
} else {
if (TRACE_EXECUTION)
System.out.println("CALL @XPathStart(" + exprIndex + ")");
// must be an @XPathStart() expression: fire it
mAXSData.callXPathStart(this, exprIndex, attrs);
}
}
}
/**
* The implementation of characters() provides text capture support for {@literal @}XPath()
* handlers. Make sure you call if via super if you override it in your handler subclass.
*/
@Override
public void characters(char[] ch, int start, int length) throws SAXException {
if (mNrActiveTextCaptures == 0)
return;
// append the characters to all the active text captures
int n = mNrActiveTextCaptures, ix = mTextCaptureStack.size() - 1;
while (n > 0) {
final StringBuilder sb = mTextCaptureStack.get(ix);
if (sb != null) {
sb.append(ch, start, length);
n--;
}
ix--;
}
}
/**
* The implementation of endElement() is responsible for firing {@literal @}XPath() and
* {@literal @}XPathEnd() handlers. Make sure to call it via super if you override it in
* your handler subclass.
*/
@Override
public void endElement(String uri, String localName, String qName) throws SAXException {
// if we've completed a capture, close it out
String text = null;
final StringBuilder sb = mTextCaptureStack.pop();
if (sb != null) {
text = sb.toString();
mNrActiveTextCaptures--;
mCachedStringBuilder = sb;
}
if (TRACE_EXECUTION) {
QName qn = makeQName(uri, localName, qName);
System.out.println("endElement: <" + qn + ">");
}
// test whether we have any expressions to fire
int[] triggeredExpressions = mTriggerTags.get(uri.equals("") ? qName : localName);
if (triggeredExpressions != null) {
for (final int exprIndex : triggeredExpressions) {
// skip @XPathStart() expressions
if (exprIndex >= mNrCaptureExpressions+mNrEndExpressions)
continue;
if (!testExpression(mExpressions[exprIndex]))
continue;
// the expression matched: execute it
if (exprIndex < mNrCaptureExpressions) {
if (TRACE_EXECUTION)
System.out.println("CALL @XPath(" + exprIndex + ",\"" + text + "\")");
// we've found the end of an @XPath() expression: fire it
mAXSData.callXPathText(this, exprIndex, text);
} else {
if (TRACE_EXECUTION)
System.out.println("CALL @XPathEnd(" + exprIndex + ")");
// must be an @XPathEnd() expression: fire it
mAXSData.callXPathEnd(this, exprIndex);
}
}
}
// pop the remaining stacks
if (mCapturePositions) {
final HashMap<QName, Position> posMap = mPositionCaptureStack.pop();
if (posMap != null)
mCachedPositionMap = posMap;
}
if (mCaptureAttributes) {
final HashMap<QName, String> attrMap = mAttributesStack.pop();
if (attrMap != null)
mCachedAttributesMap = attrMap;
}
mTagStack.pop();
}
/**
* Query what depth the current tag is at. Call this from inside an expression handler.
* @return the number of tag to the root from the current tag
*/
public int tagDepth() {
return mTagStack.size();
}
/**
* Query the tag at some other depth in the document. Depth 0 refers to the root element; the current tag
* is at {@link tagDepth}()-1.
* @param depth
* @return the QName of the element at the given @p depth
*/
public QName tagAtDepth(int depth) {
return mTagStack.get(depth);
}
/**
* Look for a tag in the path to the current tag.
* @param qName the fully-qualified name of the tag to search for
* @return the depth of the found tag, or -1 if it was not found
*/
public int findTag(QName tag) {
return mTagStack.indexOf(tag);
}
/**
* Look for a tag in the path to the current tag.
* @param qName the fully-qualified name of the tag to search for
* @param start the position to start the search at
* @return the depth of the found tag, or -1 if it was not found
*/
public int findTag(QName tag, int start) {
return mTagStack.indexOf(tag, start);
}
/**
* Query the attributes map a tag at some other depth in the document. Depth 0 refers to the root element;
* the current tag is {@link tagDepth}()-1. Use the special captureattrs() function as a predicate in
* your XPath expression to mark that attributes should be captured for a given element even if they are
* not used in any other predicate.
* @param depth
* @return either a map of attributes or null if the attributes were not captured
*/
public Map<QName, String> attributesAtDepth(int depth) {
return mAttributesStack.get(depth);
}
}
| Java |
package com.clwillingham.socket.io;
import org.json.JSONObject;
public interface MessageCallback {
public void on(String event, JSONObject... data);
public void onMessage(String message);
public void onMessage(JSONObject json);
public void onConnect();
public void onDisconnect();
}
| Java |
package com.clwillingham.socket.io;
public class Message extends IOMessage{
public Message(String message){
super(IOMessage.MESSAGE, -1, "", message);
}
}
| Java |
// MODIFIED TO REDUCE LOGGING
package com.clwillingham.socket.io;
public class IOMessage {
public static final int DISCONNECT = 0;
public static final int CONNECT = 1;
public static final int HEARTBEAT = 2;
public static final int MESSAGE = 3;
public static final int JSONMSG = 4;
public static final int EVENT = 5;
public static final int ACK = 6;
public static final int ERROR = 7;
private int type;
private int id = -1;
private String endpoint = "";
private String messageData;
public IOMessage(int type, int id, String endpoint, String data){
this.type = type;
this.id = id;
this.endpoint = endpoint;
this.messageData = data;
}
public IOMessage(int type, String endpoint, String data) {
this.type = type;
this.endpoint = endpoint;
this.messageData = data;
}
public IOMessage(){
}
public static IOMessage parseMsg(String message){
String[] content = message.split(":", 4);
IOMessage msg = new IOMessage();
msg.setType(Integer.parseInt(content[0]));
if(message.endsWith("::")){
msg.setId(-1);
msg.setMessageData("");
msg.setEndpoint("");
return msg;
}
if(!content[1].equals("")){
msg.setId(Integer.parseInt(content[1]));
}
if(!content[2].equals("")){
msg.setEndpoint(content[2]);
}
if(content.length > 3 && !content[3].equals("")){
msg.setMessageData(content[3]);
}
return msg;
}
public String toString(){
if(id == -1 && endpoint.equals("") && messageData.equals("")){
return type+"::";
}
else if(id == -1 && endpoint.equals("")){
return type+":::"+messageData;
}
else if(id > -1){
return type+":"+id+":"+endpoint+":"+messageData;
}
else{
return type+"::"+endpoint+":"+messageData;
}
}
public void setType(int type) {
this.type = type;
}
public int getType() {
return type;
}
public void setId(int id) {
this.id = id;
}
public int getId() {
return id;
}
public void setEndpoint(String endpoint) {
this.endpoint = endpoint;
}
public String getEndpoint() {
return endpoint;
}
public void setMessageData(String messageData) {
this.messageData = messageData;
}
public String getMessageData() {
return messageData;
}
}
| Java |
// MODIFIED TO REDUCE LOGGING
package com.clwillingham.socket.io;
import java.io.IOException;
import java.net.URI;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import net.tootallnate.websocket.WebSocketClient;
public class IOWebSocket extends WebSocketClient{
private MessageCallback callback;
private IOSocket ioSocket;
private static int currentID = 0;
private String namespace;
public IOWebSocket(URI arg0, IOSocket ioSocket, MessageCallback callback) {
super(arg0);
this.callback = callback;
this.ioSocket = ioSocket;
}
@Override
public void onIOError(IOException arg0) {
// TODO Auto-generated method stub
}
@Override
public void onMessage(String arg0) {
IOMessage message = IOMessage.parseMsg(arg0);
switch (message.getType()) {
case IOMessage.HEARTBEAT:
try {
send("2::");
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
break;
case IOMessage.MESSAGE:
callback.onMessage(message.getMessageData());
break;
case IOMessage.JSONMSG:
try {
callback.onMessage(new JSONObject(message.getMessageData()));
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
break;
case IOMessage.EVENT:
try {
JSONObject event = new JSONObject(message.getMessageData());
JSONArray args = event.getJSONArray("args");
JSONObject[] argsArray = new JSONObject[args.length()];
for (int i = 0; i < args.length(); i++) {
argsArray[i] = args.getJSONObject(i);
}
String eventName = event.getString("name");
callback.on(eventName, argsArray);
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
break;
case IOMessage.CONNECT:
ioSocket.onConnect();
break;
case IOMessage.ACK:
case IOMessage.ERROR:
case IOMessage.DISCONNECT:
//TODO
break;
}
}
@Override
public void onOpen() {
try {
if (namespace != "")
init(namespace);
} catch (IOException e) {
e.printStackTrace();
}
ioSocket.onOpen();
}
@Override
public void onClose() {
ioSocket.onClose();
ioSocket.onDisconnect();
}
public void init(String path) throws IOException{
send("1::"+path);
}
public void init(String path, String query) throws IOException{
this.send("1::"+path+"?"+query);
}
public void sendMessage(IOMessage message) throws IOException{
send(message.toString());
}
public void sendMessage(String message) throws IOException{
send(new Message(message).toString());
}
public static int genID(){
currentID++;
return currentID;
}
public void setNamespace(String ns) {
namespace = ns;
}
public String getNamespace() {
return namespace;
}
}
| Java |
// MODIFIED TO USE END POINTS IN OUTGOING MESSAGES
// MODIFIED TO REDUCE LOGGING
package com.clwillingham.socket.io;
import java.io.IOException;
import java.io.InputStream;
import java.net.URI;
import java.net.URL;
import java.util.Scanner;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
public class IOSocket {
private IOWebSocket webSocket;
private URL connection;
private String sessionID;
private int heartTimeOut;
private int closingTimeout;
private String[] protocals;
private String webSocketAddress;
private MessageCallback callback;
private boolean connecting;
private boolean connected;
private boolean open;
public IOSocket(String address, MessageCallback callback){
webSocketAddress = address;
this.callback = callback;
}
public void connect() throws IOException {
// check for socket.io namespace
String namespace = "";
int i = webSocketAddress.lastIndexOf("/");
if (webSocketAddress.charAt(i-1) != '/') {
namespace = webSocketAddress.substring(i);
webSocketAddress = webSocketAddress.substring(0, i);
}
// perform handshake
String url = webSocketAddress.replace("ws://", "http://");
URL connection = new URL(url+"/socket.io/1/"); //handshake url
InputStream stream = connection.openStream();
Scanner in = new Scanner(stream);
String response = in.nextLine(); //pull the response
// process handshake response
// example: 4d4f185e96a7b:15:10:websocket,xhr-polling
if(response.contains(":")) {
String[] data = response.split(":");
setSessionID(data[0]);
setHeartTimeOut(Integer.parseInt(data[1]));
setClosingTimeout(Integer.parseInt(data[2]));
setProtocals(data[3].split(","));
}
connecting = true;
webSocket = new IOWebSocket(URI.create(webSocketAddress+"/socket.io/1/websocket/"+sessionID), this, callback);
webSocket.setNamespace(namespace);
webSocket.connect();
}
public void emit(String event, JSONObject... message) throws IOException {
try {
JSONObject data = new JSONObject();
JSONArray args = new JSONArray();
for (JSONObject arg : message) {
args.put(arg);
}
data.put("name", event);
data.put("args", args);
IOMessage packet = new IOMessage(IOMessage.EVENT, webSocket.getNamespace(), data.toString());
webSocket.sendMessage(packet);
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
public void send(String message) throws IOException {
IOMessage packet = new IOMessage(IOMessage.MESSAGE, webSocket.getNamespace(), message);
webSocket.sendMessage(packet);
}
public synchronized void disconnect() {
if (connected) {
try {
if (open) {
webSocket.sendMessage(new IOMessage(IOMessage.DISCONNECT, webSocket.getNamespace(), ""));
}
} catch (IOException e) {
e.printStackTrace();
}
onDisconnect();
}
}
synchronized void onOpen() {
open = true;
}
synchronized void onClose() {
open = false;
}
synchronized void onConnect() {
if (!connected) {
connected = true;
connecting = false;
callback.onConnect();
}
}
synchronized void onDisconnect() {
boolean wasConnected = connected;
connected = false;
connecting = false;
if (open) {
try {
webSocket.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
if (wasConnected) {
callback.onDisconnect();
//TODO: reconnect
}
}
public void setConnection(URL connection) {
this.connection = connection;
}
public URL getConnection() {
return connection;
}
public void setHeartTimeOut(int heartTimeOut) {
this.heartTimeOut = heartTimeOut;
}
public int getHeartTimeOut() {
return heartTimeOut;
}
public void setClosingTimeout(int closingTimeout) {
this.closingTimeout = closingTimeout;
}
public int getClosingTimeout() {
return closingTimeout;
}
public void setSessionID(String sessionID) {
this.sessionID = sessionID;
}
public String getSessionID() {
return sessionID;
}
public void setProtocals(String[] protocals) {
this.protocals = protocals;
}
public String[] getProtocals() {
return protocals;
}
}
| Java |
package wasd;
import grits.wasd.R;
import java.io.IOException;
import org.apache.http.client.HttpClient;
import org.apache.http.client.HttpResponseException;
import org.apache.http.client.ResponseHandler;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.conn.HttpHostConnectException;
import org.apache.http.impl.client.BasicResponseHandler;
import org.apache.http.impl.client.DefaultHttpClient;
import org.json.JSONException;
import org.json.JSONObject;
import org.json.JSONTokener;
import android.accounts.Account;
import android.accounts.AccountManager;
import android.accounts.AccountManagerCallback;
import android.accounts.AccountManagerFuture;
import android.accounts.OperationCanceledException;
import android.app.Activity;
import android.app.AlertDialog;
import android.content.DialogInterface;
import android.content.DialogInterface.OnCancelListener;
import android.content.SharedPreferences;
import android.graphics.Color;
import android.hardware.Sensor;
import android.hardware.SensorEvent;
import android.hardware.SensorEventListener;
import android.hardware.SensorManager;
import android.os.AsyncTask;
import android.os.Bundle;
import android.util.Log;
import android.view.Display;
import android.view.Surface;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.WindowManager;
import android.widget.Button;
import android.widget.Toast;
import com.clwillingham.socket.io.IOSocket;
import com.clwillingham.socket.io.MessageCallback;
/**
* Main activity for the Grits WASD controller.
*/
public class WasdActivity extends Activity {
/**
* Tag used for logging.
*/
public static final String TAG = WasdActivity.class.getName();
/**
* Local IP address for testing with the dev_appserver.
*/
private static final String LOCAL_IP = "192.168.21.28";
/**
* The production origin.
*/
private static final String ORIGIN_GRITSGAME_APPSPOT_COM = "http://gritsgame.appspot.com";
/**
* The dev_appserver origin.
*/
private static final String ORIGIN_LOCAL = "http://" + LOCAL_IP + ":8080";
// private static final String HTTPS_WWW_GOOGLEAPIS_COM_PLUS_V1_PEOPLE_ME = "https://www.googleapis.com/plus/v1/people/me";
/**
* The user info API endpoint, which allows us to retrieve the same user id as is returned by App
* Engine's OAuth2 API for the {@value SCOPE_USERINFO_EMAIL} scope.
*/
private static final String HTTPS_WWW_GOOGLEAPIS_COM_OAUTH2_V1_USERINFO = "https://www.googleapis.com/oauth2/v1/userinfo";
/**
* Preference key where the current account is stored.
*/
private static final String PREF_ACCOUNT_NAME = "ACCOUNT_NAME";
/**
* Preference key prefix where the OAuth2 {@value SCOPE_USERINFO_EMAIL} scope access token is
* stored.
*/
private static final String PREF_OAUTH2_EMAIL_ACCESS_TOKEN_ = "OAUTH2_EMAIL_ACCESS_TOKEN_";
/**
* Preference key prefix where the OAuth2 {@value SCOPE_USERINFO_PROFILE} scope access token is
* stored.
*/
private static final String PREF_OAUTH2_PROFILE_ACCESS_TOKEN_ = "OAUTH2_PROFILE_ACCESS_TOKEN_";
/**
* Preference key where the preferred game origin is stored.
*/
protected static final String PREF_GAME_ORIGIN = "GAME_ORIGIN";
/**
* Determines accelerometer sensitivity, i.e. how far the device must be tilted from level before
* a directional change is detected.
*/
public static final float SENSOR_THRESHOLD = 2f;
/**
* Limits flip flopping of the accelerometer directional state, by requiring a lower sensor
* reading to turn off a particular directional input than is required to enable the same
* directional input.
*/
private static final float SENSOR_STICKINESS = 0.3f;
// private static final String SCOPE_PLUS_ME = "oauth2:https://www.googleapis.com/auth/plus.me";
/**
* OAuth2 scope which provides access to the user id and email address.
*/
private static final String SCOPE_USERINFO_EMAIL = "oauth2:https://www.googleapis.com/auth/userinfo.email";
/**
* OAuth2 scope which provides access to the user's basic profile information, although not the
* email address.
*/
private static final String SCOPE_USERINFO_PROFILE = "oauth2:https://www.googleapis.com/auth/userinfo.profile";
private SensorManager sensorManager;
private Display display;
private SensorListener sensorListener;
private View upView;
private View leftView;
private View rightView;
private View downView;
public boolean left;
public boolean right;
public boolean up;
public boolean down;
private Button reconnectButton;
private Button accountButton;
private SharedPreferences prefs;
private AccountManager accountManager;
private GameAsyncTask gameAsyncTask;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
accountManager = AccountManager.get(this);
getWindow().addFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON);
prefs = getSharedPreferences("grits", MODE_PRIVATE);
sensorManager = (SensorManager) getSystemService(SENSOR_SERVICE);
display = ((WindowManager) getSystemService(WINDOW_SERVICE)).getDefaultDisplay();
sensorListener = new SensorListener();
setContentView(R.layout.wasd);
upView = (View) findViewById(R.id.button_up);
leftView = (View) findViewById(R.id.button_left);
rightView = (View) findViewById(R.id.button_right);
downView = (View) findViewById(R.id.button_down);
reconnectButton = (Button) findViewById(R.id.reconnect_button);
accountButton = (Button) findViewById(R.id.account_button);
reconnectButton.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
chooseEndpoint();
}
});
reconnectButton.setText(prefs.getString(PREF_GAME_ORIGIN, ORIGIN_GRITSGAME_APPSPOT_COM));
accountButton.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
chooseAccount();
}
});
}
@Override
protected void onStart() {
super.onStart();
Log.i(TAG, "************* onStart()");
setAccountFromPref();
}
@Override
protected void onStop() {
super.onStop();
Log.i(TAG, "************* onStop()");
if (gameAsyncTask != null) {
gameAsyncTask.disconnect();
}
}
@Override
protected void onResume() {
super.onResume();
sensorListener.start();
}
@Override
protected void onPause() {
super.onPause();
sensorListener.stop();
}
/**
* Disconnect an existing websocket connection and attempt to reconnect.
*/
protected void reconnect() {
Log.i(TAG, "********************* reconnect()");
if (gameAsyncTask != null) {
gameAsyncTask.disconnect();
}
gameAsyncTask = new GameAsyncTask();
gameAsyncTask.execute();
}
/**
* Allow the user to select a websocket endpoint to connect to.
*/
private void chooseEndpoint() {
AlertDialog.Builder builder = new AlertDialog.Builder(this);
builder.setTitle("Select an endpoint");
final String[] origins = new String[] {ORIGIN_GRITSGAME_APPSPOT_COM, ORIGIN_LOCAL};
builder.setItems(origins, new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
prefs.edit().putString(PREF_GAME_ORIGIN, origins[which]).apply();
reconnectButton.setText(origins[which]);
reconnect();
}
});
AlertDialog dialog = builder.create();
dialog.setOnCancelListener(new OnCancelListener() {
@Override
public void onCancel(DialogInterface dialog) {
reconnect();
}
});
dialog.show();
}
/**
* Set the current account based on the stored shared preference.
*/
private void setAccountFromPref() {
Account[] accounts = accountManager.getAccountsByType("com.google");
String accountName = prefs.getString(PREF_ACCOUNT_NAME, null);
for (Account account : accounts) {
if (account.name.equals(accountName)) {
setAccount(account);
return;
}
}
// default to first account
setAccount(accounts[0]);
}
/**
* Prompt the user for which account they'd like connect with.
*/
protected void chooseAccount() {
AlertDialog.Builder builder = new AlertDialog.Builder(this);
builder.setTitle("Select a Google account");
final Account[] accounts = accountManager.getAccountsByType("com.google");
final int size = accounts.length;
String[] names = new String[size];
for (int i = 0; i < size; i++) {
names[i] = accounts[i].name;
}
builder.setItems(names, new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
prefs.edit().putString(PREF_ACCOUNT_NAME, accounts[which].name).apply();
setAccountFromPref();
}
});
AlertDialog dialog = builder.create();
dialog.setOnCancelListener(new OnCancelListener() {
@Override
public void onCancel(DialogInterface dialog) {
// if pref is not set, a new dialog will appear
setAccountFromPref();
}
});
dialog.show();
}
/**
* Set the specified account to be the current one, request new OAuth2 access tokens, and
* reconnect to the websocket endpoint.
*
* @param account the new account to use
*/
protected void setAccount(final Account account) {
accountButton.setText(account.name);
requestAccessToken(account, PREF_OAUTH2_EMAIL_ACCESS_TOKEN_, SCOPE_USERINFO_EMAIL,
new Runnable() {
@Override
public void run() {
requestAccessToken(account, PREF_OAUTH2_PROFILE_ACCESS_TOKEN_, SCOPE_USERINFO_PROFILE,
new Runnable() {
@Override
public void run() {
reconnect();
}
});
}
});
}
/**
* Asynchronously request a new OAuth2 access token.
*
* @param account the account for which to request an access token
* @param prefPrefix the shared prefs prefix under which the access tokens are kept
* @param scope the OAuth2 scope for which to request a token
* @param cmd the runnable comamnd to execute once the token has been retrieved
*/
private void requestAccessToken(final Account account, final String prefPrefix,
final String scope, final Runnable cmd) {
invalidateAccessTokens(account, prefPrefix);
// TODO Update server code to avoid http://en.wikipedia.org/wiki/Confused_deputy_problem
accountManager.getAuthToken(account, scope, null, this, new AccountManagerCallback<Bundle>() {
@Override
public void run(AccountManagerFuture<Bundle> future) {
try {
String accessToken = future.getResult().getString(AccountManager.KEY_AUTHTOKEN);
toast("Got OAuth2 access token for " + account.name + ":\n" + accessToken);
prefs.edit().putString(prefPrefix + account.name, accessToken).apply();
cmd.run();
} catch (OperationCanceledException e) {
toast("The user has denied you access to the " + scope);
} catch (Exception e) {
toast(e.toString());
Log.w("Exception: ", e);
}
}
}, null);
}
/**
* In order to hedge against potentially expired OAuth2 access token, we simply invalidate all the
* token we've received for the account.
*
* @param account the account for which to expire access token
* @param prefPrefix the shared prefs prefix under which the access tokens are kept
*/
private void invalidateAccessTokens(Account account, String prefPrefix) {
String accessToken = prefs.getString(prefPrefix + account.name, null);
if (accessToken != null) {
accountManager.invalidateAuthToken(account.type, accessToken);
prefs.edit().remove(prefPrefix + account.name).apply();
}
}
/**
* An {@link AsyncTask} which is used to request the necessary OAuth2 access tokens, invoke the
* {@code findGame} grits service, and finally connect to and maintain a websocket connection to
* the games server. We use an {@link AsyncTask} to avoid running slow network calls on the main
* UI thread.
*/
private final class GameAsyncTask extends AsyncTask<Void, String, Void> {
private IOSocket socket;
private boolean okayToRun = true;
protected Void doInBackground(Void... params) {
String profileAccessToken = prefs.getString(
PREF_OAUTH2_PROFILE_ACCESS_TOKEN_ + accountButton.getText(), null);
String emailAccessToken = prefs.getString(
PREF_OAUTH2_EMAIL_ACCESS_TOKEN_ + accountButton.getText(), null);
PlayerGame pg = findGame(profileAccessToken, emailAccessToken);
if (pg == null) {
// toast message already sent to user, so just return
return null;
}
connect(pg);
return null;
}
/**
* Convenience method for publishing progress updates which involve exceptions
*
* @param msg the message to display
* @param e the exception which was raised
*/
private void publishProgress(String msg, Exception e) {
Log.e(TAG, msg, e);
publishProgress(msg + "\n" + e);
}
@Override
protected void onProgressUpdate(String... messages) {
for (String msg : messages) {
toast(msg);
}
}
@Override
protected void onCancelled(Void result) {
if (socket != null) {
socket.disconnect();
}
}
/**
* Acquire the necessary OAuth2 tokens and invoke the grits {@code findGame} service.
*
* @param profileAccessToken OAuth2 access token for the {@value SCOPE_USERINFO_PROFILE} scope
* @param emailAccessToken OAuth2 access token for the {@value SCOPE_USERINFO_EMAIL} scope
* @return
*/
private PlayerGame findGame(String profileAccessToken, String emailAccessToken) {
JSONObject userInfo = get(HTTPS_WWW_GOOGLEAPIS_COM_OAUTH2_V1_USERINFO, profileAccessToken);
if (userInfo == null) {
// toast message already sent to user, so just return
return null;
}
String userID;
try {
userID = userInfo.getString("id");
} catch (JSONException e) {
publishProgress("failed to extract id from userInfo:" + userInfo, e);
return null;
}
String endpoint = prefs.getString(PREF_GAME_ORIGIN, ORIGIN_GRITSGAME_APPSPOT_COM);
// Note: the userID is only used in the dev_appserver
String findGameUrl = endpoint + "/grits/findGame?userID=" + userID;
JSONObject json = post(findGameUrl, emailAccessToken);
if (json == null) {
// toast message already sent to user, so just return
return null;
}
PlayerGame pg = extractPlayerGame(json);
return pg;
}
/**
* Extract player game data from a response to the Grits {@code findGame} service.
*
* @param json the {@link JSONObject} returned from thr {@code findGame} service.
* @return the {@link PlayerGame} data or {@ocde null}
*/
private PlayerGame extractPlayerGame(JSONObject json) {
try {
if (!json.has("game")) {
publishProgress("result does not contain game: " + json.toString(4));
return null;
}
JSONObject game = json.getJSONObject("game");
String player_game_key = json.getString("player_game_key");
String userID = json.getString("userID");
String gameURL = game.getString("gameURL");
JSONObject game_state = game.getJSONObject("game_state");
JSONObject players = game_state.getJSONObject("players");
publishProgress("LOOKING UP userID " + userID);
String player_name = players.getString(userID);
if ("TBD".equals(player_name)) {
publishProgress("Please first login at gritsgame.appspot.com with the same id.");
return null;
}
Log.d(TAG, "player_name = " + player_name);
gameURL = gameURL.replace("127.0.0.1", LOCAL_IP);
gameURL = gameURL + player_name;
Log.d(TAG, "gameUrl = " + gameURL);
return new PlayerGame(gameURL, player_game_key, player_name);
} catch (JSONException e) {
publishProgress("failed to extract player game from json: " + json, e);
return null;
}
}
/**
* Send HTTP GET request and return the response as a {@link JSONObject}.
*
* @param url the resource to connect to
* @param accessToken the OAuth2 bearer access token
* @return the {@link JSONObject} response
*/
private JSONObject get(String url, String accessToken) {
Log.d(TAG, "Connecting to " + url);
HttpClient httpClient = new DefaultHttpClient();
HttpGet httpGet = new HttpGet(url);
Log.d(TAG, "Authorization: Bearer " + accessToken);
httpGet.addHeader("Authorization", "Bearer " + accessToken);
ResponseHandler<String> responseHandler = new BasicResponseHandler();
String json;
try {
json = httpClient.execute(httpGet, responseHandler);
} catch (HttpResponseException e) {
publishProgress("failed to reach " + url + " due HTTP status " + e.getStatusCode() + ": "
+ e.getMessage());
return null;
} catch (Exception e) {
publishProgress("failed to reach " + url, e);
return null;
}
Log.d(TAG, url + " -> " + json);
try {
JSONObject result = (JSONObject) new JSONTokener(json).nextValue();
return result;
} catch (JSONException e) {
publishProgress("failed to digest result as JSON " + json, e);
return null;
}
}
/**
* Send HTTP POST request and return the response as a {@link JSONObject}.
*
* @param url the resource to connect to
* @param accessToken the OAuth2 bearer access token
* @return the {@link JSONObject} response
*/
private JSONObject post(String url, String accessToken) {
Log.d(TAG, "Connecting to " + url);
HttpClient httpClient = new DefaultHttpClient();
HttpPost httpPost = new HttpPost(url);
Log.d(TAG, "Authorization: Bearer " + accessToken);
httpPost.addHeader("Authorization", "Bearer " + accessToken);
ResponseHandler<String> responseHandler = new BasicResponseHandler();
String json;
try {
json = httpClient.execute(httpPost, responseHandler);
} catch (HttpHostConnectException e) {
publishProgress("failed to reach " + e.getHost() + ": " + e.getMessage());
return null;
} catch (HttpResponseException e) {
publishProgress("failed to reach " + url + " due HTTP status " + e.getStatusCode() + ": "
+ e.getMessage());
return null;
} catch (Exception e) {
Log.e(TAG, "failed to reach " + url, e);
publishProgress("failed to reach " + url, e);
return null;
}
Log.d(TAG, url + " -> " + json);
try {
JSONObject result = (JSONObject) new JSONTokener(json).nextValue();
return result;
} catch (JSONException e) {
publishProgress("failed to digest result as JSON " + json, e);
return null;
}
}
public void disconnect() {
cancel(true);
okayToRun = false;
}
private void connect(final PlayerGame pg) {
socket = new IOSocket(pg.gameURL, new MessageCallback() {
@Override
public void on(String event, JSONObject... data) {
// JSON message; not used
Log.i(TAG, "on(" + event + ", JSONObject: " + data + ")");
}
@Override
public void onMessage(String message) {
if (!message.startsWith("ack")) {
Log.i(TAG, "\nonMessage(String " + message + "):");
}
String m = (up ? "Y" : "N") + (left ? "Y" : "N") + (down ? "Y" : "N")
+ (right ? "Y" : "N");
send(m);
}
private void send(String m) {
if (!okayToRun) {
socket.disconnect();
return;
}
try {
socket.send(m);
} catch (Exception e) {
publishProgress("failed to send", e);
// prevent continuous failures
socket.disconnect();
}
}
@Override
public void onMessage(JSONObject message) {
// JSON message; not used
Log.i(TAG, "onMessage(JSONObject: " + message + ")");
}
@Override
public void onConnect() {
publishProgress("onConnect(): Connection established - Yay!");
send("init{ \"player_game_key\": \"" + pg.player_game_key + "\", \"player_name\": \""
+ pg.player_name + "\"}");
}
@Override
public void onDisconnect() {
publishProgress("onDisconnect(): Boo!");
}
});
try {
socket.connect();
} catch (IOException e) {
publishProgress("failed to connect", e);
}
}
}
/**
* Simple bag of properties for passing around.
*/
private static class PlayerGame {
private final String gameURL;
private final String player_game_key;
private final String player_name;
public PlayerGame(String gameURL, String player_game_key, String player_name) {
this.gameURL = gameURL;
this.player_game_key = player_game_key;
this.player_name = player_name;
}
}
/**
* Convenience method for displaying brief messages to the user.
*
* @param msg the message to display
*/
private void toast(String msg) {
Toast.makeText(WasdActivity.this, msg, Toast.LENGTH_SHORT).show();
Log.d(TAG, msg);
}
private void updateDirections(float sensorX, float sensorY) {
if (sensorX > SENSOR_THRESHOLD) {
left = true;
} else if (sensorX < SENSOR_THRESHOLD - SENSOR_STICKINESS) {
left = false;
}
if (sensorX < -SENSOR_THRESHOLD) {
right = true;
} else if (sensorX > -SENSOR_THRESHOLD + SENSOR_STICKINESS) {
right = false;
}
if (sensorY > SENSOR_THRESHOLD) {
down = true;
} else if (sensorY < SENSOR_THRESHOLD - SENSOR_STICKINESS) {
down = false;
}
if (sensorY < -SENSOR_THRESHOLD) {
up = true;
} else if (sensorY > -SENSOR_THRESHOLD + SENSOR_STICKINESS) {
up = false;
}
upView.setBackgroundColor(up ? Color.rgb(0, 200, 0) : Color.rgb(0, 80, 0));
downView.setBackgroundColor(down ? Color.rgb(0, 200, 0) : Color.rgb(0, 80, 0));
leftView.setBackgroundColor(left ? Color.rgb(0, 200, 0) : Color.rgb(0, 80, 0));
rightView.setBackgroundColor(right ? Color.rgb(0, 200, 0) : Color.rgb(0, 80, 0));
}
/**
* Class dedicated to listening for accelerometer events. The results are published to few boolean
* fields in the parent class. We're lazy, so we also update the UI directional indicators here.
*/
class SensorListener implements SensorEventListener {
private Sensor accelerometer;
private float sensorX;
private float sensorY;
public SensorListener() {
accelerometer = sensorManager.getDefaultSensor(Sensor.TYPE_ACCELEROMETER);
}
/**
* Start listening for accelerometer events. Call from {@link Activity#onResume()}.
*/
public void start() {
// plenty fast; you can always try SENSOR_DELAY_GAME
sensorManager.registerListener(this, accelerometer, SensorManager.SENSOR_DELAY_UI);
}
/**
* Start listening for accelerometer events. Call from {@link Activity#onPause()}.
*/
public void stop() {
sensorManager.unregisterListener(this);
}
@Override
public void onAccuracyChanged(Sensor sensor, int accuracy) {
}
@Override
public void onSensorChanged(SensorEvent event) {
if (event.sensor.getType() != Sensor.TYPE_ACCELEROMETER)
return;
switch (display.getRotation()) {
case Surface.ROTATION_0:
sensorX = event.values[0];
sensorY = event.values[1];
break;
case Surface.ROTATION_90:
sensorX = -event.values[1];
sensorY = event.values[0];
break;
case Surface.ROTATION_180:
sensorX = -event.values[0];
sensorY = -event.values[1];
break;
case Surface.ROTATION_270:
sensorX = event.values[1];
sensorY = -event.values[0];
break;
}
// Log.d(TAG, "rotation=" + display.getRotation() + "; x=" + sensorX + "; y=" + sensorY);
updateDirections(sensorX, sensorY);
}
}
}
| Java |
package net.tootallnate.websocket;
import java.io.IOException;
import java.security.NoSuchAlgorithmException;
/**
* Implemented by <tt>WebSocketClient</tt> and <tt>WebSocketServer</tt>.
* The methods within are called by <tt>WebSocket</tt>.
* @author Nathan Rajlich
*/
interface WebSocketListener {
/**
* Called when the socket connection is first established, and the WebSocket
* handshake has been recieved. This method should parse the
* <var>handshake</var>, and return a boolean indicating whether or not the
* connection is a valid WebSocket connection.
* @param conn The <tt>WebSocket</tt> instance this event is occuring on.
* @param handshake The entire UTF-8 decoded handshake from the connection.
* @return <var>true</var> if the handshake is valid, and <var>onOpen</var>
* should be immediately called afterwards. <var>false</var> if the
* handshake was invalid, and the connection should be terminated.
* @throws NoSuchAlgorithmException
*/
public boolean onHandshakeRecieved(WebSocket conn, String handshake, byte[] handShakeBody) throws IOException, NoSuchAlgorithmException;
/**
* Called when an entire text frame has been recieved. Do whatever you want
* here...
* @param conn The <tt>WebSocket</tt> instance this event is occuring on.
* @param message The UTF-8 decoded message that was recieved.
*/
public void onMessage(WebSocket conn, String message);
/**
* Called after <var>onHandshakeRecieved</var> returns <var>true</var>.
* Indicates that a complete WebSocket connection has been established,
* and we are ready to send/recieve data.
* @param conn The <tt>WebSocket</tt> instance this event is occuring on.
*/
public void onOpen(WebSocket conn);
/**
* Called after <tt>WebSocket#close</tt> is explicity called, or when the
* other end of the WebSocket connection is closed.
* @param conn The <tt>WebSocket</tt> instance this event is occuring on.
*/
public void onClose(WebSocket conn);
/**
* Triggered on any IOException error. This method should be overridden for custom
* implementation of error handling (e.g. when network is not available).
* @param ex
*/
public void onIOError(IOException ex);
/**
* Called to retrieve the Draft of this listener.
*/
public WebSocketDraft getDraft();
}
| Java |
package net.tootallnate.websocket;
import java.io.IOException;
import java.nio.ByteBuffer;
import java.nio.channels.SelectionKey;
import java.nio.channels.Selector;
import java.nio.channels.ServerSocketChannel;
import java.nio.channels.SocketChannel;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.util.Iterator;
import java.util.Properties;
import java.util.Set;
import java.util.concurrent.CopyOnWriteArraySet;
import java.util.concurrent.LinkedBlockingQueue;
/**
* <tt>WebSocketServer</tt> is an abstract class that only takes care of the
* HTTP handshake portion of WebSockets. It's up to a subclass to add
* functionality/purpose to the server.
* @author Nathan Rajlich
*/
public abstract class WebSocketServer implements Runnable, WebSocketListener {
// CONSTANTS ///////////////////////////////////////////////////////////////
/**
* The value of <var>handshake</var> when a Flash client requests a policy
* file on this server.
*/
private static final String FLASH_POLICY_REQUEST = "<policy-file-request/>\0";
// INSTANCE PROPERTIES /////////////////////////////////////////////////////
/**
* Holds the list of active WebSocket connections. "Active" means WebSocket
* handshake is complete and socket can be written to, or read from.
*/
private final CopyOnWriteArraySet<WebSocket> connections;
/**
* The port number that this WebSocket server should listen on. Default is
* WebSocket.DEFAULT_PORT.
*/
private int port;
/**
* The socket channel for this WebSocket server.
*/
private ServerSocketChannel server;
/**
* The 'Selector' used to get event keys from the underlying socket.
*/
private Selector selector;
/**
* The Draft of the WebSocket protocol the Server is adhering to.
*/
private WebSocketDraft draft;
// CONSTRUCTORS ////////////////////////////////////////////////////////////
/**
* Nullary constructor. Creates a WebSocketServer that will attempt to
* listen on port WebSocket.DEFAULT_PORT.
*/
public WebSocketServer() {
this(WebSocket.DEFAULT_PORT, WebSocketDraft.AUTO);
}
/**
* Creates a WebSocketServer that will attempt to listen on port
* <var>port</var>.
* @param port The port number this server should listen on.
*/
public WebSocketServer(int port) {
this(port, WebSocketDraft.AUTO);
}
/**
* Creates a WebSocketServer that will attempt to listen on port <var>port</var>,
* and comply with <tt>WebSocketDraft</tt> version <var>draft</var>.
* @param port The port number this server should listen on.
* @param draft The version of the WebSocket protocol that this server
* instance should comply to.
*/
public WebSocketServer(int port, WebSocketDraft draft) {
this.connections = new CopyOnWriteArraySet<WebSocket>();
this.draft = draft;
setPort(port);
}
/**
* Starts the server thread that binds to the currently set port number and
* listeners for WebSocket connection requests.
*/
public void start() {
(new Thread(this)).start();
}
/**
* Closes all connected clients sockets, then closes the underlying
* ServerSocketChannel, effectively killing the server socket thread and
* freeing the port the server was bound to.
* @throws IOException When socket related I/O errors occur.
*/
public void stop() throws IOException {
for (WebSocket ws : connections) {
ws.close();
}
this.server.close();
}
/**
* Sends <var>text</var> to all currently connected WebSocket clients.
* @param text The String to send across the network.
* @throws IOException When socket related I/O errors occur.
*/
public void sendToAll(String text) throws IOException {
for (WebSocket c : this.connections) {
c.send(text);
}
}
/**
* Sends <var>text</var> to all currently connected WebSocket clients,
* except for the specified <var>connection</var>.
* @param connection The {@link WebSocket} connection to ignore.
* @param text The String to send to every connection except <var>connection</var>.
* @throws IOException When socket related I/O errors occur.
*/
public void sendToAllExcept(WebSocket connection, String text) throws IOException {
if (connection == null) {
throw new NullPointerException("'connection' cannot be null");
}
for (WebSocket c : this.connections) {
if (!connection.equals(c)) {
c.send(text);
}
}
}
/**
* Sends <var>text</var> to all currently connected WebSocket clients,
* except for those found in the Set <var>connections</var>.
* @param connections
* @param text
* @throws IOException When socket related I/O errors occur.
*/
public void sendToAllExcept(Set<WebSocket> connections, String text) throws IOException {
if (connections == null) {
throw new NullPointerException("'connections' cannot be null");
}
for (WebSocket c : this.connections) {
if (!connections.contains(c)) {
c.send(text);
}
}
}
/**
* Returns a WebSocket[] of currently connected clients.
* @return The currently connected clients in a WebSocket[].
*/
public WebSocket[] connections() {
return this.connections.toArray(new WebSocket[0]);
}
/**
* Sets the port that this WebSocketServer should listen on.
* @param port The port number to listen on.
*/
public void setPort(int port) {
this.port = port;
}
/**
* Gets the port number that this server listens on.
* @return The port number.
*/
public int getPort() {
return this.port;
}
public WebSocketDraft getDraft() {
return this.draft;
}
// Runnable IMPLEMENTATION /////////////////////////////////////////////////
public void run() {
try {
server = ServerSocketChannel.open();
server.configureBlocking(false);
server.socket().bind(new java.net.InetSocketAddress(port));
selector = Selector.open();
server.register(selector, server.validOps());
} catch (IOException ex) {
onIOError(ex);
return;
}
while(true) {
try {
selector.select();
Set<SelectionKey> keys = selector.selectedKeys();
Iterator<SelectionKey> i = keys.iterator();
while(i.hasNext()) {
SelectionKey key = i.next();
// Remove the current key
i.remove();
// if isAcceptable == true
// then a client required a connection
if (key.isAcceptable()) {
SocketChannel client = server.accept();
client.configureBlocking(false);
WebSocket c = new WebSocket(client, new LinkedBlockingQueue<ByteBuffer>(), this);
client.register(selector, SelectionKey.OP_READ, c);
}
// if isReadable == true
// then the server is ready to read
if (key.isReadable()) {
WebSocket conn = (WebSocket)key.attachment();
conn.handleRead();
}
// if isWritable == true
// then we need to send the rest of the data to the client
if (key.isValid() && key.isWritable()) {
WebSocket conn = (WebSocket)key.attachment();
if (conn.handleWrite()) {
conn.socketChannel().register(selector,
SelectionKey.OP_READ, conn);
}
}
}
for (WebSocket conn : this.connections) {
// We have to do this check here, and not in the thread that
// adds the buffered data to the WebSocket, because the
// Selector is not thread-safe, and can only be accessed
// by this thread.
if (conn.hasBufferedData()) {
conn.socketChannel().register(selector,
SelectionKey.OP_READ | SelectionKey.OP_WRITE, conn);
}
}
} catch (IOException ex) {
onIOError(ex);
} catch (RuntimeException ex) {
ex.printStackTrace();
} catch (NoSuchAlgorithmException ex) {
ex.printStackTrace();
}
}
//System.err.println("WebSocketServer thread ended!");
}
/**
* Gets the XML string that should be returned if a client requests a Flash
* security policy.
*
* The default implementation allows access from all remote domains, but
* only on the port that this WebSocketServer is listening on.
*
* This is specifically implemented for gitime's WebSocket client for Flash:
* http://github.com/gimite/web-socket-js
*
* @return An XML String that comforms to Flash's security policy. You MUST
* not include the null char at the end, it is appended automatically.
*/
protected String getFlashSecurityPolicy() {
return "<cross-domain-policy><allow-access-from domain=\"*\" to-ports=\""
+ getPort() + "\" /></cross-domain-policy>";
}
// WebSocketListener IMPLEMENTATION ////////////////////////////////////////
/**
* Called by a {@link WebSocket} instance when a client connection has
* finished sending a handshake. This method verifies that the handshake is
* a valid WebSocket cliend request. Then sends a WebSocket server handshake
* if it is valid, or closes the connection if it is not.
* @param conn The {@link WebSocket} instance who's handshake has been recieved.
* @param handshake The entire UTF-8 decoded handshake from the connection.
* @return True if the client sent a valid WebSocket handshake and this server
* successfully sent a WebSocket server handshake, false otherwise.
* @throws IOException When socket related I/O errors occur.
* @throws NoSuchAlgorithmException
*/
public boolean onHandshakeRecieved(WebSocket conn, String handshake, byte[] key3) throws IOException, NoSuchAlgorithmException {
// If a Flash client requested the Policy File...
if (FLASH_POLICY_REQUEST.equals(handshake)) {
String policy = getFlashSecurityPolicy() + "\0";
conn.socketChannel().write(ByteBuffer.wrap(policy.getBytes(WebSocket.UTF8_CHARSET)));
return false;
}
String[] requestLines = handshake.split("\r\n");
boolean isWebSocketRequest = true;
String line = requestLines[0].trim();
String path = null;
if (!(line.startsWith("GET") && line.endsWith("HTTP/1.1"))) {
isWebSocketRequest = false;
} else {
String[] firstLineTokens = line.split(" ");
path = firstLineTokens[1];
}
// 'p' will hold the HTTP headers
Properties p = new Properties();
for (int i = 1; i < requestLines.length; i++) {
line = requestLines[i];
int firstColon = line.indexOf(":");
if (firstColon != -1) {
p.setProperty(line.substring(0, firstColon).trim(), line.substring(firstColon+1).trim());
}
}
String prop = p.getProperty("Upgrade");
if (prop == null || !prop.equals("WebSocket")) {
isWebSocketRequest = false;
}
prop = p.getProperty("Connection");
if (prop == null || !prop.equals("Upgrade")) {
isWebSocketRequest = false;
}
String key1 = p.getProperty("Sec-WebSocket-Key1");
String key2 = p.getProperty("Sec-WebSocket-Key2");
String headerPrefix = "";
byte[] responseChallenge = null;
switch (this.draft) {
case DRAFT75:
if (key1 != null || key2 != null || key3 != null) {
isWebSocketRequest = false;
}
break;
case DRAFT76:
if (key1 == null || key2 == null || key3 == null) {
isWebSocketRequest = false;
}
break;
}
if (isWebSocketRequest) {
if (key1 != null && key2 != null && key3 != null) {
headerPrefix = "Sec-";
byte[] part1 = this.getPart(key1);
byte[] part2 = this.getPart(key2);
byte[] challenge = new byte[16];
challenge[0] = part1[0];
challenge[1] = part1[1];
challenge[2] = part1[2];
challenge[3] = part1[3];
challenge[4] = part2[0];
challenge[5] = part2[1];
challenge[6] = part2[2];
challenge[7] = part2[3];
challenge[8] = key3[0];
challenge[9] = key3[1];
challenge[10] = key3[2];
challenge[11] = key3[3];
challenge[12] = key3[4];
challenge[13] = key3[5];
challenge[14] = key3[6];
challenge[15] = key3[7];
MessageDigest md5 = MessageDigest.getInstance("MD5");
responseChallenge = md5.digest(challenge);
}
String responseHandshake = "HTTP/1.1 101 Web Socket Protocol Handshake\r\n" +
"Upgrade: WebSocket\r\n" +
"Connection: Upgrade\r\n";
responseHandshake += headerPrefix+"WebSocket-Origin: " + p.getProperty("Origin") + "\r\n";
responseHandshake += headerPrefix+"WebSocket-Location: ws://" + p.getProperty("Host") + path + "\r\n";
if (p.containsKey(headerPrefix+"WebSocket-Protocol")) {
responseHandshake += headerPrefix+"WebSocket-Protocol: " + p.getProperty("WebSocket-Protocol") + "\r\n";
}
if (p.containsKey("Cookie")){
responseHandshake += "Cookie: " + p.getProperty("Cookie")+"\r\n";
}
responseHandshake += "\r\n"; // Signifies end of handshake
//Can not use UTF-8 here because we might lose bytes in response during conversion
conn.socketChannel().write(ByteBuffer.wrap(responseHandshake.getBytes()));
//Only set when Draft 76
if(responseChallenge!=null){
conn.socketChannel().write(ByteBuffer.wrap(responseChallenge));
}
return true;
}
// If we got to here, then the client sent an invalid handshake, and we
// return false to make the WebSocket object close the connection.
return false;
}
public void onMessage(WebSocket conn, String message) {
onClientMessage(conn, message);
}
public void onOpen(WebSocket conn) {
if (this.connections.add(conn)) {
onClientOpen(conn);
}
}
public void onClose(WebSocket conn) {
if (this.connections.remove(conn)) {
onClientClose(conn);
}
}
private byte[] getPart(String key) {
long keyNumber = Long.parseLong(key.replaceAll("[^0-9]",""));
long keySpace = key.split("\u0020").length - 1;
long part = new Long(keyNumber / keySpace);
return new byte[] {
(byte)( part >> 24 ),
(byte)( (part << 8) >> 24 ),
(byte)( (part << 16) >> 24 ),
(byte)( (part << 24) >> 24 )
};
}
// ABTRACT METHODS /////////////////////////////////////////////////////////
public abstract void onClientOpen(WebSocket conn);
public abstract void onClientClose(WebSocket conn);
public abstract void onClientMessage(WebSocket conn, String message);
public abstract void onIOError(IOException ex);
}
| Java |
package net.tootallnate.websocket;
import java.io.IOException;
import java.net.InetSocketAddress;
import java.net.URI;
import java.nio.ByteBuffer;
import java.nio.channels.SelectionKey;
import java.nio.channels.Selector;
import java.nio.channels.SocketChannel;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.util.Iterator;
import java.util.Random;
import java.util.Set;
import java.util.concurrent.LinkedBlockingQueue;
/**
* The <tt>WebSocketClient</tt> is an abstract class that expects a valid
* "ws://" URI to connect to. When connected, an instance recieves important
* events related to the life of the connection. A subclass must implement
* <var>onOpen</var>, <var>onClose</var>, and <var>onMessage</var> to be
* useful. An instance can send messages to it's connected server via the
* <var>send</var> method.
* @author Nathan Rajlich
*/
public abstract class WebSocketClient implements Runnable, WebSocketListener {
// INSTANCE PROPERTIES /////////////////////////////////////////////////////
/**
* The URI this client is supposed to connect to.
*/
private URI uri = null;
/**
* The WebSocket instance this client object wraps.
*/
private WebSocket conn = null;
/**
* The SocketChannel instance this client uses.
*/
private SocketChannel client = null;
/**
* The 'Selector' used to get event keys from the underlying socket.
*/
private Selector selector = null;
/**
* Keeps track of whether or not the client thread should continue running.
*/
private boolean running = false;
/**
* The Draft of the WebSocket protocol the Client is adhering to.
*/
private WebSocketDraft draft = null;
/**
* Number 1 used in handshake
*/
private int number1 = 0;
/**
* Number 2 used in handshake
*/
private int number2 = 0;
/**
* Key3 used in handshake
*/
private byte[] key3 = null;
// CONSTRUCTORS ////////////////////////////////////////////////////////////
public WebSocketClient(URI serverURI) {
this(serverURI, WebSocketDraft.DRAFT76);
}
/**
* Constructs a WebSocketClient instance and sets it to the connect to the
* specified URI. The client does not attampt to connect automatically. You
* must call <var>connect</var> first to initiate the socket connection.
* @param serverUri The <tt>URI</tt> of the WebSocket server to connect to.
* @throws IllegalArgumentException If <var>draft</var>
* is <code>WebSocketDraft.AUTO</code>
*/
public WebSocketClient(URI serverUri, WebSocketDraft draft) {
this.uri = serverUri;
if (draft == WebSocketDraft.AUTO) {
throw new IllegalArgumentException(draft + " is meant for `WebSocketServer` only!");
}
this.draft = draft;
}
// PUBLIC INSTANCE METHODS /////////////////////////////////////////////////
/**
* Gets the URI that this WebSocketClient is connected to.
* @return The <tt>URI</tt> for this WebSocketClient.
*/
public URI getURI() {
return uri;
}
@Override
public WebSocketDraft getDraft() {
return draft;
}
/**
* Starts a background thread that attempts and maintains a WebSocket
* connection to the URI specified in the constructor or via <var>setURI</var>.
* <var>setURI</var>.
*/
public void connect() {
if (!running) {
this.running = true;
(new Thread(this)).start();
}
}
/**
* Calls <var>close</var> on the underlying SocketChannel, which in turn
* closes the socket connection, and ends the client socket thread.
* @throws IOException When socket related I/O errors occur.
*/
public void close() throws IOException
{
if (running)
{
selector.wakeup();
conn.close();
}
}
/**
* Sends <var>text</var> to the connected WebSocket server.
* @param text The String to send to the WebSocket server.
* @throws IOException When socket related I/O errors occur.
*/
public void send(String text) throws IOException {
if (conn != null)
{
conn.send(text);
}
}
/**
* Reinitializes and prepares the class to be used for reconnect.
* @return
*/
public void releaseAndInitialize()
{
conn = null;
client = null;
selector = null;
running = false;
draft = null;
number1 = 0;
number2 = 0;
key3 = null;
}
private boolean tryToConnect(InetSocketAddress remote) {
// The WebSocket constructor expects a SocketChannel that is
// non-blocking, and has a Selector attached to it.
try {
client = SocketChannel.open();
client.configureBlocking(false);
client.connect(remote);
selector = Selector.open();
this.conn = new WebSocket(client, new LinkedBlockingQueue<ByteBuffer>(), this);
// At first, we're only interested in the 'CONNECT' keys.
client.register(selector, SelectionKey.OP_CONNECT);
} catch (IOException ex) {
onIOError(conn, ex);
return false;
}
return true;
}
// Runnable IMPLEMENTATION /////////////////////////////////////////////////
public void run() {
running = tryToConnect(new InetSocketAddress(uri.getHost(), getPort()));
while (this.running) {
try {
selector.select();
Set<SelectionKey> keys = selector.selectedKeys();
Iterator<SelectionKey> i = keys.iterator();
while (i.hasNext()) {
SelectionKey key = i.next();
i.remove();
if (key.isConnectable()) {
finishConnect();
}
if (key.isReadable()) {
conn.handleRead();
}
}
} catch (IOException ex) {
onIOError(conn, ex);
} catch (NoSuchAlgorithmException ex) {
ex.printStackTrace();
}
}
//System.err.println("WebSocketClient thread ended!");
}
private int getPort() {
int port = uri.getPort();
return port == -1 ? WebSocket.DEFAULT_PORT : port;
}
private void finishConnect() throws IOException {
if (client.isConnectionPending()) {
client.finishConnect();
}
// Now that we're connected, re-register for only 'READ' keys.
client.register(selector, SelectionKey.OP_READ);
sendHandshake();
}
private void sendHandshake() throws IOException {
String path = uri.getPath();
if (path.indexOf("/") != 0) {
path = "/" + path;
}
int port = getPort();
String host = uri.getHost() + (port != WebSocket.DEFAULT_PORT ? ":" + port : "");
String origin = null; // TODO: Make 'origin' configurable
String request = "GET " + path + " HTTP/1.1\r\n" +
"Upgrade: WebSocket\r\n" +
"Connection: Upgrade\r\n" +
"Host: " + host + "\r\n" +
"Origin: " + origin + "\r\n";
if (this.draft == WebSocketDraft.DRAFT76) {
request += "Sec-WebSocket-Key1: " + this.generateKey() + "\r\n";
request += "Sec-WebSocket-Key2: " + this.generateKey() + "\r\n";
this.key3 = new byte[8];
(new Random()).nextBytes(this.key3);
}
request += "\r\n";
if (this.key3 != null) {
conn.socketChannel().write(new ByteBuffer[] {
ByteBuffer.wrap(request.getBytes(WebSocket.UTF8_CHARSET)),
ByteBuffer.wrap(this.key3)
});
}
else
{
conn.socketChannel().write(ByteBuffer.wrap(request.getBytes(WebSocket.UTF8_CHARSET)));
}
}
private String generateKey() {
Random r = new Random();
long maxNumber = 4294967295L;
long spaces = r.nextInt(12) + 1;
int max = new Long(maxNumber / spaces).intValue();
max = Math.abs(max);
int number = r.nextInt(max) + 1;
if (this.number1 == 0) {
this.number1 = number;
}
else {
this.number2 = number;
}
long product = number * spaces;
String key = Long.toString(product);
//always insert atleast one random character
int numChars = r.nextInt(12)+1;
for (int i=0; i < numChars; i++){
int position = r.nextInt(key.length());
position = Math.abs(position);
char randChar = (char)(r.nextInt(95) + 33);
//exclude numbers here
if(randChar >= 48 && randChar <= 57){
randChar -= 15;
}
key = new StringBuilder(key).insert(position, randChar).toString();
}
for (int i = 0; i < spaces; i++){
int position = r.nextInt(key.length() - 1) + 1;
position = Math.abs(position);
key = new StringBuilder(key).insert(position,"\u0020").toString();
}
return key;
}
// WebSocketListener IMPLEMENTATION ////////////////////////////////////////
/**
* Parses the server's handshake to verify that it's a valid WebSocket
* handshake.
* @param conn The {@link WebSocket} instance who's handshake has been recieved.
* In the case of <tt>WebSocketClient</tt>, this.conn == conn.
* @param handshake The entire UTF-8 decoded handshake from the connection.
* @return <var>true</var> if <var>handshake</var> is a valid WebSocket server
* handshake, <var>false</var> otherwise.
* @throws IOException When socket related I/O errors occur.
* @throws NoSuchAlgorithmException
*/
public boolean onHandshakeRecieved(WebSocket conn, String handshake, byte[] reply) throws IOException, NoSuchAlgorithmException {
// TODO: Do some parsing of the returned handshake, and close connection
// (return false) if we recieved anything unexpected.
if(this.draft == WebSocketDraft.DRAFT76) {
if (reply == null) {
return false;
}
byte[] challenge = new byte[] {
(byte)( this.number1 >> 24 ),
(byte)( (this.number1 << 8) >> 24 ),
(byte)( (this.number1 << 16) >> 24 ),
(byte)( (this.number1 << 24) >> 24 ),
(byte)( this.number2 >> 24 ),
(byte)( (this.number2 << 8) >> 24 ),
(byte)( (this.number2 << 16) >> 24 ),
(byte)( (this.number2 << 24) >> 24 ),
this.key3[0],
this.key3[1],
this.key3[2],
this.key3[3],
this.key3[4],
this.key3[5],
this.key3[6],
this.key3[7]
};
MessageDigest md5 = MessageDigest.getInstance("MD5");
byte[] expected = md5.digest(challenge);
for (int i = 0; i < reply.length; i++) {
if (expected[i] != reply[i]) {
return false;
}
}
}
return true;
}
/**
* Calls subclass' implementation of <var>onMessage</var>.
* @param conn
* @param message
*/
public void onMessage(WebSocket conn, String message) {
onMessage(message);
}
/**
* Calls subclass' implementation of <var>onOpen</var>.
* @param conn
*/
public void onOpen(WebSocket conn) {
onOpen();
}
/**
* Calls subclass' implementation of <var>onClose</var>.
* @param conn
*/
public void onClose(WebSocket conn)
{
if (running)
{
onClose();
}
releaseAndInitialize();
}
/**
* Calls subclass' implementation of <var>onIOError</var>.
* @param conn
*/
public void onIOError(WebSocket conn, IOException ex)
{
releaseAndInitialize();
onIOError(ex);
}
// ABTRACT METHODS /////////////////////////////////////////////////////////
public abstract void onMessage(String message);
public abstract void onOpen();
public abstract void onClose();
public abstract void onIOError(IOException ex);
}
| Java |
package net.tootallnate.websocket;
/**
* Enum for WebSocket Draft
*/
public enum WebSocketDraft {
AUTO,
DRAFT75,
DRAFT76
}
| Java |
package net.tootallnate.websocket;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.nio.ByteBuffer;
import java.nio.channels.NotYetConnectedException;
import java.nio.channels.SocketChannel;
import java.security.NoSuchAlgorithmException;
import java.util.concurrent.BlockingQueue;
/**
* Represents one end (client or server) of a single WebSocket connection.
* Takes care of the "handshake" phase, then allows for easy sending of
* text frames, and recieving frames through an event-based model.
*
* This is an inner class, used by <tt>WebSocketClient</tt> and
* <tt>WebSocketServer</tt>, and should never need to be instantiated directly
* by your code. However, instances are exposed in <tt>WebSocketServer</tt>
* through the <i>onClientOpen</i>, <i>onClientClose</i>,
* <i>onClientMessage</i> callbacks.
* @author Nathan Rajlich
*/
public final class WebSocket {
// CONSTANTS ///////////////////////////////////////////////////////////////
/**
* The default port of WebSockets, as defined in the spec. If the nullary
* constructor is used, DEFAULT_PORT will be the port the WebSocketServer
* is binded to. Note that ports under 1024 usually require root permissions.
*/
public static final int DEFAULT_PORT = 80;
/**
* The WebSocket protocol expects UTF-8 encoded bytes.
*/
public static final String UTF8_CHARSET = "UTF-8";
/**
* The byte representing CR, or Carriage Return, or \r
*/
public static final byte CR = (byte)0x0D;
/**
* The byte representing LF, or Line Feed, or \n
*/
public static final byte LF = (byte)0x0A;
/**
* The byte representing the beginning of a WebSocket text frame.
*/
public static final byte START_OF_FRAME = (byte)0x00;
/**
* The byte representing the end of a WebSocket text frame.
*/
public static final byte END_OF_FRAME = (byte)0xFF;
// INSTANCE PROPERTIES /////////////////////////////////////////////////////
/**
* The <tt>SocketChannel</tt> instance to use for this server connection.
* This is used to read and write data to.
*/
private final SocketChannel socketChannel;
/**
* Internally used to determine whether to recieve data as part of the
* remote handshake, or as part of a text frame.
*/
private boolean handshakeComplete;
/**
* The listener to notify of WebSocket events.
*/
private WebSocketListener wsl;
/**
* The 1-byte buffer reused throughout the WebSocket connection to read data.
*/
private ByteBuffer buffer;
/**
* Buffer where data is read to from the socket
*/
private ByteBuffer socketBuffer;
/**
* The bytes that make up the remote handshake.
*/
private ByteBuffer remoteHandshake;
/**
* The bytes that make up the current text frame being read.
*/
private ByteBuffer currentFrame;
/**
* Queue of buffers that need to be sent to the client.
*/
private BlockingQueue<ByteBuffer> bufferQueue;
/**
* Lock object to ensure that data is sent from the bufferQueue in
* the proper order.
*/
private Object bufferQueueMutex = new Object();
private boolean readingState = false;
// CONSTRUCTOR /////////////////////////////////////////////////////////////
/**
* Used in {@link WebSocketServer} and {@link WebSocketClient}.
* @param socketChannel The <tt>SocketChannel</tt> instance to read and
* write to. The channel should already be registered
* with a Selector before construction of this object.
* @param bufferQueue The Queue that we should use to buffer data that
* hasn't been sent to the client yet.
* @param listener The {@link WebSocketListener} to notify of events when
* they occur.
*/
WebSocket(SocketChannel socketChannel, BlockingQueue<ByteBuffer> bufferQueue, WebSocketListener listener) {
this.socketChannel = socketChannel;
this.bufferQueue = bufferQueue;
this.handshakeComplete = false;
this.remoteHandshake = this.currentFrame = null;
this.socketBuffer = ByteBuffer.allocate(8192);
this.buffer = ByteBuffer.allocate(1);
this.wsl = listener;
}
/**
* Should be called when a Selector has a key that is writable for this
* WebSocket's SocketChannel connection.
* @throws IOException When socket related I/O errors occur.
* @throws NoSuchAlgorithmException
*/
void handleRead() throws IOException, NoSuchAlgorithmException {
int bytesRead = -1;
try {
socketBuffer.rewind();
bytesRead = this.socketChannel.read(this.socketBuffer);
} catch(Exception ex) {}
if (bytesRead == -1) {
close();
} else if (bytesRead > 0) {
for(int i = 0; i < bytesRead; i++) {
buffer.rewind();
buffer.put(socketBuffer.get(i));
this.buffer.rewind();
if (!this.handshakeComplete)
recieveHandshake();
else
recieveFrame();
}
}
}
// PUBLIC INSTANCE METHODS /////////////////////////////////////////////////
/**
* Closes the underlying SocketChannel, and calls the listener's onClose
* event handler.
* @throws IOException When socket related I/O errors occur.
*/
public void close() throws IOException {
this.socketChannel.close();
this.wsl.onClose(this);
}
/**
* @return True if all of the text was sent to the client by this thread.
* False if some of the text had to be buffered to be sent later.
*/
public boolean send(String text) throws IOException {
if (!this.handshakeComplete) throw new NotYetConnectedException();
if (text == null) throw new NullPointerException("Cannot send 'null' data to a WebSocket.");
// Get 'text' into a WebSocket "frame" of bytes
byte[] textBytes = text.getBytes(UTF8_CHARSET);
ByteBuffer b = ByteBuffer.allocate(textBytes.length + 2);
b.put(START_OF_FRAME);
b.put(textBytes);
b.put(END_OF_FRAME);
b.rewind();
// See if we have any backlog that needs to be sent first
if (handleWrite()) {
// Write the ByteBuffer to the socket
this.socketChannel.write(b);
}
// If we didn't get it all sent, add it to the buffer of buffers
if (b.remaining() > 0) {
if (!this.bufferQueue.offer(b)) {
throw new IOException("Buffers are full, message could not be sent to" +
this.socketChannel.socket().getRemoteSocketAddress());
}
return false;
}
return true;
}
boolean hasBufferedData() {
return !this.bufferQueue.isEmpty();
}
/**
* @return True if all data has been sent to the client, false if there
* is still some buffered.
*/
boolean handleWrite() throws IOException {
synchronized (this.bufferQueueMutex) {
ByteBuffer buffer = this.bufferQueue.peek();
while (buffer != null) {
this.socketChannel.write(buffer);
if (buffer.remaining() > 0) {
return false; // Didn't finish this buffer. There's more to send.
} else {
this.bufferQueue.poll(); // Buffer finished. Remove it.
buffer = this.bufferQueue.peek();
}
}
return true;
}
}
public SocketChannel socketChannel() {
return this.socketChannel;
}
// PRIVATE INSTANCE METHODS ////////////////////////////////////////////////
private void recieveFrame() {
byte newestByte = this.buffer.get();
if (newestByte == START_OF_FRAME && !readingState) { // Beginning of Frame
this.currentFrame = null;
readingState = true;
} else if (newestByte == END_OF_FRAME && readingState) { // End of Frame
readingState = false;
String textFrame = null;
// currentFrame will be null if END_OF_FRAME was send directly after
// START_OF_FRAME, thus we will send 'null' as the sent message.
if (this.currentFrame != null) {
try {
textFrame = new String(this.currentFrame.array(), UTF8_CHARSET);
} catch (UnsupportedEncodingException ex) {
// TODO: Fire an 'onError' handler here
ex.printStackTrace();
textFrame = "";
}
}
this.wsl.onMessage(this, textFrame);
} else { // Regular frame data, add to current frame buffer
ByteBuffer frame = ByteBuffer.allocate((this.currentFrame != null ? this.currentFrame.capacity() : 0) + this.buffer.capacity());
if (this.currentFrame != null) {
this.currentFrame.rewind();
frame.put(this.currentFrame);
}
frame.put(newestByte);
this.currentFrame = frame;
}
}
private void recieveHandshake() throws IOException, NoSuchAlgorithmException {
ByteBuffer ch = ByteBuffer.allocate((this.remoteHandshake != null ? this.remoteHandshake.capacity() : 0) + this.buffer.capacity());
if (this.remoteHandshake != null) {
this.remoteHandshake.rewind();
ch.put(this.remoteHandshake);
}
ch.put(this.buffer);
this.remoteHandshake = ch;
byte[] h = this.remoteHandshake.array();
// If the ByteBuffer contains 16 random bytes, and ends with
// 0x0D 0x0A 0x0D 0x0A (or two CRLFs), then the client
// handshake is complete for Draft 76 Client.
if((h.length >= 20 && h[h.length-20] == CR
&& h[h.length-19] == LF
&& h[h.length-18] == CR
&& h[h.length-17] == LF)) {
completeHandshake(new byte[] {
h[h.length-16],
h[h.length-15],
h[h.length-14],
h[h.length-13],
h[h.length-12],
h[h.length-11],
h[h.length-10],
h[h.length-9],
h[h.length-8],
h[h.length-7],
h[h.length-6],
h[h.length-5],
h[h.length-4],
h[h.length-3],
h[h.length-2],
h[h.length-1]
});
// If the ByteBuffer contains 8 random bytes,ends with
// 0x0D 0x0A 0x0D 0x0A (or two CRLFs), and the response
// contains Sec-WebSocket-Key1 then the client
// handshake is complete for Draft 76 Server.
} else if ((h.length>=12 && h[h.length-12] == CR
&& h[h.length-11] == LF
&& h[h.length-10] == CR
&& h[h.length-9] == LF) && new String(this.remoteHandshake.array(), UTF8_CHARSET).contains("Sec-WebSocket-Key1")) {
completeHandshake(new byte[] {
h[h.length-8],
h[h.length-7],
h[h.length-6],
h[h.length-5],
h[h.length-4],
h[h.length-3],
h[h.length-2],
h[h.length-1]
});
// Consider Draft 75, and the Flash Security Policy
// Request edge-case.
} else if ((h.length>=4 && h[h.length-4] == CR
&& h[h.length-3] == LF
&& h[h.length-2] == CR
&& h[h.length-1] == LF) && !(new String(this.remoteHandshake.array(), UTF8_CHARSET).contains("Sec")) ||
(h.length==23 && h[h.length-1] == 0) ) {
completeHandshake(null);
}
}
private void completeHandshake(byte[] handShakeBody) throws IOException, NoSuchAlgorithmException {
byte[] handshakeBytes = this.remoteHandshake.array();
String handshake = new String(handshakeBytes, UTF8_CHARSET);
this.handshakeComplete = true;
if (this.wsl.onHandshakeRecieved(this, handshake, handShakeBody)) {
this.wsl.onOpen(this);
} else {
close();
}
}
}
| Java |
/* NFCard is free software; you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation; either version 3 of the License, or
(at your option) any later version.
NFCard is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with Wget. If not, see <http://www.gnu.org/licenses/>.
Additional permission under GNU GPL version 3 section 7 */
package com.sinpo.xnfc.nfc;
import static android.nfc.NfcAdapter.EXTRA_TAG;
import static android.os.Build.VERSION_CODES.GINGERBREAD_MR1;
import static android.os.Build.VERSION_CODES.ICE_CREAM_SANDWICH;
import android.annotation.SuppressLint;
import android.app.Activity;
import android.app.PendingIntent;
import android.content.Intent;
import android.content.IntentFilter;
import android.nfc.NdefMessage;
import android.nfc.NdefRecord;
import android.nfc.NfcAdapter;
import android.nfc.Tag;
import android.nfc.tech.IsoDep;
import android.nfc.tech.NfcF;
import com.sinpo.xnfc.nfc.reader.ReaderListener;
import com.sinpo.xnfc.nfc.reader.ReaderManager;
public final class NfcManager {
private final Activity activity;
private NfcAdapter nfcAdapter;
private PendingIntent pendingIntent;
private static String[][] TECHLISTS;
private static IntentFilter[] TAGFILTERS;
private int status;
static {
try {
TECHLISTS = new String[][] { { IsoDep.class.getName() },
{ NfcF.class.getName() }, };
TAGFILTERS = new IntentFilter[] { new IntentFilter(
NfcAdapter.ACTION_TECH_DISCOVERED, "*/*") };
} catch (Exception e) {
}
}
public NfcManager(Activity activity) {
this.activity = activity;
nfcAdapter = NfcAdapter.getDefaultAdapter(activity);
pendingIntent = PendingIntent.getActivity(activity, 0, new Intent(
activity, activity.getClass())
.addFlags(Intent.FLAG_ACTIVITY_SINGLE_TOP), 0);
setupBeam(true);
status = getStatus();
}
public void onPause() {
setupOldFashionBeam(false);
if (nfcAdapter != null)
nfcAdapter.disableForegroundDispatch(activity);
}
public void onResume() {
setupOldFashionBeam(true);
if (nfcAdapter != null)
nfcAdapter.enableForegroundDispatch(activity, pendingIntent,
TAGFILTERS, TECHLISTS);
}
public boolean updateStatus() {
int sta = getStatus();
if (sta != status) {
status = sta;
return true;
}
return false;
}
public boolean readCard(Intent intent, ReaderListener listener) {
final Tag tag = (Tag) intent.getParcelableExtra(EXTRA_TAG);
if (tag != null) {
ReaderManager.readCard(tag, listener);
return true;
}
return false;
}
private int getStatus() {
return (nfcAdapter == null) ? -1 : nfcAdapter.isEnabled() ? 1 : 0;
}
@SuppressLint("NewApi")
private void setupBeam(boolean enable) {
final int api = android.os.Build.VERSION.SDK_INT;
if (nfcAdapter != null && api >= ICE_CREAM_SANDWICH) {
if (enable)
nfcAdapter.setNdefPushMessage(createNdefMessage(), activity);
}
}
@SuppressWarnings("deprecation")
private void setupOldFashionBeam(boolean enable) {
final int api = android.os.Build.VERSION.SDK_INT;
if (nfcAdapter != null && api >= GINGERBREAD_MR1
&& api < ICE_CREAM_SANDWICH) {
if (enable)
nfcAdapter.enableForegroundNdefPush(activity,
createNdefMessage());
else
nfcAdapter.disableForegroundNdefPush(activity);
}
}
NdefMessage createNdefMessage() {
String uri = "3play.google.com/store/apps/details?id=com.sinpo.xnfc";
byte[] data = uri.getBytes();
// about this '3'.. see NdefRecord.createUri which need api level 14
data[0] = 3;
NdefRecord record = new NdefRecord(NdefRecord.TNF_WELL_KNOWN,
NdefRecord.RTD_URI, null, data);
return new NdefMessage(new NdefRecord[] { record });
}
}
| Java |
/* NFCard is free software; you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation; either version 3 of the License, or
(at your option) any later version.
NFCard is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with Wget. If not, see <http://www.gnu.org/licenses/>.
Additional permission under GNU GPL version 3 section 7 */
package com.sinpo.xnfc.nfc;
public final class Util {
private final static char[] HEX = { '0', '1', '2', '3', '4', '5', '6', '7',
'8', '9', 'A', 'B', 'C', 'D', 'E', 'F' };
private Util() {
}
public static byte[] toBytes(int a) {
return new byte[] { (byte) (0x000000ff & (a >>> 24)),
(byte) (0x000000ff & (a >>> 16)),
(byte) (0x000000ff & (a >>> 8)), (byte) (0x000000ff & (a)) };
}
public static boolean testBit(byte data, int bit) {
final byte mask = (byte) ((1 << bit) & 0x000000FF);
return (data & mask) == mask;
}
public static int toInt(byte[] b, int s, int n) {
int ret = 0;
final int e = s + n;
for (int i = s; i < e; ++i) {
ret <<= 8;
ret |= b[i] & 0xFF;
}
return ret;
}
public static int toIntR(byte[] b, int s, int n) {
int ret = 0;
for (int i = s; (i >= 0 && n > 0); --i, --n) {
ret <<= 8;
ret |= b[i] & 0xFF;
}
return ret;
}
public static int toInt(byte... b) {
int ret = 0;
for (final byte a : b) {
ret <<= 8;
ret |= a & 0xFF;
}
return ret;
}
public static int toIntR(byte... b) {
return toIntR(b, b.length - 1, b.length);
}
public static String toHexString(byte... d) {
return (d == null || d.length == 0) ? "" : toHexString(d, 0, d.length);
}
public static String toHexString(byte[] d, int s, int n) {
final char[] ret = new char[n * 2];
final int e = s + n;
int x = 0;
for (int i = s; i < e; ++i) {
final byte v = d[i];
ret[x++] = HEX[0x0F & (v >> 4)];
ret[x++] = HEX[0x0F & v];
}
return new String(ret);
}
public static String toHexStringR(byte[] d, int s, int n) {
final char[] ret = new char[n * 2];
int x = 0;
for (int i = s + n - 1; i >= s; --i) {
final byte v = d[i];
ret[x++] = HEX[0x0F & (v >> 4)];
ret[x++] = HEX[0x0F & v];
}
return new String(ret);
}
public static String ensureString(String str) {
return str == null ? "" : str;
}
public static String toStringR(int n) {
final StringBuilder ret = new StringBuilder(16).append('0');
long N = 0xFFFFFFFFL & n;
while (N != 0) {
ret.append((int) (N % 100));
N /= 100;
}
return ret.toString();
}
public static int parseInt(String txt, int radix, int def) {
int ret;
try {
ret = Integer.valueOf(txt, radix);
} catch (Exception e) {
ret = def;
}
return ret;
}
public static int BCDtoInt(byte[] b, int s, int n) {
int ret = 0;
final int e = s + n;
for (int i = s; i < e; ++i) {
int h = (b[i] >> 4) & 0x0F;
int l = b[i] & 0x0F;
if (h > 9 || l > 9)
return -1;
ret = ret * 100 + h * 10 + l;
}
return ret;
}
public static int BCDtoInt(byte... b) {
return BCDtoInt(b, 0, b.length);
}
}
| Java |
/* NFCard is free software; you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation; either version 3 of the License, or
(at your option) any later version.
NFCard is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with Wget. If not, see <http://www.gnu.org/licenses/>.
Additional permission under GNU GPL version 3 section 7 */
package com.sinpo.xnfc.nfc.tech;
import java.io.IOException;
import java.nio.ByteBuffer;
import java.util.ArrayList;
import java.util.Arrays;
import android.nfc.tech.NfcF;
import com.sinpo.xnfc.nfc.Util;
public class FeliCa {
public static final byte[] EMPTY = {};
protected byte[] data;
protected FeliCa() {
}
protected FeliCa(byte[] bytes) {
data = (bytes == null) ? FeliCa.EMPTY : bytes;
}
public int size() {
return data.length;
}
public byte[] getBytes() {
return data;
}
@Override
public String toString() {
return Util.toHexString(data, 0, data.length);
}
public final static class IDm extends FeliCa {
public static final byte[] EMPTY = { 0, 0, 0, 0, 0, 0, 0, 0, };
public IDm(byte[] bytes) {
super((bytes == null || bytes.length < 8) ? IDm.EMPTY : bytes);
}
public final String getManufactureCode() {
return Util.toHexString(data, 0, 2);
}
public final String getCardIdentification() {
return Util.toHexString(data, 2, 6);
}
public boolean isEmpty() {
final byte[] d = data;
for (final byte v : d) {
if (v != 0)
return false;
}
return true;
}
}
public final static class PMm extends FeliCa {
public static final byte[] EMPTY = { 0, 0, 0, 0, 0, 0, 0, 0, };
public PMm(byte[] bytes) {
super((bytes == null || bytes.length < 8) ? PMm.EMPTY : bytes);
}
public final String getIcCode() {
return Util.toHexString(data, 0, 2);
}
public final String getMaximumResponseTime() {
return Util.toHexString(data, 2, 6);
}
}
public final static class SystemCode extends FeliCa {
public static final byte[] EMPTY = { 0, 0, };
public SystemCode(byte[] sc) {
super((sc == null || sc.length < 2) ? SystemCode.EMPTY : sc);
}
public int toInt() {
return toInt(data);
}
public static int toInt(byte[] data) {
return 0x0000FFFF & ((data[0] << 8) | (0x000000FF & data[1]));
}
}
public final static class ServiceCode extends FeliCa {
public static final byte[] EMPTY = { 0, 0, };
public static final int T_UNKNOWN = 0;
public static final int T_RANDOM = 1;
public static final int T_CYCLIC = 2;
public static final int T_PURSE = 3;
public ServiceCode(byte[] sc) {
super((sc == null || sc.length < 2) ? ServiceCode.EMPTY : sc);
}
public ServiceCode(int code) {
this(new byte[] { (byte) (code & 0xFF), (byte) (code >> 8) });
}
public int toInt() {
return 0x0000FFFF & ((data[1] << 8) | (0x000000FF & data[0]));
}
public boolean isEncrypt() {
return (data[0] & 0x1) == 0;
}
public boolean isWritable() {
final int f = data[0] & 0x3F;
return (f & 0x2) == 0 || f == 0x13 || f == 0x12;
}
public int getAccessAttr() {
return data[0] & 0x3F;
}
public int getDataType() {
final int f = data[0] & 0x3F;
if ((f & 0x10) == 0)
return T_PURSE;
return ((f & 0x04) == 0) ? T_RANDOM : T_CYCLIC;
}
}
public final static class Block extends FeliCa {
public Block() {
data = new byte[16];
}
public Block(byte[] bytes) {
super((bytes == null || bytes.length < 16) ? new byte[16] : bytes);
}
}
public final static class BlockListElement extends FeliCa {
private static final byte LENGTH_2_BYTE = (byte) 0x80;
private static final byte LENGTH_3_BYTE = (byte) 0x00;
// private static final byte ACCESSMODE_DECREMENT = (byte) 0x00;
// private static final byte ACCESSMODE_CACHEBACK = (byte) 0x01;
private final byte lengthAndaccessMode;
private final byte serviceCodeListOrder;
public BlockListElement(byte mode, byte order, byte... blockNumber) {
if (blockNumber.length > 1) {
lengthAndaccessMode = (byte) (mode | LENGTH_2_BYTE & 0xFF);
} else {
lengthAndaccessMode = (byte) (mode | LENGTH_3_BYTE & 0xFF);
}
serviceCodeListOrder = (byte) (order & 0x0F);
data = (blockNumber == null) ? FeliCa.EMPTY : blockNumber;
}
@Override
public byte[] getBytes() {
if ((this.lengthAndaccessMode & LENGTH_2_BYTE) == 1) {
ByteBuffer buff = ByteBuffer.allocate(2);
buff.put(
(byte) ((this.lengthAndaccessMode | this.serviceCodeListOrder) & 0xFF))
.put(data[0]);
return buff.array();
} else {
ByteBuffer buff = ByteBuffer.allocate(3);
buff.put(
(byte) ((this.lengthAndaccessMode | this.serviceCodeListOrder) & 0xFF))
.put(data[1]).put(data[0]);
return buff.array();
}
}
}
public final static class MemoryConfigurationBlock extends FeliCa {
public MemoryConfigurationBlock(byte[] bytes) {
super((bytes == null || bytes.length < 4) ? new byte[4] : bytes);
}
public boolean isNdefSupport() {
return (data == null) ? false : (data[3] & (byte) 0xff) == 1;
}
public void setNdefSupport(boolean ndefSupport) {
data[3] = (byte) (ndefSupport ? 1 : 0);
}
public boolean isWritable(int... addrs) {
if (data == null)
return false;
boolean result = true;
for (int a : addrs) {
byte b = (byte) ((a & 0xff) + 1);
if (a < 8) {
result &= (data[0] & b) == b;
continue;
} else if (a < 16) {
result &= (data[1] & b) == b;
continue;
} else
result &= (data[2] & b) == b;
}
return result;
}
}
public final static class Service extends FeliCa {
private final ServiceCode[] serviceCodes;
private final BlockListElement[] blockListElements;
public Service(ServiceCode[] codes, BlockListElement... blocks) {
serviceCodes = (codes == null) ? new ServiceCode[0] : codes;
blockListElements = (blocks == null) ? new BlockListElement[0]
: blocks;
}
@Override
public byte[] getBytes() {
int length = 0;
for (ServiceCode s : this.serviceCodes) {
length += s.getBytes().length;
}
for (BlockListElement b : blockListElements) {
length += b.getBytes().length;
}
ByteBuffer buff = ByteBuffer.allocate(length);
for (ServiceCode s : this.serviceCodes) {
buff.put(s.getBytes());
}
for (BlockListElement b : blockListElements) {
buff.put(b.getBytes());
}
return buff.array();
}
@Override
public String toString() {
StringBuilder sb = new StringBuilder();
for (ServiceCode s : serviceCodes) {
sb.append(s.toString());
}
for (BlockListElement b : blockListElements) {
sb.append(b.toString());
}
return sb.toString();
}
}
public final static class Command extends FeliCa {
private final int length;
private final byte code;
private final IDm idm;
public Command(final byte[] bytes) {
this(bytes[0], Arrays.copyOfRange(bytes, 1, bytes.length));
}
public Command(byte code, final byte... bytes) {
this.code = code;
if (bytes.length >= 8) {
idm = new IDm(Arrays.copyOfRange(bytes, 0, 8));
data = Arrays.copyOfRange(bytes, 8, bytes.length);
} else {
idm = null;
data = bytes;
}
length = bytes.length + 2;
}
public Command(byte code, IDm idm, final byte... bytes) {
this.code = code;
this.idm = idm;
this.data = bytes;
this.length = idm.getBytes().length + data.length + 2;
}
public Command(byte code, byte[] idm, final byte... bytes) {
this.code = code;
this.idm = new IDm(idm);
this.data = bytes;
this.length = idm.length + data.length + 2;
}
@Override
public byte[] getBytes() {
ByteBuffer buff = ByteBuffer.allocate(length);
byte length = (byte) this.length;
if (idm != null) {
buff.put(length).put(code).put(idm.getBytes()).put(data);
} else {
buff.put(length).put(code).put(data);
}
return buff.array();
}
}
public static class Response extends FeliCa {
protected final int length;
protected final byte code;
protected final IDm idm;
public Response(byte[] bytes) {
if (bytes != null && bytes.length >= 10) {
length = bytes[0] & 0xff;
code = bytes[1];
idm = new IDm(Arrays.copyOfRange(bytes, 2, 10));
data = bytes;
} else {
length = 0;
code = 0;
idm = new IDm(null);
data = FeliCa.EMPTY;
}
}
public IDm getIDm() {
return idm;
}
}
public final static class PollingResponse extends Response {
private final PMm pmm;
public PollingResponse(byte[] bytes) {
super(bytes);
if (size() >= 18) {
pmm = new PMm(Arrays.copyOfRange(data, 10, 18));
} else {
pmm = new PMm(null);
}
}
public PMm getPMm() {
return pmm;
}
}
public final static class ReadResponse extends Response {
public static final byte[] EMPTY = { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
(byte) 0xFF, (byte) 0xFF };
private final byte[] blockData;
public ReadResponse(byte[] rsp) {
super((rsp == null || rsp.length < 12) ? ReadResponse.EMPTY : rsp);
if (getStatusFlag1() == STA1_NORMAL && getBlockCount() > 0) {
blockData = Arrays.copyOfRange(data, 13, data.length);
} else {
blockData = FeliCa.EMPTY;
}
}
public int getStatusFlag1() {
return data[10] & 0x000000FF;
}
public int getStatusFlag2() {
return data[11] & 0x000000FF;
}
public int getStatusFlag12() {
return (getStatusFlag1() << 8) | getStatusFlag2();
}
public int getBlockCount() {
return (data.length > 12) ? (0xFF & data[12]) : 0;
}
public byte[] getBlockData() {
return blockData;
}
public boolean isOkey() {
return getStatusFlag1() == STA1_NORMAL;
}
}
public final static class WriteResponse extends Response {
public WriteResponse(byte[] rsp) {
super((rsp == null || rsp.length < 12) ? ReadResponse.EMPTY : rsp);
}
public int getStatusFlag1() {
return data[0] & 0x000000FF;
}
public int getStatusFlag2() {
return data[1] & 0x000000FF;
}
public int getStatusFlag12() {
return (getStatusFlag1() << 8) | getStatusFlag2();
}
public boolean isOkey() {
return getStatusFlag1() == STA1_NORMAL;
}
}
public final static class Tag {
private final NfcF nfcTag;
private boolean isFeliCaLite;
private byte[] sys;
private IDm idm;
private PMm pmm;
public Tag(NfcF tag) {
nfcTag = tag;
sys = tag.getSystemCode();
idm = new IDm(tag.getTag().getId());
pmm = new PMm(tag.getManufacturer());
}
public int getSystemCode() {
return SystemCode.toInt(sys);
}
public byte[] getSystemCodeByte() {
return sys;
}
public IDm getIDm() {
return idm;
}
public PMm getPMm() {
return pmm;
}
public boolean checkFeliCaLite() throws IOException {
isFeliCaLite = !polling(SYS_FELICA_LITE).getIDm().isEmpty();
return isFeliCaLite;
}
public boolean isFeliCaLite() {
return isFeliCaLite;
}
public PollingResponse polling(int systemCode) throws IOException {
Command cmd = new Command(CMD_POLLING, new byte[] {
(byte) (systemCode >> 8), (byte) (systemCode & 0xff),
(byte) 0x01, (byte) 0x00 });
final byte s[] = cmd.getBytes();
final byte r[] = transceive(s);
final PollingResponse rsp = new PollingResponse(r);
idm = rsp.getIDm();
pmm = rsp.getPMm();
return rsp;
}
public PollingResponse polling() throws IOException {
return polling(SYS_FELICA_LITE);
}
public final SystemCode[] getSystemCodeList() throws IOException {
final Command cmd = new Command(CMD_REQUEST_SYSTEMCODE, idm);
final byte s[] = cmd.getBytes();
final byte r[] = transceive(s);
final int num;
if (r == null || r.length < 12 || r[1] != (byte) 0x0d) {
num = 0;
} else {
num = r[10] & 0x000000FF;
}
final SystemCode ret[] = new SystemCode[num];
for (int i = 0; i < num; ++i) {
ret[i] = new SystemCode(Arrays.copyOfRange(r, 11 + i * 2,
13 + i * 2));
}
return ret;
}
public ServiceCode[] getServiceCodeList() throws IOException {
ArrayList<ServiceCode> ret = new ArrayList<ServiceCode>();
int index = 1;
while (true) {
byte[] bytes = searchServiceCode(index);
if (bytes.length != 2 && bytes.length != 4)
break;
if (bytes.length == 2) {
if (bytes[0] == (byte) 0xff && bytes[1] == (byte) 0xff)
break;
ret.add(new ServiceCode(bytes));
}
++index;
}
return ret.toArray(new ServiceCode[ret.size()]);
}
public byte[] searchServiceCode(int index) throws IOException {
Command cmd = new Command(CMD_SEARCH_SERVICECODE, idm, new byte[] {
(byte) (index & 0xff), (byte) (index >> 8) });
final byte s[] = cmd.getBytes();
final byte r[] = transceive(s);
final byte ret[];
if (r == null || r.length < 12 || r[1] != (byte) 0x0b)
ret = FeliCa.EMPTY;
else
ret = Arrays.copyOfRange(r, 10, r.length);
return ret;
}
public ReadResponse readWithoutEncryption(byte addr, byte... service)
throws IOException {
Command cmd = new Command(CMD_READ_WO_ENCRYPTION, idm, new byte[] {
(byte) 0x01, (byte) service[0], (byte) service[1],
(byte) 0x01, (byte) 0x80, addr });
final byte s[] = cmd.getBytes();
final byte r[] = transceive(s);
final ReadResponse ret = new ReadResponse(r);
return ret;
}
public ReadResponse readWithoutEncryption(ServiceCode code, byte addr)
throws IOException {
return readWithoutEncryption(addr, code.getBytes());
}
public ReadResponse readWithoutEncryption(byte addr) throws IOException {
final byte code0 = (byte) (SRV_FELICA_LITE_READWRITE >> 8);
final byte code1 = (byte) (SRV_FELICA_LITE_READWRITE & 0xff);
return readWithoutEncryption(addr, code0, code1);
}
public WriteResponse writeWithoutEncryption(ServiceCode code,
byte addr, byte[] buff) throws IOException {
byte[] bytes = code.getBytes();
ByteBuffer b = ByteBuffer.allocate(22);
b.put(new byte[] { (byte) 0x01, (byte) bytes[0], (byte) bytes[1],
(byte) 0x01, (byte) 0x80, (byte) addr });
b.put(buff, 0, buff.length > 16 ? 16 : buff.length);
Command cmd = new Command(CMD_WRITE_WO_ENCRYPTION, idm, b.array());
return new WriteResponse(transceive(cmd));
}
public WriteResponse writeWithoutEncryption(byte addr, byte[] buff)
throws IOException {
ByteBuffer b = ByteBuffer.allocate(22);
b.put(new byte[] { (byte) 0x01,
(byte) (SRV_FELICA_LITE_READWRITE >> 8),
(byte) (SRV_FELICA_LITE_READWRITE & 0xff), (byte) 0x01,
(byte) 0x80, addr });
b.put(buff, 0, buff.length > 16 ? 16 : buff.length);
Command cmd = new Command(CMD_WRITE_WO_ENCRYPTION, idm, b.array());
return new WriteResponse(transceive(cmd));
}
public MemoryConfigurationBlock getMemoryConfigBlock()
throws IOException {
ReadResponse r = readWithoutEncryption((byte) 0x88);
return new MemoryConfigurationBlock(r.getBlockData());
}
@Override
public String toString() {
StringBuilder sb = new StringBuilder();
if (idm != null) {
sb.append(idm.toString());
if (pmm != null)
sb.append(pmm.toString());
}
return sb.toString();
}
public void connect() throws IOException {
nfcTag.connect();
}
public void close() throws IOException {
nfcTag.close();
}
public byte[] transceive(Command cmd) throws IOException {
return transceive(cmd.getBytes());
}
public byte[] transceive(byte... cmd) throws IOException {
return nfcTag.transceive(cmd);
}
}
// polling
public static final byte CMD_POLLING = 0x00;
public static final byte RSP_POLLING = 0x01;
// request service
public static final byte CMD_REQUEST_SERVICE = 0x02;
public static final byte RSP_REQUEST_SERVICE = 0x03;
// request RESPONSE
public static final byte CMD_REQUEST_RESPONSE = 0x04;
public static final byte RSP_REQUEST_RESPONSE = 0x05;
// read without encryption
public static final byte CMD_READ_WO_ENCRYPTION = 0x06;
public static final byte RSP_READ_WO_ENCRYPTION = 0x07;
// write without encryption
public static final byte CMD_WRITE_WO_ENCRYPTION = 0x08;
public static final byte RSP_WRITE_WO_ENCRYPTION = 0x09;
// search service code
public static final byte CMD_SEARCH_SERVICECODE = 0x0a;
public static final byte RSP_SEARCH_SERVICECODE = 0x0b;
// request system code
public static final byte CMD_REQUEST_SYSTEMCODE = 0x0c;
public static final byte RSP_REQUEST_SYSTEMCODE = 0x0d;
// authentication 1
public static final byte CMD_AUTHENTICATION1 = 0x10;
public static final byte RSP_AUTHENTICATION1 = 0x11;
// authentication 2
public static final byte CMD_AUTHENTICATION2 = 0x12;
public static final byte RSP_AUTHENTICATION2 = 0x13;
// read
public static final byte CMD_READ = 0x14;
public static final byte RSP_READ = 0x15;
// write
public static final byte CMD_WRITE = 0x16;
public static final byte RSP_WRITE = 0x17;
public static final int SYS_ANY = 0xffff;
public static final int SYS_FELICA_LITE = 0x88b4;
public static final int SYS_COMMON = 0xfe00;
public static final int SRV_FELICA_LITE_READONLY = 0x0b00;
public static final int SRV_FELICA_LITE_READWRITE = 0x0900;
public static final int STA1_NORMAL = 0x00;
public static final int STA1_ERROR = 0xff;
public static final int STA2_NORMAL = 0x00;
public static final int STA2_ERROR_LENGTH = 0x01;
public static final int STA2_ERROR_FLOWN = 0x02;
public static final int STA2_ERROR_MEMORY = 0x70;
public static final int STA2_ERROR_WRITELIMIT = 0x71;
}
| Java |
/* NFCard is free software; you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation; either version 3 of the License, or
(at your option) any later version.
NFCard is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with Wget. If not, see <http://www.gnu.org/licenses/>.
Additional permission under GNU GPL version 3 section 7 */
package com.sinpo.xnfc.nfc.tech;
import java.io.IOException;
import java.nio.ByteBuffer;
import java.util.ArrayList;
import java.util.Arrays;
import com.sinpo.xnfc.nfc.Util;
import android.nfc.tech.IsoDep;
public class Iso7816 {
public static final byte[] EMPTY = { 0 };
protected byte[] data;
protected Iso7816() {
data = Iso7816.EMPTY;
}
protected Iso7816(byte[] bytes) {
data = (bytes == null) ? Iso7816.EMPTY : bytes;
}
public boolean match(byte[] bytes) {
return match(bytes, 0);
}
public boolean match(byte[] bytes, int start) {
final byte[] data = this.data;
if (data.length <= bytes.length - start) {
for (final byte v : data) {
if (v != bytes[start++])
return false;
}
} else {
return false;
}
return true;
}
public boolean match(byte tag) {
return (data.length == 1 && data[0] == tag);
}
public boolean match(short tag) {
final byte[] data = this.data;
if (data.length == 2) {
final byte d0 = (byte) (0x000000FF & (tag >> 8));
final byte d1 = (byte) (0x000000FF & tag);
return (data[0] == d0 && data[1] == d1);
}
return (tag >= 0 && tag <= 255) ? match((byte) tag) : false;
}
public int size() {
return data.length;
}
public byte[] getBytes() {
return data;
}
public byte[] getBytes(int start, int count) {
return Arrays.copyOfRange(data, start, start + count);
}
public int toInt() {
return Util.toInt(getBytes());
}
public int toIntR() {
return Util.toIntR(getBytes());
}
@Override
public String toString() {
return Util.toHexString(data, 0, data.length);
}
@Override
public boolean equals(Object obj) {
if (this == obj)
return true;
if (obj == null || !(obj instanceof Iso7816))
return false;
return match(((Iso7816) obj).getBytes(), 0);
}
public final static class ID extends Iso7816 {
public ID(byte... bytes) {
super(bytes);
}
}
public static class Response extends Iso7816 {
public static final byte[] EMPTY = {};
public static final byte[] ERROR = { 0x6F, 0x00 }; // SW_UNKNOWN
public Response(byte[] bytes) {
super((bytes == null || bytes.length < 2) ? Response.ERROR : bytes);
}
public byte getSw1() {
return data[data.length - 2];
}
public byte getSw2() {
return data[data.length - 1];
}
public String getSw12String() {
int sw1 = getSw1() & 0x000000FF;
int sw2 = getSw2() & 0x000000FF;
return String.format("0x%02X%02X", sw1, sw2);
}
public short getSw12() {
final byte[] d = this.data;
int n = d.length;
return (short) ((d[n - 2] << 8) | (0xFF & d[n - 1]));
}
public boolean isOkey() {
return equalsSw12(SW_NO_ERROR);
}
public boolean equalsSw12(short val) {
return getSw12() == val;
}
public int size() {
return data.length - 2;
}
public byte[] getBytes() {
return isOkey() ? Arrays.copyOfRange(data, 0, size())
: Response.EMPTY;
}
}
public final static class MifareDResponse extends Response {
public MifareDResponse(byte[] bytes) {
super(bytes);
}
}
public final static class BerT extends Iso7816 {
// tag template
public static final byte TMPL_FCP = 0x62; // File Control Parameters
public static final byte TMPL_FMD = 0x64; // File Management Data
public static final byte TMPL_FCI = 0x6F; // FCP and FMD
// proprietary information
public final static BerT CLASS_PRI = new BerT((byte) 0xA5);
// short EF identifier
public final static BerT CLASS_SFI = new BerT((byte) 0x88);
// dedicated file name
public final static BerT CLASS_DFN = new BerT((byte) 0x84);
// application data object
public final static BerT CLASS_ADO = new BerT((byte) 0x61);
// application id
public final static BerT CLASS_AID = new BerT((byte) 0x4F);
// proprietary information
public static int test(byte[] bytes, int start) {
int len = 1;
if ((bytes[start] & 0x1F) == 0x1F) {
while ((bytes[start + len] & 0x80) == 0x80)
++len;
++len;
}
return len;
}
public static BerT read(byte[] bytes, int start) {
return new BerT(Arrays.copyOfRange(bytes, start,
start + test(bytes, start)));
}
public BerT(byte tag) {
this(new byte[] { tag });
}
public BerT(short tag) {
this(new byte[] { (byte) (0x000000FF & (tag >> 8)),
(byte) (0x000000FF & tag) });
}
public BerT(byte[] bytes) {
super(bytes);
}
public boolean hasChild() {
return ((data[0] & 0x20) == 0x20);
}
public short toShort() {
if (size() <= 2) {
return (short) Util.toInt(data);
}
return 0;
}
}
public final static class BerL extends Iso7816 {
private final int val;
public static int test(byte[] bytes, int start) {
int len = 1;
if ((bytes[start] & 0x80) == 0x80) {
len += bytes[start] & 0x07;
}
return len;
}
public static int calc(byte[] bytes, int start) {
if ((bytes[start] & 0x80) == 0x80) {
int v = 0;
int e = start + bytes[start] & 0x07;
while (++start <= e) {
v <<= 8;
v |= bytes[start] & 0xFF;
}
return v;
}
return bytes[start];
}
public static BerL read(byte[] bytes, int start) {
return new BerL(Arrays.copyOfRange(bytes, start,
start + test(bytes, start)));
}
public BerL(byte[] bytes) {
super(bytes);
val = calc(bytes, 0);
}
public BerL(int len) {
super(null);
val = len;
}
public int toInt() {
return val;
}
}
public final static class BerV extends Iso7816 {
public static BerV read(byte[] bytes, int start, int len) {
return new BerV(Arrays.copyOfRange(bytes, start, start + len));
}
public BerV(byte[] bytes) {
super(bytes);
}
}
public final static class BerTLV extends Iso7816 {
public static int test(byte[] bytes, int start) {
final int lt = BerT.test(bytes, start);
final int ll = BerL.test(bytes, start + lt);
final int lv = BerL.calc(bytes, start + lt);
return lt + ll + lv;
}
public static byte[] getValue(BerTLV tlv) {
if (tlv == null || tlv.length() == 0)
return null;
return tlv.v.getBytes();
}
public static BerTLV read(Iso7816 obj) {
return read(obj.getBytes(), 0);
}
public static BerTLV read(byte[] bytes, int start) {
int s = start;
final BerT t = BerT.read(bytes, s);
s += t.size();
final BerL l = BerL.read(bytes, s);
s += l.size();
final BerV v = BerV.read(bytes, s, l.toInt());
s += v.size();
final BerTLV tlv = new BerTLV(t, l, v);
tlv.data = Arrays.copyOfRange(bytes, start, s);
return tlv;
}
public static void extractChildren(ArrayList<BerTLV> out, Iso7816 obj) {
extractChildren(out, obj.getBytes());
}
public static void extractChildren(ArrayList<BerTLV> out, byte[] data) {
int start = 0;
int end = data.length - 3;
while (start <= end) {
final BerTLV tlv = read(data, start);
out.add(tlv);
start += tlv.size();
}
}
public static void extractPrimitives(BerHouse out, Iso7816 obj) {
extractPrimitives(out.tlvs, obj.getBytes());
}
public static void extractPrimitives(ArrayList<BerTLV> out, Iso7816 obj) {
extractPrimitives(out, obj.getBytes());
}
public static void extractPrimitives(BerHouse out, byte[] data) {
extractPrimitives(out.tlvs, data);
}
public static void extractPrimitives(ArrayList<BerTLV> out, byte[] data) {
int start = 0;
int end = data.length - 3;
while (start <= end) {
final BerTLV tlv = read(data, start);
if (tlv.t.hasChild())
extractPrimitives(out, tlv.v.getBytes());
else
out.add(tlv);
start += tlv.size();
}
}
public static ArrayList<BerTLV> extractOptionList(byte[] data) {
final ArrayList<BerTLV> ret = new ArrayList<BerTLV>();
int start = 0;
int end = data.length;
while (start < end) {
final BerT t = BerT.read(data, start);
start += t.size();
if (start < end) {
BerL l = BerL.read(data, start);
start += l.size();
if (start <= end)
ret.add(new BerTLV(t, l, null));
}
}
return ret;
}
public final BerT t;
public final BerL l;
public final BerV v;
public BerTLV(BerT t, BerL l, BerV v) {
this.t = t;
this.l = l;
this.v = v;
}
public int length() {
return l.toInt();
}
}
public final static class BerHouse {
final ArrayList<BerTLV> tlvs = new ArrayList<BerTLV>();
public int count() {
return tlvs.size();
}
public void add(short t, Response v) {
tlvs.add(new BerTLV(new BerT(t), new BerL(v.size()), new BerV(v
.getBytes())));
}
public void add(short t, byte[] v) {
tlvs.add(new BerTLV(new BerT(t), new BerL(v.length), new BerV(v)));
}
public void add(BerT t, byte[] v) {
tlvs.add(new BerTLV(t, new BerL(v.length), new BerV(v)));
}
public void add(BerTLV tlv) {
tlvs.add(tlv);
}
public BerTLV get(int index) {
return tlvs.get(index);
}
public BerTLV findFirst(byte tag) {
for (BerTLV tlv : tlvs)
if (tlv.t.match(tag))
return tlv;
return null;
}
public BerTLV findFirst(byte... tag) {
for (BerTLV tlv : tlvs)
if (tlv.t.match(tag))
return tlv;
return null;
}
public BerTLV findFirst(short tag) {
for (BerTLV tlv : tlvs)
if (tlv.t.match(tag))
return tlv;
return null;
}
public BerTLV findFirst(BerT tag) {
for (BerTLV tlv : tlvs)
if (tlv.t.match(tag.getBytes()))
return tlv;
return null;
}
public ArrayList<BerTLV> findAll(byte tag) {
final ArrayList<BerTLV> ret = new ArrayList<BerTLV>();
for (BerTLV tlv : tlvs)
if (tlv.t.match(tag))
ret.add(tlv);
return ret;
}
public ArrayList<BerTLV> findAll(byte... tag) {
final ArrayList<BerTLV> ret = new ArrayList<BerTLV>();
for (BerTLV tlv : tlvs)
if (tlv.t.match(tag))
ret.add(tlv);
return ret;
}
public ArrayList<BerTLV> findAll(short tag) {
final ArrayList<BerTLV> ret = new ArrayList<BerTLV>();
for (BerTLV tlv : tlvs)
if (tlv.t.match(tag))
ret.add(tlv);
return ret;
}
public ArrayList<BerTLV> findAll(BerT tag) {
final ArrayList<BerTLV> ret = new ArrayList<BerTLV>();
for (BerTLV tlv : tlvs)
if (tlv.t.match(tag.getBytes()))
ret.add(tlv);
return ret;
}
public String toString() {
final StringBuilder ret = new StringBuilder();
for (BerTLV t : tlvs) {
ret.append(t.t.toString()).append(' ');
ret.append(t.l.toInt()).append(' ');
ret.append(t.v.toString()).append('\n');
}
return ret.toString();
}
}
public final static class StdTag {
private final IsoDep nfcTag;
private ID id;
public StdTag(IsoDep tag) {
nfcTag = tag;
id = new ID(tag.getTag().getId());
}
public ID getID() {
return id;
}
public Response getBalance(boolean isEP) throws IOException {
final byte[] cmd = { (byte) 0x80, // CLA Class
(byte) 0x5C, // INS Instruction
(byte) 0x00, // P1 Parameter 1
(byte) (isEP ? 2 : 1), // P2 Parameter 2
(byte) 0x04, // Le
};
return new Response(transceive(cmd));
}
public Response readRecord(int sfi, int index) throws IOException {
final byte[] cmd = { (byte) 0x00, // CLA Class
(byte) 0xB2, // INS Instruction
(byte) index, // P1 Parameter 1
(byte) ((sfi << 3) | 0x04), // P2 Parameter 2
(byte) 0x00, // Le
};
return new Response(transceive(cmd));
}
public Response readRecord(int sfi) throws IOException {
final byte[] cmd = { (byte) 0x00, // CLA Class
(byte) 0xB2, // INS Instruction
(byte) 0x01, // P1 Parameter 1
(byte) ((sfi << 3) | 0x05), // P2 Parameter 2
(byte) 0x00, // Le
};
return new Response(transceive(cmd));
}
public Response readBinary(int sfi) throws IOException {
final byte[] cmd = { (byte) 0x00, // CLA Class
(byte) 0xB0, // INS Instruction
(byte) (0x00000080 | (sfi & 0x1F)), // P1 Parameter 1
(byte) 0x00, // P2 Parameter 2
(byte) 0x00, // Le
};
return new Response(transceive(cmd));
}
public Response readData(int sfi) throws IOException {
final byte[] cmd = { (byte) 0x80, // CLA Class
(byte) 0xCA, // INS Instruction
(byte) 0x00, // P1 Parameter 1
(byte) (sfi & 0x1F), // P2 Parameter 2
(byte) 0x00, // Le
};
return new Response(transceive(cmd));
}
public Response getData(short tag) throws IOException {
final byte[] cmd = {
(byte) 0x80, // CLA Class
(byte) 0xCA, // INS Instruction
(byte) ((tag >> 8) & 0xFF), (byte) (tag & 0xFF),
(byte) 0x00, // Le
};
return new Response(transceive(cmd));
}
public Response readData(short tag) throws IOException {
final byte[] cmd = { (byte) 0x80, // CLA Class
(byte) 0xCA, // INS Instruction
(byte) ((tag >> 8) & 0xFF), // P1 Parameter 1
(byte) (tag & 0x1F), // P2 Parameter 2
(byte) 0x00, // Lc
(byte) 0x00, // Le
};
return new Response(transceive(cmd));
}
public Response selectByID(byte... id) throws IOException {
ByteBuffer buff = ByteBuffer.allocate(id.length + 6);
buff.put((byte) 0x00) // CLA Class
.put((byte) 0xA4) // INS Instruction
.put((byte) 0x00) // P1 Parameter 1
.put((byte) 0x00) // P2 Parameter 2
.put((byte) id.length) // Lc
.put(id).put((byte) 0x00); // Le
return new Response(transceive(buff.array()));
}
public Response selectByName(byte... name) throws IOException {
ByteBuffer buff = ByteBuffer.allocate(name.length + 6);
buff.put((byte) 0x00) // CLA Class
.put((byte) 0xA4) // INS Instruction
.put((byte) 0x04) // P1 Parameter 1
.put((byte) 0x00) // P2 Parameter 2
.put((byte) name.length) // Lc
.put(name).put((byte) 0x00); // Le
return new Response(transceive(buff.array()));
}
public Response getProcessingOptions(byte... pdol) throws IOException {
ByteBuffer buff = ByteBuffer.allocate(pdol.length + 6);
buff.put((byte) 0x80) // CLA Class
.put((byte) 0xA8) // INS Instruction
.put((byte) 0x00) // P1 Parameter 1
.put((byte) 0x00) // P2 Parameter 2
.put((byte) pdol.length) // Lc
.put(pdol).put((byte) 0x00); // Le
return new Response(transceive(buff.array()));
}
public void connect() throws IOException {
nfcTag.connect();
}
public void close() throws IOException {
nfcTag.close();
}
public byte[] transceive(final byte[] cmd) throws IOException {
try {
byte[] rsp = null;
byte c[] = cmd;
do {
byte[] r = nfcTag.transceive(c);
if (r == null)
break;
int N = r.length - 2;
if (N < 0) {
rsp = r;
break;
}
if (r[N] == CH_STA_LE) {
c[c.length - 1] = r[N + 1];
continue;
}
if (rsp == null) {
rsp = r;
} else {
int n = rsp.length;
N += n;
rsp = Arrays.copyOf(rsp, N);
n -= 2;
for (byte i : r)
rsp[n++] = i;
}
if (r[N] != CH_STA_MORE)
break;
byte s = r[N + 1];
if (s != 0) {
c = CMD_GETRESPONSE.clone();
} else {
rsp[rsp.length - 1] = CH_STA_OK;
break;
}
} while (true);
return rsp;
} catch (Exception e) {
return Response.ERROR;
}
}
private static final byte CH_STA_OK = (byte) 0x90;
private static final byte CH_STA_MORE = (byte) 0x61;
private static final byte CH_STA_LE = (byte) 0x6C;
private static final byte CMD_GETRESPONSE[] = { 0, (byte) 0xC0, 0, 0,
0, };
}
public static final short SW_NO_ERROR = (short) 0x9000;
public static final short SW_DESFIRE_NO_ERROR = (short) 0x9100;
public static final short SW_BYTES_REMAINING_00 = 0x6100;
public static final short SW_WRONG_LENGTH = 0x6700;
public static final short SW_SECURITY_STATUS_NOT_SATISFIED = 0x6982;
public static final short SW_FILE_INVALID = 0x6983;
public static final short SW_DATA_INVALID = 0x6984;
public static final short SW_CONDITIONS_NOT_SATISFIED = 0x6985;
public static final short SW_COMMAND_NOT_ALLOWED = 0x6986;
public static final short SW_APPLET_SELECT_FAILED = 0x6999;
public static final short SW_WRONG_DATA = 0x6A80;
public static final short SW_FUNC_NOT_SUPPORTED = 0x6A81;
public static final short SW_FILE_NOT_FOUND = 0x6A82;
public static final short SW_RECORD_NOT_FOUND = 0x6A83;
public static final short SW_INCORRECT_P1P2 = 0x6A86;
public static final short SW_WRONG_P1P2 = 0x6B00;
public static final short SW_CORRECT_LENGTH_00 = 0x6C00;
public static final short SW_INS_NOT_SUPPORTED = 0x6D00;
public static final short SW_CLA_NOT_SUPPORTED = 0x6E00;
public static final short SW_UNKNOWN = 0x6F00;
public static final short SW_FILE_FULL = 0x6A84;
}
| Java |
/* NFCard is free software; you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation; either version 3 of the License, or
(at your option) any later version.
NFCard is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with Wget. If not, see <http://www.gnu.org/licenses/>.
Additional permission under GNU GPL version 3 section 7 */
package com.sinpo.xnfc.nfc.bean;
import com.sinpo.xnfc.SPEC;
import android.util.SparseArray;
public class Application {
private final SparseArray<Object> properties = new SparseArray<Object>();
public final void setProperty(SPEC.PROP prop, Object value) {
properties.put(prop.ordinal(), value);
}
public final Object getProperty(SPEC.PROP prop) {
return properties.get(prop.ordinal());
}
public final boolean hasProperty(SPEC.PROP prop) {
return getProperty(prop) != null;
}
public final String getStringProperty(SPEC.PROP prop) {
final Object v = getProperty(prop);
return (v != null) ? v.toString() : "";
}
public final float getFloatProperty(SPEC.PROP prop) {
final Object v = getProperty(prop);
if (v == null)
return Float.NaN;
if (v instanceof Float)
return ((Float) v).floatValue();
return Float.parseFloat(v.toString());
}
}
| Java |
/* NFCard is free software; you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation; either version 3 of the License, or
(at your option) any later version.
NFCard is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with Wget. If not, see <http://www.gnu.org/licenses/>.
Additional permission under GNU GPL version 3 section 7 */
package com.sinpo.xnfc.nfc.bean;
import java.util.ArrayList;
import com.sinpo.xnfc.SPEC;
public class Card extends Application {
public static final Card EMPTY = new Card();
private final ArrayList<Application> applications;
public Card() {
applications = new ArrayList<Application>(2);
}
public Exception getReadingException() {
return (Exception) getProperty(SPEC.PROP.EXCEPTION);
}
public boolean hasReadingException() {
return hasProperty(SPEC.PROP.EXCEPTION);
}
public final boolean isUnknownCard() {
return applicationCount() == 0;
}
public final int applicationCount() {
return applications.size();
}
public final Application getApplication(int index) {
return applications.get(index);
}
public final void addApplication(Application app) {
if (app != null)
applications.add(app);
}
public String toHtml() {
return HtmlFormatter.formatCardInfo(this);
}
}
| Java |
/* NFCard is free software; you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation; either version 3 of the License, or
(at your option) any later version.
NFCard is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with Wget. If not, see <http://www.gnu.org/licenses/>.
Additional permission under GNU GPL version 3 section 7 */
package com.sinpo.xnfc.nfc.bean;
import com.sinpo.xnfc.SPEC;
public final class HtmlFormatter {
static String formatCardInfo(Card card) {
final StringBuilder ret = new StringBuilder();
startTag(ret, SPEC.TAG_BLK);
final int N = card.applicationCount();
for (int i = 0; i < N; ++i) {
if (i > 0) {
newline(ret);
newline(ret);
}
formatApplicationInfo(ret, card.getApplication(i));
}
endTag(ret, SPEC.TAG_BLK);
return ret.toString();
}
private static void startTag(StringBuilder out, String tag) {
out.append('<').append(tag).append('>');
}
private static void endTag(StringBuilder out, String tag) {
out.append('<').append('/').append(tag).append('>');
}
private static void newline(StringBuilder out) {
out.append("<br />");
}
private static void spliter(StringBuilder out) {
out.append("\n<").append(SPEC.TAG_SP).append(" />\n");
}
private static boolean formatProperty(StringBuilder out, String tag,
Object value) {
if (value == null)
return false;
startTag(out, tag);
out.append(value.toString());
endTag(out, tag);
return true;
}
private static boolean formatProperty(StringBuilder out, String tag,
Object prop, String value) {
if (value == null || value.isEmpty())
return false;
startTag(out, tag);
out.append(prop.toString());
endTag(out, tag);
startTag(out, SPEC.TAG_TEXT);
out.append(value);
endTag(out, SPEC.TAG_TEXT);
return true;
}
private static boolean formatApplicationInfo(StringBuilder out,
Application app) {
if (!formatProperty(out, SPEC.TAG_H1, app.getProperty(SPEC.PROP.ID)))
return false;
newline(out);
spliter(out);
newline(out);
{
SPEC.PROP prop = SPEC.PROP.SERIAL;
if (formatProperty(out, SPEC.TAG_LAB, prop,
app.getStringProperty(prop)))
newline(out);
}
{
SPEC.PROP prop = SPEC.PROP.PARAM;
if (formatProperty(out, SPEC.TAG_LAB, prop,
app.getStringProperty(prop)))
newline(out);
}
{
SPEC.PROP prop = SPEC.PROP.VERSION;
if (formatProperty(out, SPEC.TAG_LAB, prop,
app.getStringProperty(prop)))
newline(out);
}
{
SPEC.PROP prop = SPEC.PROP.DATE;
if (formatProperty(out, SPEC.TAG_LAB, prop,
app.getStringProperty(prop)))
newline(out);
}
{
SPEC.PROP prop = SPEC.PROP.COUNT;
if (formatProperty(out, SPEC.TAG_LAB, prop,
app.getStringProperty(prop)))
newline(out);
}
{
SPEC.PROP prop = SPEC.PROP.TLIMIT;
Float balance = (Float) app.getProperty(prop);
if (balance != null && !balance.isNaN()) {
String cur = app.getProperty(SPEC.PROP.CURRENCY).toString();
String val = String.format("%.2f %s", balance, cur);
if (formatProperty(out, SPEC.TAG_LAB, prop, val))
newline(out);
}
}
{
SPEC.PROP prop = SPEC.PROP.DLIMIT;
Float balance = (Float) app.getProperty(prop);
if (balance != null && !balance.isNaN()) {
String cur = app.getProperty(SPEC.PROP.CURRENCY).toString();
String val = String.format("%.2f %s", balance, cur);
if (formatProperty(out, SPEC.TAG_LAB, prop, val))
newline(out);
}
}
{
SPEC.PROP prop = SPEC.PROP.ECASH;
Float balance = (Float) app.getProperty(prop);
if (balance != null) {
formatProperty(out, SPEC.TAG_LAB, prop);
if (balance.isNaN()) {
out.append(SPEC.PROP.ACCESS);
} else {
formatProperty(out, SPEC.TAG_H2,
String.format("%.2f ", balance));
formatProperty(out, SPEC.TAG_LAB,
app.getProperty(SPEC.PROP.CURRENCY).toString());
}
newline(out);
}
}
{
SPEC.PROP prop = SPEC.PROP.BALANCE;
Float balance = (Float) app.getProperty(prop);
if (balance != null) {
formatProperty(out, SPEC.TAG_LAB, prop);
if (balance.isNaN()) {
out.append(SPEC.PROP.ACCESS);
} else {
formatProperty(out, SPEC.TAG_H2,
String.format("%.2f ", balance));
formatProperty(out, SPEC.TAG_LAB,
app.getProperty(SPEC.PROP.CURRENCY).toString());
}
newline(out);
}
}
{
SPEC.PROP prop = SPEC.PROP.TRANSLOG;
String[] logs = (String[]) app.getProperty(prop);
if (logs != null && logs.length > 0) {
spliter(out);
newline(out);
startTag(out, SPEC.TAG_PARAG);
formatProperty(out, SPEC.TAG_LAB, prop);
newline(out);
endTag(out, SPEC.TAG_PARAG);
for (String log : logs) {
formatProperty(out, SPEC.TAG_H3, log);
newline(out);
}
newline(out);
}
}
return true;
}
}
| Java |
/* NFCard is free software; you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation; either version 3 of the License, or
(at your option) any later version.
NFCard is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with Wget. If not, see <http://www.gnu.org/licenses/>.
Additional permission under GNU GPL version 3 section 7 */
package com.sinpo.xnfc.nfc.reader;
import android.nfc.Tag;
import android.nfc.tech.IsoDep;
import android.nfc.tech.NfcF;
import android.os.AsyncTask;
import com.sinpo.xnfc.SPEC;
import com.sinpo.xnfc.nfc.Util;
import com.sinpo.xnfc.nfc.bean.Card;
import com.sinpo.xnfc.nfc.reader.pboc.StandardPboc;
public final class ReaderManager extends AsyncTask<Tag, SPEC.EVENT, Card> {
public static void readCard(Tag tag, ReaderListener listener) {
new ReaderManager(listener).execute(tag);
}
private ReaderListener realListener;
private ReaderManager(ReaderListener listener) {
realListener = listener;
}
@Override
protected Card doInBackground(Tag... detectedTag) {
return readCard(detectedTag[0]);
}
@Override
protected void onProgressUpdate(SPEC.EVENT... events) {
if (realListener != null)
realListener.onReadEvent(events[0]);
}
@Override
protected void onPostExecute(Card card) {
if (realListener != null)
realListener.onReadEvent(SPEC.EVENT.FINISHED, card);
}
private Card readCard(Tag tag) {
final Card card = new Card();
try {
publishProgress(SPEC.EVENT.READING);
card.setProperty(SPEC.PROP.ID, Util.toHexString(tag.getId()));
final IsoDep isodep = IsoDep.get(tag);
if (isodep != null)
StandardPboc.readCard(isodep, card);
final NfcF nfcf = NfcF.get(tag);
if (nfcf != null)
FelicaReader.readCard(nfcf, card);
publishProgress(SPEC.EVENT.IDLE);
} catch (Exception e) {
card.setProperty(SPEC.PROP.EXCEPTION, e);
publishProgress(SPEC.EVENT.ERROR);
}
return card;
}
}
| Java |
/* NFCard is free software; you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation; either version 3 of the License, or
(at your option) any later version.
NFCard is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with Wget. If not, see <http://www.gnu.org/licenses/>.
Additional permission under GNU GPL version 3 section 7 */
package com.sinpo.xnfc.nfc.reader;
import com.sinpo.xnfc.SPEC;
public interface ReaderListener {
void onReadEvent(SPEC.EVENT event, Object... obj);
}
| Java |
/* NFCard is free software; you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation; either version 3 of the License, or
(at your option) any later version.
NFCard is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with Wget. If not, see <http://www.gnu.org/licenses/>.
Additional permission under GNU GPL version 3 section 7 */
package com.sinpo.xnfc.nfc.reader.pboc;
import java.io.IOException;
import java.util.ArrayList;
import com.sinpo.xnfc.SPEC;
import com.sinpo.xnfc.nfc.Util;
import com.sinpo.xnfc.nfc.bean.Application;
import com.sinpo.xnfc.nfc.bean.Card;
import com.sinpo.xnfc.nfc.tech.Iso7816;
final class WuhanTong extends StandardPboc {
@Override
protected SPEC.APP getApplicationId() {
return SPEC.APP.WUHANTONG;
}
@Override
protected byte[] getMainApplicationId() {
return new byte[] { (byte) 0x41, (byte) 0x50, (byte) 0x31, (byte) 0x2E,
(byte) 0x57, (byte) 0x48, (byte) 0x43, (byte) 0x54,
(byte) 0x43, };
}
@SuppressWarnings("unchecked")
@Override
protected HINT readCard(Iso7816.StdTag tag, Card card) throws IOException {
Iso7816.Response INFO, SERL, BALANCE;
/*--------------------------------------------------------------*/
// read card info file, binary (5, 10)
/*--------------------------------------------------------------*/
if (!(SERL = tag.readBinary(SFI_SERL)).isOkey())
return HINT.GONEXT;
if (!(INFO = tag.readBinary(SFI_INFO)).isOkey())
return HINT.GONEXT;
BALANCE = tag.getBalance(true);
/*--------------------------------------------------------------*/
// select Main Application
/*--------------------------------------------------------------*/
if (!tag.selectByName(getMainApplicationId()).isOkey())
return HINT.RESETANDGONEXT;
/*--------------------------------------------------------------*/
// read balance
/*--------------------------------------------------------------*/
if (!BALANCE.isOkey())
BALANCE = tag.getBalance(true);
/*--------------------------------------------------------------*/
// read log file, record (24)
/*--------------------------------------------------------------*/
ArrayList<byte[]> LOG = readLog24(tag, SFI_LOG);
/*--------------------------------------------------------------*/
// build result
/*--------------------------------------------------------------*/
final Application app = createApplication();
parseBalance(app, BALANCE);
parseInfo5(app, SERL, INFO);
parseLog24(app, LOG);
configApplication(app);
card.addApplication(app);
return HINT.STOP;
}
private final static int SFI_INFO = 5;
private final static int SFI_SERL = 10;
private void parseInfo5(Application app, Iso7816.Response sn,
Iso7816.Response info) {
if (sn.size() < 27 || info.size() < 27) {
return;
}
final byte[] d = info.getBytes();
app.setProperty(SPEC.PROP.SERIAL, Util.toHexString(sn.getBytes(), 0, 5));
app.setProperty(SPEC.PROP.VERSION, String.format("%02d", d[24]));
app.setProperty(SPEC.PROP.DATE, String.format(
"%02X%02X.%02X.%02X - %02X%02X.%02X.%02X", d[20], d[21], d[22],
d[23], d[16], d[17], d[18], d[19]));
}
}
| Java |
/* NFCard is free software; you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation; either version 3 of the License, or
(at your option) any later version.
NFCard is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with Wget. If not, see <http://www.gnu.org/licenses/>.
Additional permission under GNU GPL version 3 section 7 */
package com.sinpo.xnfc.nfc.reader.pboc;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Arrays;
import com.sinpo.xnfc.SPEC;
import com.sinpo.xnfc.nfc.Util;
import com.sinpo.xnfc.nfc.bean.Application;
import com.sinpo.xnfc.nfc.bean.Card;
import com.sinpo.xnfc.nfc.tech.Iso7816;
import android.nfc.tech.IsoDep;
@SuppressWarnings("unchecked")
public abstract class StandardPboc {
private static Class<?>[][] readers = {
{ BeijingMunicipal.class, WuhanTong.class, ShenzhenTong.class,
CityUnion.class, }, { Quickpass.class, } };
public static void readCard(IsoDep tech, Card card)
throws InstantiationException, IllegalAccessException, IOException {
final Iso7816.StdTag tag = new Iso7816.StdTag(tech);
tag.connect();
for (final Class<?> g[] : readers) {
HINT hint = HINT.RESETANDGONEXT;
for (final Class<?> r : g) {
final StandardPboc reader = (StandardPboc) r.newInstance();
switch (hint) {
case RESETANDGONEXT:
if (!reader.resetTag(tag))
continue;
case GONEXT:
hint = reader.readCard(tag, card);
break;
default:
break;
}
if (hint == HINT.STOP)
break;
}
}
tag.close();
}
protected boolean resetTag(Iso7816.StdTag tag) throws IOException {
return tag.selectByID(DFI_MF).isOkey()
|| tag.selectByName(DFN_PSE).isOkey();
}
protected enum HINT {
STOP, GONEXT, RESETANDGONEXT,
}
protected final static byte[] DFI_MF = { (byte) 0x3F, (byte) 0x00 };
protected final static byte[] DFI_EP = { (byte) 0x10, (byte) 0x01 };
protected final static byte[] DFN_PSE = { (byte) '1', (byte) 'P',
(byte) 'A', (byte) 'Y', (byte) '.', (byte) 'S', (byte) 'Y',
(byte) 'S', (byte) '.', (byte) 'D', (byte) 'D', (byte) 'F',
(byte) '0', (byte) '1', };
protected final static byte[] DFN_PXX = { (byte) 'P' };
protected final static int SFI_EXTRA = 21;
protected static int MAX_LOG = 10;
protected static int SFI_LOG = 24;
protected final static byte TRANS_CSU = 6;
protected final static byte TRANS_CSU_CPX = 9;
protected abstract SPEC.APP getApplicationId();
protected byte[] getMainApplicationId() {
return DFI_EP;
}
protected SPEC.CUR getCurrency() {
return SPEC.CUR.CNY;
}
protected boolean selectMainApplication(Iso7816.StdTag tag)
throws IOException {
final byte[] aid = getMainApplicationId();
return ((aid.length == 2) ? tag.selectByID(aid) : tag.selectByName(aid))
.isOkey();
}
protected HINT readCard(Iso7816.StdTag tag, Card card) throws IOException {
/*--------------------------------------------------------------*/
// select Main Application
/*--------------------------------------------------------------*/
if (!selectMainApplication(tag))
return HINT.GONEXT;
Iso7816.Response INFO, BALANCE;
/*--------------------------------------------------------------*/
// read card info file, binary (21)
/*--------------------------------------------------------------*/
INFO = tag.readBinary(SFI_EXTRA);
/*--------------------------------------------------------------*/
// read balance
/*--------------------------------------------------------------*/
BALANCE = tag.getBalance(true);
/*--------------------------------------------------------------*/
// read log file, record (24)
/*--------------------------------------------------------------*/
ArrayList<byte[]> LOG = readLog24(tag, SFI_LOG);
/*--------------------------------------------------------------*/
// build result
/*--------------------------------------------------------------*/
final Application app = createApplication();
parseBalance(app, BALANCE);
parseInfo21(app, INFO, 4, true);
parseLog24(app, LOG);
configApplication(app);
card.addApplication(app);
return HINT.STOP;
}
protected void parseBalance(Application app, Iso7816.Response... data) {
int amount = 0;
for (Iso7816.Response rsp : data) {
if (rsp.isOkey() && rsp.size() >= 4) {
int n = Util.toInt(rsp.getBytes(), 0, 4);
if (n > 1000000 || n < -1000000)
n -= 0x80000000;
amount += n;
}
}
app.setProperty(SPEC.PROP.BALANCE, (amount / 100.0f));
}
protected void parseInfo21(Application app, Iso7816.Response data, int dec,
boolean bigEndian) {
if (!data.isOkey() || data.size() < 30) {
return;
}
final byte[] d = data.getBytes();
if (dec < 1 || dec > 10) {
app.setProperty(SPEC.PROP.SERIAL, Util.toHexString(d, 10, 10));
} else {
final int sn = bigEndian ? Util.toIntR(d, 19, dec) : Util.toInt(d,
20 - dec, dec);
app.setProperty(SPEC.PROP.SERIAL,
String.format("%d", 0xFFFFFFFFL & sn));
}
if (d[9] != 0)
app.setProperty(SPEC.PROP.VERSION, String.valueOf(d[9]));
app.setProperty(SPEC.PROP.DATE, String.format(
"%02X%02X.%02X.%02X - %02X%02X.%02X.%02X", d[20], d[21], d[22],
d[23], d[24], d[25], d[26], d[27]));
}
protected boolean addLog24(final Iso7816.Response r, ArrayList<byte[]> l) {
if (!r.isOkey())
return false;
final byte[] raw = r.getBytes();
final int N = raw.length - 23;
if (N < 0)
return false;
for (int s = 0, e = 0; s <= N; s = e) {
l.add(Arrays.copyOfRange(raw, s, (e = s + 23)));
}
return true;
}
protected ArrayList<byte[]> readLog24(Iso7816.StdTag tag, int sfi)
throws IOException {
final ArrayList<byte[]> ret = new ArrayList<byte[]>(MAX_LOG);
final Iso7816.Response rsp = tag.readRecord(sfi);
if (rsp.isOkey()) {
addLog24(rsp, ret);
} else {
for (int i = 1; i <= MAX_LOG; ++i) {
if (!addLog24(tag.readRecord(sfi, i), ret))
break;
}
}
return ret;
}
protected void parseLog24(Application app, ArrayList<byte[]>... logs) {
final ArrayList<String> ret = new ArrayList<String>(MAX_LOG);
for (final ArrayList<byte[]> log : logs) {
if (log == null)
continue;
for (final byte[] v : log) {
final int money = Util.toInt(v, 5, 4);
if (money > 0) {
final char s = (v[9] == TRANS_CSU || v[9] == TRANS_CSU_CPX) ? '-'
: '+';
final int over = Util.toInt(v, 2, 3);
final String slog;
if (over > 0) {
slog = String
.format("%02X%02X.%02X.%02X %02X:%02X %c%.2f [o:%.2f] [%02X%02X%02X%02X%02X%02X]",
v[16], v[17], v[18], v[19], v[20],
v[21], s, (money / 100.0f),
(over / 100.0f), v[10], v[11], v[12],
v[13], v[14], v[15]);
} else {
slog = String
.format("%02X%02X.%02X.%02X %02X:%02X %C%.2f [%02X%02X%02X%02X%02X%02X]",
v[16], v[17], v[18], v[19], v[20],
v[21], s, (money / 100.0f), v[10],
v[11], v[12], v[13], v[14], v[15]);
}
ret.add(slog);
}
}
}
if (!ret.isEmpty())
app.setProperty(SPEC.PROP.TRANSLOG,
ret.toArray(new String[ret.size()]));
}
protected Application createApplication() {
return new Application();
}
protected void configApplication(Application app) {
app.setProperty(SPEC.PROP.ID, getApplicationId());
app.setProperty(SPEC.PROP.CURRENCY, getCurrency());
}
}
| Java |
/* NFCard is free software; you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation; either version 3 of the License, or
(at your option) any later version.
NFCard is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with Wget. If not, see <http://www.gnu.org/licenses/>.
Additional permission under GNU GPL version 3 section 7 */
package com.sinpo.xnfc.nfc.reader.pboc;
import java.io.IOException;
import java.util.ArrayList;
import com.sinpo.xnfc.SPEC;
import com.sinpo.xnfc.nfc.Util;
import com.sinpo.xnfc.nfc.bean.Application;
import com.sinpo.xnfc.nfc.bean.Card;
import com.sinpo.xnfc.nfc.tech.Iso7816;
final class BeijingMunicipal extends StandardPboc {
@Override
protected SPEC.APP getApplicationId() {
return SPEC.APP.BEIJINGMUNICIPAL;
}
@SuppressWarnings("unchecked")
@Override
protected HINT readCard(Iso7816.StdTag tag, Card card) throws IOException {
Iso7816.Response INFO, CNT, BALANCE;
/*--------------------------------------------------------------*/
// read card info file, binary (4)
/*--------------------------------------------------------------*/
INFO = tag.readBinary(SFI_EXTRA_LOG);
if (!INFO.isOkey())
return HINT.GONEXT;
/*--------------------------------------------------------------*/
// read card operation file, binary (5)
/*--------------------------------------------------------------*/
CNT = tag.readBinary(SFI_EXTRA_CNT);
/*--------------------------------------------------------------*/
// select Main Application
/*--------------------------------------------------------------*/
if (!tag.selectByID(DFI_EP).isOkey())
return HINT.RESETANDGONEXT;
BALANCE = tag.getBalance(true);
/*--------------------------------------------------------------*/
// read log file, record (24)
/*--------------------------------------------------------------*/
ArrayList<byte[]> LOG = readLog24(tag, SFI_LOG);
/*--------------------------------------------------------------*/
// build result
/*--------------------------------------------------------------*/
final Application app = createApplication();
parseBalance(app, BALANCE);
parseInfo4(app, INFO, CNT);
parseLog24(app, LOG);
configApplication(app);
card.addApplication(app);
return HINT.STOP;
}
private final static int SFI_EXTRA_LOG = 4;
private final static int SFI_EXTRA_CNT = 5;
private void parseInfo4(Application app, Iso7816.Response info,
Iso7816.Response cnt) {
if (!info.isOkey() || info.size() < 32) {
return;
}
final byte[] d = info.getBytes();
app.setProperty(SPEC.PROP.SERIAL, Util.toHexString(d, 0, 8));
app.setProperty(SPEC.PROP.VERSION,
String.format("%02X.%02X%02X", d[8], d[9], d[10]));
app.setProperty(SPEC.PROP.DATE, String.format(
"%02X%02X.%02X.%02X - %02X%02X.%02X.%02X", d[24], d[25], d[26],
d[27], d[28], d[29], d[30], d[31]));
if (cnt != null && cnt.isOkey() && cnt.size() > 4) {
byte[] e = cnt.getBytes();
final int n = Util.toInt(e, 1, 4);
if (e[0] == 0)
app.setProperty(SPEC.PROP.COUNT, String.format("%d", n));
else
app.setProperty(SPEC.PROP.COUNT, String.format("%d*", n));
}
}
}
| Java |
/* NFCard is free software; you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation; either version 3 of the License, or
(at your option) any later version.
NFCard is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with Wget. If not, see <http://www.gnu.org/licenses/>.
Additional permission under GNU GPL version 3 section 7 */
package com.sinpo.xnfc.nfc.reader.pboc;
import com.sinpo.xnfc.SPEC;
import com.sinpo.xnfc.nfc.Util;
import com.sinpo.xnfc.nfc.bean.Application;
import com.sinpo.xnfc.nfc.tech.Iso7816;
import android.annotation.SuppressLint;
final class CityUnion extends StandardPboc {
private SPEC.APP applicationId = SPEC.APP.UNKNOWN;
@Override
protected SPEC.APP getApplicationId() {
return applicationId;
}
@Override
protected byte[] getMainApplicationId() {
return new byte[] { (byte) 0xA0, (byte) 0x00, (byte) 0x00, (byte) 0x00,
(byte) 0x03, (byte) 0x86, (byte) 0x98, (byte) 0x07,
(byte) 0x01, };
}
@SuppressLint("DefaultLocale")
@Override
protected void parseInfo21(Application app, Iso7816.Response data, int dec,
boolean bigEndian) {
if (!data.isOkey() || data.size() < 30) {
return;
}
final byte[] d = data.getBytes();
if (d[2] == 0x20 && d[3] == 0x00) {
applicationId = SPEC.APP.SHANGHAIGJ;
bigEndian = true;
} else {
applicationId = SPEC.APP.CHANGANTONG;
bigEndian = false;
}
if (dec < 1 || dec > 10) {
app.setProperty(SPEC.PROP.SERIAL, Util.toHexString(d, 10, 10));
} else {
final int sn = Util.toInt(d, 20 - dec, dec);
final String ss = bigEndian ? Util.toStringR(sn) : String.format(
"%d", 0xFFFFFFFFL & sn);
app.setProperty(SPEC.PROP.SERIAL, ss);
}
if (d[9] != 0)
app.setProperty(SPEC.PROP.VERSION, String.valueOf(d[9]));
app.setProperty(SPEC.PROP.DATE, String.format(
"%02X%02X.%02X.%02X - %02X%02X.%02X.%02X", d[20], d[21], d[22],
d[23], d[24], d[25], d[26], d[27]));
}
}
| Java |
/* NFCard is free software; you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation; either version 3 of the License, or
(at your option) any later version.
NFCard is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with Wget. If not, see <http://www.gnu.org/licenses/>.
Additional permission under GNU GPL version 3 section 7 */
package com.sinpo.xnfc.nfc.reader.pboc;
import com.sinpo.xnfc.SPEC;
final class ShenzhenTong extends StandardPboc {
@Override
protected SPEC.APP getApplicationId() {
return SPEC.APP.SHENZHENTONG;
}
}
| Java |
/* NFCard is free software; you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation; either version 3 of the License, or
(at your option) any later version.
NFCard is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with Wget. If not, see <http://www.gnu.org/licenses/>.
Additional permission under GNU GPL version 3 section 7 */
package com.sinpo.xnfc.nfc.reader.pboc;
import java.io.IOException;
import java.util.ArrayList;
import com.sinpo.xnfc.SPEC;
import com.sinpo.xnfc.nfc.Util;
import com.sinpo.xnfc.nfc.bean.Application;
import com.sinpo.xnfc.nfc.bean.Card;
import com.sinpo.xnfc.nfc.tech.Iso7816;
import com.sinpo.xnfc.nfc.tech.Iso7816.BerHouse;
import com.sinpo.xnfc.nfc.tech.Iso7816.BerTLV;
public class Quickpass extends StandardPboc {
protected final static byte[] DFN_PPSE = { (byte) '2', (byte) 'P',
(byte) 'A', (byte) 'Y', (byte) '.', (byte) 'S', (byte) 'Y',
(byte) 'S', (byte) '.', (byte) 'D', (byte) 'D', (byte) 'F',
(byte) '0', (byte) '1', };
protected final static byte[] AID_DEBIT = { (byte) 0xA0, 0x00, 0x00, 0x03,
0x33, 0x01, 0x01, 0x01 };
protected final static byte[] AID_CREDIT = { (byte) 0xA0, 0x00, 0x00, 0x03,
0x33, 0x01, 0x01, 0x02 };
protected final static byte[] AID_QUASI_CREDIT = { (byte) 0xA0, 0x00, 0x00,
0x03, 0x33, 0x01, 0x01, 0x03 };
public final static short MARK_LOG = (short) 0xDFFF;
protected final static short[] TAG_GLOBAL = { (short) 0x9F79 /* 电子现金余额 */,
(short) 0x9F78 /* 电子现金单笔上限 */, (short) 0x9F77 /* 电子现金余额上限 */,
(short) 0x9F13 /* 联机ATC */, (short) 0x9F36 /* ATC */,
(short) 0x9F51 /* 货币代码 */, (short) 0x9F4F /* 日志文件格式 */,
(short) 0x9F4D /* 日志文件ID */, (short) 0x5A /* 帐号 */,
(short) 0x5F24 /* 失效日期 */, (short) 0x5F25 /* 生效日期 */, };
@Override
protected SPEC.APP getApplicationId() {
return SPEC.APP.QUICKPASS;
}
@Override
protected boolean resetTag(Iso7816.StdTag tag) throws IOException {
Iso7816.Response rsp = tag.selectByName(DFN_PPSE);
if (!rsp.isOkey())
return false;
BerTLV.extractPrimitives(topTLVs, rsp);
return true;
}
protected HINT readCard(Iso7816.StdTag tag, Card card) throws IOException {
final ArrayList<Iso7816.ID> aids = getApplicationIds(tag);
for (Iso7816.ID aid : aids) {
/*--------------------------------------------------------------*/
// select application
/*--------------------------------------------------------------*/
Iso7816.Response rsp = tag.selectByName(aid.getBytes());
if (!rsp.isOkey())
continue;
final BerHouse subTLVs = new BerHouse();
/*--------------------------------------------------------------*/
// collect info
/*--------------------------------------------------------------*/
BerTLV.extractPrimitives(subTLVs, rsp);
collectTLVFromGlobalTags(tag, subTLVs);
/*--------------------------------------------------------------*/
// parse PDOL and get processing options
// 这是正规途径,但是每次GPO都会使ATC加1,达到65535卡片就锁定了
/*--------------------------------------------------------------*/
// rsp = tag.getProcessingOptions(buildPDOL(subTLVs));
// if (rsp.isOkey())
// BerTLV.extractPrimitives(subTLVs, rsp);
/*--------------------------------------------------------------*/
// 遍历目录下31个文件,山寨途径,微暴力,不知会对卡片折寿多少
// 相对于GPO不停的增加ATC,这是一种折中
// (遍历过程一般不会超过15个文件就会结束)
/*--------------------------------------------------------------*/
collectTLVFromRecords(tag, subTLVs);
// String dump = subTLVs.toString();
/*--------------------------------------------------------------*/
// build result
/*--------------------------------------------------------------*/
final Application app = createApplication();
parseInfo(app, subTLVs);
parseLogs(app, subTLVs);
card.addApplication(app);
}
return card.isUnknownCard() ? HINT.RESETANDGONEXT : HINT.STOP;
}
private static void parseInfo(Application app, BerHouse tlvs) {
Object prop = parseString(tlvs, (short) 0x5A);
if (prop != null)
app.setProperty(SPEC.PROP.SERIAL, prop);
prop = parseApplicationName(tlvs, (String) prop);
if (prop != null)
app.setProperty(SPEC.PROP.ID, prop);
prop = parseInteger(tlvs, (short) 0x9F08);
if (prop != null)
app.setProperty(SPEC.PROP.VERSION, prop);
prop = parseInteger(tlvs, (short) 0x9F36);
if (prop != null)
app.setProperty(SPEC.PROP.COUNT, prop);
prop = parseValidity(tlvs, (short) 0x5F25, (short) 0x5F24);
if (prop != null)
app.setProperty(SPEC.PROP.DATE, prop);
prop = parseCurrency(tlvs, (short) 0x9F51);
if (prop != null)
app.setProperty(SPEC.PROP.CURRENCY, prop);
prop = parseAmount(tlvs, (short) 0x9F77);
if (prop != null)
app.setProperty(SPEC.PROP.DLIMIT, prop);
prop = parseAmount(tlvs, (short) 0x9F78);
if (prop != null)
app.setProperty(SPEC.PROP.TLIMIT, prop);
prop = parseAmount(tlvs, (short) 0x9F79);
if (prop != null)
app.setProperty(SPEC.PROP.ECASH, prop);
}
private ArrayList<Iso7816.ID> getApplicationIds(Iso7816.StdTag tag)
throws IOException {
final ArrayList<Iso7816.ID> ret = new ArrayList<Iso7816.ID>();
// try to read DDF
BerTLV sfi = topTLVs.findFirst(Iso7816.BerT.CLASS_SFI);
if (sfi != null && sfi.length() == 1) {
final int SFI = sfi.v.toInt();
Iso7816.Response r = tag.readRecord(SFI, 1);
for (int p = 2; r.isOkey(); ++p) {
BerTLV.extractPrimitives(topTLVs, r);
r = tag.readRecord(SFI, p);
}
}
// add extracted
ArrayList<BerTLV> aids = topTLVs.findAll(Iso7816.BerT.CLASS_AID);
if (aids != null) {
for (BerTLV aid : aids)
ret.add(new Iso7816.ID(aid.v.getBytes()));
}
// use default list
if (ret.isEmpty()) {
ret.add(new Iso7816.ID(AID_DEBIT));
ret.add(new Iso7816.ID(AID_CREDIT));
ret.add(new Iso7816.ID(AID_QUASI_CREDIT));
}
return ret;
}
/**
* private static void buildPDO(ByteBuffer out, int len, byte... val) {
* final int n = Math.min((val != null) ? val.length : 0, len);
*
* int i = 0; while (i < n) out.put(val[i++]);
*
* while (i++ < len) out.put((byte) 0); }
*
* private static byte[] buildPDOL(Iso7816.BerHouse tlvs) {
*
* final ByteBuffer buff = ByteBuffer.allocate(64);
*
* buff.put((byte) 0x83).put((byte) 0x00);
*
* try { final byte[] pdol = tlvs.findFirst((short) 0x9F38).v.getBytes();
*
* ArrayList<BerTLV> list = BerTLV.extractOptionList(pdol); for
* (Iso7816.BerTLV tlv : list) { final int tag = tlv.t.toInt(); final int
* len = tlv.l.toInt();
*
* switch (tag) { case 0x9F66: // 终端交易属性 buildPDO(buff, len, (byte) 0x48);
* break; case 0x9F02: // 授权金额 buildPDO(buff, len); break; case 0x9F03: //
* 其它金额 buildPDO(buff, len); break; case 0x9F1A: // 终端国家代码 buildPDO(buff,
* len, (byte) 0x01, (byte) 0x56); break; case 0x9F37: // 不可预知数
* buildPDO(buff, len); break; case 0x5F2A: // 交易货币代码 buildPDO(buff, len,
* (byte) 0x01, (byte) 0x56); break; case 0x95: // 终端验证结果 buildPDO(buff,
* len); break; case 0x9A: // 交易日期 buildPDO(buff, len); break; case 0x9C: //
* 交易类型 buildPDO(buff, len); break; default: throw null; } } // 更新数据长度
* buff.put(1, (byte) (buff.position() - 2)); } catch (Exception e) {
* buff.position(2); }
*
* return Arrays.copyOfRange(buff.array(), 0, buff.position()); }
*/
private static void collectTLVFromGlobalTags(Iso7816.StdTag tag,
BerHouse tlvs) throws IOException {
for (short t : TAG_GLOBAL) {
Iso7816.Response r = tag.getData(t);
if (r.isOkey())
tlvs.add(BerTLV.read(r));
}
}
private static void collectTLVFromRecords(Iso7816.StdTag tag, BerHouse tlvs)
throws IOException {
// info files
for (int sfi = 1; sfi <= 10; ++sfi) {
Iso7816.Response r = tag.readRecord(sfi, 1);
for (int idx = 2; r.isOkey() && idx <= 10; ++idx) {
BerTLV.extractPrimitives(tlvs, r);
r = tag.readRecord(sfi, idx);
}
}
// check if already get sfi of log file
BerTLV logEntry = tlvs.findFirst((short) 0x9F4D);
final int S, E;
if (logEntry != null && logEntry.length() == 2) {
S = E = logEntry.v.getBytes()[0] & 0x000000FF;
} else {
S = 11;
E = 31;
}
// log files
for (int sfi = S; sfi <= E; ++sfi) {
Iso7816.Response r = tag.readRecord(sfi, 1);
boolean findOne = r.isOkey();
for (int idx = 2; r.isOkey() && idx <= 10; ++idx) {
tlvs.add(MARK_LOG, r);
r = tag.readRecord(sfi, idx);
}
if (findOne)
break;
}
}
private static SPEC.APP parseApplicationName(BerHouse tlvs, String serial) {
String f = parseString(tlvs, (short) 0x84);
if (f != null) {
if (f.endsWith("010101"))
return SPEC.APP.DEBIT;
if (f.endsWith("010102"))
return SPEC.APP.CREDIT;
if (f.endsWith("010103"))
return SPEC.APP.QCREDIT;
}
return SPEC.APP.UNKNOWN;
}
private static SPEC.CUR parseCurrency(BerHouse tlvs, short tag) {
return SPEC.CUR.CNY;
}
private static String parseValidity(BerHouse tlvs, short from, short to) {
final byte[] f = BerTLV.getValue(tlvs.findFirst(from));
final byte[] t = BerTLV.getValue(tlvs.findFirst(to));
if (t == null || t.length != 3 || t[0] == 0 || t[0] == (byte) 0xFF)
return null;
if (f == null || f.length != 3 || f[0] == 0 || f[0] == (byte) 0xFF)
return String.format("? - 20%02x.%02x.%02x", t[0], t[1], t[2]);
return String.format("20%02x.%02x.%02x - 20%02x.%02x.%02x", f[0], f[1],
f[2], t[0], t[1], t[2]);
}
private static String parseString(BerHouse tlvs, short tag) {
final byte[] v = BerTLV.getValue(tlvs.findFirst(tag));
return (v != null) ? Util.toHexString(v) : null;
}
private static Float parseAmount(BerHouse tlvs, short tag) {
Integer v = parseIntegerBCD(tlvs, tag);
return (v != null) ? v / 100.0f : null;
}
private static Integer parseInteger(BerHouse tlvs, short tag) {
final byte[] v = BerTLV.getValue(tlvs.findFirst(tag));
return (v != null) ? Util.toInt(v) : null;
}
private static Integer parseIntegerBCD(BerHouse tlvs, short tag) {
final byte[] v = BerTLV.getValue(tlvs.findFirst(tag));
return (v != null) ? Util.BCDtoInt(v) : null;
}
private static void parseLogs(Application app, BerHouse tlvs) {
final byte[] rawTemp = BerTLV.getValue(tlvs.findFirst((short) 0x9F4F));
if (rawTemp == null)
return;
final ArrayList<BerTLV> temp = BerTLV.extractOptionList(rawTemp);
if (temp == null || temp.isEmpty())
return;
final ArrayList<BerTLV> logs = tlvs.findAll(MARK_LOG);
final ArrayList<String> ret = new ArrayList<String>(logs.size());
for (BerTLV log : logs) {
String l = parseLog(temp, log.v.getBytes());
if (l != null)
ret.add(l);
}
if (!ret.isEmpty())
app.setProperty(SPEC.PROP.TRANSLOG,
ret.toArray(new String[ret.size()]));
}
private static String parseLog(ArrayList<BerTLV> temp, byte[] data) {
try {
int date = -1, time = -1;
int amount = 0, type = -1;
int cursor = 0;
for (BerTLV f : temp) {
final int n = f.length();
switch (f.t.toInt()) {
case 0x9A: // 交易日期
date = Util.BCDtoInt(data, cursor, n);
break;
case 0x9F21: // 交易时间
time = Util.BCDtoInt(data, cursor, n);
break;
case 0x9F02: // 授权金额
amount = Util.BCDtoInt(data, cursor, n);
break;
case 0x9C: // 交易类型
type = Util.BCDtoInt(data, cursor, n);
break;
case 0x9F03: // 其它金额
case 0x9F1A: // 终端国家代码
case 0x5F2A: // 交易货币代码
case 0x9F4E: // 商户名称
case 0x9F36: // 应用交易计数器(ATC)
default:
break;
}
cursor += n;
}
if (amount <= 0)
return null;
final char sign;
switch (type) {
case 0: // 刷卡消费
case 1: // 取现
case 8: // 转账
case 9: // 支付
case 20: // 退款
case 40: // 持卡人账户转账
sign = '-';
break;
default:
sign = '+';
break;
}
String sd = (date <= 0) ? "****.**.**" : String.format(
"20%02d.%02d.%02d", (date / 10000) % 100,
(date / 100) % 100, date % 100);
String st = (time <= 0) ? "**:**" : String.format("%02d:%02d",
(time / 10000) % 100, (time / 100) % 100);
final StringBuilder ret = new StringBuilder();
ret.append(String.format("%s %s %c%.2f", sd, st, sign,
amount / 100f));
return ret.toString();
} catch (Exception e) {
return null;
}
}
private final BerHouse topTLVs = new BerHouse();
}
| Java |
/* NFCard is free software; you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation; either version 3 of the License, or
(at your option) any later version.
NFCard is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with Wget. If not, see <http://www.gnu.org/licenses/>.
Additional permission under GNU GPL version 3 section 7 */
package com.sinpo.xnfc.nfc.reader;
import java.io.IOException;
import com.sinpo.xnfc.SPEC;
import com.sinpo.xnfc.nfc.Util;
import com.sinpo.xnfc.nfc.bean.Application;
import com.sinpo.xnfc.nfc.bean.Card;
import com.sinpo.xnfc.nfc.tech.FeliCa;
import android.nfc.tech.NfcF;
final class FelicaReader {
static void readCard(NfcF tech, Card card) throws IOException {
final FeliCa.Tag tag = new FeliCa.Tag(tech);
tag.connect();
/*
*
FeliCa.SystemCode systems[] = tag.getSystemCodeList();
if (systems.length == 0) {
systems = new FeliCa.SystemCode[] { new FeliCa.SystemCode(
tag.getSystemCodeByte()) };
}
for (final FeliCa.SystemCode sys : systems)
card.addApplication(readApplication(tag, sys.toInt()));
*/
// better old card compatibility
card.addApplication(readApplication(tag, SYS_OCTOPUS));
try {
card.addApplication(readApplication(tag, SYS_SZT));
} catch (IOException e) {
// for early version of OCTOPUS which will throw shit
}
tag.close();
}
private static final int SYS_SZT = 0x8005;
private static final int SYS_OCTOPUS = 0x8008;
private static final int SRV_SZT = 0x0118;
private static final int SRV_OCTOPUS = 0x0117;
private static Application readApplication(FeliCa.Tag tag, int system)
throws IOException {
final FeliCa.ServiceCode scode;
final Application app;
if (system == SYS_OCTOPUS) {
app = new Application();
app.setProperty(SPEC.PROP.ID, SPEC.APP.OCTOPUS);
app.setProperty(SPEC.PROP.CURRENCY, SPEC.CUR.HKD);
scode = new FeliCa.ServiceCode(SRV_OCTOPUS);
} else if (system == SYS_SZT) {
app = new Application();
app.setProperty(SPEC.PROP.ID, SPEC.APP.SHENZHENTONG);
app.setProperty(SPEC.PROP.CURRENCY, SPEC.CUR.CNY);
scode = new FeliCa.ServiceCode(SRV_SZT);
} else {
return null;
}
app.setProperty(SPEC.PROP.SERIAL, tag.getIDm().toString());
app.setProperty(SPEC.PROP.PARAM, tag.getPMm().toString());
tag.polling(system);
final float[] data = new float[] { 0, 0, 0 };
int p = 0;
for (byte i = 0; p < data.length; ++i) {
final FeliCa.ReadResponse r = tag.readWithoutEncryption(scode, i);
if (!r.isOkey())
break;
data[p++] = (Util.toInt(r.getBlockData(), 0, 4) - 350) / 10.0f;
}
if (p != 0)
app.setProperty(SPEC.PROP.BALANCE, parseBalance(data));
else
app.setProperty(SPEC.PROP.BALANCE, Float.NaN);
return app;
}
private static float parseBalance(float[] value) {
float balance = 0f;
for (float v : value)
balance += v;
return balance;
}
}
| Java |
/* NFCard is free software; you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation; either version 3 of the License, or
(at your option) any later version.
NFCard is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with Wget. If not, see <http://www.gnu.org/licenses/>.
Additional permission under GNU GPL version 3 section 7 */
package com.sinpo.xnfc;
import com.sinpo.xnfc.R;
public final class SPEC {
public enum PAGE {
DEFAULT, INFO, ABOUT,
}
public enum EVENT {
IDLE, ERROR, READING, FINISHED,
}
public enum PROP {
ID(R.string.spec_prop_id),
SERIAL(R.string.spec_prop_serial),
PARAM(R.string.spec_prop_param),
VERSION(R.string.spec_prop_version),
DATE(R.string.spec_prop_date),
COUNT(R.string.spec_prop_count),
CURRENCY(R.string.spec_prop_currency),
TLIMIT(R.string.spec_prop_tlimit),
DLIMIT(R.string.spec_prop_dlimit),
ECASH(R.string.spec_prop_ecash),
BALANCE(R.string.spec_prop_balance),
TRANSLOG(R.string.spec_prop_translog),
ACCESS(R.string.spec_prop_access),
EXCEPTION(R.string.spec_prop_exception);
public String toString() {
return ThisApplication.getStringResource(resId);
}
private final int resId;
private PROP(int resId) {
this.resId = resId;
}
}
public enum APP {
UNKNOWN(R.string.spec_app_unknown),
SHENZHENTONG(R.string.spec_app_shenzhentong),
QUICKPASS(R.string.spec_app_quickpass),
OCTOPUS(R.string.spec_app_octopus_hk),
BEIJINGMUNICIPAL(R.string.spec_app_beijing),
WUHANTONG(R.string.spec_app_wuhantong),
CHANGANTONG(R.string.spec_app_changantong),
SHANGHAIGJ(R.string.spec_app_shanghai),
DEBIT(R.string.spec_app_debit),
CREDIT(R.string.spec_app_credit),
QCREDIT(R.string.spec_app_qcredit);
public String toString() {
return ThisApplication.getStringResource(resId);
}
private final int resId;
private APP(int resId) {
this.resId = resId;
}
}
public enum CUR {
UNKNOWN(R.string.spec_cur_unknown),
USD(R.string.spec_cur_usd),
CNY(R.string.spec_cur_cny),
HKD(R.string.spec_cur_hkd);
public String toString() {
return ThisApplication.getStringResource(resId);
}
private final int resId;
private CUR(int resId) {
this.resId = resId;
}
}
public static final String TAG_BLK = "div";
public static final String TAG_TIP = "t_tip";
public static final String TAG_ACT = "t_action";
public static final String TAG_EM = "t_em";
public static final String TAG_H1 = "t_head1";
public static final String TAG_H2 = "t_head2";
public static final String TAG_H3 = "t_head3";
public static final String TAG_SP = "t_splitter";
public static final String TAG_TEXT = "t_text";
public static final String TAG_ITEM = "t_item";
public static final String TAG_LAB = "t_label";
public static final String TAG_PARAG = "t_parag";
}
| Java |
/* NFCard is free software; you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation; either version 3 of the License, or
(at your option) any later version.
NFCard is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with Wget. If not, see <http://www.gnu.org/licenses/>.
Additional permission under GNU GPL version 3 section 7 */
package com.sinpo.xnfc;
import java.lang.Thread.UncaughtExceptionHandler;
import com.sinpo.xnfc.R;
import android.app.Application;
import android.graphics.Typeface;
import android.graphics.drawable.Drawable;
import android.util.DisplayMetrics;
import android.widget.Toast;
public final class ThisApplication extends Application implements
UncaughtExceptionHandler {
private static ThisApplication instance;
@Override
public void uncaughtException(Thread thread, Throwable ex) {
System.exit(0);
}
@Override
public void onCreate() {
super.onCreate();
Thread.setDefaultUncaughtExceptionHandler(this);
instance = this;
}
public static String name() {
return getStringResource(R.string.app_name);
}
public static String version() {
try {
return instance.getPackageManager().getPackageInfo(
instance.getPackageName(), 0).versionName;
} catch (Exception e) {
return "1.0";
}
}
public static void showMessage(int fmt, CharSequence... msgs) {
String msg = String.format(getStringResource(fmt), msgs);
Toast.makeText(instance, msg, Toast.LENGTH_LONG).show();
}
public static Typeface getFontResource(int pathId) {
String path = getStringResource(pathId);
return Typeface.createFromAsset(instance.getAssets(), path);
}
public static int getDimensionResourcePixelSize(int resId) {
return instance.getResources().getDimensionPixelSize(resId);
}
public static int getColorResource(int resId) {
return instance.getResources().getColor(resId);
}
public static String getStringResource(int resId) {
return instance.getString(resId);
}
public static Drawable getDrawableResource(int resId) {
return instance.getResources().getDrawable(resId);
}
public static DisplayMetrics getDisplayMetrics() {
return instance.getResources().getDisplayMetrics();
}
}
| Java |
/* NFCard is free software; you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation; either version 3 of the License, or
(at your option) any later version.
NFCard is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with Wget. If not, see <http://www.gnu.org/licenses/>.
Additional permission under GNU GPL version 3 section 7 */
package com.sinpo.xnfc;
import android.app.Activity;
import android.content.Intent;
import android.graphics.Typeface;
import android.os.Bundle;
import android.text.method.LinkMovementMethod;
import android.view.Gravity;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;
import android.widget.ViewSwitcher;
import com.sinpo.xnfc.R;
import com.sinpo.xnfc.nfc.NfcManager;
import com.sinpo.xnfc.ui.AboutPage;
import com.sinpo.xnfc.ui.MainPage;
import com.sinpo.xnfc.ui.NfcPage;
import com.sinpo.xnfc.ui.Toolbar;
public class MainActivity extends Activity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
initViews();
nfc = new NfcManager(this);
onNewIntent(getIntent());
}
@Override
public void onBackPressed() {
if (isCurrentPage(SPEC.PAGE.ABOUT))
loadDefaultPage();
else if (safeExit)
super.onBackPressed();
}
@Override
public void setIntent(Intent intent) {
if (NfcPage.isSendByMe(intent))
loadNfcPage(intent);
else if (AboutPage.isSendByMe(intent))
loadAboutPage();
else
super.setIntent(intent);
}
@Override
protected void onPause() {
super.onPause();
nfc.onPause();
}
@Override
protected void onResume() {
super.onResume();
nfc.onResume();
}
@Override
public void onWindowFocusChanged(boolean hasFocus) {
if (hasFocus) {
if (nfc.updateStatus())
loadDefaultPage();
// 有些ROM将关闭系统状态下拉面板的BACK事件发给最顶层窗口
// 这里加入一个延迟避免意外退出
board.postDelayed(new Runnable() {
public void run() {
safeExit = true;
}
}, 800);
} else {
safeExit = false;
}
}
@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
loadDefaultPage();
}
@Override
protected void onNewIntent(Intent intent) {
if (!nfc.readCard(intent, new NfcPage(this)))
loadDefaultPage();
}
public void onSwitch2DefaultPage(View view) {
if (!isCurrentPage(SPEC.PAGE.DEFAULT))
loadDefaultPage();
}
public void onSwitch2AboutPage(View view) {
if (!isCurrentPage(SPEC.PAGE.ABOUT))
loadAboutPage();
}
public void onCopyPageContent(View view) {
toolbar.copyPageContent(getFrontPage());
}
private void loadDefaultPage() {
toolbar.show(null);
TextView ta = getBackPage();
resetTextArea(ta, SPEC.PAGE.DEFAULT, Gravity.CENTER);
ta.setText(MainPage.getContent(this));
board.showNext();
}
private void loadAboutPage() {
toolbar.show(R.id.btnBack);
TextView ta = getBackPage();
resetTextArea(ta, SPEC.PAGE.ABOUT, Gravity.LEFT);
ta.setText(AboutPage.getContent(this));
board.showNext();
}
private void loadNfcPage(Intent intent) {
final CharSequence info = NfcPage.getContent(this, intent);
TextView ta = getBackPage();
if (NfcPage.isNormalInfo(intent)) {
toolbar.show(R.id.btnCopy, R.id.btnReset);
resetTextArea(ta, SPEC.PAGE.INFO, Gravity.LEFT);
} else {
toolbar.show(R.id.btnBack);
resetTextArea(ta, SPEC.PAGE.INFO, Gravity.CENTER);
}
ta.setText(info);
board.showNext();
}
private boolean isCurrentPage(SPEC.PAGE which) {
Object obj = getFrontPage().getTag();
if (obj == null)
return which.equals(SPEC.PAGE.DEFAULT);
return which.equals(obj);
}
private void resetTextArea(TextView textArea, SPEC.PAGE type, int gravity) {
((View) textArea.getParent()).scrollTo(0, 0);
textArea.setTag(type);
textArea.setGravity(gravity);
}
private TextView getFrontPage() {
return (TextView) ((ViewGroup) board.getCurrentView()).getChildAt(0);
}
private TextView getBackPage() {
return (TextView) ((ViewGroup) board.getNextView()).getChildAt(0);
}
private void initViews() {
board = (ViewSwitcher) findViewById(R.id.switcher);
Typeface tf = ThisApplication.getFontResource(R.string.font_oem1);
TextView tv = (TextView) findViewById(R.id.txtAppName);
tv.setTypeface(tf);
tf = ThisApplication.getFontResource(R.string.font_oem2);
tv = getFrontPage();
tv.setMovementMethod(LinkMovementMethod.getInstance());
tv.setTypeface(tf);
tv = getBackPage();
tv.setMovementMethod(LinkMovementMethod.getInstance());
tv.setTypeface(tf);
toolbar = new Toolbar((ViewGroup) findViewById(R.id.toolbar));
}
private ViewSwitcher board;
private Toolbar toolbar;
private NfcManager nfc;
private boolean safeExit;
}
| Java |
/* NFCard is free software; you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation; either version 3 of the License, or
(at your option) any later version.
NFCard is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with Wget. If not, see <http://www.gnu.org/licenses/>.
Additional permission under GNU GPL version 3 section 7 */
package com.sinpo.xnfc.ui;
import java.lang.ref.WeakReference;
import org.xml.sax.XMLReader;
import android.graphics.Canvas;
import android.graphics.Paint;
import android.graphics.Paint.FontMetricsInt;
import android.graphics.Typeface;
import android.text.Editable;
import android.text.Html;
import android.text.Spannable;
import android.text.Spanned;
import android.text.TextPaint;
import android.text.style.ClickableSpan;
import android.text.style.LineHeightSpan;
import android.text.style.MetricAffectingSpan;
import android.text.style.ReplacementSpan;
import android.util.DisplayMetrics;
import android.view.View;
import com.sinpo.xnfc.R;
import com.sinpo.xnfc.SPEC;
import com.sinpo.xnfc.ThisApplication;
public final class SpanFormatter implements Html.TagHandler {
public interface ActionHandler {
void handleAction(CharSequence name);
}
private final ActionHandler handler;
public SpanFormatter(ActionHandler handler) {
this.handler = handler;
}
public CharSequence toSpanned(String html) {
return Html.fromHtml(html, null, this);
}
private static final class ActionSpan extends ClickableSpan {
private final String action;
private final ActionHandler handler;
private final int color;
ActionSpan(String action, ActionHandler handler, int color) {
this.action = action;
this.handler = handler;
this.color = color;
}
@Override
public void onClick(View widget) {
if (handler != null)
handler.handleAction(action);
}
@Override
public void updateDrawState(TextPaint ds) {
super.updateDrawState(ds);
ds.setColor(color);
}
}
private static final class FontSpan extends MetricAffectingSpan {
final int color;
final float size;
final Typeface face;
final boolean bold;
FontSpan(int color, float size, Typeface face) {
this.color = color;
this.size = size;
if (face == Typeface.DEFAULT) {
this.face = null;
this.bold = false;
} else if (face == Typeface.DEFAULT_BOLD) {
this.face = null;
this.bold = true;
} else {
this.face = face;
this.bold = false;
}
}
@Override
public void updateDrawState(TextPaint ds) {
ds.setTextSize(size);
ds.setColor(color);
if (face != null) {
ds.setTypeface(face);
} else if (bold) {
Typeface tf = ds.getTypeface();
if (tf != null) {
int style = tf.getStyle() | Typeface.BOLD;
tf = Typeface.create(tf, style);
ds.setTypeface(tf);
style &= ~tf.getStyle();
if ((style & Typeface.BOLD) != 0) {
ds.setFakeBoldText(true);
}
}
}
}
@Override
public void updateMeasureState(TextPaint p) {
updateDrawState(p);
}
}
private static final class ParagSpan implements LineHeightSpan {
private final int linespaceDelta;
ParagSpan(int linespaceDelta) {
this.linespaceDelta = linespaceDelta;
}
@Override
public void chooseHeight(CharSequence text, int start, int end,
int spanstartv, int v, FontMetricsInt fm) {
fm.bottom += linespaceDelta;
fm.descent += linespaceDelta;
}
}
private static final class SplitterSpan extends ReplacementSpan {
private final int color;
private final int width;
private final int height;
SplitterSpan(int color, int width, int height) {
this.color = color;
this.width = width;
this.height = height;
}
@Override
public void updateDrawState(TextPaint ds) {
ds.setTextSize(1);
}
@Override
public int getSize(Paint paint, CharSequence text, int start, int end,
Paint.FontMetricsInt fm) {
return 0;
}
@Override
public void draw(Canvas canvas, CharSequence text, int start, int end,
float x, int top, int y, int bottom, Paint paint) {
canvas.save();
canvas.translate(x, (bottom + top) / 2 - height);
final int c = paint.getColor();
paint.setColor(color);
canvas.drawRect(x, 0, x + width, height, paint);
paint.setColor(c);
canvas.restore();
}
}
@Override
public void handleTag(boolean opening, String tag, Editable output,
XMLReader xmlReader) {
final int len = output.length();
if (opening) {
if (SPEC.TAG_TEXT.equals(tag)) {
markFontSpan(output, len, R.color.tag_text, R.dimen.tag_text,
Typeface.DEFAULT);
} else if (SPEC.TAG_TIP.equals(tag)) {
markParagSpan(output, len, R.dimen.tag_parag);
markFontSpan(output, len, R.color.tag_tip, R.dimen.tag_tip,
getTipFont());
} else if (SPEC.TAG_LAB.equals(tag)) {
markFontSpan(output, len, R.color.tag_lab, R.dimen.tag_lab,
Typeface.DEFAULT_BOLD);
} else if (SPEC.TAG_ITEM.equals(tag)) {
markFontSpan(output, len, R.color.tag_item, R.dimen.tag_item,
Typeface.DEFAULT);
} else if (SPEC.TAG_H1.equals(tag)) {
markFontSpan(output, len, R.color.tag_h1, R.dimen.tag_h1,
Typeface.DEFAULT_BOLD);
} else if (SPEC.TAG_H2.equals(tag)) {
markFontSpan(output, len, R.color.tag_h2, R.dimen.tag_h2,
Typeface.DEFAULT_BOLD);
} else if (SPEC.TAG_H3.equals(tag)) {
markFontSpan(output, len, R.color.tag_h3, R.dimen.tag_h3,
Typeface.SERIF);
} else if (tag.startsWith(SPEC.TAG_ACT)) {
markActionSpan(output, len, tag, R.color.tag_action);
} else if (SPEC.TAG_PARAG.equals(tag)) {
markParagSpan(output, len, R.dimen.tag_parag);
} else if (SPEC.TAG_SP.equals(tag)) {
markSpliterSpan(output, len, R.color.tag_action,
R.dimen.tag_spliter);
}
} else {
if (SPEC.TAG_TEXT.equals(tag)) {
setSpan(output, len, FontSpan.class);
} else if (SPEC.TAG_TIP.equals(tag)) {
setSpan(output, len, FontSpan.class);
setSpan(output, len, ParagSpan.class);
} else if (SPEC.TAG_LAB.equals(tag)) {
setSpan(output, len, FontSpan.class);
} else if (SPEC.TAG_ITEM.equals(tag)) {
setSpan(output, len, FontSpan.class);
} else if (SPEC.TAG_H1.equals(tag)) {
setSpan(output, len, FontSpan.class);
} else if (SPEC.TAG_H2.equals(tag)) {
setSpan(output, len, FontSpan.class);
} else if (SPEC.TAG_H3.equals(tag)) {
setSpan(output, len, FontSpan.class);
} else if (tag.startsWith(SPEC.TAG_ACT)) {
setSpan(output, len, ActionSpan.class);
} else if (SPEC.TAG_PARAG.equals(tag)) {
setSpan(output, len, ParagSpan.class);
}
}
}
private static void markSpliterSpan(Editable out, int pos, int colorId,
int heightId) {
DisplayMetrics dm = ThisApplication.getDisplayMetrics();
int color = ThisApplication.getColorResource(colorId);
int height = ThisApplication.getDimensionResourcePixelSize(heightId);
out.append("-------------------").setSpan(
new SplitterSpan(color, dm.widthPixels, height), pos,
out.length(), Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
}
private static void markFontSpan(Editable out, int pos, int colorId,
int sizeId, Typeface face) {
int color = ThisApplication.getColorResource(colorId);
float size = ThisApplication.getDimensionResourcePixelSize(sizeId);
FontSpan span = new FontSpan(color, size, face);
out.setSpan(span, pos, pos, Spannable.SPAN_MARK_MARK);
}
private static void markParagSpan(Editable out, int pos, int linespaceId) {
int linespace = ThisApplication
.getDimensionResourcePixelSize(linespaceId);
ParagSpan span = new ParagSpan(linespace);
out.setSpan(span, pos, pos, Spannable.SPAN_MARK_MARK);
}
private void markActionSpan(Editable out, int pos, String tag, int colorId) {
int color = ThisApplication.getColorResource(colorId);
out.setSpan(new ActionSpan(tag, handler, color), pos, pos,
Spannable.SPAN_MARK_MARK);
}
private static void setSpan(Editable out, int pos, Class<?> kind) {
Object span = getLastMarkSpan(out, kind);
out.setSpan(span, out.getSpanStart(span), pos,
Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
}
private static Object getLastMarkSpan(Spanned text, Class<?> kind) {
Object[] objs = text.getSpans(0, text.length(), kind);
if (objs.length == 0) {
return null;
} else {
return objs[objs.length - 1];
}
}
private static Typeface getTipFont() {
Typeface ret = null;
WeakReference<Typeface> wr = TIPFONT;
if (wr != null)
ret = wr.get();
if (ret == null) {
ret = ThisApplication.getFontResource(R.string.font_oem3);
TIPFONT = new WeakReference<Typeface>(ret);
}
return ret;
}
private static WeakReference<Typeface> TIPFONT;
}
| Java |
/* NFCard is free software; you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation; either version 3 of the License, or
(at your option) any later version.
NFCard is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with Wget. If not, see <http://www.gnu.org/licenses/>.
Additional permission under GNU GPL version 3 section 7 */
package com.sinpo.xnfc.ui;
import static android.provider.Settings.ACTION_SETTINGS;
import android.app.Activity;
import android.content.Intent;
import android.nfc.NfcAdapter;
import com.sinpo.xnfc.R;
import com.sinpo.xnfc.ThisApplication;
public final class MainPage {
public static CharSequence getContent(Activity activity) {
final NfcAdapter nfc = NfcAdapter.getDefaultAdapter(activity);
final int resid;
if (nfc == null)
resid = R.string.info_nfc_notsupport;
else if (!nfc.isEnabled())
resid = R.string.info_nfc_disabled;
else
resid = R.string.info_nfc_nocard;
String tip = ThisApplication.getStringResource(resid);
return new SpanFormatter(new Handler(activity)).toSpanned(tip);
}
private static final class Handler implements SpanFormatter.ActionHandler {
private final Activity activity;
Handler(Activity activity) {
this.activity = activity;
}
@Override
public void handleAction(CharSequence name) {
startNfcSettingsActivity();
}
private void startNfcSettingsActivity() {
activity.startActivityForResult(new Intent(ACTION_SETTINGS), 0);
}
}
private MainPage() {
}
}
| Java |
/* NFCard is free software; you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation; either version 3 of the License, or
(at your option) any later version.
NFCard is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with Wget. If not, see <http://www.gnu.org/licenses/>.
Additional permission under GNU GPL version 3 section 7 */
package com.sinpo.xnfc.ui;
import android.app.Activity;
import android.content.Intent;
import com.sinpo.xnfc.R;
import com.sinpo.xnfc.ThisApplication;
public final class AboutPage {
private static final String TAG = "ABOUTPAGE_ACTION";
public static CharSequence getContent(Activity activity) {
String tip = ThisApplication
.getStringResource(R.string.info_main_about);
tip = tip.replace("<app />", ThisApplication.name());
tip = tip.replace("<version />", ThisApplication.version());
return new SpanFormatter(null).toSpanned(tip);
}
public static boolean isSendByMe(Intent intent) {
return intent != null && TAG.equals(intent.getAction());
}
static SpanFormatter.ActionHandler getActionHandler(Activity activity) {
return new Handler(activity);
}
private static final class Handler implements SpanFormatter.ActionHandler {
private final Activity activity;
Handler(Activity activity) {
this.activity = activity;
}
@Override
public void handleAction(CharSequence name) {
activity.setIntent(new Intent(TAG));
}
}
private AboutPage() {
}
}
| Java |
/* NFCard is free software; you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation; either version 3 of the License, or
(at your option) any later version.
NFCard is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with Wget. If not, see <http://www.gnu.org/licenses/>.
Additional permission under GNU GPL version 3 section 7 */
package com.sinpo.xnfc.ui;
import android.animation.LayoutTransition;
import android.annotation.SuppressLint;
import android.content.Context;
import android.os.Build;
import android.text.ClipboardManager;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;
import com.sinpo.xnfc.R;
import com.sinpo.xnfc.ThisApplication;
public final class Toolbar {
final ViewGroup toolbar;
@SuppressLint("NewApi")
public Toolbar(ViewGroup toolbar) {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB)
toolbar.setLayoutTransition(new LayoutTransition());
this.toolbar = toolbar;
}
public void copyPageContent(TextView textArea) {
final CharSequence text = textArea.getText();
if (text != null) {
((ClipboardManager) textArea.getContext().getSystemService(
Context.CLIPBOARD_SERVICE)).setText(text);
ThisApplication.showMessage(R.string.info_main_copied);
}
}
public void show(int... buttons) {
hide();
showDelayed(1000, buttons);
}
private void hide() {
final int n = toolbar.getChildCount();
for (int i = 0; i < n; ++i)
toolbar.getChildAt(i).setVisibility(View.GONE);
}
private void showDelayed(int delay, int... buttons) {
toolbar.postDelayed(new Helper(buttons), delay);
}
private final class Helper implements Runnable {
private final int[] buttons;
Helper(int... buttons) {
this.buttons = buttons;
}
@Override
public void run() {
final int n = toolbar.getChildCount();
for (int i = 0; i < n; ++i) {
final View view = toolbar.getChildAt(i);
int visibility = View.GONE;
if (buttons != null) {
final int id = view.getId();
for (int btn : buttons) {
if (btn == id) {
visibility = View.VISIBLE;
break;
}
}
}
view.setVisibility(visibility);
}
}
}
}
| Java |
/* NFCard is free software; you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation; either version 3 of the License, or
(at your option) any later version.
NFCard is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with Wget. If not, see <http://www.gnu.org/licenses/>.
Additional permission under GNU GPL version 3 section 7 */
package com.sinpo.xnfc.ui;
import android.app.Activity;
import android.app.Dialog;
import android.content.Intent;
import com.sinpo.xnfc.R;
import com.sinpo.xnfc.ThisApplication;
import com.sinpo.xnfc.SPEC.EVENT;
import com.sinpo.xnfc.nfc.bean.Card;
import com.sinpo.xnfc.nfc.reader.ReaderListener;
public final class NfcPage implements ReaderListener {
private static final String TAG = "READCARD_ACTION";
private static final String RET = "READCARD_RESULT";
private static final String STA = "READCARD_STATUS";
private final Activity activity;
public NfcPage(Activity activity) {
this.activity = activity;
}
public static boolean isSendByMe(Intent intent) {
return intent != null && TAG.equals(intent.getAction());
}
public static boolean isNormalInfo(Intent intent) {
return intent != null && intent.hasExtra(STA);
}
public static CharSequence getContent(Activity activity, Intent intent) {
String info = intent.getStringExtra(RET);
if (info == null || info.length() == 0)
return null;
return new SpanFormatter(AboutPage.getActionHandler(activity))
.toSpanned(info);
}
@Override
public void onReadEvent(EVENT event, Object... objs) {
if (event == EVENT.IDLE) {
showProgressBar();
} else if (event == EVENT.FINISHED) {
hideProgressBar();
final Card card;
if (objs != null && objs.length > 0)
card = (Card) objs[0];
else
card = null;
activity.setIntent(buildResult(card));
}
}
private Intent buildResult(Card card) {
final Intent ret = new Intent(TAG);
if (card != null && !card.hasReadingException()) {
if (card.isUnknownCard()) {
ret.putExtra(RET, ThisApplication
.getStringResource(R.string.info_nfc_unknown));
} else {
ret.putExtra(RET, card.toHtml());
ret.putExtra(STA, 1);
}
} else {
ret.putExtra(RET,
ThisApplication.getStringResource(R.string.info_nfc_error));
}
return ret;
}
private void showProgressBar() {
Dialog d = progressBar;
if (d == null) {
d = new Dialog(activity, R.style.progressBar);
d.setCancelable(false);
d.setContentView(R.layout.progress);
progressBar = d;
}
if (!d.isShowing())
d.show();
}
private void hideProgressBar() {
final Dialog d = progressBar;
if (d != null && d.isShowing())
d.cancel();
}
private Dialog progressBar;
}
| Java |
/*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
package com.mycompany.biblio.model;
import java.io.Serializable;
import javax.persistence.*;
/**
*
* @author Haythem & Seif
*/
@Entity
@NamedQueries({
@NamedQuery(name = Annonce.FIND_ALL, query = "SELECT a FROM Annonce a"),
@NamedQuery(name = Annonce.FIND_BY_KEYWORD, query = "SELECT a FROM Annonce a WHERE (a.titre LIKE :key1 OR a.description LIKE :key2 OR a.type LIKE :key3)")
//@NamedQuery(name = Annonce.FIND_BY_TYPE, query = "SELECT a FROM Annonce a WHERE (a.type LIKE :key)")
})
public class Annonce implements Serializable {
public final static String FIND_ALL = "Annonce.findAll";
public final static String FIND_BY_KEYWORD = "Annonce.findByKeyWord";
// public final static String FIND_BY_TYPE = "Annonce.findByType";
private static final long serialVersionUID = 1L;
@Id@GeneratedValue
private Long id;
@Column(nullable = false)
private String titre;
@Column(nullable = false)
private String description;
@Column(nullable = false)
private Double prix;
@Column(nullable = false)
private String type;
@ManyToOne
private Utilisateur utilisateur;
@Transient
private Boolean selected;
// ======================================
// = Constructors =
// ======================================
public Annonce() {
}
public Annonce(String titre, String description, Double prix,String type) {
this.titre = titre;
this.description = description;
this.prix = prix;
this.type=type;
}
// ======================================
// = Getters & Setters =
// ======================================
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
public String getTitre() {
return titre;
}
public void setTitre(String titre) {
this.titre = titre;
}
public String getDescription() {
return description;
}
public void setDescription(String description) {
this.description = description;
}
public Double getPrix() {
return prix;
}
public void setPrix(Double prix) {
this.prix = prix;
}
public String getType() {
return type;
}
public void setType(String type) {
this.type = type;
}
public Utilisateur getUtilisateur() {
return utilisateur;
}
public void setUtilisateur(Utilisateur utilisateur) {
this.utilisateur = utilisateur;
}
public Boolean isSelected() {
return selected;
}
public Boolean getSelected() {
return selected;
}
public void setSelected(Boolean selected) {
this.selected = selected;
}
// ======================================
// = hash, equals, toString =
// ======================================
@Override
public int hashCode() {
int hash = 0;
hash += (id != null ? id.hashCode() : 0);
return hash;
}
@Override
public boolean equals(Object object) {
// TODO: Warning - this method won't work in the case the id fields are not set
if (!(object instanceof Annonce)) {
return false;
}
Annonce other = (Annonce) object;
if ((this.id == null && other.id != null) || (this.id != null && !this.id.equals(other.id))) {
return false;
}
return true;
}
@Override
public String toString() {
return "com.mycompany.biblio.model.Annonce[ id=" + id + " ]";
}
}
| Java |
/*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
package com.mycompany.biblio.model;
import java.io.Serializable;
import java.util.*;
import javax.persistence.*;
/**
*
* @author Haythem & Seif..
*/
@Entity
@NamedQueries({
@NamedQuery(name = Utilisateur.FIND_ALL, query = "SELECT u FROM Utilisateur u"),
@NamedQuery(name = Utilisateur.FIND_BY_USERNAME,query="SELECT u FROM Utilisateur AS u WHERE u.username = :username")
})
public class Utilisateur implements Serializable {
private final static long serialVersionUID = 1L;
public final static String FIND_ALL = "Utilisateur.findAll";
public final static String FIND_BY_USERNAME = "Utilisateur.findByUsername";
@Id@GeneratedValue(strategy = GenerationType.AUTO)
private Long id;
@Column(nullable = false)
private String nom;
@Column(nullable = false)
private String prenom;
@Column(nullable = false)
private String email;
private Integer telephone;
private String adresse;
@OneToMany(mappedBy="utilisateur",cascade=CascadeType.ALL)
private List<Annonce> annonces;
@Column(name="username", nullable = false)
private String username;
@Column(name="password", nullable = false)
private String password;
@Transient
private Boolean selected;
// ======================================
// = Constructors =
// ======================================
public Utilisateur() {
annonces= new ArrayList<Annonce>();
}
public Utilisateur(String nom, String prenom, String email, Integer telephone, String adresse, String username, String password) {
this.nom = nom;
this.prenom = prenom;
this.email = email;
this.telephone = telephone;
this.adresse = adresse;
this.username = username;
this.password = password;
annonces= new ArrayList<Annonce>();
}
// ======================================
// = Getters & Setters =
// ======================================
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
public String getNom() {
return nom;
}
public void setNom(String nom) {
this.nom = nom;
}
public String getPrenom() {
return prenom;
}
public void setPrenom(String prenom) {
this.prenom = prenom;
}
public String getEmail() {
return email;
}
public void setEmail(String email) {
this.email = email;
}
public Integer getTelephone() {
return telephone;
}
public void setTelephone(Integer telephone) {
this.telephone = telephone;
}
public String getAdresse() {
return adresse;
}
public void setAdresse(String Adresse) {
this.adresse = Adresse;
}
public List<Annonce> getAnnonces() {
return annonces;
}
public void setAnnonces(List<Annonce> annonces) {
this.annonces = annonces;
}
public String getUsername() {
return username;
}
public void setUsername(String username) {
this.username = username;
}
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
public Boolean isSelected() {
return selected;
}
public Boolean getSelected() {
return selected;
}
public void setSelected(Boolean selected) {
this.selected = selected;
}
public void addAnnonce(Annonce a){
annonces.add(a);
}
// ======================================
// = hash, equals, toString =
// ======================================
@Override
public int hashCode() {
int hash = 0;
hash += (id != null ? id.hashCode() : 0);
return hash;
}
@Override
public boolean equals(Object object) {
// TODO: Warning - this method won't work in the case the id fields are not set
if (!(object instanceof Utilisateur)) {
return false;
}
Utilisateur other = (Utilisateur) object;
if ((this.id == null && other.id != null) || (this.id != null && !this.id.equals(other.id))) {
return false;
}
return true;
}
@Override
public String toString() {
final StringBuilder sb = new StringBuilder();
sb.append("Utilisateur");
sb.append("{id=").append(id);
sb.append(", nom='").append(nom).append('\'');
sb.append(", prenom=").append(prenom).append('\'');
sb.append(", email='").append(email).append('\'');
sb.append(", telephone='").append(telephone).append('\'');
sb.append(", adresse='").append(adresse).append('\'');
sb.append(", username='").append(username).append('\'');
sb.append(", password='").append(password);
sb.append('}');
return sb.toString();
}
} | Java |
/*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
package com.mycompany.biblio.model;
import java.io.Serializable;
import java.util.*;
import javax.persistence.*;
/**
*
* @author Haythem & Seif
*/
@Entity
@NamedQueries({
@NamedQuery(name = Categorie.FIND_ALL, query = "SELECT c FROM Categorie c")
})
public class Categorie implements Serializable {
public final static String FIND_ALL = "Categorie.findAll";
private static final long serialVersionUID = 1L;
@Id
@GeneratedValue(strategy = GenerationType.AUTO)
private Long id;
@Column(nullable = false)
private String nom;
@OneToMany(cascade = CascadeType.ALL)
private List<Annonce> annonces;
// ======================================
// = Constructors =
// ======================================
public Categorie() {
}
public Categorie(String nom) {
this.nom = nom;
this.annonces = new ArrayList<Annonce>();
}
// ======================================
// = Getters & Setters =
// ======================================
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
public String getNom() {
return nom;
}
public void setNom(String nom) {
this.nom = nom;
}
public List<Annonce> getAnnonces() {
return annonces;
}
public void setAnnonces(List<Annonce> annonces) {
this.annonces = annonces;
}
public void addAnnonce(Annonce a){
annonces.add(a);
}
// ======================================
// = hash, equals, toString =
// ======================================
@Override
public int hashCode() {
int hash = 0;
hash += (id != null ? id.hashCode() : 0);
return hash;
}
@Override
public boolean equals(Object object) {
// TODO: Warning - this method won't work in the case the id fields are not set
if (!(object instanceof Categorie)) {
return false;
}
Categorie other = (Categorie) object;
if ((this.id == null && other.id != null) || (this.id != null && !this.id.equals(other.id))) {
return false;
}
return true;
}
@Override
public String toString() {
return "com.mycompany.biblio.model.Categorie[ id=" + id + " ]";
}
}
| Java |
package com.mycompany.biblio.business;
import com.mycompany.biblio.model.Annonce;
import java.util.List;
import javax.ejb.Stateless;
import javax.persistence.*;
/**
*
* @author sifo
*/
@Stateless
public class AnnonceEJB {
// ======================================
// = Attributes =
// ======================================
@PersistenceContext(unitName = "jsfAnnonce")
private EntityManager em;
// ======================================
// = Public Methods =
// ======================================
public List<Annonce> findAll() {
Query query = em.createNamedQuery(Annonce.FIND_ALL);
return query.getResultList();
}
public Annonce create(Annonce annonce) {
em.persist(annonce);
return annonce;
}
public Annonce update(Annonce annonce) {
return em.merge(annonce);
}
public void delete(List<Annonce> list) {
for (Annonce annonce : list) {
delete(annonce);
}
}
public void delete(Annonce annonce) {
em.remove(em.merge(annonce));
}
/* Chercher par mot clé. */
public List<Annonce> findByKeyWord(String key) {
Query query = em.createNamedQuery(Annonce.FIND_BY_KEYWORD);
query.setParameter("key1", "%"+key+"%");
query.setParameter("key2", "%"+key+"%");
return query.getResultList();
}
/* public List<Annonce> findByTypeAnnonce(String type) {
Query query = em.createNamedQuery(Annonce.FIND_BY_TYPE);
query.setParameter("type", "%"+type+"%");
return query.getResultList();
}*/
} | Java |
/*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
package com.mycompany.biblio.business;
import com.mycompany.biblio.model.Annonce;
import com.mycompany.biblio.model.Utilisateur;
import java.util.List;
import javax.ejb.Stateless;
import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;
import javax.persistence.Query;
import org.apache.shiro.SecurityUtils;
/**
*
* @author Haythem & Seif
*/
@Stateless
public class UtilisateurEJB {
// ======================================
// = Attributes =
// ======================================
@PersistenceContext(unitName = "jsfAnnonce")
private EntityManager em;
// ======================================
// = Public Methods =
// ======================================
public Utilisateur create(Utilisateur utilisateur) {
em.persist(utilisateur);
return utilisateur;
}
public Utilisateur update(Utilisateur utilisateur) {
return em.merge(utilisateur);
}
public void delete(List<Utilisateur> list) {
for (Utilisateur user : list) {
delete(user);
}
}
public void delete(Utilisateur user) {
em.remove(em.merge(user));
}
public List<Annonce> getAnnnonces(Utilisateur user){
return user.getAnnonces();
}
public List<Utilisateur> findAll() {
Query query = em.createNamedQuery(Utilisateur.FIND_ALL);
return query.getResultList();
}
public Utilisateur findByUsername(String user){
Query query = em.createNamedQuery(Utilisateur.FIND_BY_USERNAME);
try {
query.setParameter("username", user);
return (Utilisateur) query.getSingleResult();
} catch (Exception e) {
return null;
}
}
public Utilisateur getConnectedUtilisateur(){
String username= (String) SecurityUtils.getSubject().getPrincipal();
return findByUsername(username);
}
}
| Java |
/*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
package com.mycompany.biblio.controller;
import com.mycompany.biblio.business.UtilisateurEJB;
import com.mycompany.biblio.model.Utilisateur;
import java.util.Iterator;
import java.util.List;
import javax.ejb.EJB;
import javax.faces.bean.ManagedBean;
import javax.faces.bean.SessionScoped;
import javax.faces.component.html.HtmlDataTable;
import javax.faces.model.ListDataModel;
/**
*
* @author Haythem
*/
@ManagedBean
@SessionScoped
public class UtilisateurController {
// ======================================
// = Attributes =
// ======================================
@EJB
private UtilisateurEJB utilisateurEJB;
private HtmlDataTable dataTable;
private Utilisateur utilisateur = new Utilisateur();
private ListDataModel utilisateurList; // j'ai utilisé un ListDataModel et pas List parce que cela permet de retrouver l'élément sélectionné dans la liste (pour l'édition d'un livre)
// private ListDataModel annoncesUserList;
private void updateUtilisateurList() {
utilisateurList = new ListDataModel(utilisateurEJB.findAll());
// annoncesUserList = new ListDataModel(utilisateurEJB.getAnnnonces(utilisateur));
}
// ======================================
// = Public Methods =
// ======================================
public String doNew() {
utilisateur = new Utilisateur();
return "newUser.xhtml?faces-redirect=true";
}
public String doCreate() {
utilisateur = utilisateurEJB.create(utilisateur);
return "/index.xhtml?faces-redirect=true";
}
public String doCancel() {
return "/index.xhtml?faces-redirect=true";
}
public String doDelete() {
List<Utilisateur> users = (List<Utilisateur>)utilisateurList.getWrappedData();
utilisateurEJB.delete(onlySelected(users));
updateUtilisateurList();
return "listAnnonces.xhtml?faces-redirect=true";
}
private List<Utilisateur> onlySelected(List<Utilisateur> list) {
for (Iterator<Utilisateur> it = list.iterator(); it.hasNext(); ) {
if (!(it.next().isSelected()))
it.remove();
}
return list;
}
public String doEdit() {
utilisateur = (Utilisateur)utilisateurList.getRowData(); // Voici comment on trouve le livre sélectionné
return "editUtilisateur.xhtml?faces-redirect=true";
}
public String doSave() {
utilisateur = utilisateurEJB.update(utilisateur);
return "listUtilisateurs.xhtml?faces-redirect=true";
}
// ======================================
// = Getters & Setters =
// ======================================
public Utilisateur getUtilisateur() {
return utilisateur;
}
public void setUtilisateur(Utilisateur utilisateur) {
this.utilisateur = utilisateur;
}
public ListDataModel getUtilisateurList() {
updateUtilisateurList();
return utilisateurList;
}
public void setUtilisateurList(ListDataModel utilisateurList) {
this.utilisateurList = utilisateurList;
}
public HtmlDataTable getDataTable() {
return dataTable;
}
public void setDataTable(HtmlDataTable dataTable) {
this.dataTable = dataTable;
}
/* public ListDataModel getAnnoncesUserList() {
return annoncesUserList;
}
public void setAnnoncesUserList(ListDataModel annoncesUserList) {
this.annoncesUserList = annoncesUserList;
}*/
}
| Java |
package com.mycompany.biblio.controller;
import com.mycompany.biblio.business.AnnonceEJB;
import com.mycompany.biblio.business.UtilisateurEJB;
import com.mycompany.biblio.model.Annonce;
import com.mycompany.biblio.model.Utilisateur;
import java.util.ArrayList;
import java.util.List;
import javax.ejb.EJB;
import javax.faces.bean.ManagedBean;
import javax.faces.bean.SessionScoped;
import javax.faces.component.html.HtmlDataTable;
import javax.faces.model.ListDataModel;
/**
*
* @author sifo
*/
@ManagedBean
@SessionScoped
public class AnnonceController {
// ======================================
// = Attributes =
// ======================================
@EJB
private UtilisateurEJB utilisateurEJB;
@EJB
private AnnonceEJB annonceEJB;
private HtmlDataTable dataTable;
private Annonce annonce = new Annonce();
private Utilisateur user;
private ListDataModel annonceList;
private ListDataModel annonceListUser;
private void updateAnnonceList() {
annonceList = new ListDataModel();
user=utilisateurEJB.getConnectedUtilisateur();
annonceListUser = new ListDataModel(user.getAnnonces());
}
// ======================================
// = Public Methods =
// ======================================
public String doNew() {
annonce = new Annonce();
return "newAnnonce.xhtml?faces-redirect=true";
}
public String doCreate() {
user=utilisateurEJB.getConnectedUtilisateur();
annonce.setUtilisateur(user);
user.addAnnonce(annonce);
utilisateurEJB.update(user);
return "listAnnoncesUser.xhtml?faces-redirect=true";
}
public String doCancel() {
return "/index.xhtml?faces-redirect=true";
}
public String doDelete() {
List<Annonce> annonces = (List<Annonce>)annonceListUser.getWrappedData();
List<Annonce> l = new ArrayList<Annonce>();
for(Annonce a : annonces){
if(a.isSelected())
l.add(a);
}
annonceEJB.delete(l);
user.getAnnonces().removeAll(l);
user=utilisateurEJB.update(user);
return "/private/listAnnoncesUser.xhtml?faces-redirect=true";
}
public String doEdit() {
annonce = (Annonce)annonceListUser.getRowData(); // Voici comment on trouve le livre sélectionné
return "/private/editAnnonce.xhtml?faces-redirect=true";
}
public String doSave() {
annonce = annonceEJB.update(annonce);
return "listAnnoncesUser.xhtml?faces-redirect=true";
}
public ListDataModel find(String m,String mot){
if(m.equals("keyWord")){
annonceList = new ListDataModel(annonceEJB.findByKeyWord(mot));
}//else if(m.equals("type"))
//annonceList = new ListDataModel(annonceEJB.findByTypeAnnonce(mot));
return annonceList;
}
// ======================================
// = Getters & Setters =
// ======================================
public Annonce getAnnonce() {
return annonce;
}
public void setAnnonce(Annonce annonce) {
this.annonce = annonce;
}
public Utilisateur getUser() {
return user;
}
public void setUser(Utilisateur user) {
this.user = user;
}
public ListDataModel getAnnonceList() {
//updateAnnonceList();
return annonceList;
}
public void setAnnonceList(ListDataModel annonceList) {
this.annonceList = annonceList;
}
public ListDataModel getAnnonceListUser() {
updateAnnonceList();
return annonceListUser;
}
public void setAnnonceListUser(ListDataModel annonceListUser) {
this.annonceListUser = annonceListUser;
}
public HtmlDataTable getDataTable() {
return dataTable;
}
public void setDataTable(HtmlDataTable dataTable) {
this.dataTable = dataTable;
}
}
| Java |
package com.turbomanage.httpclient;
/**
* An HTTP DELETE request.
*
* @author David M. Chandler
*/
public class HttpDelete extends HttpRequest {
/**
* Constructs an HTTP DELETE request.
*
* @param path Partial URL
* @param params Name-value pairs to be appended to the URL
*/
public HttpDelete(String path, ParameterMap params) {
super(path, params);
this.httpMethod = HttpMethod.DELETE;
}
}
| Java |
/**
* Minimal HTTP client wrapping {@link java.net.HttpURLConnection}.
* The base class for all implementations is {@link com.turbomanage.httpclient.AbstractHttpClient}.
* You can make asynchronous calls using {@link com.turbomanage.httpclient.AsyncHttpClient}.
*
* <p>To get started, see {@link com.turbomanage.httpclient.BasicHttpClient}.</p>
*/
package com.turbomanage.httpclient; | Java |
package com.turbomanage.httpclient;
/**
* Callback passed to an {@link AsyncRequestExecutor} so that the
* calling code can be notified when a request is complete or
* has thrown an exception.
*
* @author David M. Chandler
*/
public abstract class AsyncCallback {
/**
* Called when response is available or max retries exhausted.
*
* @param httpResponse may be null!
*/
public abstract void onComplete(HttpResponse httpResponse);
/**
* Called when a non-recoverable exception has occurred.
* Timeout exceptions are considered recoverable and won't
* trigger this call.
*
* @param e
*/
public void onError(Exception e) {
e.printStackTrace();
}
}
| Java |
package com.turbomanage.httpclient;
import java.io.IOException;
import java.net.HttpURLConnection;
import java.util.List;
import java.util.Map;
/**
* Default {@link RequestLogger} used by {@link BasicHttpClient}. In recent
* versions of Android, log() gets directed to LogCat so this can
* work for Android, too.
* http://stackoverflow.com/questions/2220547/why-doesnt-system
* -out-println-work-in-android
*
* @author David M. Chandler
*/
public class ConsoleRequestLogger implements RequestLogger {
/*
* (non-Javadoc)
* @see com.turbomanage.httpclient.RequestLogger#isLoggingEnabled()
*/
public boolean isLoggingEnabled() {
return true;
}
/* (non-Javadoc)
* @see com.turbomanage.httpclient.RequestLogger#log(java.lang.String)
*/
@Override
public void log(String msg) {
System.out.println(msg);
}
/*
* (non-Javadoc)
* @see com.turbomanage.httpclient.RequestLogger#logRequest(java.net.
* HttpURLConnection, java.lang.Object)
*/
@Override
public void logRequest(HttpURLConnection uc, Object content) throws IOException {
log("=== HTTP Request ===");
log(uc.getRequestMethod() + " " + uc.getURL().toString());
if (content instanceof String) {
log("Content: " + (String) content);
}
logHeaders(uc.getRequestProperties());
}
/*
* (non-Javadoc)
* @see com.turbomanage.httpclient.RequestLogger#logResponse(java.net.
* HttpURLConnection)
*/
@Override
public void logResponse(HttpResponse res) {
if (res != null) {
log("=== HTTP Response ===");
log("Receive url: " + res.getUrl());
log("Status: " + res.getStatus());
logHeaders(res.getHeaders());
log("Content:\n" + res.getBodyAsString());
}
}
/**
* Iterate over request or response headers and log them.
*
* @param map
*/
private void logHeaders(Map<String, List<String>> map) {
if (map != null) {
for (String field : map.keySet()) {
List<String> headers = map.get(field);
for (String header : headers) {
log(field + ":" + header);
}
}
}
}
}
| Java |
/**
* Minimal HTTP client for Android wrapping {@link java.net.HttpURLConnection}.
*
* Main class is {@link com.turbomanage.httpclient.android.AndroidHttpClient}.
*/
package com.turbomanage.httpclient.android; | Java |
package com.turbomanage.httpclient.android;
import android.os.AsyncTask;
import android.os.Build;
import com.turbomanage.httpclient.AsyncHttpClient;
import com.turbomanage.httpclient.RequestHandler;
import com.turbomanage.httpclient.RequestLogger;
import java.net.HttpURLConnection;
/**
* HTTP client for Android providing both synchronous (blocking) and asynchronous
* interfaces so it can be used on or off the UI thread.
*
* <p>Sample usage:</p>
*
* <p>Synchronous (for use off the UI thread in an {@link AsyncTask} or {@link Runnable})</p>
* <pre>
* AndroidHttpClient httpClient = new AndroidHttpClient("http://www.google.com");
* ParameterMap params = httpClient.newParams().add("q", "GOOG");
* HttpResponse httpResponse = httpClient.get("/finance", params);
* System.out.println(httpResponse.getBodyAsString());
* </pre>
*
* <p>Asynchronous (can be used anywhere, automatically wraps in an {@link AsyncTask})</p>
* <pre>
* AndroidHttpClient httpClient = new AndroidHttpClient("http://www.google.com");
* ParameterMap params = httpClient.newParams().add("q", "GOOG");
* httpClient.setMaxRetries(3);
* httpClient.get("/finance", params, new AsyncCallback() {
* public void onComplete(HttpResponse httpResponse) {
* System.out.println(httpResponse.getBodyAsString());
* }
* public void onError(Exception e) {
* e.printStackTrace();
* }
* });
* </pre>
*
* @author David M. Chandler
*/
public class AndroidHttpClient extends AsyncHttpClient {
static {
disableConnectionReuseIfNecessary();
// See http://code.google.com/p/basic-http-client/issues/detail?id=8
if (Build.VERSION.SDK_INT > 8)
ensureCookieManager();
}
/**
* Constructs a new client with empty baseUrl. When used this way, the path
* passed to a request method must be the complete URL.
*/
public AndroidHttpClient() {
this("");
}
/**
* Constructs a new client using the default {@link RequestHandler} and
* {@link RequestLogger}.
*/
public AndroidHttpClient(String baseUrl) {
super(new AsyncTaskFactory(), baseUrl);
}
/**
* Constructs a client with baseUrl and custom {@link RequestHandler}.
*
* @param baseUrl
* @param requestHandler
*/
public AndroidHttpClient(String baseUrl, RequestHandler requestHandler) {
super(new AsyncTaskFactory(), baseUrl, requestHandler);
}
/**
* Work around bug in {@link HttpURLConnection} on older versions of
* Android.
* http://android-developers.blogspot.com/2011/09/androids-http-clients.html
*/
private static void disableConnectionReuseIfNecessary() {
// HTTP connection reuse which was buggy pre-froyo
if (Integer.parseInt(Build.VERSION.SDK) < Build.VERSION_CODES.FROYO) {
System.setProperty("http.keepAlive", "false");
}
}
}
| Java |
package com.turbomanage.httpclient.android;
import android.os.AsyncTask;
import com.turbomanage.httpclient.AsyncCallback;
import com.turbomanage.httpclient.AsyncHttpClient;
import com.turbomanage.httpclient.AsyncRequestExecutor;
import com.turbomanage.httpclient.AsyncRequestExecutorFactory;
/**
* Android-specific factory produces an {@link AsyncTask} that can
* execute an HTTP request.
*
* @author David M. Chandler
*/
public class AsyncTaskFactory implements AsyncRequestExecutorFactory {
/* (non-Javadoc)
* @see com.turbomanage.httpclient.AsyncRequestExecutorFactory#getAsyncRequestExecutor(com.turbomanage.httpclient.AsyncHttpClient, com.turbomanage.httpclient.AsyncCallback)
*/
@Override
public AsyncRequestExecutor getAsyncRequestExecutor(AsyncHttpClient client,
AsyncCallback callback) {
return new DoHttpRequestTask(client, callback);
}
}
| Java |
package com.turbomanage.httpclient.android;
import android.os.AsyncTask;
import com.turbomanage.httpclient.AsyncCallback;
import com.turbomanage.httpclient.AsyncHttpClient;
import com.turbomanage.httpclient.AsyncRequestExecutor;
import com.turbomanage.httpclient.HttpRequest;
import com.turbomanage.httpclient.HttpResponse;
/**
* AsyncTask that wraps an HttpRequest. Designed to be used in conjunction with
* {@link AsyncHttpClient} so that requests can be made off the UI thread.
*
* @author David M. Chandler
*/
public class DoHttpRequestTask extends AsyncTask<HttpRequest, Void, HttpResponse> implements AsyncRequestExecutor {
private AsyncHttpClient client;
private AsyncCallback callback;
private Exception savedException;
/**
* Construct a new task with a callback to invoke when the request completes
* or fails.
*
* @param callback
*/
public DoHttpRequestTask(AsyncHttpClient httpClient, AsyncCallback callback) {
this.client = httpClient;
this.callback = callback;
}
@Override
protected HttpResponse doInBackground(HttpRequest... params) {
try {
if (params != null && params.length > 0) {
HttpRequest httpRequest = params[0];
return client.tryMany(httpRequest);
}
else {
throw new IllegalArgumentException(
"DoHttpRequestTask takes exactly one argument of type HttpRequest");
}
} catch (Exception e) {
this.savedException = e;
cancel(true);
}
return null;
}
@Override
protected void onPostExecute(HttpResponse result) {
callback.onComplete(result);
}
@Override
protected void onCancelled() {
callback.onError(this.savedException);
}
/**
* Needed in order for this Task class to implement the {@link AsyncRequestExecutor} interface.
*
* @see com.turbomanage.httpclient.AsyncRequestExecutor#execute(com.turbomanage.httpclient.HttpRequest)
*/
@Override
public void execute(HttpRequest httpRequest) {
super.execute(httpRequest);
}
}
| Java |
package com.turbomanage.httpclient;
/**
* Minimal HTTP client that facilitates simple GET, POST, PUT, and DELETE
* requests. To implement buffering, streaming, or set other request properties,
* set an alternate {@link RequestHandler}.
*
* <p>Sample usage:</p>
* <pre>
* BasicHttpClient httpClient = new BasicHttpClient("http://www.google.com");
* ParameterMap params = httpClient.newParams().add("q", "GOOG");
* HttpResponse httpResponse = httpClient.get("/finance", params);
* System.out.println(httpResponse.getBodyAsString());
* </pre>
*
* @author David M. Chandler
*/
public class BasicHttpClient extends AbstractHttpClient {
static {
ensureCookieManager();
}
/**
* Constructs the default client with empty baseUrl.
*/
public BasicHttpClient() {
this("");
}
/**
* Constructs the default client with baseUrl.
*
* @param baseUrl
*/
public BasicHttpClient(String baseUrl) {
this(baseUrl, new BasicRequestHandler() {
});
}
/**
* Constructs a client with baseUrl and custom {@link RequestHandler}.
*
* @param baseUrl
* @param requestHandler
*/
public BasicHttpClient(String baseUrl, RequestHandler requestHandler) {
super(baseUrl, requestHandler);
}
}
| Java |
package com.turbomanage.httpclient;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.ConnectException;
import java.net.HttpURLConnection;
import java.net.SocketTimeoutException;
/**
* Interface that defines the request lifecycle used by {@link AbstractHttpClient}.
* RequestHandler is composed of many sub-interfaces so that each handler can
* be set independently if needed. You can provide your own implementation by providing
* it in the client constructor.
*
* See {@link BasicRequestHandler} for a simple implementation.
*
* @author David M. Chandler
*/
public interface RequestHandler {
public static final String UTF8 = "UTF-8";
/**
* Opens an HTTP connection.
*
* @param url Absolute URL
* @return an open {@link HttpURLConnection}
* @throws IOException
*/
HttpURLConnection openConnection(String url) throws IOException;
/**
* Prepares a previously opened connection. It is called before
* writing to the OutputStream, so it's possible to set or
* modify connection properties. This is where to set the request method,
* content type, timeouts, etc.
*
* @param urlConnection An open connection
* @param httpMethod The request method
* @param contentType MIME type
* @throws IOException
*/
void prepareConnection(HttpURLConnection urlConnection, HttpMethod httpMethod,
String contentType) throws IOException;
/**
* Optionally opens the output stream. This hook was added
* mainly for symmetry with openInput(), but may be useful
* in rare cases to check or modify connection properties
* before writing. The HTTP response code on urlConnection
* is not yet populated at the time this method is invoked.
* There is no need to catch exceptions as they'll be handled
* by {@link AbstractHttpClient}. Any exceptions caught should
* be rethrown to enable standard handling.
*
* @param urlConnection
* @return open OutputStream or null
*/
OutputStream openOutput(HttpURLConnection urlConnection) throws IOException;
/**
* Writes to an open, prepared connection. This method is only called when
* {@link HttpURLConnection#getDoOutput()} is true and there is non-null content.
*
* @param out An open {@link OutputStream}
* @param content Data to send with the request
* @throws IOException
*/
void writeStream(OutputStream out, byte[] content) throws IOException;
/**
* Optionally opens the input stream. May want to check the HTTP
* response code first to avoid unnecessarily opening the stream.
* There is no need to catch exceptions as they'll be handled
* by {@link AbstractHttpClient}. Any exceptions caught should
* be rethrown to enable standard handling.
*
* @param urlConnection
* @return open InputStream or null
*/
InputStream openInput(HttpURLConnection urlConnection) throws IOException;
/**
* Reads from the InputStream.
*
* @param in An open {@link InputStream}
* @return Object contained in the response
* @throws IOException
*/
byte[] readStream(InputStream in) throws IOException;
/**
* Invoked for any exceptions. Of particular interest are
* {@link ConnectException}
* {@link SocketTimeoutException}
*
* @param e The exception that was thrown
* @return true if recoverable. Async clients may use this to try again
*/
boolean onError(HttpRequestException e);
}
| Java |
package com.turbomanage.httpclient;
/**
* An HTTP GET request.
*
* @author David M. Chandler
*/
public class HttpGet extends HttpRequest {
/**
* Constructs an HTTP GET request.
*
* @param path Partial URL
* @param params Name-value pairs to be appended to the URL
*/
public HttpGet(String path, ParameterMap params) {
super(path, params);
this.httpMethod = HttpMethod.GET;
}
}
| Java |
package com.turbomanage.httpclient;
/**
* An HTTP POST request.
*
* @author David M. Chandler
*/
public class HttpPost extends HttpRequest {
/**
* Constructs an HTTP POST request with name-value pairs to
* be sent in the request BODY.
*
* @param path Partial URL
* @param params Name-value pairs to be sent in request BODY
*/
public HttpPost(String path, ParameterMap params) {
super(path, null);
this.httpMethod = HttpMethod.POST;
this.path = path;
this.contentType = URLENCODED;
if (params != null) {
this.content = params.urlEncodedBytes();
}
}
/**
* Constructs an HTTP POST request with arbitrary content.
* If params is non-null, the name-value pairs will be appended to the QUERY STRING
* while the content is sent in the request BODY.
* This is not a common use case and is therefore not represented in the post()
* methods in {@link AbstractHttpClient} or {@link AsyncHttpClient},
* but is nevertheless possible using this constructor.
*
* @param path Partial URL
* @param params Optional name-value pairs to be appended to QUERY STRING
* @param contentType MIME type
* @param data Content to be sent in the request body
*/
public HttpPost(String path, ParameterMap params, String contentType, byte[] data) {
super(path, params);
this.httpMethod = HttpMethod.POST;
this.contentType = contentType;
this.content = data;
}
}
| Java |
package com.turbomanage.httpclient;
import java.io.IOException;
import java.net.HttpURLConnection;
/**
* HTTP request logger used by {@link BasicHttpClient}.
*
* @author David M. Chandler
*/
public interface RequestLogger {
/**
* Determine whether requests should be logged.
*
* @return true if enabled
*/
boolean isLoggingEnabled();
/**
* Writes a log message.
*
* @param msg
*/
void log(String msg);
/**
* Log the HTTP request and content to be sent with the request.
*
* @param urlConnection
* @param content
* @throws IOException
*/
void logRequest(HttpURLConnection urlConnection, Object content) throws IOException;
/**
* Logs the HTTP response.
*
* @param httpResponse
* @throws IOException
*/
void logResponse(HttpResponse httpResponse);
}
| Java |
package com.turbomanage.httpclient;
/**
* Factory that provides an async wrapper for a request, that is, something
* that can execute a request asynchronously.
*
* @author David M. Chandler
*/
public interface AsyncRequestExecutorFactory {
AsyncRequestExecutor getAsyncRequestExecutor(AsyncHttpClient client, AsyncCallback callback);
}
| Java |
package com.turbomanage.httpclient;
/**
* An HTTP PUT request.
*
* @author David M. Chandler
*/
public class HttpPut extends HttpRequest {
/**
* Constructs an HTTP PUT request with name-value pairs to
* be sent in the request BODY.
*
* @param path Partial URL
* @param params Name-value pairs to be sent in request BODY
*/
public HttpPut(String path, ParameterMap params) {
super(path, null);
this.httpMethod = HttpMethod.PUT;
this.path = path;
this.contentType = URLENCODED;
if (params != null) {
this.content = params.urlEncodedBytes();
}
}
/**
* Constructs an HTTP PUT request with arbitrary content.
*
* @param path Partial URL
* @param params Optional, appended to query string
* @param contentType MIME type
* @param data Content to be sent in the request body
*/
public HttpPut(String path, ParameterMap params, String contentType, byte[] data) {
super(path, params);
this.httpMethod = HttpMethod.PUT;
this.contentType = contentType;
this.content = data;
}
}
| Java |
package com.turbomanage.httpclient;
/**
* An HTTP HEAD request.
*
* @author David M. Chandler
*/
public class HttpHead extends HttpRequest {
/**
* Constructs an HTTP HEAD request.
*
* @param path Partial URL
* @param params Name-value pairs to be appended to the URL
*/
public HttpHead(String path, ParameterMap params) {
super(path, params);
this.httpMethod = HttpMethod.HEAD;
}
}
| Java |
package com.turbomanage.httpclient;
import com.turbomanage.httpclient.android.DoHttpRequestTask;
/**
* An HTTP client that completes all requests asynchronously using
* {@link DoHttpRequestTask}. All methods take a callback argument which is
* passed to the task and whose methods are invoked when the request completes
* or throws on exception.
*
* @author David M. Chandler
*/
public class AsyncHttpClient extends AbstractHttpClient {
static int[] fib = new int[20];
static {
// Compute Fibonacci series for backoff
for (int i=0; i<20; i++) {
fib[i] = i<2 ? i : fib[i-2] + fib[i-1];
}
}
// Configurable default
private int maxRetries = 3;
/*
* The factory that will be used to obtain an async wrapper for the
* request. Usually set in a subclass that provides a platform-specific
* async wrapper such as a new thread or Android AsyncTask.
*/
protected final AsyncRequestExecutorFactory execFactory;
/**
* Constructs a new client with factory and empty baseUrl.
*
* @param factory
*/
public AsyncHttpClient(AsyncRequestExecutorFactory factory) {
this(factory, "");
}
/**
* Constructs a new client with factory and baseUrl.
*
* @param factory
* @param baseUrl
*/
public AsyncHttpClient(AsyncRequestExecutorFactory factory, String baseUrl) {
this(factory, baseUrl, new BasicRequestHandler() {
});
}
/**
* Constructs a new client with factory, baseUrl, and custom {@link RequestHandler}.
*
* @param factory
* @param baseUrl
* @param handler
*/
public AsyncHttpClient(AsyncRequestExecutorFactory factory, String baseUrl, RequestHandler handler) {
super(baseUrl, handler);
this.execFactory = factory;
}
/**
* Execute a HEAD request and invoke the callback on completion. The supplied
* parameters are URL encoded and sent as the query string.
*
* @param path
* @param params
* @param callback
*/
public void head(String path, ParameterMap params, AsyncCallback callback) {
HttpRequest req = new HttpHead(path, params);
executeAsync(req, callback);
}
/**
* Execute a GET request and invoke the callback on completion. The supplied
* parameters are URL encoded and sent as the query string.
*
* @param path
* @param params
* @param callback
*/
public void get(String path, ParameterMap params, AsyncCallback callback) {
HttpRequest req = new HttpGet(path, params);
executeAsync(req, callback);
}
/**
* Execute a POST request with parameter map and invoke the callback on
* completion.
*
* @param path
* @param params
* @param callback
*/
public void post(String path, ParameterMap params, AsyncCallback callback) {
HttpRequest req = new HttpPost(path, params);
executeAsync(req, callback);
}
/**
* Execute a POST request with a chunk of data and invoke the callback on
* completion.
*
* To include name-value pairs in the query string, add them to the path
* argument or use the constructor in {@link HttpPost}. This is not a
* common use case, so it is not included here.
*
* @param path
* @param contentType
* @param data
* @param callback
*/
public void post(String path, String contentType, byte[] data, AsyncCallback callback) {
HttpPost req = new HttpPost(path, null, contentType, data);
executeAsync(req, callback);
}
/**
* Execute a PUT request with the supplied content and invoke the callback
* on completion.
*
* To include name-value pairs in the query string, add them to the path
* argument or use the constructor in {@link HttpPut}. This is not a
* common use case, so it is not included here.
*
* @param path
* @param contentType
* @param data
* @param callback
*/
public void put(String path, String contentType, byte[] data, AsyncCallback callback) {
HttpRequest req = new HttpPut(path, null, contentType, data);
executeAsync(req, callback);
}
/**
* Execute a DELETE request and invoke the callback on completion. The
* supplied parameters are URL encoded and sent as the query string.
*
* @param path
* @param params
* @param callback
*/
public void delete(String path, ParameterMap params, AsyncCallback callback) {
HttpDelete req = new HttpDelete (path, params);
executeAsync(req, callback);
}
/**
* Execute an {@link HttpRequest} asynchronously. Uses a factory to obtain a
* suitable async wrapper in order to decouple from Android.
*
* @param httpRequest
* @param callback
*/
protected void executeAsync(HttpRequest httpRequest, AsyncCallback callback) {
AsyncRequestExecutor executor = execFactory.getAsyncRequestExecutor(this, callback);
executor.execute(httpRequest);
}
/**
* Tries several times until successful or maxRetries exhausted.
* Must throw exception in order for the async process to forward
* it to the callback's onError method.
*
* @param httpRequest
* @return Response object, may be null
* @throws HttpRequestException
*/
public HttpResponse tryMany(HttpRequest httpRequest) throws HttpRequestException {
int numTries = 0;
long startTime = System.currentTimeMillis();
HttpResponse res = null;
while (numTries < maxRetries) {
try {
setConnectionTimeout(getNextTimeout(numTries));
if (requestLogger.isLoggingEnabled()) {
requestLogger.log((numTries+1) + "of" + maxRetries + ", trying " + httpRequest.getPath());
}
startTime = System.currentTimeMillis();
res = doHttpMethod(httpRequest.getPath(),
httpRequest.getHttpMethod(), httpRequest.getContentType(),
httpRequest.getContent());
if (res != null) {
return res;
}
} catch (HttpRequestException e) {
if (isTimeoutException(e, startTime) && numTries < (maxRetries-1)) {
// Fall through loop, retry
// On last attempt, throw the exception regardless
} else {
boolean isRecoverable = requestHandler.onError(e);
if (isRecoverable && numTries < (maxRetries-1)) {
try {
// Wait a while and fall through loop to try again
Thread.sleep(connectionTimeout);
} catch (InterruptedException ie) {
// App stopping, perhaps? No point in further retries
throw e;
}
} else {
// Not recoverable or last attempt, time to bail
throw e;
}
}
}
numTries++;
}
return null;
}
/**
* Implements exponential backoff using the Fibonacci series, which
* has the effect of backing off with a multiplier of ~1.618
* (the golden mean) instead of 2, which is rather boring.
*
* @param numTries Current number of attempts completed
* @return Connection timeout in ms for next attempt
*/
protected int getNextTimeout(int numTries) {
// For n=0,1,2,3 returns 1000,2000,3000,5000
return 1000 * fib[numTries + 2];
}
/**
* Set maximum number of retries to attempt, capped at 18. On the
* 18th retry, the connection timeout will be 4,181 sec = 1 hr 9 min.
*
* @param maxRetries
*/
public void setMaxRetries(int maxRetries) {
if (maxRetries < 1 || maxRetries > 18) {
throw new IllegalArgumentException("Maximum retries must be between 1 and 18");
}
this.maxRetries = maxRetries;
}
} | Java |
package com.turbomanage.httpclient;
import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.util.Collection;
import java.util.HashMap;
import java.util.Map;
import java.util.Set;
/**
* Parameter map knows offers convenience methods for chaining add()s
* as well as URL encoding.
*
* @author David M. Chandler
*/
public class ParameterMap implements Map<String, String> {
private Map<String, String> map = new HashMap<String, String>();
@Override
public void clear() {
map.clear();
}
@Override
public boolean containsKey(Object key) {
return map.containsKey(key);
}
@Override
public boolean containsValue(Object value) {
return map.containsValue(value);
}
@Override
public Set<java.util.Map.Entry<String, String>> entrySet() {
return map.entrySet();
}
@Override
public String get(Object key) {
return map.get(key);
}
@Override
public boolean isEmpty() {
return map.isEmpty();
}
@Override
public Set<String> keySet() {
return map.keySet();
}
@Override
public String put(String key, String value) {
return map.put(key, value);
}
@Override
public void putAll(Map<? extends String, ? extends String> arg) {
map.putAll(arg);
}
@Override
public String remove(Object key) {
return map.remove(key);
}
@Override
public int size() {
return map.size();
}
@Override
public Collection<String> values() {
return map.values();
}
/**
* Convenience method returns this class so multiple calls can be chained.
*
* @param name
* @param value
* @return This map
*/
public ParameterMap add(String name, String value) {
map.put(name, value);
return this;
}
/**
* Returns URL encoded data
*
* @return URL encoded String
*/
public String urlEncode() {
StringBuilder sb = new StringBuilder();
for (String key : map.keySet()) {
if (sb.length() > 0) {
sb.append("&");
}
sb.append(key);
String value = map.get(key);
if (value != null) {
sb.append("=");
try {
sb.append(URLEncoder.encode(value, RequestHandler.UTF8));
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
}
}
}
return sb.toString();
}
/**
* Return a URL encoded byte array in UTF-8 charset.
*
* @return URL encoded bytes
*/
public byte[] urlEncodedBytes() {
byte[] bytes = null;
try {
bytes = this.urlEncode().getBytes(RequestHandler.UTF8);
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
}
return bytes;
}
}
| Java |
package com.turbomanage.httpclient;
/**
* Enumerated type that represents an HTTP request method.
* Besides the method name, it determines whether the client
* should do the output phase of the connection.
*
* @author David M. Chandler
*/
public enum HttpMethod {
GET(true, false),
POST(true, true),
PUT(true, true),
DELETE(true, false),
HEAD(false, false);
private boolean doInput;
private boolean doOutput;
private HttpMethod(boolean doInput, boolean doOutput) {
this.doInput = doInput;
this.doOutput = doOutput;
}
public boolean getDoInput() {
return doInput;
}
/**
* Whether the client should do the write phase, or just read
*
* @return doOutput
*/
public boolean getDoOutput() {
return this.doOutput;
}
/**
* Accessor method.
*
* @return HTTP method name (GET, PUT, POST, DELETE)
*/
public String getMethodName() {
return this.toString();
}
}
| Java |
package com.turbomanage.httpclient;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.HttpURLConnection;
import java.net.URL;
/**
* Default {@link RequestHandler} used by {@link BasicHttpClient}. It is
* intended to be used for simple requests with small amounts of data only (a
* few kB), as it does no buffering, chunking, streaming, etc. Only character
* set supported is UTF-8. Only {@link String} content is supported. All
* responses are treated as {@link String}s. This class is abstract so that
* it can be easily extended in an anonymous inner class when constructing
* a client.
*
* @author David M. Chandler
*/
public abstract class BasicRequestHandler implements RequestHandler {
private final RequestLogger logger;
/**
* Constructs a handler with default logger.
*/
public BasicRequestHandler() {
this(new ConsoleRequestLogger());
}
/**
* Constructs a handler with supplied logger.
*
* @param logger
*/
public BasicRequestHandler(RequestLogger logger) {
this.logger = logger;
}
@Override
public HttpURLConnection openConnection(String urlString) throws IOException {
URL url = new URL(urlString);
HttpURLConnection uc = (HttpURLConnection) url.openConnection();
return uc;
}
@Override
public void prepareConnection(HttpURLConnection urlConnection, HttpMethod httpMethod,
String contentType) throws IOException {
// Configure connection for request method
urlConnection.setRequestMethod(httpMethod.getMethodName());
urlConnection.setDoOutput(httpMethod.getDoOutput());
urlConnection.setDoInput(httpMethod.getDoInput());
if (contentType != null) {
urlConnection.setRequestProperty("Content-Type", contentType);
}
// Set additional properties
urlConnection.setRequestProperty("Accept-Charset", UTF8);
}
@Override
public OutputStream openOutput(HttpURLConnection urlConnection)
throws IOException {
return urlConnection.getOutputStream();
}
@Override
public void writeStream(OutputStream out, byte[] content) throws IOException {
out.write(content);
}
@Override
public InputStream openInput(HttpURLConnection urlConnection)
throws IOException {
return urlConnection.getInputStream();
}
@Override
public byte[] readStream(InputStream in) throws IOException {
int nRead;
byte[] data = new byte[16384];
ByteArrayOutputStream buffer = new ByteArrayOutputStream();
while ((nRead = in.read(data)) != -1) {
buffer.write(data, 0, nRead);
}
buffer.flush();
return buffer.toByteArray();
}
@Override
public boolean onError(HttpRequestException e) {
HttpResponse res = e.getHttpResponse();
if (logger.isLoggingEnabled()) {
logger.log("BasicRequestHandler.onError got");
e.printStackTrace();
}
if (res != null) {
int status = res.getStatus();
if (status > 0) {
// Perhaps a 404, 501, or something that will be fixed later
return true;
}
}
// Connection refused, host unreachable, etc.
return false;
}
}
| Java |
package com.turbomanage.httpclient;
import java.io.IOException;
import java.net.HttpURLConnection;
import java.util.List;
import java.util.Map;
/**
* Minimal representation of the raw HTTP response copied from {@link HttpURLConnection}.
*
* @author David M. Chandler
*/
public class HttpResponse {
private int status;
private String url;
private Map<String, List<String>> headers;
private byte[] body;
public HttpResponse(HttpURLConnection urlConnection, byte[] body) {
try {
this.status = urlConnection.getResponseCode();
this.url = urlConnection.getURL().toString();
} catch (IOException e) {
e.printStackTrace();
}
this.headers = urlConnection.getHeaderFields();
this.body = body;
}
public int getStatus() {
return status;
}
public String getUrl() {
return url;
}
public Map<String, List<String>> getHeaders() {
return headers;
}
public byte[] getBody() {
return body;
}
public String getBodyAsString() {
if (body != null) {
return new String(body);
}
return null;
}
}
| Java |
package com.turbomanage.httpclient;
/**
* Describes a class that can execute a request asynchronously. These are
* produced by a {@link AsyncRequestExecutorFactory}.
*
* @author David M. Chandler
*/
public interface AsyncRequestExecutor {
void execute(HttpRequest httpRequest);
}
| Java |
package com.turbomanage.httpclient;
/**
* Custom exception class that holds an {@link HttpResponse}.
* This allows upstream code to receive an HTTP status code and
* any content received as well as the underlying exception.
*
* @author David M. Chandler
*/
public class HttpRequestException extends Exception {
private static final long serialVersionUID = -2413629666163901633L;
private HttpResponse httpResponse;
/**
* Constructs the exception with
*
* @param e
* @param httpResponse
*/
public HttpRequestException(Exception e, HttpResponse httpResponse) {
super(e);
this.httpResponse = httpResponse;
}
/**
* Access the response.
*
* @return Response object
*/
public HttpResponse getHttpResponse() {
return httpResponse;
}
}
| Java |
package com.turbomanage.httpclient;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.CookieHandler;
import java.net.CookieManager;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.Map;
import java.util.TreeMap;
/**
* Lightweight HTTP client that facilitates GET, POST, PUT, and DELETE requests
* using {@link HttpURLConnection}. Extend this class to support specialized
* content and response types (see {@link BasicHttpClient} for an example). To
* enable streaming, buffering, or other types of readers / writers, set an
* alternate {@link RequestHandler}.
*
* @author David M. Chandler
*/
public abstract class AbstractHttpClient {
public static final String URLENCODED = "application/x-www-form-urlencoded;charset=UTF-8";
public static final String MULTIPART = "multipart/form-data";
/**
* An unrestricted SSL hostname verifier that does not check for a
* certificate.
*/
private static final HostnameVerifier HOSTNAME_VERIFIER_UNRESTRICTED = new HostnameVerifier() {
public boolean verify(String hostname, SSLSession session) {
return true;
}
};
protected String baseUrl = "";
protected RequestLogger requestLogger = new ConsoleRequestLogger();
protected final RequestHandler requestHandler;
private Map<String, String> requestHeaders = new TreeMap<String, String>();
/**
* Default 2s, deliberately short. If you need longer, you should be using
* {@link AsyncHttpClient} instead.
*/
protected int connectionTimeout = 2000;
/**
* Default 8s, reasonably short if accidentally called from the UI thread.
*/
protected int readTimeout = 8000;
/**
* Indicates connection status, used by timeout logic
*/
private boolean isConnected;
/**
* Constructs a client with empty baseUrl. Prevent sub-classes from calling
* this as it doesn't result in an instance of the subclass.
*/
@SuppressWarnings("unused")
private AbstractHttpClient() {
this("");
}
/**
* Constructs a new client with base URL that will be appended in the
* request methods. It may be empty or any part of a URL. Examples:
* http://turbomanage.com http://turbomanage.com:987
* http://turbomanage.com:987/resources
*
* @param baseUrl
*/
private AbstractHttpClient(String baseUrl) {
this(baseUrl, new BasicRequestHandler() {
});
}
/**
* Construct a client with baseUrl and RequestHandler.
*
* @param baseUrl
* @param requestHandler
*/
public AbstractHttpClient(String baseUrl, RequestHandler requestHandler) {
this.baseUrl = baseUrl;
this.requestHandler = requestHandler;
}
/**
* Execute a HEAD request and return the response. The supplied parameters
* are URL encoded and sent as the query string.
*
* @param path
* @param params
* @return Response object
*/
public HttpResponse head(String path, ParameterMap params) {
return execute(new HttpHead(path, params));
}
/**
* Execute a GET request and return the response. The supplied parameters
* are URL encoded and sent as the query string.
*
* @param path
* @param params
* @return Response object
*/
public HttpResponse get(String path, ParameterMap params) {
return execute(new HttpGet(path, params));
}
/**
* Execute a POST request with parameter map and return the response.
*
* @param path
* @param params
* @return Response object
*/
public HttpResponse post(String path, ParameterMap params) {
return execute(new HttpPost(path, params));
}
/**
* Execute a POST request with a chunk of data and return the response.
*
* To include name-value pairs in the query string, add them to the path
* argument or use the constructor in {@link HttpPost}. This is not a
* common use case, so it is not included here.
*
* @param path
* @param contentType
* @param data
* @return Response object
*/
public HttpResponse post(String path, String contentType, byte[] data) {
return execute(new HttpPost(path, null, contentType, data));
}
/**
* Execute a PUT request with the supplied content and return the response.
*
* To include name-value pairs in the query string, add them to the path
* argument or use the constructor in {@link HttpPut}. This is not a
* common use case, so it is not included here.
*
* @param path
* @param contentType
* @param data
* @return Response object
*/
public HttpResponse put(String path, String contentType, byte[] data) {
return execute(new HttpPut(path, null, contentType, data));
}
/**
* Execute a DELETE request and return the response. The supplied parameters
* are URL encoded and sent as the query string.
*
* @param path
* @param params
* @return Response object
*/
public HttpResponse delete(String path, ParameterMap params) {
return execute(new HttpDelete(path, params));
}
/**
* This method wraps the call to doHttpMethod and invokes the custom error
* handler in case of exception. It may be overridden by other clients such
* {@link AsyncHttpClient} in order to wrap the exception handling for
* purposes of retries, etc.
*
* @param httpRequest
* @return Response object (may be null if request did not complete)
*/
public HttpResponse execute(HttpRequest httpRequest) {
HttpResponse httpResponse = null;
try {
httpResponse = doHttpMethod(httpRequest.getPath(),
httpRequest.getHttpMethod(), httpRequest.getContentType(),
httpRequest.getContent());
} catch (HttpRequestException hre) {
requestHandler.onError(hre);
} catch (Exception e) {
// In case a RuntimeException has leaked out, wrap it in HRE
requestHandler.onError(new HttpRequestException(e, httpResponse));
}
return httpResponse;
}
/**
* This is the method that drives each request. It implements the request
* lifecycle defined as open, prepare, write, read. Each of these methods in
* turn delegates to the {@link RequestHandler} associated with this client.
*
* @param path Whole or partial URL string, will be appended to baseUrl
* @param httpMethod Request method
* @param contentType MIME type of the request
* @param content Request data
* @return Response object
* @throws HttpRequestException
*/
@SuppressWarnings("finally")
protected HttpResponse doHttpMethod(String path, HttpMethod httpMethod, String contentType,
byte[] content) throws HttpRequestException {
HttpURLConnection uc = null;
HttpResponse httpResponse = null;
try {
isConnected = false;
if (isSecureConnection) {
trustAllHosts();
}
uc = openConnection(path);
if (isSecureConnection) {
prepareSecureConnection(uc);
}
prepareConnection(uc, httpMethod, contentType);
appendRequestHeaders(uc);
if (requestLogger.isLoggingEnabled()) {
requestLogger.logRequest(uc, content);
}
// Explicit connect not required, but lets us easily determine when
// possible timeout exception occurred
uc.connect();
isConnected = true;
if (uc.getDoOutput() && content != null) {
writeOutputStream(uc, content);
}
if (uc.getDoInput()) {
httpResponse = readInputStream(uc);
} else {
httpResponse = new HttpResponse(uc, null);
}
} catch (Exception e) {
// Try reading the error stream to populate status code such as 404
try {
httpResponse = readErrorStream(uc);
} catch (Exception ee) {
e.printStackTrace();
// Must catch IOException, but swallow to show first cause only
} finally {
// if status available, return it else throw
if (httpResponse != null && httpResponse.getStatus() > 0) {
return httpResponse;
}
throw new HttpRequestException(e, httpResponse);
}
} finally {
if (requestLogger.isLoggingEnabled()) {
requestLogger.logResponse(httpResponse);
}
if (uc != null) {
uc.disconnect();
}
}
return httpResponse;
}
/**
* Validates a URL and opens a connection. This does not actually connect
* to a server, but rather opens it on the client only to allow writing
* to begin. Delegates the open operation to the {@link RequestHandler}.
*
* @param path Appended to this client's baseUrl
* @return An open connection (or null)
* @throws IOException
*/
protected HttpURLConnection openConnection(String path) throws IOException {
String requestUrl = baseUrl + path;
try {
new URL(requestUrl);
} catch (MalformedURLException e) {
throw new IllegalArgumentException(requestUrl + " is not a valid URL", e);
}
return requestHandler.openConnection(requestUrl);
}
protected void prepareSecureConnection(HttpURLConnection httpConnection) {
if ((httpConnection == null) || !(httpConnection instanceof HttpsURLConnection)) {
return;
}
HttpsURLConnection httpsConnection = (HttpsURLConnection) httpConnection;
httpsConnection.setHostnameVerifier(HOSTNAME_VERIFIER_UNRESTRICTED);
}
protected void prepareConnection(HttpURLConnection urlConnection, HttpMethod httpMethod,
String contentType) throws IOException {
urlConnection.setConnectTimeout(connectionTimeout);
urlConnection.setReadTimeout(readTimeout);
requestHandler.prepareConnection(urlConnection, httpMethod, contentType);
}
/**
* Append all headers added with {@link #addHeader(String, String)} to the
* request.
*
* @param urlConnection
*/
private void appendRequestHeaders(HttpURLConnection urlConnection) {
for (String name : requestHeaders.keySet()) {
String value = requestHeaders.get(name);
urlConnection.setRequestProperty(name, value);
}
}
/**
* Writes the request to the server. Delegates I/O to the {@link RequestHandler}.
*
* @param urlConnection
* @param content to be written
* @return HTTP status code
* @throws Exception in order to force calling code to deal with possible
* NPEs also
*/
protected int writeOutputStream(HttpURLConnection urlConnection, byte[] content) throws Exception {
OutputStream out = null;
try {
out = requestHandler.openOutput(urlConnection);
if (out != null) {
requestHandler.writeStream(out, content);
}
return urlConnection.getResponseCode();
} finally {
// catch not necessary since method throws Exception
if (out != null) {
try {
out.close();
} catch (Exception e) {
// Swallow to show first cause only
}
}
}
}
/**
* Reads the input stream. Delegates I/O to the {@link RequestHandler}.
*
* @param urlConnection
* @return HttpResponse, may be null
* @throws Exception
*/
protected HttpResponse readInputStream(HttpURLConnection urlConnection) throws Exception {
InputStream in = null;
byte[] responseBody = null;
try {
in = requestHandler.openInput(urlConnection);
if (in != null) {
responseBody = requestHandler.readStream(in);
}
return new HttpResponse(urlConnection, responseBody);
} finally {
if (in != null) {
try {
in.close();
} catch (Exception e) {
// Swallow to avoid dups
}
}
}
}
/**
* Reads the error stream to get an HTTP status code like 404.
* Delegates I/O to the {@link RequestHandler}.
*
* @param urlConnection
* @return HttpResponse, may be null
* @throws Exception
*/
protected HttpResponse readErrorStream(HttpURLConnection urlConnection) throws Exception {
InputStream err = null;
byte[] responseBody = null;
try {
err = urlConnection.getErrorStream();
if (err != null) {
responseBody = requestHandler.readStream(err);
}
return new HttpResponse(urlConnection, responseBody);
} finally {
if (err != null) {
try {
err.close();
} catch (Exception e) {
// Swallow to avoid dups
}
}
}
}
/**
* Convenience method creates a new ParameterMap to hold query params
*
* @return Parameter map
*/
public ParameterMap newParams() {
return new ParameterMap();
}
/**
* Adds to the headers that will be sent with each request from this client
* instance. The request headers added with this method are applied by
* calling {@link HttpURLConnection#setRequestProperty(String, String)}
* after {@link #prepareConnection(HttpURLConnection, HttpMethod, String)},
* so they may supplement or replace headers which have already been set.
* Calls to {@link #addHeader(String, String)} may be chained. To clear all
* headers added with this method, call {@link #clearHeaders()}.
*
* @param name
* @param value
* @return this client for method chaining
*/
public AbstractHttpClient addHeader(String name, String value) {
requestHeaders.put(name, value);
return this;
}
/**
* Clears all request headers that have been added using
* {@link #addHeader(String, String)}. This method has no effect on headers
* which result from request properties set by this class or its associated
* {@link RequestHandler} when preparing the {@link HttpURLConnection}.
*/
public void clearHeaders() {
requestHeaders.clear();
}
/**
* Returns the {@link CookieManager} associated with this client.
*
* @return CookieManager
*/
public static CookieManager getCookieManager() {
return (CookieManager) CookieHandler.getDefault();
}
/**
* Sets the logger to be used for each request.
*
* @param logger
*/
public void setRequestLogger(RequestLogger logger) {
this.requestLogger = logger;
}
/**
* Initialize the app-wide {@link CookieManager}. This is all that's
* necessary to enable all Web requests within the app to automatically send
* and receive cookies.
*/
protected static void ensureCookieManager() {
if (CookieHandler.getDefault() == null) {
CookieHandler.setDefault(new CookieManager());
}
}
/**
* Determines whether an exception was due to a timeout. If the elapsed time
* is longer than the current timeout, the exception is assumed to be the
* result of the timeout.
*
* @param t Any Throwable
* @return true if caused by connection or read timeout
*/
protected boolean isTimeoutException(Throwable t, long startTime) {
long elapsedTime = System.currentTimeMillis() - startTime + 10; // fudge
if (requestLogger.isLoggingEnabled()) {
requestLogger.log("ELAPSED TIME = " + elapsedTime + ", CT = " + connectionTimeout
+ ", RT = " + readTimeout);
}
if (isConnected) {
return elapsedTime >= readTimeout;
} else {
return elapsedTime >= connectionTimeout;
}
}
/**
* Sets the connection timeout in ms. This is the amount of time that
* {@link HttpURLConnection} will wait to successfully connect to the remote
* server. The read timeout begins once connection has been established.
*
* @param connectionTimeout
*/
public void setConnectionTimeout(int connectionTimeout) {
this.connectionTimeout = connectionTimeout;
}
/**
* Sets the read timeout in ms, which begins after connection has been made.
* For large amounts of data expected, bump this up to make sure you allow
* adequate time to receive it.
*
* @param readTimeout
*/
public void setReadTimeout(int readTimeout) {
this.readTimeout = readTimeout;
}
/**
* Updates the SSL context with an all-trusting trust manager.
*/
private static void trustAllHosts() {
// Create a trust manager that does not validate certificate chains
TrustManager[] trustAllCerts = new TrustManager[] {
new X509TrustManager() {
public X509Certificate[] getAcceptedIssuers() {
return new X509Certificate[] {};
}
public void checkClientTrusted(X509Certificate[] chain,
String authType) throws CertificateException {
}
public void checkServerTrusted(X509Certificate[] chain,
String authType) throws CertificateException {
}
}
};
// Install the all-trusting trust manager
try {
SSLContext sc = SSLContext.getInstance("TLS");
sc.init(null, trustAllCerts, new SecureRandom());
HttpsURLConnection
.setDefaultSSLSocketFactory(sc.getSocketFactory());
} catch (Exception e) {
e.printStackTrace();
}
}
}
| Java |
package com.turbomanage.httpclient;
/**
* Holds data for an HTTP request to be made with the attached HTTP client.
*
* @author David M. Chandler
*/
public abstract class HttpRequest {
public static final String URLENCODED = "application/x-www-form-urlencoded;charset=UTF-8";
public static final String MULTIPART = "multipart/form-data";
protected String path = ""; // avoid null in URL
protected HttpMethod httpMethod;
protected String contentType;
protected byte[] content;
/**
* Constructs a request with optional params appended
* to the query string.
*
* @param path
* @param params
*/
public HttpRequest(String path, ParameterMap params) {
String queryString = null;
if (path != null) {
this.path = path;
}
if (params != null) {
queryString = params.urlEncode();
this.path += "?" + queryString;
}
}
public String getPath() {
return path;
}
public HttpMethod getHttpMethod() {
return httpMethod;
}
public String getContentType() {
return contentType;
}
public byte[] getContent() {
return content;
}
}
| Java |
package com.xyz.jira.plugin.responses;
import java.util.ArrayList;
import java.util.Collection;
import javax.xml.bind.annotation.*;
import com.atlassian.jira.issue.issuetype.IssueType;
/**
* A message returned from the {@link IssueTypes}
*/
@XmlRootElement(name = "issueTypes")
@XmlAccessorType(XmlAccessType.FIELD)
public class IssueTypesInfo {
@XmlAttribute
private String pid;
@XmlElement(name = "issueTypesList")
private Collection<IssueTypeItem> issueTypes = new ArrayList<IssueTypeItem>();
public IssueTypesInfo() {
}
public IssueTypesInfo(String pid, Collection<IssueType> issueTypes) {
this.pid = pid;
this.setIssueTypes(issueTypes);
}
public String getPid() {
return pid;
}
public void setPid(String pid) {
this.pid = pid;
}
public Collection<IssueTypeItem> getIssueTypes() {
return issueTypes;
}
public void setIssueTypes(Collection<IssueType> issueTypes) {
if (issueTypes != null) {
for (IssueType iType : issueTypes) {
this.issueTypes.add(new IssueTypeItem(iType.getId(), iType
.getName()));
}
} else {
this.issueTypes.add(new IssueTypeItem("-1", "No issue types available"));
}
}
@XmlRootElement(name = "issue")
@XmlAccessorType(XmlAccessType.FIELD)
private class IssueTypeItem {
private String id;
private String name;
IssueTypeItem(String id, String name) {
this.setId(id);
this.setName(name);
}
@XmlElement(name = "id")
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
@XmlElement(name = "name")
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
}
}
| Java |
package com.xyz.jira.plugin.responses;
import javax.xml.bind.annotation.*;
/**
* A message returned from the {@link MessageResource}
*/
@XmlRootElement(name = "message")
@XmlAccessorType(XmlAccessType.FIELD)
public class Message {
@XmlAttribute
private String key;
@XmlElement(name = "value")
private String message;
public Message() {
}
public Message(String key, String message) {
this.key = key;
this.message = message;
}
public String getKey() {
return key;
}
public void setKey(String key) {
this.key = key;
}
public String getMessage() {
return message;
}
public void setMessage(String message) {
this.message = message;
}
}
| Java |
package com.xyz.jira.plugin.responses;
import javax.xml.bind.annotation.*;
/**
* A message returned from the {@link MessageResource}
*/
@XmlRootElement(name = "project")
@XmlAccessorType(XmlAccessType.FIELD)
public class ProjectInfo {
@XmlAttribute
private String pid;
@XmlElement(name = "key")
private String key;
@XmlElement(name = "name")
private String name;
public ProjectInfo() {
}
public ProjectInfo(String pid, String key, String name) {
this.pid = pid;
this.key = key;
this.name = name;
}
public String getPid() {
return pid;
}
public void setPid(String pid) {
this.pid = pid;
}
public String getKey() {
return key;
}
public void setKey(String key) {
this.key = key;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
}
| Java |
package com.xyz.jira.plugin.responses;
import javax.xml.bind.annotation.*;
/**
* A message returned from the {@link CreateAnonIssue}
*/
@XmlRootElement(name = "issueCreated")
@XmlAccessorType(XmlAccessType.FIELD)
public class IssueCreated {
@XmlAttribute(name="pid")
private String projectId;
@XmlElement(name = "iid")
private String issueId;
@XmlElement(name = "ikey")
private String issueKey;
public IssueCreated() {
}
public IssueCreated(String projectId, String issueId, String issueKey) {
this.projectId = projectId;
this.issueId = issueId;
this.issueKey = issueKey;
}
public String getProjectId() {
return projectId;
}
public void setProjectId(String projectId) {
this.projectId = projectId;
}
public String getIssueId() {
return issueId;
}
public void setIssueId(String issueId) {
this.issueId = issueId;
}
public String getIssueKey() {
return issueKey;
}
public void setIssueKey(String issueKey) {
this.issueKey = issueKey;
}
}
| Java |
package com.xyz.jira.plugin;
import com.atlassian.jira.ComponentManager;
import com.atlassian.jira.project.Project;
import com.atlassian.plugins.rest.common.security.AnonymousAllowed;
import com.xyz.jira.plugin.responses.IssueTypesInfo;
import com.xyz.jira.plugin.responses.ProjectInfo;
import javax.ws.rs.*;
import javax.ws.rs.core.MediaType;
import javax.ws.rs.core.Response;
/**
* A resource of message.
*/
@Path("/projectInfo")
public class ProjectDetails {
/**
* Gets a listing of issue types available for a project.
*
* @param pid
* Project id for which to get the issue types
* @return the message from the key parameter or the default message
*/
@GET
@AnonymousAllowed
@Produces({ MediaType.APPLICATION_JSON })
public Response getIssueTypes(@QueryParam("pid") String pid) {
long projectId = -1;
if (pid != null && pid.length() > 0) {
// Load the project by id
Project project;
try {
projectId = Long.parseLong(pid);
project = ComponentManager.getInstance().getProjectManager()
.getProjectObj(projectId);
} catch (NumberFormatException nfe) {
// Ignore number format error
// Try loading the project by key
project = ComponentManager.getInstance().getProjectManager()
.getProjectObjByKey(pid.toUpperCase());
}
if (project != null) {
return Response.ok(
new ProjectInfo(project.getId() + "", project.getKey(),
project.getName())).build();
} else {
return Response.ok(
new ProjectInfo("No project found with given id/key", null, null)).build();
}
} else {
return Response.ok(new ProjectInfo("No pid provided", null, null))
.build();
}
}
} | Java |
package com.xyz.jira.plugin;
import java.sql.Timestamp;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;
import com.atlassian.core.user.UserUtils;
import com.atlassian.jira.ComponentManager;
import com.atlassian.jira.config.ConstantsManager;
import com.atlassian.jira.config.properties.ApplicationProperties;
import com.atlassian.jira.exception.CreateException;
import com.atlassian.jira.issue.CustomFieldManager;
import com.atlassian.jira.issue.IssueFactory;
import com.atlassian.jira.issue.IssueManager;
import com.atlassian.jira.issue.MutableIssue;
import com.atlassian.jira.issue.fields.CustomField;
import com.atlassian.jira.project.Project;
import com.atlassian.jira.project.ProjectManager;
import com.atlassian.jira.project.version.VersionManager;
import com.atlassian.jira.security.JiraAuthenticationContext;
import com.atlassian.plugins.rest.common.security.AnonymousAllowed;
import com.xyz.jira.plugin.responses.IssueCreated;
import com.xyz.jira.plugin.responses.Message;
import com.opensymphony.user.EntityNotFoundException;
import javax.ws.rs.*;
import javax.ws.rs.core.MediaType;
import javax.ws.rs.core.Response;
import org.ofbiz.core.entity.GenericValue;
/**
* A resource of message.
*/
@Path("/createAnonIssue")
public class CreateAnonIssue {
/**
* This method will be called if no extra path information is used in the
* request.
*
* @param key
* optional key for the message
* @return the message from the key parameter or the default message
*/
@POST
@AnonymousAllowed
@Produces({ MediaType.APPLICATION_JSON })
public Response createIssue(@FormParam("pid") String pid,
@FormParam("summary") String summary,
@FormParam("issuetype") String issueType,
@FormParam("priority") String priority,
@FormParam("description") String description,
@FormParam("reporter") String reporter,
@FormParam("duedate") String dueDate,
@FormParam("customfields") String customFields) {
IssueFactory issueFactory = ComponentManager.getInstance()
.getIssueFactory();
ProjectManager projectManager = ComponentManager.getInstance()
.getProjectManager();
ConstantsManager constantsManager = ComponentManager.getInstance()
.getConstantsManager();
VersionManager versionManager = ComponentManager.getInstance()
.getVersionManager();
CustomFieldManager customFieldManager = ComponentManager.getInstance()
.getCustomFieldManager();
IssueManager issueManager = ComponentManager.getInstance()
.getIssueManager();
JiraAuthenticationContext authenticationContext = ComponentManager
.getInstance().getJiraAuthenticationContext();
// Regular Fields
Project project = ComponentManager.getInstance().getProjectManager()
.getProjectObj(new Long(pid));
MutableIssue issueObject = issueFactory.getIssue();
issueObject.setProject(project.getGenericValue());
issueObject.setIssueType(constantsManager.getIssueType(issueType));
issueObject.setSummary(summary);
if (reporter != null && reporter.length() > 0) {
try {
issueObject.setReporter(UserUtils.getUser(reporter));
} catch (EntityNotFoundException enf) {
// We are creating anonymously, this is ok
}
}
// issueObject.setAssignee(null);
issueObject.setPriority(constantsManager.getPriority(priority));
issueObject.setDescription(description);
if ( dueDate != null && dueDate.trim().length() > 0 ) {
ApplicationProperties ap = ComponentManager.getInstance().getApplicationProperties();
String dateFormat = ap.getString("jira.date.picker.java.format");
SimpleDateFormat sdf = new SimpleDateFormat(dateFormat);
try {
Date date = sdf.parse(dueDate);
Timestamp tStamp = new Timestamp(date.getTime());
issueObject.setDueDate(tStamp);
} catch ( ParseException pe ) {
// Ignore. The format should had been tested by javascript
}
}
// issueObject.setAffectedVersions(EasyList.build(versionManager.getVersion(new
// Long(10000)), versionManager.getVersion(new Long(10001))));
// issueObject.setFixVersions(EasyList.build(versionManager.getVersion(new
// Long(10002))));
// issueObject.setComponents(EasyList.build(projectManager.getComponent(new
// Long(10000)), projectManager.getComponent(new Long(10001))));
// Custom fields
if (customFields != null && customFields.length() > 0) {
String[] pairs = customFields.split(";");
String tmp[];
for (String pair : pairs) {
tmp = pair.split("=");
String id = tmp[0];
String value = "";
if (tmp.length > 1) {
value = tmp[1];
}
CustomField customField = customFieldManager
.getCustomFieldObject(new Long(id));
issueObject.setCustomFieldValue(customField, value);
}
}
try {
Map<String, Object> params = new HashMap<String, Object>();
params.put("issue", issueObject);
GenericValue issue = issueManager.createIssue(
authenticationContext.getUser(), params);
} catch (CreateException ce) {
return Response
.ok(new Message(pid,
"Issue Creation Failed. Please Contact JIRA administrators."))
.build();
}
return Response.ok(
new IssueCreated(pid, issueObject.getId() + "", issueObject
.getKey())).build();
}
} | Java |
package com.xyz.jira.plugin;
import java.io.File;
import java.util.Iterator;
import java.util.List;
import com.atlassian.jira.ComponentManager;
import com.atlassian.jira.bc.issue.IssueService;
import com.atlassian.jira.issue.AttachmentManager;
import com.atlassian.jira.issue.MutableIssue;
import com.atlassian.jira.issue.history.ChangeItemBean;
import com.atlassian.jira.web.util.AttachmentException;
import com.atlassian.plugins.rest.common.security.AnonymousAllowed;
import javax.servlet.http.HttpServletRequest;
import javax.ws.rs.*;
import javax.ws.rs.core.Context;
import javax.ws.rs.core.MediaType;
import org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.FileItemFactory;
import org.apache.commons.fileupload.FileUploadException;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;
import org.ofbiz.core.entity.GenericEntityException;
/**
* A resource of message.
*/
@Path("/anonIssueAttachment")
public class AnonIssueAttachment {
@POST
@AnonymousAllowed
@Produces({ MediaType.TEXT_HTML })
public String addAttachment(@Context HttpServletRequest request) {
String iid = request.getParameter("iid");
String ikey = request.getParameter("ikey");
System.out.println(iid + " : " + ikey);
String fileRepository = "C:\\Temp\\";
if (ServletFileUpload.isMultipartContent(request)) {
FileItemFactory factory = new DiskFileItemFactory();
ServletFileUpload upload = new ServletFileUpload(factory);
List<FileItem> items = null;
try {
items = upload.parseRequest(request);
} catch (FileUploadException e) {
e.printStackTrace();
}
Iterator<FileItem> iter = items.iterator();
if (items != null) {
iter = items.iterator();
while (iter.hasNext()) {
FileItem item = iter.next();
if (!item.isFormField() && item.getSize() > 0) {
String fileName = processFileName(item.getName());
try {
File file = new File(fileRepository + fileName);
item.write(file);
IssueService iService = ComponentManager.getInstance().getIssueService();
MutableIssue issue;
if ( iid != null && iid.length() > 0 ) {
issue = iService.getIssue(null, new Long(iid)).getIssue();
} else if ( ikey != null && ikey.length() > 0 ) {
issue = iService.getIssue(null, ikey).getIssue();
} else {
return "<html><head></head><body onload=\"parent.uploadDone()\">ERROR: No issue id/key provided</html>";
}
AttachmentManager attachmentManager = ComponentManager
.getInstance().getAttachmentManager();
try {
ChangeItemBean changeItemBean = attachmentManager
.createAttachment(file, fileName,
item.getContentType(), null,
issue.getGenericValue());
return "<html><head></head><body onload=\"parent.uploadDone()\">OK</html>";
} catch (GenericEntityException gee) {
System.err.println(gee);
return "<html><head></head><body onload=\"parent.uploadDone()\">ERROR: GEE</html>";
} catch (AttachmentException aee) {
System.err.println(aee);
return "<html><head></head><body onload=\"parent.uploadDone()\">ERROR: AEE</html>";
}
} catch (Exception e) {
e.printStackTrace();
return "<html><head></head><body onload=\"parent.uploadDone()\">ERROR</html>";
}
}
}
return "<html><head></head><body onload=\"parent.uploadDone()\">ERROR: No file item found</html>";
} else {
return "<html><head></head><body onload=\"parent.uploadDone()\">ERROR: No upload item found</html>";
}
} else {
return "<html><head></head><body onload=\"parent.uploadDone()\">ERROR: Not a multipart form</html>";
}
}
private String processFileName(String fileNameInput) {
String fileNameOutput = null;
fileNameOutput = fileNameInput.substring(
fileNameInput.lastIndexOf("\\") + 1, fileNameInput.length());
return fileNameOutput;
}
} | Java |
package com.xyz.jira.plugin;
import com.atlassian.jira.ComponentManager;
import com.atlassian.jira.project.Project;
import com.atlassian.plugins.rest.common.security.AnonymousAllowed;
import com.xyz.jira.plugin.responses.IssueTypesInfo;
import javax.ws.rs.*;
import javax.ws.rs.core.MediaType;
import javax.ws.rs.core.Response;
/**
* A resource of message.
*/
@Path("/issueTypes")
public class IssueTypes {
/**
* Gets a listing of issue types available for a project.
*
* @param pid
* Project id for which to get the issue types
* @return the message from the key parameter or the default message
*/
@GET
@AnonymousAllowed
@Produces({ MediaType.APPLICATION_JSON })
public Response getIssueTypes(@QueryParam("pid") String pid) {
long projectId = -1;
if (pid.length() > 0) {
// Load the project issues by id
try {
projectId = Long.parseLong(pid);
Project project = ComponentManager.getInstance()
.getProjectManager().getProjectObj(projectId);
return Response.ok(
new IssueTypesInfo(pid, project.getIssueTypes()))
.build();
} catch (NumberFormatException nfe) {
// Ignore number format error, the pid can be the project key also
// Load the project issues by key
Project project = ComponentManager.getInstance()
.getProjectManager().getProjectObjByKey(pid);
return Response.ok(
new IssueTypesInfo(pid, project.getIssueTypes()))
.build();
}
} else {
return Response.ok(new IssueTypesInfo("No pid provided", null))
.build();
}
}
} | Java |
package com.xyz.jira.plugin.responses;
import java.util.ArrayList;
import java.util.Collection;
import javax.xml.bind.annotation.*;
import com.atlassian.jira.issue.issuetype.IssueType;
/**
* A message returned from the {@link IssueTypes}
*/
@XmlRootElement(name = "issueTypes")
@XmlAccessorType(XmlAccessType.FIELD)
public class IssueTypesInfo {
@XmlAttribute
private String pid;
@XmlElement(name = "issueTypesList")
private Collection<IssueTypeItem> issueTypes = new ArrayList<IssueTypeItem>();
public IssueTypesInfo() {
}
public IssueTypesInfo(String pid, Collection<IssueType> issueTypes) {
this.pid = pid;
this.setIssueTypes(issueTypes);
}
public String getPid() {
return pid;
}
public void setPid(String pid) {
this.pid = pid;
}
public Collection<IssueTypeItem> getIssueTypes() {
return issueTypes;
}
public void setIssueTypes(Collection<IssueType> issueTypes) {
if (issueTypes != null) {
for (IssueType iType : issueTypes) {
this.issueTypes.add(new IssueTypeItem(iType.getId(), iType
.getName()));
}
} else {
this.issueTypes.add(new IssueTypeItem("-1", "No issue types available"));
}
}
@XmlRootElement(name = "issue")
@XmlAccessorType(XmlAccessType.FIELD)
private class IssueTypeItem {
private String id;
private String name;
IssueTypeItem(String id, String name) {
this.setId(id);
this.setName(name);
}
@XmlElement(name = "id")
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
@XmlElement(name = "name")
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
}
}
| Java |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.