code stringlengths 3 1.18M | language stringclasses 1 value |
|---|---|
package com.birdorg.anpr.sdk.simple.camera.example;
import android.app.Activity;
import android.app.AlertDialog;
import android.app.ProgressDialog;
import android.content.ActivityNotFoundException;
import android.content.ComponentName;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.SharedPreferences;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Color;
import android.graphics.drawable.BitmapDrawable;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.Environment;
import android.preference.PreferenceManager;
import android.provider.Settings;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;
import org.apache.http.NameValuePair;
import org.apache.http.message.BasicNameValuePair;
import org.json.JSONException;
import org.json.JSONObject;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.FileWriter;
import java.io.OutputStreamWriter;
import java.text.DateFormat;
import java.text.Format;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.List;
import java.util.Vector;
import it.sauronsoftware.ftp4j.FTPClient;
public class Kontrollo extends Activity
{
// Progress Dialog
private ProgressDialog pDialog;
// JSON parser class
JSONParser jsonParser = new JSONParser();
private static final String POST_KONTROLLO_URL = "http://www.comport.first.al/anpr/kontrollo.php";
private static final String TAG_SUCCESS = "success";
private static final String TAG_MESSAGE = "message";
TextView txt_targa,txt_date, txt_id;
/********* work only for Dedicated IP ***********/
static final String FTP_HOST= "comport.first.al";
/********* FTP USERNAME ***********/
static final String FTP_USER = "androidfirst";
/********* FTP PASSWORD ***********/
static final String FTP_PASS ="MNXjqJET";
private String CAP_PATH="CAP_PATH";
static int ANPR_REQUEST = 1; // Identifier of our calling
AnprSdkMenu mm = new AnprSdkMenu();
private static String targafin = "TARGA" ;
Context context = this;
public static String pathsdk;
String time;
@Override
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.anpr);
setTitle("FIRST AUTO-LPR - Version 1.0.8 - Tirana");
DateFormat dateFormat = new SimpleDateFormat("dd-MM-yyyy");
//get current date time with Date()
Date date = new Date();
Format formatter = new SimpleDateFormat("HH.mm.ss");
time = formatter.format(new Date());
pathsdk = "/sdcard/sdk/example/images/"+dateFormat.format(date)+"/";
// Button button = (Button) findViewById(R.id.Button_Main_StartAnpr_ALPR);
// button.setOnClickListener(this);
// @Override
// public void onClick(View v)
// {
// int id = v.getId();
// if (id == R.id.Button_Main_StartAnpr_ALPR)
// {
ImageView imageView = (ImageView)findViewById(R.id.Bitmap_Main_Photo_ALPR); // delete image on screen
imageView.setImageBitmap(null);
Intent intent = new Intent("android.intent.action.SEND"); // set intent to call ANPR SDK
intent.addCategory("android.intent.category.DEFAULT");
intent.setComponent(new ComponentName("com.birdorg.anpr.sdk.simple.camera", "com.birdorg.anpr.sdk.simple.camera.ANPRSimpleCameraSDK"));
///////////////////////////////////////////////// setup the parameters //////////////////
intent.putExtra("Orientation", "landscape"); // portrait orientation
intent.putExtra("FullScreen", false); // not fullscreen (with titlebar)
intent.putExtra("TitleText", "DOKLEA-Test: FIRST AUTO-LPR - Version 1.0.8 - Tirana"); // text on titlebar
// intent.putExtra("IndicatorVisible", true); // ANPR indicator (litle cirle) will shown
// intent.putExtra("MaxRecognizeNumber", 0); // infinite recogzing
// intent.putExtra("DelayAfterRecognize", 1000); // recognized string will displayed until 3 secundum
intent.putExtra("SoundEnable", true); // sound will be hearing when recognized
intent.putExtra("ResolutionSettingByUserEnable", true); // allows user to change camera resolution
intent.putExtra("ResolutionSettingDialogText", "Camera resolution:"); // title of the resolution setting dialog
// intent.putExtra("ResolutionWidth", 640); // camera resolution x
// intent.putExtra("ResolutionHeight", 480); // camera resolution y
intent.putExtra("ResultTextColor", Color.GREEN); // color of the display of recognized string
// intent.putExtra("ListEnable", true); // recognized strings displayed in list
intent.putExtra("ListMaxItems", 1); // max 5 items in list
intent.putExtra("ListTextColor", 0xff7070f0); // color of the list
intent.putExtra("ListTitle", "Lasts:"); // title of the list
intent.putExtra("ListDeletable", true); // allow to delete string from list
intent.putExtra("ListDeleteDialogMessage", "Are you sure to delete: "); // message in delete dialog
intent.putExtra("ListDeleteDialogYesButtonText", "Yes"); // text of yes button
intent.putExtra("ListDeleteDialogNoButtonText", "No"); // text of no button
intent.putExtra("ImageSaveDirectory", pathsdk); // pictures will be saved in this directory
//intent.putExtra("CheckServiceClass", "com.birdorg.anpr.sdk.simple.camera.example.AnprSdkExampleCheckingService"); // every NumberPlate will be checked in this service
try
{
startActivityForResult(intent, ANPR_REQUEST); // call ANPR app with intent
}
catch (ActivityNotFoundException e) // if ANPR intent not found (not installed)
{
Toast toast = Toast.makeText(context, "The ANPR not installed!", Toast.LENGTH_LONG);
toast.show();
}
// }
}
public void uploadFile(File fileName, String name){
FTPClient client = new FTPClient();
try {
client.connect(FTP_HOST,21);
client.login(FTP_USER, FTP_PASS);
client.setType(FTPClient.TYPE_BINARY);
// client.changeDirectory("/mdoklea/");
DateFormat dateFormat = new SimpleDateFormat("dd-MM-yyyy");
//get current date time with Date()
Date date = new Date();
// client.createDirectory(dateFormat.format(date));
Format formatter = new SimpleDateFormat("HH.mm.ss");
String time = formatter.format(new Date());
client.changeDirectory("/comport.first.al/anpr/uploads/"+dateFormat.format(date)+"/");
client.createDirectory(time+name+"/");
String getf = fileName.getName();
CAP_PATH = "http://www.comport.first.al/anpr/uploads/"+dateFormat.format(date)+"/"+time+name+"/"+getf;
client.changeDirectory("/comport.first.al/anpr/uploads/"+dateFormat.format(date)+"/"+time+name+"/");
client.upload(fileName);
} catch (Exception e) {
e.printStackTrace();
try {
client.disconnect(true);
} catch (Exception e2) {
e2.printStackTrace();
}
}
}
@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) // this called when ANPR app finished
{
Bitmap bitmap;
if (requestCode == ANPR_REQUEST) {// ANPR app id
if (resultCode == RESULT_OK) // if ANPR app terminated normally
{
Bundle b = data.getExtras(); // result of ANPR app (a Bundle var)
if (b != null) {
String error = b.getString("Errors"); // in bundle the recognized string
String s = b.getString("PlateNums"); // in bundle the error string
// String user = getIntent().getExtras().getString("Username");
// Toast.makeText(context, "Username: "+user, Toast.LENGTH_LONG);
String ss = s.substring(2,s.length());
String sfin = "AA "+ss;
targafin = sfin;
String name = pathsdk+s+".jpg"; // photo file on the SD card
File fs = new File(name);
uploadFile(fs, "-"+s);
new PostComment().execute();
String sm = ss.substring(0, 1);
int some = Integer.parseInt(sm);
Intent intent = new Intent(Kontrollo.this, Info.class);
if (some == 1) {
intent.putExtra("Ngjyra","Bardhe");
intent.putExtra("Marka","Peageut");
intent.putExtra("Gjoba","jo");
intent.putExtra("Siguracion","2014-06-11");
intent.putExtra("Sgs","2014-08-01");
intent.putExtra("Pronar","Altin Gjokaj");
}else if (some == 2 ){
intent.putExtra("Ngjyra","Kuqe");
intent.putExtra("Marka","BMW");
intent.putExtra("Gjoba","po");
intent.putExtra("Siguracion","2014-09-30");
intent.putExtra("Sgs","2014-10-01");
intent.putExtra("Pronar","Manushaqe Veli");
}else if (some == 3)
{
intent.putExtra("Ngjyra","Zeze");
intent.putExtra("Marka","Fiat");
intent.putExtra("Gjoba","jo");
intent.putExtra("Siguracion","2014-11-01");
intent.putExtra("Sgs","2014-10-30");
intent.putExtra("Pronar","Maria Mari");
}else if (some == 4)
{
intent.putExtra("Ngjyra","Gri");
intent.putExtra("Marka","Alfa Romeo");
intent.putExtra("Gjoba","po");
intent.putExtra("Siguracion","2014-12-31");
intent.putExtra("Sgs","2014-11-30");
intent.putExtra("Pronar","Albert Beri");
}else if (some == 5)
{
intent.putExtra("Ngjyra","Zeze");
intent.putExtra("Marka","Suzuki");
intent.putExtra("Gjoba","po");
intent.putExtra("Siguracion","2014-11-01");
intent.putExtra("Sgs","2014-10-30");
intent.putExtra("Pronar","Mario Shabani");
}else if (some == 6)
{
intent.putExtra("Ngjyra","Blu");
intent.putExtra("Marka","Subaru");
intent.putExtra("Gjoba","jo");
intent.putExtra("Siguracion","2014-11-01");
intent.putExtra("Sgs","2014-10-30");
intent.putExtra("Pronar","Elton Anori");
}else if (some == 7){
intent.putExtra("Ngjyra","Gri");
intent.putExtra("Marka","Ford");
intent.putExtra("Gjoba","po");
intent.putExtra("Siguracion","2014-11-01");
intent.putExtra("Sgs","2014-10-30");
intent.putExtra("Pronar","Anxhela Katrin");
}
else if (some == 8) {
intent.putExtra("Ngjyra", "Bardh");
intent.putExtra("Marka", "Fiat");
intent.putExtra("Gjoba", "jo");
intent.putExtra("Siguracion", "2014-09-01");
intent.putExtra("Sgs", "2014-08-30");
intent.putExtra("Pronar", "Qemal Rexhepaj");
}else if (some == 9){
intent.putExtra("Ngjyra","Kuqe");
intent.putExtra("Marka","Benz");
intent.putExtra("Gjoba","po");
intent.putExtra("Siguracion","2014-09-20");
intent.putExtra("Sgs","2014-08-10");
intent.putExtra("Pronar","Vaso Balla");
}else
{
intent.putExtra("Ngjyra","Zez");
intent.putExtra("Marka","Toyota");
intent.putExtra("Gjoba","jo");
intent.putExtra("Siguracion","2014-11-01");
intent.putExtra("Sgs","2014-11-30");
intent.putExtra("Pronar","Taulant Tano");
}
intent.putExtra("Targa",sfin);
intent.putExtra("FotoPath", CAP_PATH);
startActivity(intent);
}
} else {
TextView text = (TextView) findViewById(R.id.Text_Main_Result_ALPR);
text.setText("---NO PHOTO TAKEN");
}
}
}
class PostComment extends AsyncTask<String, String, String> {
@Override
protected void onPreExecute() {
super.onPreExecute();
pDialog = new ProgressDialog(Kontrollo.this);
pDialog.setMessage("Posting Values...");
pDialog.setIndeterminate(false);
pDialog.setCancelable(true);
pDialog.show();
}
@Override
protected String doInBackground(String... args) {
// TODO Auto-generated method stub
// Check for success tag
int success;
String targa = targafin;
String pajisje_id = Settings.Secure.getString(getContentResolver(), Settings.Secure.ANDROID_ID);
Calendar c = Calendar.getInstance();
System.out.println("Current time => "+c.getTime());
SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
String data = df.format(c.getTime());
String username = getIntent().getExtras().getString("Username");
String cap_img = CAP_PATH;
try {
// Building Parameters
List<NameValuePair> params = new ArrayList<NameValuePair>();
params.add(new BasicNameValuePair("targa", targa));
params.add(new BasicNameValuePair("data", data));
params.add(new BasicNameValuePair("pajisje_id", pajisje_id));
params.add(new BasicNameValuePair("user_id", username));
params.add(new BasicNameValuePair("capture_image", CAP_PATH));
Log.d("request!", "starting");
//Posting user data to script
JSONObject json = jsonParser.makeHttpRequest(
POST_KONTROLLO_URL, "POST", params);
// full json response
Log.d("Post Comment attempt", json.toString());
// json success element
success = json.getInt(TAG_SUCCESS);
if (success == 1) {
Log.d("Values Added!", json.toString());
finish();
return json.getString(TAG_MESSAGE);
}else{
Log.d("Insert Failure!", json.getString(TAG_MESSAGE));
return json.getString(TAG_MESSAGE);
}
} catch (JSONException e) {
e.printStackTrace();
}
return null;
}
protected void onPostExecute(String file_url) {
// dismiss the dialog once product deleted
pDialog.dismiss();
if (file_url != null){
Toast.makeText(Kontrollo.this, file_url, Toast.LENGTH_LONG).show();
}
}
}
}
| Java |
package com.birdorg.anpr.sdk.simple.camera.example;
import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.provider.Settings;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;
import java.text.SimpleDateFormat;
import java.util.Calendar;
public class Printo extends Activity {
TextView txt_targa, txt_tipi, txt_gjoba, txt_shkelja,txt_gjoba2, txt_shkelja2,txt_shkelja3,txt_date, txt_id, txt_punonjesi;
Button print;
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_print);
print = (Button) findViewById(R.id.button);
String pajisja_id = Settings.Secure.getString(getContentResolver(), Settings.Secure.ANDROID_ID);
Calendar c = Calendar.getInstance();
System.out.println("Current time => "+c.getTime());
SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
String formattedDate = df.format(c.getTime());
txt_targa = (TextView) findViewById(R.id.txt_targa);
txt_tipi = (TextView) findViewById(R.id.txt_tipi);
txt_gjoba = (TextView) findViewById(R.id.txt_gjoba);
txt_shkelja = (TextView) findViewById(R.id.txt_shkelja);
txt_gjoba2 = (TextView) findViewById(R.id.txt_gjoba2);
txt_shkelja2 = (TextView) findViewById(R.id.txt_shkelja2);
txt_shkelja3 = (TextView) findViewById(R.id.txt_shkelja3);
txt_date = (TextView) findViewById(R.id.txt_date);
txt_id = (TextView) findViewById(R.id.txt_id);
txt_punonjesi= (TextView) findViewById(R.id.txt_punonjesi);
txt_targa.setText(""+getIntent().getExtras().getString("Targa"));
txt_tipi.setText(""+getIntent().getExtras().getString("Marka"));
txt_shkelja.setText("" + getIntent().getExtras().getString("Gjoba"));
txt_shkelja2.setText("" + getIntent().getExtras().getString("Gjoba2"));
txt_shkelja3.setText("" + getIntent().getExtras().getString("Shuma3"));
txt_gjoba.setText(""+getIntent().getExtras().getString("Shuma"));
txt_gjoba2.setText(""+getIntent().getExtras().getString("Shuma2"));
txt_date.setText(""+formattedDate);
txt_id.setText(""+pajisja_id);
txt_punonjesi.setText(""+getIntent().getExtras().getString("Username"));
print.setOnClickListener(new View.OnClickListener()
{
@Override
public void onClick (View v) {
Intent i = new Intent(Printo.this, AnprSdkMain.class);
startActivity(i);
}
});
}
}
| Java |
package com.birdorg.anpr.sdk.simple.camera.example;
/**
* Created by john on 8/2/2014.
*/
public class ItemKontrollo {
private String targa;
private String data;
private String user_id;
private String imgpath;
private String gjoba;
private String shuma;
public ItemKontrollo(){}
public void setTarga(String t){
this.targa=t;
}
public void setData(String d)
{
this.data=d;
}
public void setUser(String u){
this.user_id = u;
}
public void setImgpath(String p){
this.imgpath = p;
}
public void setGjoba(String p){
this.gjoba = p;
}
public void setShuma(String p){
this.shuma = p;
}
public String getTarga()
{
return this.targa;
}
public String getData()
{
return this.data;
}
public String getUser()
{
return this.user_id;
}
public String getImgpath()
{
return this.imgpath;
}
public String getGjoba()
{
return this.gjoba;
}
public String getShuma()
{
return this.shuma;
}
}
| Java |
package com.birdorg.anpr.sdk.simple.camera.example;
import java.util.ArrayList;
import java.util.HashMap;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import android.app.ListActivity;
import android.app.ProgressDialog;
import android.content.Intent;
import android.os.AsyncTask;
import android.os.Bundle;
import android.view.View;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.ListAdapter;
import android.widget.ListView;
import android.widget.SimpleAdapter;
import android.widget.TextView;
import android.widget.EditText;
import android.text.TextWatcher;
import android.widget.ArrayAdapter;
import android.text.Editable;
import java.util.Set;
import java.util.HashSet;
public class Lista extends ListActivity {
private ProgressDialog pDialog;
private static final String TARGA_URL = "http://www.comport.first.al/anpr/lista.php";
private static final String TAG_NGJYRA = "ngjyra";
private static final String TAG_TARGA = "targa";
private static final String TAG_POSTS = "posts";
private static final String TAG_GJOBA = "gjoba";
private static final String TAG_GJOBA_STATUS = "gjoba_status";
private static final String TAG_MARKA = "marka";
private static final String TAG_SIGURACION = "siguracion";
private static final String TAG_PRONAR = "pronar";
private static final String TAG_SGS = "sgs";
private static final String TAG_IMAZHI = "imazhi";
ArrayAdapter<String> myAdapter;
EditText inputSearch;
private JSONArray mPlates = null;
// manages all of our comments in a list.
private ArrayList<HashMap<String, String>> mPlatesList;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
// note that use read_comments.xml instead of our single_post.xml
setContentView(R.layout.listatargave);
}
@Override
protected void onResume() {
// TODO Auto-generated method stub
super.onResume();
new LoadLista().execute();
}
public void updateJSONdata() {
mPlatesList = new ArrayList<HashMap<String, String>>();
JSONParser jParser = new JSONParser();
JSONObject json = jParser.getJSONFromUrl(TARGA_URL);
try {
mPlates = json.getJSONArray(TAG_POSTS);
// looping through all posts according to the json object returned
for (int i = 0; i < mPlates.length(); i++) {
JSONObject c = mPlates.getJSONObject(i);
// gets the content of each tag
String targa = c.getString(TAG_TARGA);
String ngjyra = c.getString(TAG_NGJYRA);
String marka = c.getString(TAG_MARKA);
String gjoba_status = c.getString(TAG_GJOBA_STATUS);
String siguracion = c.getString(TAG_SIGURACION);
String sgs = c.getString(TAG_SGS);
String pronar = c.getString(TAG_PRONAR);
String imazhi = c.getString(TAG_IMAZHI);
String po = "po";
String jo = "jo";
// creating new HashMap
HashMap<String, String> map = new HashMap<String, String>();
map.put(TAG_NGJYRA, ngjyra);
map.put(TAG_MARKA, marka);
map.put(TAG_SIGURACION, siguracion);
if (gjoba_status.equals("1")) {
map.put(TAG_GJOBA, po);
} else if ((gjoba_status == null) || (gjoba_status.equals("0"))) {
map.put(TAG_GJOBA, jo);
}
map.put(TAG_PRONAR, pronar);
map.put(TAG_SGS, sgs);
map.put(TAG_IMAZHI, imazhi);
map.put(TAG_TARGA, targa.replace(" ", ""));
// adding HashList to ArrayList
mPlatesList.add(map);
}
} catch (JSONException e) {
e.printStackTrace();
}
}
/**
* Inserts the parsed data into the listview.
*/
ListAdapter adapter;
private void updateList() {
ListView lv = getListView();
adapter = new SimpleAdapter(this, mPlatesList, R.layout.plates,
new String[] { TAG_TARGA, TAG_NGJYRA, TAG_MARKA,
TAG_SIGURACION, TAG_GJOBA, TAG_PRONAR, TAG_SGS,
TAG_IMAZHI }, new int[] { R.id.title, R.id.ngjyra,
R.id.marka, R.id.siguracion, R.id.gjoba, R.id.pronar,
R.id.sgs, R.id.imazhi });
setListAdapter(adapter);
lv.setOnItemClickListener(new OnItemClickListener() {
@Override
public void onItemClick(AdapterView<?> parent, View view,
int position, long id) {
String targa = ((TextView) view.findViewById(R.id.title))
.getText().toString();
String ngjyra = ((TextView) view.findViewById(R.id.ngjyra))
.getText().toString();
String marka = ((TextView) view.findViewById(R.id.marka))
.getText().toString();
String siguracion = ((TextView) view
.findViewById(R.id.siguracion)).getText().toString();
String gjoba = ((TextView) view.findViewById(R.id.gjoba))
.getText().toString();
String sgs = ((TextView) view.findViewById(R.id.sgs)).getText()
.toString();
String pronar = ((TextView) view.findViewById(R.id.pronar))
.getText().toString();
String imazhi = ((TextView) view.findViewById(R.id.imazhi))
.getText().toString();
String username = getIntent().getExtras().getString("Username");
Intent intent = new Intent(Lista.this, Info.class);
intent.putExtra("Targa", targa);
intent.putExtra("Ngjyra", ngjyra);
intent.putExtra("Marka", marka);
intent.putExtra("Gjoba", gjoba);
intent.putExtra("Siguracion", siguracion);
intent.putExtra("Sgs", sgs);
intent.putExtra("Pronar", pronar);
intent.putExtra("Username", username);
intent.putExtra("FotoPath", imazhi);
startActivity(intent);
}
});
}
public void search() {
ListView lv = getListView();
Set<String> unionSet = new HashSet<String>();
ArrayList<HashMap<String, String>> mPlateClone = new ArrayList<HashMap<String, String>>(
mPlatesList);
for (HashMap<String, String> hashMap : mPlateClone) {
for (String key : hashMap.keySet())
if (key.equals(TAG_TARGA))
unionSet.add(hashMap.get(key));
}
String[] table = unionSet.toArray(new String[unionSet.size()]);
inputSearch = (EditText) findViewById(R.id.searchText);
// myAdapter = new ArrayAdapter<String>(this, R.layout.plates,
// R.id.title,
// table);
// lv.setAdapter(myAdapter);
inputSearch.addTextChangedListener(new TextWatcher() {
@Override
public void onTextChanged(CharSequence cs, int arg1, int arg2,
int arg3) {
}
@Override
public void beforeTextChanged(CharSequence arg0, int arg1,
int arg2, int arg3) {
}
@Override
public void afterTextChanged(Editable s) {
// // ((SimpleAdapter)
// //
// adapter).getFilter().filter(inputSearch.getText().toString().trim());
((SimpleAdapter) Lista.this.adapter).getFilter().filter(
inputSearch.getText().toString().trim());
}
});
}
public class LoadLista extends AsyncTask<Void, Void, Boolean> {
@Override
protected void onPreExecute() {
super.onPreExecute();
pDialog = new ProgressDialog(Lista.this);
pDialog.setMessage("Targat po ngarkohen...");
pDialog.setIndeterminate(false);
pDialog.setCancelable(true);
pDialog.show();
}
@Override
protected Boolean doInBackground(Void... arg0) {
updateJSONdata();
return null;
}
@Override
protected void onPostExecute(Boolean result) {
super.onPostExecute(result);
pDialog.dismiss();
updateList();
search();
}
}
}
| Java |
package com.birdorg.anpr.sdk.simple.camera.example;
import android.view.View;
import android.widget.AdapterView;
import android.widget.Toast;
public class SelectingItem implements AdapterView.OnItemSelectedListener {
public void onItemSelected(AdapterView<?> parent, View view, int pos,long id) {
Toast.makeText(parent.getContext(),
"Penalizo:" + parent.getItemAtPosition(pos).toString(), Toast.LENGTH_SHORT).show();
}
@Override
public void onNothingSelected(AdapterView<?> arg0) {
// TODO Auto-generated method stub
}
}
| Java |
package com.birdorg.anpr.sdk.simple.camera.example;
import it.sauronsoftware.ftp4j.FTPClient;
import it.sauronsoftware.ftp4j.FTPDataTransferListener;
import java.io.File;
import android.app.Activity;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.Toast;
public class FtpUpload extends Activity implements OnClickListener {
/********* work only for Dedicated IP ***********/
static final String FTP_HOST= "ftp.codevsoft.net";
/********* FTP USERNAME ***********/
static final String FTP_USER = "codevsof";
/********* FTP PASSWORD ***********/
static final String FTP_PASS ="82,LD.kf%Rtemi";
Kontrollo ko = new Kontrollo();
Button btn;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.ftp);
btn = (Button) findViewById(R.id.button1);
btn.setOnClickListener(this);
}
public void onClick(View v) {
/********** Pick file from sdcard *******/
File f = new File("/sdcard/sdk/example/images/26-07-2014/YX171EK.jpg");// "/sdcard/logo.png");
// Upload sdcard file
uploadFile(f);
/********** Pick file from sdcard *******/
File f2 = new File("26-07-2014/");// "/sdcard/logo.png");
// Upload sdcard file
uploadFile(f);
}
public void uploadFile(File fileName){
FTPClient client = new FTPClient();
try {
client.connect(FTP_HOST,21);
client.login(FTP_USER, FTP_PASS);
client.setType(FTPClient.TYPE_BINARY);
client.changeDirectory("/mdoklea/");
client.createDirectory("26-07-2014");
client.changeDirectory("/mdoklea/26-07-2014/");
client.upload(fileName, new MyTransferListener());
// client.upload(f2);
} catch (Exception e) {
e.printStackTrace();
try {
client.disconnect(true);
} catch (Exception e2) {
e2.printStackTrace();
}
}
}
/******* Used to file upload and show progress **********/
public class MyTransferListener implements FTPDataTransferListener {
public void started() {
btn.setVisibility(View.GONE);
// Transfer started
Toast.makeText(getBaseContext(), " Upload Started ...", Toast.LENGTH_SHORT).show();
//System.out.println(" Upload Started ...");
}
public void transferred(int length) {
// Yet other length bytes has been transferred since the last time this
// method was called
Toast.makeText(getBaseContext(), " transferred ..." + length, Toast.LENGTH_SHORT).show();
//System.out.println(" transferred ..." + length);
}
public void completed() {
btn.setVisibility(View.VISIBLE);
// Transfer completed
Toast.makeText(getBaseContext(), " completed ...", Toast.LENGTH_SHORT).show();
//System.out.println(" completed ..." );
}
public void aborted() {
btn.setVisibility(View.VISIBLE);
// Transfer aborted
Toast.makeText(getBaseContext()," transfer aborted , please try again...", Toast.LENGTH_SHORT).show();
//System.out.println(" aborted ..." );
}
public void failed() {
btn.setVisibility(View.VISIBLE);
// Transfer failed
System.out.println(" failed ..." );
}
}
} | Java |
package com.birdorg.anpr.sdk.simple.camera.example;
import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.ImageView;
import android.widget.TextView;
import java.util.Vector;
/**
* Created by john on 7/25/2014.
*/
public class KontrollArrayAdapter extends ArrayAdapter<String> {
private final Context context;
Vector<String> vec = new Vector<String>();
public KontrollArrayAdapter(Context context, Vector<String> vec) {
super(context, R.layout.kontrolletsotme, vec);
this.context = context;
this.vec = vec;
}
@Override
public View getView(int position, View convertView, ViewGroup parent) {
LayoutInflater inflater = (LayoutInflater) context
.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
View rowView = inflater.inflate(R.layout.kontrolletsotme, parent, false);
TextView textView = (TextView) rowView.findViewById(R.id.label);
ImageView imageView = (ImageView) rowView.findViewById(R.id.logo);
textView.setText(vec.get(position));
// Change icon based on name
String s = vec.get(position);
String ss = s.substring(2,3);
int some = Integer.parseInt(ss);
if(some == 1 || some == 3 || some == 6)
{
imageView.setImageResource(R.drawable.ksotj);
}else
imageView.setImageResource(R.drawable.ksotk);
return rowView;
}
}
| Java |
package com.birdorg.anpr.sdk.simple.camera.example;
import android.os.Environment;
import android.widget.Toast;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.StringTokenizer;
import java.util.Vector;
/**
* Created by john on 7/22/2014.
*/
public class ReadFromFile {
public String readFromFileSDKCut() {
DateFormat dateFormat = new SimpleDateFormat("dd-MM-yyyy");
//get current date time with Date()
Date date = new Date();
String pathsdk = "/sdcard/sdk/example/images/"+dateFormat.format(date)+"/";
File dirr = new File(pathsdk);//"/sdcard/sdk/example/images/");
String str = "FILE";
if (dirr.isDirectory()) {
str = "--->>DIR";
}
String tt = "TARGA IS NULL";
int sz = 0;
Vector vec = new Vector();
String some = null;
for (File imageFile : dirr.listFiles()) {
if (imageFile != null) {
// array[i++] = imageFile.getName();
tt = imageFile.getName();
int len = tt.length();
some = tt.substring(2, (len - 4));
String ss = some;
ss = "AA" + ss;
vec.add(sz, ss);
sz++;
}
// Toast.makeText(getBaseContext(), "PIRA: " + tt, Toast.LENGTH_SHORT).show();
}
return some;
}
public String readFromFileSDK() {
DateFormat dateFormat = new SimpleDateFormat("dd-MM-yyyy");
//get current date time with Date()
Date date = new Date();
String pathsdk = "/sdcard/sdk/example/images/"+dateFormat.format(date)+"/";
File dirr = new File(pathsdk);//"/sdcard/sdk/example/images/");
String str = "FILE";
if (dirr.isDirectory()) {
str = "--->>DIR";
}
String tt = "TARGA IS NULL";
int sz = 0;
Vector vec = new Vector();
String some = null;
for (File imageFile : dirr.listFiles()) {
// array[i++] = imageFile.getName();
tt = imageFile.getName();
// ss = "AA"+ss;
vec.add(sz, tt);
sz++;
// Toast.makeText(getBaseContext(), "PIRA: " + tt, Toast.LENGTH_SHORT).show();
}
return tt;
}
}
| Java |
package com.birdorg.anpr.sdk.simple.camera.example;
import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.ImageView;
import android.widget.TextView;
import java.io.InputStream;
import java.lang.reflect.Array;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Vector;
/**
* Created by john on 8/2/2014.
*/
public class PenalizimetSotemAdapter extends ArrayAdapter<ItemKontrollo> {
private final Context context;
ItemKontrollo item ;
Vector<ItemKontrollo> vec = new Vector<ItemKontrollo>();
public PenalizimetSotemAdapter(Context context, Vector<ItemKontrollo> vecc) {
super(context, R.layout.penalizimet_sotme, vecc);
this.context = context;
this.vec = vecc;
}
@Override
public View getView(int position, View convertView, ViewGroup parent) {
LayoutInflater inflater = (LayoutInflater) context
.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
View rowView = inflater.inflate(R.layout.penalizimet_sotme, parent, false);
TextView t1 = (TextView) rowView.findViewById(R.id.label_targa);
TextView t2 = (TextView) rowView.findViewById(R.id.label_data);
TextView t3 = (TextView) rowView.findViewById(R.id.label_user);
TextView t4hidden = (TextView) rowView.findViewById(R.id.label_path);
TextView t5 = (TextView) rowView.findViewById(R.id.label_gjobat);
TextView t6 = (TextView) rowView.findViewById(R.id.label_shuma);
t1.setText(vec.get(position).getTarga());
t2.setText(vec.get(position).getData());
t3.setText(vec.get(position).getUser());
t4hidden.setText(vec.get(position).getImgpath());
t5.setText(vec.get(position).getGjoba());
t6.setText(vec.get(position).getShuma());
String path = t4hidden.getText().toString();
Bitmap bitmap = getBitmap(path);
if (bitmap != null) {
ImageView imageView = (ImageView) rowView.findViewById(R.id.label_capture_image);
imageView.setImageBitmap(bitmap);
}
return rowView;
}
private Bitmap getBitmap(String url)
{
try {
Bitmap bitmap=null;
URL imageUrl = new URL(url);
HttpURLConnection conn = (HttpURLConnection)imageUrl.openConnection();
conn.setDoInput(true);
conn.connect();
InputStream input = conn.getInputStream();
bitmap = BitmapFactory.decodeStream(input);
return bitmap;
} catch (Exception ex){
ex.printStackTrace();
return null;
}
}
}
| Java |
package com.birdorg.anpr.sdk.simple.camera.example;
import android.app.Activity;
import android.app.AlertDialog;
import android.os.Bundle;
import android.widget.Button;
import android.widget.TextView;
import android.widget.Spinner;
import android.content.Intent;
import android.provider.Settings.Secure;
import android.view.View;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import android.widget.CheckBox;
import java.util.ArrayList;
import java.util.List;
import org.apache.http.NameValuePair;
import org.apache.http.message.BasicNameValuePair;
import org.json.JSONException;
import org.json.JSONObject;
import android.app.ProgressDialog;
import android.content.SharedPreferences;
import android.os.AsyncTask;
import android.preference.PreferenceManager;
import android.util.Log;
import android.widget.Toast;
public class Penalizo extends Activity {
private Spinner spinner1, spinner2, spinner3;
private Button print;
CheckBox checkbox1;
CheckBox checkbox2;
CheckBox checkbox3;
// Progress Dialog
private ProgressDialog pDialog;
// JSON parser class
JSONParser jsonParser = new JSONParser();
private static final String POST_COMMENT_URL = "http://www.comport.first.al/anpr/penalizo.php";
private static final String TAG_SUCCESS = "success";
private static final String TAG_MESSAGE = "message";
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_penalize);
final AlertDialog.Builder alertbox = new AlertDialog.Builder(this);
checkbox1 = (CheckBox) findViewById(R.id.checkBox1);
checkbox2 = (CheckBox) findViewById(R.id.checkBox);
checkbox3 = (CheckBox) findViewById(R.id.checkBox3);
final String username = getIntent().getExtras().getString("Username");
TextView tv3 = (TextView) findViewById(R.id.intent3);
TextView tv4 = (TextView) findViewById(R.id.intent4);
TextView tv5 = (TextView) findViewById(R.id.intent5);
TextView tv6 = (TextView) findViewById(R.id.pathfoto);
tv3.setText("" + getIntent().getExtras().getString("Targa"));
tv4.setText("" + getIntent().getExtras().getString("Ngjyra"));
tv5.setText("" + getIntent().getExtras().getString("Marka"));
tv6.setText(""+getIntent().getExtras().getString("FotoPath"));
String path = tv6.getText().toString();
spinner1 = (Spinner) findViewById(R.id.spinner1);
spinner1.setOnItemSelectedListener(new SelectingItem());
print = (Button) findViewById(R.id.button);
spinner2 = (Spinner) findViewById(R.id.spinner2);
spinner2.setOnItemSelectedListener(new SelectingItem());
spinner3 = (Spinner) findViewById(R.id.spinner3);
spinner3.setOnItemSelectedListener(new SelectingItem());
print.setOnClickListener(new View.OnClickListener()
{
@Override
public void onClick (View v){
if(checkbox1.isChecked())
{
Intent i = new Intent(Penalizo.this, Printo.class);
i.putExtra("Targa", getIntent().getExtras().getString("Targa"));
i.putExtra("Marka", getIntent().getExtras().getString("Marka"));
i.putExtra("Gjoba", String.valueOf(spinner1.getSelectedItem()));
i.putExtra("Shuma", checkbox1.getText().toString());
i.putExtra("Gjoba2", "");
i.putExtra("Shuma2", "");
i.putExtra("Shuma3", "");
i.putExtra("Username", username);
startActivity(i);
}
if(checkbox2.isChecked())
{
Intent i = new Intent(Penalizo.this, Printo.class);
i.putExtra("Targa", getIntent().getExtras().getString("Targa"));
i.putExtra("Marka", getIntent().getExtras().getString("Marka"));
i.putExtra("Gjoba", String.valueOf(spinner2.getSelectedItem()));
i.putExtra("Shuma", checkbox2.getText().toString());
i.putExtra("Gjoba2", "");
i.putExtra("Shuma2", "");
i.putExtra("Shuma3", "");
i.putExtra("Username", username);
startActivity(i);
}
if(checkbox3.isChecked())
{
Intent i = new Intent(Penalizo.this, Printo.class);
i.putExtra("Targa", getIntent().getExtras().getString("Targa"));
i.putExtra("Marka", getIntent().getExtras().getString("Marka"));
i.putExtra("Shuma", String.valueOf(spinner3.getSelectedItem()));
i.putExtra("Gjoba2", "");
i.putExtra("Gjoba", "");
i.putExtra("Shuma2", "");
i.putExtra("Shuma3", "");
i.putExtra("Username", username);
startActivity(i);
}
if(!checkbox1.isChecked()&&!checkbox2.isChecked()&&!checkbox3.isChecked())
{
alertbox.setMessage("Ju lutem perzgjidhni nje gjobe.");
alertbox.show();
}
if(checkbox1.isChecked()&&checkbox2.isChecked()&&!checkbox3.isChecked())
{
Intent i = new Intent(Penalizo.this, Printo.class);
i.putExtra("Targa", getIntent().getExtras().getString("Targa"));
i.putExtra("Marka", getIntent().getExtras().getString("Marka"));
i.putExtra("Gjoba", String.valueOf(spinner1.getSelectedItem()));
i.putExtra("Gjoba2", String.valueOf(spinner2.getSelectedItem()));
i.putExtra("Shuma", checkbox1.getText().toString());
i.putExtra("Shuma2", checkbox2.getText().toString());
i.putExtra("Shuma3", "");
i.putExtra("Username", username);
startActivity(i);
}
if(checkbox1.isChecked()&&checkbox2.isChecked()&&checkbox3.isChecked())
{
Intent i = new Intent(Penalizo.this, Printo.class);
i.putExtra("Targa", getIntent().getExtras().getString("Targa"));
i.putExtra("Marka", getIntent().getExtras().getString("Marka"));
i.putExtra("Gjoba", String.valueOf(spinner1.getSelectedItem()));
i.putExtra("Gjoba2", String.valueOf(spinner2.getSelectedItem()));
i.putExtra("Shuma3", String.valueOf(spinner3.getSelectedItem()));
i.putExtra("Shuma", checkbox1.getText().toString());
i.putExtra("Shuma2", checkbox2.getText().toString());
i.putExtra("Username", username);
startActivity(i);
}
if(checkbox2.isChecked()&&checkbox3.isChecked()&&!checkbox1.isChecked())
{
Intent i = new Intent(Penalizo.this, Printo.class);
i.putExtra("Targa", getIntent().getExtras().getString("Targa"));
i.putExtra("Marka", getIntent().getExtras().getString("Marka"));
i.putExtra("Gjoba", String.valueOf(spinner2.getSelectedItem()));
i.putExtra("Shuma2", String.valueOf(spinner3.getSelectedItem()));
i.putExtra("Shuma", checkbox2.getText().toString());
i.putExtra("Shuma3", "");
i.putExtra("Gjoba2", "");
i.putExtra("Username", username);
startActivity(i);
}
if(checkbox1.isChecked()&&checkbox3.isChecked()&&!checkbox2.isChecked())
{
Intent i = new Intent(Penalizo.this, Printo.class);
i.putExtra("Targa", getIntent().getExtras().getString("Targa"));
i.putExtra("Marka", getIntent().getExtras().getString("Marka"));
i.putExtra("Gjoba", String.valueOf(spinner1.getSelectedItem()));
i.putExtra("Shuma2", String.valueOf(spinner3.getSelectedItem()));
i.putExtra("Shuma", checkbox1.getText().toString());
i.putExtra("Gjoba2", "");
i.putExtra("Shuma3", "");
i.putExtra("Username", username);
startActivity(i);
}
new PostComment().execute();
}
});
}
class PostComment extends AsyncTask<String, String, String> {
@Override
protected void onPreExecute() {
super.onPreExecute();
pDialog = new ProgressDialog(Penalizo.this);
pDialog.setMessage("Posting Values...");
pDialog.setIndeterminate(false);
pDialog.setCancelable(true);
pDialog.show();
}
@Override
protected String doInBackground(String... args) {
// TODO Auto-generated method stub
// Check for success tag
int success;
String targa = getIntent().getExtras().getString("Targa");
String pajisje_id = Secure.getString(getContentResolver(), Secure.ANDROID_ID);
Calendar c = Calendar.getInstance();
System.out.println("Current time => "+c.getTime());
SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
String formattedDate = df.format(c.getTime());
String username = getIntent().getExtras().getString("Username");
TextView tv6 = (TextView) findViewById(R.id.pathfoto);
tv6.setText(""+getIntent().getExtras().getString("FotoPath"));
String path = tv6.getText().toString();
//We need to change this:
SharedPreferences sp = PreferenceManager.getDefaultSharedPreferences(Penalizo.this);
try {
// Building Parameters
List<NameValuePair> params = new ArrayList<NameValuePair>();
params.add(new BasicNameValuePair("user_id", username));
params.add(new BasicNameValuePair("pajisje_id", pajisje_id));
params.add(new BasicNameValuePair("data", formattedDate));
params.add(new BasicNameValuePair("targa", targa));
params.add(new BasicNameValuePair("imazhi", path));
if(checkbox1.isChecked()) {
params.add(new BasicNameValuePair("gjoba1", String.valueOf(spinner1.getSelectedItem())));
params.add(new BasicNameValuePair("shuma1", checkbox1.getText().toString()));
}
if(checkbox2.isChecked())
{
params.add(new BasicNameValuePair("gjoba2", String.valueOf(spinner2.getSelectedItem())));
params.add(new BasicNameValuePair("shuma2", checkbox2.getText().toString()));
}
if(checkbox3.isChecked())
{
params.add(new BasicNameValuePair("gjoba3", String.valueOf(spinner3.getSelectedItem())));
}
if(checkbox1.isChecked()&&checkbox2.isChecked()&&!checkbox3.isChecked())
{
params.add(new BasicNameValuePair("gjoba1", String.valueOf(spinner1.getSelectedItem())));
params.add(new BasicNameValuePair("gjoba2", String.valueOf(spinner2.getSelectedItem())));
params.add(new BasicNameValuePair("shuma1", checkbox1.getText().toString()));
params.add(new BasicNameValuePair("shuma2", checkbox2.getText().toString()));
}
if(checkbox1.isChecked()&&checkbox2.isChecked()&&checkbox3.isChecked())
{
params.add(new BasicNameValuePair("gjoba1", String.valueOf(spinner1.getSelectedItem())));
params.add(new BasicNameValuePair("gjoba2", String.valueOf(spinner2.getSelectedItem())));
params.add(new BasicNameValuePair("gjoba3", String.valueOf(spinner3.getSelectedItem())));
params.add(new BasicNameValuePair("shuma1", checkbox1.getText().toString()));
params.add(new BasicNameValuePair("shuma2", checkbox2.getText().toString()));
}
if(checkbox2.isChecked()&&checkbox3.isChecked()&&!checkbox1.isChecked())
{
params.add(new BasicNameValuePair("gjoba2", String.valueOf(spinner2.getSelectedItem())));
params.add(new BasicNameValuePair("gjoba3", String.valueOf(spinner3.getSelectedItem())));
params.add(new BasicNameValuePair("shuma2", checkbox2.getText().toString()));
}
if(checkbox1.isChecked()&&checkbox3.isChecked()&&!checkbox2.isChecked())
{
params.add(new BasicNameValuePair("gjoba1", String.valueOf(spinner1.getSelectedItem())));
params.add(new BasicNameValuePair("gjoba3", String.valueOf(spinner3.getSelectedItem())));
params.add(new BasicNameValuePair("shuma1", checkbox1.getText().toString()));
}
Log.d("request!", "starting");
//Posting user data to script
JSONObject json = jsonParser.makeHttpRequest(
POST_COMMENT_URL, "POST", params);
// full json response
Log.d("Post Comment attempt", json.toString());
// json success element
success = json.getInt(TAG_SUCCESS);
if (success == 1) {
Log.d("Values Added!", json.toString());
finish();
return json.getString(TAG_MESSAGE);
}else{
Log.d("Insert Failure!", json.getString(TAG_MESSAGE));
return json.getString(TAG_MESSAGE);
}
} catch (JSONException e) {
e.printStackTrace();
}
return null;
}
protected void onPostExecute(String file_url) {
// dismiss the dialog once product deleted
pDialog.dismiss();
if (file_url != null){
Toast.makeText(Penalizo.this, file_url, Toast.LENGTH_LONG).show();
}
}
}
}
| Java |
package com.birdorg.anpr.sdk.simple.camera.example;
import android.app.Activity;
import android.app.ListActivity;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.Bundle;
import android.text.Editable;
import android.text.TextWatcher;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.ListAdapter;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;
import java.io.FileInputStream;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.Date;
/**
* Created by john on 7/18/2014.
*/
public class ANPRInfo extends Activity implements View.OnClickListener {
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activityinfo);
setTitle("FIRST AUTO-LPR - Version 1.0.8 - Tirana");
ImageView imageView2 = (ImageView) findViewById(R.id.imageView2);
ImageView imageView3 = (ImageView) findViewById(R.id.imageView3);
TextView tv3 = (TextView) findViewById(R.id.intent3);
//tv3.setText("Targa: ");
ReadFromFile rd = new ReadFromFile();
String tr = rd.readFromFileSDK();
DateFormat dateFormat = new SimpleDateFormat("dd-MM-yyyy");
//get current date time with Date()
Date date = new Date();
String pathsdk = "/sdcard/sdk/example/images/"+dateFormat.format(date)+"/";
String name = pathsdk+tr; // photo file on the SD card
Bitmap bitmap = BitmapFactory.decodeFile(name);
String tt = rd.readFromFileSDKCut();
String sm = tt.substring(0, 1);
tv3.setText("AA "+tt);
Toast.makeText(getApplicationContext(), "Targa: AA"+tt+"-", Toast.LENGTH_SHORT).show();
int some = Integer.parseInt(sm);
if (some == 1) {
TextView tv4 = (TextView) findViewById(R.id.intent4);
tv4.setText("Ngjyra: E Bardhe");
TextView tv5 = (TextView) findViewById(R.id.intent5);
tv5.setText("Marka: Peageut");
TextView tv6 = (TextView) findViewById(R.id.intent6);
tv6.setText("Gjoba: Jo");
TextView tv7 = (TextView) findViewById(R.id.intent7);
tv7.setText("Kontroll Teknik: Po");
TextView tv8 = (TextView) findViewById(R.id.intent8);
tv8.setText("Siguracione: Po");
}else if (some == 2 ){
TextView tv4 = (TextView) findViewById(R.id.intent4);
tv4.setText("Ngjyra: E Zeze ");
TextView tv5 = (TextView) findViewById(R.id.intent5);
tv5.setText("Marka: Ford");
TextView tv6 = (TextView) findViewById(R.id.intent6);
tv6.setText("Gjoba: Po");
TextView tv7 = (TextView) findViewById(R.id.intent7);
tv7.setText("Kontroll Teknik: Jo");
TextView tv8 = (TextView) findViewById(R.id.intent8);
tv8.setText("Siguracione: Jo");
}else if (some == 3)
{
TextView tv4 = (TextView) findViewById(R.id.intent4);
tv4.setText("Ngjyra: E Kuqe");
TextView tv5 = (TextView) findViewById(R.id.intent5);
tv5.setText("Marka: Toyota");
TextView tv6 = (TextView) findViewById(R.id.intent6);
tv6.setText("Gjoba: Jo");
TextView tv7 = (TextView) findViewById(R.id.intent7);
tv7.setText("Kontroll Teknik: Po");
TextView tv8 = (TextView) findViewById(R.id.intent8);
tv8.setText("Siguracione: Po");
}else if (some == 4)
{
TextView tv4 = (TextView) findViewById(R.id.intent4);
tv4.setText("Ngjyra: Blu");
TextView tv5 = (TextView) findViewById(R.id.intent5);
tv5.setText("Marka: BMW");
TextView tv6 = (TextView) findViewById(R.id.intent6);
tv6.setText("Gjoba: Po");
TextView tv7 = (TextView) findViewById(R.id.intent7);
tv7.setText("Kontroll Teknik: Po");
TextView tv8 = (TextView) findViewById(R.id.intent8);
tv8.setText("Siguracione: Po");
}else if (some == 5)
{
TextView tv4 = (TextView) findViewById(R.id.intent4);
tv4.setText("Ngjyra: Gri");
TextView tv5 = (TextView) findViewById(R.id.intent5);
tv5.setText("Marka: Renault");
TextView tv6 = (TextView) findViewById(R.id.intent6);
tv6.setText("Gjoba: Po");
TextView tv7 = (TextView) findViewById(R.id.intent7);
tv7.setText("Kontroll Teknik: Po");
TextView tv8 = (TextView) findViewById(R.id.intent8);
tv8.setText("Siguracione: Jo");
}else if (some == 6)
{
TextView tv4 = (TextView) findViewById(R.id.intent4);
tv4.setText("Ngjyra: E Zeze");
TextView tv5 = (TextView) findViewById(R.id.intent5);
tv5.setText("Marka: Chevrolet");
TextView tv6 = (TextView) findViewById(R.id.intent6);
tv6.setText("Gjoba: Jo");
TextView tv7 = (TextView) findViewById(R.id.intent7);
tv7.setText("Kontroll Teknik: Po");
TextView tv8 = (TextView) findViewById(R.id.intent8);
tv8.setText("Siguracione: Po");
}else {
TextView tv4 = (TextView) findViewById(R.id.intent4);
tv4.setText("Ngjyra: E Kuqe");
TextView tv5 = (TextView) findViewById(R.id.intent5);
tv5.setText("Marka: Ford");
TextView tv6 = (TextView) findViewById(R.id.intent6);
tv6.setText("Gjoba: Jo");
TextView tv7 = (TextView) findViewById(R.id.intent7);
tv7.setText("Kontroll Teknik: Po");
TextView tv8 = (TextView) findViewById(R.id.intent8);
tv8.setText("Siguracione: Jo");
}
if (bitmap != null) {
imageView2.setImageBitmap(bitmap);
} else {
imageView2.setImageResource(R.drawable.car2);
}
Button but1 = (Button) findViewById(R.id.button);
but1.setOnClickListener(ANPRInfo.this);
Button but2 = (Button) findViewById(R.id.button2);
but2.setOnClickListener(ANPRInfo.this);
Button but3 = (Button) findViewById(R.id.button3);
but3.setOnClickListener(ANPRInfo.this);
}
@Override
public void onClick(View view) {
int id = view.getId();
if (id == R.id.button) {
Class ourClass = null;
try {
ourClass = Class.forName("com.birdorg.anpr.sdk.simple.camera.example.ANPRPenalizo");
Intent ourIntent = new Intent(ANPRInfo.this, ourClass);
startActivity(ourIntent);
} catch (ClassNotFoundException e) {
e.printStackTrace();
}
}else if (id == R.id.button2) {
Class ourClass = null;
try {
ourClass = Class.forName("com.birdorg.anpr.sdk.simple.camera.example.KontrolletSotme");
Intent ourIntent = new Intent(ANPRInfo.this, ourClass);
startActivity(ourIntent);
} catch (ClassNotFoundException e) {
e.printStackTrace();
}
}else if (id == R.id.button3) {
Class ourClass = null;
try {
ourClass = Class.forName("com.birdorg.anpr.sdk.simple.camera.example.Kontrollo");
Intent ourIntent = new Intent(ANPRInfo.this, ourClass);
startActivity(ourIntent);
} catch (ClassNotFoundException e) {
e.printStackTrace();
}
}
}
}
| Java |
package com.birdorg.anpr.sdk.simple.camera.example;
import android.app.Activity;
import android.content.DialogInterface;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.view.View;
/**
* Created by john on 7/18/2014.
*/
import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;
import java.io.File;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.text.DateFormat;
import java.text.Format;
import java.text.SimpleDateFormat;
import java.util.Date;
import it.sauronsoftware.ftp4j.FTPClient;
public class Info extends Activity {
ImageView imageView2;
ImageView imageView3;
String path;
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.activityinfo);
imageView2=(ImageView)findViewById(R.id.imageView2);
imageView3=(ImageView)findViewById(R.id.imageView3);
TextView tv3 = (TextView) findViewById(R.id.intent3);
TextView tv4 = (TextView) findViewById(R.id.intent4);
TextView tv5 = (TextView) findViewById(R.id.intent5);
TextView tv6 = (TextView) findViewById(R.id.intent6);
TextView tv7 = (TextView) findViewById(R.id.intent7);
TextView tv8 = (TextView) findViewById(R.id.intent8);
TextView tv9 = (TextView) findViewById(R.id.intent9);
TextView tv11 = (TextView) findViewById(R.id.intent11);
Button btnValidate = (Button)findViewById(R.id.button);
Button lista = (Button)findViewById(R.id.button2);
Button kontrollo = (Button)findViewById(R.id.button3);
String username = getIntent().getExtras().getString("Username");
tv3.setText(""+getIntent().getExtras().getString("Targa"));
tv4.setText("Ngjyra: "+getIntent().getExtras().getString("Ngjyra"));
tv5.setText("Marka: "+getIntent().getExtras().getString("Marka"));
tv6.setText("Gjoba: "+getIntent().getExtras().getString("Gjoba"));
tv7.setText("Siguracion: "+getIntent().getExtras().getString("Siguracion"));
tv8.setText("Sgs: "+getIntent().getExtras().getString("Sgs"));
tv9.setText("Pronar: "+getIntent().getExtras().getString("Pronar"));
tv11.setText(""+getIntent().getExtras().getString("FotoPath"));
if(getIntent().getExtras().getString("Gjoba").equals("jo")) {
imageView3.setImageResource(R.drawable.status2);
}else if(getIntent().getExtras().getString("Gjoba").equals("po"))
{
imageView3.setImageResource(R.drawable.status1);
}else
imageView3.setImageResource(R.drawable.status1);
path = tv11.getText().toString();
Bitmap bitmap = getBitmap(path);
if (bitmap != null) {
ImageView imageView = (ImageView) findViewById(R.id.imageView2);
imageView.setImageBitmap(bitmap);
}
btnValidate.setOnClickListener(new View.OnClickListener()
{
public void onClick(View arg0) {
final TextView plate = (TextView) findViewById(R.id.intent3);
final TextView ngjyra = (TextView) findViewById(R.id.intent4);
final TextView marka = (TextView) findViewById(R.id.intent5);
// final TextView pronar = (TextView) findViewById(R.id.intent9);
Intent intent = new Intent(Info.this,Penalizo.class);
intent.putExtra("Targa", plate.getText().toString());
intent.putExtra("Ngjyra", ngjyra.getText().toString());
intent.putExtra("Marka", marka.getText().toString());
intent.putExtra("FotoPath", path);
intent.putExtra("Username", getIntent().getExtras().getString("Username"));
startActivity(intent);
}
});
lista.setOnClickListener(new View.OnClickListener()
{
public void onClick(View arg0) {
Intent intent = new Intent(Info.this,Lista.class);
intent.putExtra("Username", getIntent().getExtras().getString("Username"));
startActivity(intent);
}
});
kontrollo.setOnClickListener(new View.OnClickListener()
{
public void onClick(View arg0) {
Intent intent = new Intent(Info.this,Kontrollo.class);
intent.putExtra("Username", getIntent().getExtras().getString("Username"));
startActivity(intent);
}
});
}
private Bitmap getBitmap(String url)
{
try {
Bitmap bitmap=null;
URL imageUrl = new URL(url);
HttpURLConnection conn = (HttpURLConnection)imageUrl.openConnection();
conn.setDoInput(true);
conn.connect();
InputStream input = conn.getInputStream();
bitmap = BitmapFactory.decodeStream(input);
return bitmap;
} catch (Exception ex){
ex.printStackTrace();
return null;
}
}
} | Java |
package com.birdorg.anpr.sdk.simple.camera.example;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.Environment;
import android.util.Log;
import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStreamWriter;
import java.text.DateFormat;
import java.text.Format;
import java.text.SimpleDateFormat;
import java.util.Date;
/**
* Created by john on 7/30/2014.
*/
public class StoreFile {
public boolean storeImage(String filename) {
//get path to external storage (SD card)
String iconsStoragePath = Environment.getExternalStorageDirectory() + "/myAppDir/myImages/";
File sdIconStorageDir = new File(iconsStoragePath);
//create storage directories, if they don't exist
sdIconStorageDir.mkdirs();
DateFormat dateFormat = new SimpleDateFormat("dd-MM-yyyy ");
//get current date time with Date()
Date date = new Date();
Format formatter = new SimpleDateFormat("HH.mm.ss");
String time = formatter.format(new Date());
File dir = new File("/sdcard/sdk/example/images/"+dateFormat.format(date)+"/");
try {
File file = new File ("/sdcard/sdk/example/images/"+dateFormat.format(date)+"/"+filename+".txt");
file.createNewFile();
FileOutputStream fOut = new FileOutputStream(file);
OutputStreamWriter myOutWriter =new OutputStreamWriter(fOut);
myOutWriter.append("----"+filename);
myOutWriter.close();
fOut.close();
} catch (FileNotFoundException e) {
Log.w("TAG", "Error saving image file: " + e.getMessage());
return false;
} catch (IOException e) {
Log.w("TAG", "Error saving image file: " + e.getMessage());
return false;
}
return false;
}
}
| Java |
package com.birdorg.anpr.sdk.simple.camera.example;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.UnsupportedEncodingException;
import java.util.List;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.client.utils.URLEncodedUtils;
import org.apache.http.impl.client.DefaultHttpClient;
import org.json.JSONException;
import org.json.JSONObject;
import android.util.Log;
public class JSONParser {
static InputStream is = null;
static JSONObject jObj = null;
static String json = "";
// constructor
public JSONParser() {
}
public JSONObject getJSONFromUrl(final String url) {
// Making HTTP request
try {
// Construct the client and the HTTP request.
DefaultHttpClient httpClient = new DefaultHttpClient();
HttpPost httpPost = new HttpPost(url);
// Execute the POST request and store the response locally.
HttpResponse httpResponse = httpClient.execute(httpPost);
// Extract data from the response.
HttpEntity httpEntity = httpResponse.getEntity();
// Open an inputStream with the data content.
is = httpEntity.getContent();
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
} catch (ClientProtocolException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
try {
// Create a BufferedReader to parse through the inputStream.
BufferedReader reader = new BufferedReader(new InputStreamReader(
is, "iso-8859-1"), 8);
// Declare a string builder to help with the parsing.
StringBuilder sb = new StringBuilder();
// Declare a string to store the JSON object data in string form.
String line = null;
// Build the string until null.
while ((line = reader.readLine()) != null) {
sb.append(line + "\n");
}
// Close the input stream.
is.close();
// Convert the string builder data to an actual string.
json = sb.toString();
} catch (Exception e) {
Log.e("Buffer Error", "Error converting result " + e.toString());
}
// Try to parse the string to a JSON object
try {
jObj = new JSONObject(json);
} catch (JSONException e) {
Log.e("JSON Parser", "Error parsing data " + e.toString());
}
// Return the JSON Object.
return jObj;
}
// function get json from url
// by making HTTP POST or GET mehtod
public JSONObject makeHttpRequest(String url, String method,
List<NameValuePair> params) {
// Making HTTP request
try {
// check for request method
if(method == "POST"){
// request method is POST
// defaultHttpClient
DefaultHttpClient httpClient = new DefaultHttpClient();
HttpPost httpPost = new HttpPost(url);
httpPost.setEntity(new UrlEncodedFormEntity(params));
HttpResponse httpResponse = httpClient.execute(httpPost);
HttpEntity httpEntity = httpResponse.getEntity();
is = httpEntity.getContent();
}else if(method == "GET"){
// request method is GET
DefaultHttpClient httpClient = new DefaultHttpClient();
String paramString = URLEncodedUtils.format(params, "utf-8");
url += "?" + paramString;
HttpGet httpGet = new HttpGet(url);
HttpResponse httpResponse = httpClient.execute(httpGet);
HttpEntity httpEntity = httpResponse.getEntity();
is = httpEntity.getContent();
}
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
} catch (ClientProtocolException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
try {
BufferedReader reader = new BufferedReader(new InputStreamReader(
is, "iso-8859-1"), 8);
StringBuilder sb = new StringBuilder();
String line = null;
while ((line = reader.readLine()) != null) {
sb.append(line + "\n");
}
is.close();
json = sb.toString();
} catch (Exception e) {
Log.e("Buffer Error", "Error converting result " + e.toString());
}
// try parse the string to a JSON object
try {
jObj = new JSONObject(json);
} catch (JSONException e) {
Log.e("JSON Parser", "Error parsing data " + e.toString());
}
// return JSON String
return jObj;
}
}
| Java |
package com.birdorg.anpr.sdk.simple.camera.example;
import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.ImageView;
import android.widget.TextView;
import java.io.InputStream;
import java.lang.reflect.Array;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Vector;
/**
* Created by john on 8/2/2014.
*/
public class KontrolletSotmeAdapter extends ArrayAdapter<ItemKontrollo> {
private final Context context;
ItemKontrollo item ;
Vector<ItemKontrollo> vec = new Vector<ItemKontrollo>();
public KontrolletSotmeAdapter(Context context, Vector<ItemKontrollo> vecc) {
super(context, R.layout.kontrolletsotme, vecc);
this.context = context;
this.vec = vecc;
}
@Override
public View getView(int position, View convertView, ViewGroup parent) {
LayoutInflater inflater = (LayoutInflater) context
.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
View rowView = inflater.inflate(R.layout.kontrolletsotme, parent, false);
TextView t1 = (TextView) rowView.findViewById(R.id.label_targa);
TextView t2 = (TextView) rowView.findViewById(R.id.label_data);
TextView t3 = (TextView) rowView.findViewById(R.id.label_user);
TextView t4hidden = (TextView) rowView.findViewById(R.id.label_path);
t1.setText(vec.get(position).getTarga());
t2.setText(vec.get(position).getData());
t3.setText(vec.get(position).getUser());
t4hidden.setText(vec.get(position).getImgpath());
String path = t4hidden.getText().toString();
Bitmap bitmap = getBitmap(path);
if (bitmap != null) {
ImageView imageView = (ImageView) rowView.findViewById(R.id.label_capture_image);
imageView.setImageBitmap(bitmap);
}
return rowView;
}
private Bitmap getBitmap(String url)
{
try {
Bitmap bitmap=null;
URL imageUrl = new URL(url);
HttpURLConnection conn = (HttpURLConnection)imageUrl.openConnection();
conn.setDoInput(true);
conn.connect();
InputStream input = conn.getInputStream();
bitmap = BitmapFactory.decodeStream(input);
return bitmap;
} catch (Exception ex){
ex.printStackTrace();
return null;
}
}
}
| Java |
package com.birdorg.anpr.sdk.simple.camera.example;
import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.ImageView;
import android.widget.TextView;
import java.util.Vector;
/**
* Created by gh on 7/21/2014.
*/
public class MenuArrayAdapter extends ArrayAdapter<String> {
private final Context context;
private final String[] values;
Vector some = new Vector();
public MenuArrayAdapter(Context context, String[] values) {
super(context, R.layout.list_menu, values);
this.context = context;
this.values = values;
}
@Override
public View getView(int position, View convertView, ViewGroup parent) {
LayoutInflater inflater = (LayoutInflater) context
.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
View rowView = inflater.inflate(R.layout.list_menu, parent, false);
TextView textView = (TextView) rowView.findViewById(R.id.label);
ImageView imageView = (ImageView) rowView.findViewById(R.id.logo);
textView.setText(values[position]);
// Change icon based on name
String s = values[position];
//"Kontrollet e Sotme", "Penalizimet e Sotme",
System.out.println(s);
if (s.equals("Kontrollo")) {
imageView.setImageResource(R.drawable.cam);
} else if (s.equals("Lista")) {
imageView.setImageResource(R.drawable.listm);
} else if (s.equals("Konfigurimet")) {
imageView.setImageResource(R.drawable.set);
} else if (s.equals("Kontrollet e Sotme")) {
imageView.setImageResource(R.drawable.ksot);
}else if (s.equals("Penalizimet e Sotme")) {
imageView.setImageResource(R.drawable.write);
}
return rowView;
}
}
| Java |
package com.birdorg.anpr.sdk.simple.camera.example;
import java.util.ArrayList;
import java.util.List;
import org.apache.http.NameValuePair;
import org.apache.http.message.BasicNameValuePair;
import org.json.JSONException;
import org.json.JSONObject;
import android.app.Activity;
import android.app.ProgressDialog;
import android.content.Intent;
import android.os.AsyncTask;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;
import android.app.AlertDialog;
public class AnprSdkMain extends Activity implements OnClickListener{
private EditText user, pass;
private Button mSubmit, mRegister;
// Progress Dialog
private ProgressDialog pDialog;
// JSON parser class
JSONParser jsonParser = new JSONParser();
private static final String LOGIN_URL = "http://www.comport.first.al/anpr/login.php";
private static final String TAG_SUCCESS = "success";
private static final String TAG_MESSAGE = "message";
@Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
//setup input fields
user = (EditText)findViewById(R.id.editText1);
pass = (EditText)findViewById(R.id.editText2);
//setup buttons
mSubmit = (Button)findViewById(R.id.button1);
//register listeners
mSubmit.setOnClickListener(this);
}
@Override
public void onClick(View v) {
// TODO Auto-generated method stub
new AttemptLogin().execute();
}
class AttemptLogin extends AsyncTask<String, String, String> {
/**
* Before starting background thread Show Progress Dialog
* */
boolean failure = false;
@Override
protected void onPreExecute() {
super.onPreExecute();
pDialog = new ProgressDialog(AnprSdkMain.this);
pDialog.setMessage("Login...");
pDialog.setIndeterminate(false);
pDialog.setCancelable(true);
pDialog.show();
}
@Override
protected String doInBackground(String... args) {
// TODO Auto-generated method stub
// Check for success tag
int success;
String username = user.getText().toString();
String password = pass.getText().toString();
try {
// Building Parameters
List<NameValuePair> params = new ArrayList<NameValuePair>();
params.add(new BasicNameValuePair("username", username));
params.add(new BasicNameValuePair("password", password));
Log.d("request!", "starting");
// getting product details by making HTTP request
JSONObject json = jsonParser.makeHttpRequest(
LOGIN_URL, "POST", params);
// check your log for json response
Log.d("Login attempt", json.toString());
success = json.getInt(TAG_SUCCESS);
if (success == 1) {
Log.d("Login u krye me sukses!", json.toString());
Intent i = new Intent(AnprSdkMain.this, AnprSdkMenu.class);
i.putExtra("Username",username);
finish();
startActivity(i);
return json.getString(TAG_MESSAGE);
}else if(success == 0){
Log.d("Login deshtoi!", json.toString());
return json.getString(TAG_MESSAGE);
}
} catch (JSONException e) {
e.printStackTrace();
}
return null;
}
/**
* After completing background task Dismiss the progress dialog
* **/
protected void onPostExecute(String file_url) {
// dismiss the dialog once product deleted
pDialog.dismiss();
if (file_url != null){
Toast.makeText(AnprSdkMain.this, file_url, Toast.LENGTH_LONG).show();
}
}
}
}
| Java |
/*
* Copyright (c) 1997, 2006, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation. Oracle designates this
* particular file as subject to the "Classpath" exception as provided
* by Oracle in the LICENSE file that accompanied this code.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
package java.util;
/**
* {@collect.stats}
* fdslkgjhfklghjdfklghjfdkgjfdglkfdjgdflg
* gfjlkdgjdflkgjdflkgjdfklgfjgdlkfgjfdlkgjdfgk
* fgjlkfdjglkfdjglkdfjglkfdjglkfdjgkldfjglkdfjgl
*{@description.open}
* The root interface in the <i>collection hierarchy</i>. A collection
* represents a group of objects, known as its <i>elements</i>. Some
* collections allow duplicate elements and others do not. Some are ordered
* and others unordered. The JDK does not provide any <i>direct</i>
* implementations of this interface: it provides implementations of more
* specific subinterfaces like <tt>Set</tt> and <tt>List</tt>. This interface
* is typically used to pass collections around and manipulate them where
* maximum generality is desired.
*
* <p><i>Bags</i> or <i>multisets</i> (unordered collections that may contain
* duplicate elements) should implement this interface directly.
* {@description.close}
*
* {@property.open}
* <p>All general-purpose <tt>Collection</tt> implementation classes (which
* typically implement <tt>Collection</tt> indirectly through one of its
* subinterfaces) should provide two "standard" constructors: a void (no
* arguments) constructor, which creates an empty collection, and a
* constructor with a single argument of type <tt>Collection</tt>, which
* creates a new collection with the same elements as its argument.
*{@property.close} {@description.open} In
* effect, the latter constructor allows the user to copy any collection,
* producing an equivalent collection of the desired implementation type.
* There is no way to enforce this convention (as interfaces cannot contain
* constructors) but all of the general-purpose <tt>Collection</tt>
* implementations in the Java platform libraries comply. {@description.close}
*
* {@property.open}
* <p>The "destructive" methods contained in this interface, that is, the
* methods that modify the collection on which they operate, are specified to
* throw <tt>UnsupportedOperationException</tt> if this collection does not
* support the operation. If this is the case, these methods may, but are not
* required to, throw an <tt>UnsupportedOperationException</tt> if the
* invocation would have no effect on the collection. {@property.close}
* {@description.open} For example, invoking
* the {@link #addAll(Collection)} method on an unmodifiable collection may,
* but is not required to, throw the exception if the collection to be added
* is empty. {@description.close}
*
* {@description.open}
* <p>Some collection implementations have restrictions on the elements that
* they may contain. For example, some implementations prohibit null elements,
* and some have restrictions on the types of their elements. Attempting to
* add an ineligible element throws an unchecked exception, typically
* <tt>NullPointerException</tt> or <tt>ClassCastException</tt>. Attempting
* to query the presence of an ineligible element may throw an exception,
* or it may simply return false; some implementations will exhibit the former
* behavior and some will exhibit the latter. More generally, attempting an
* operation on an ineligible element whose completion would not result in
* the insertion of an ineligible element into the collection may throw an
* exception or it may succeed, at the option of the implementation.
* Such exceptions are marked as "optional" in the specification for this
* interface. {@description.close}
*
* {@description.open}
* <p>It is up to each collection to determine its own synchronization
* policy. In the absence of a stronger guarantee by the
* implementation, undefined behavior may result from the invocation
* of any method on a collection that is being mutated by another
* thread; this includes direct invocations, passing the collection to
* a method that might perform invocations, and using an existing
* iterator to examine the collection.
* {@description.close}
*
* {@description.open}
* <p>Many methods in Collections Framework interfaces are defined in
* terms of the {@link Object#equals(Object) equals} method. For example,
* the specification for the {@link #contains(Object) contains(Object o)}
* method says: "returns <tt>true</tt> if and only if this collection
* contains at least one element <tt>e</tt> such that
* <tt>(o==null ? e==null : o.equals(e))</tt>." This specification should
* <i>not</i> be construed to imply that invoking <tt>Collection.contains</tt>
* with a non-null argument <tt>o</tt> will cause <tt>o.equals(e)</tt> to be
* invoked for any element <tt>e</tt>. Implementations are free to implement
* optimizations whereby the <tt>equals</tt> invocation is avoided, for
* example, by first comparing the hash codes of the two elements. (The
* {@link Object#hashCode()} specification guarantees that two objects with
* unequal hash codes cannot be equal.) More generally, implementations of
* the various Collections Framework interfaces are free to take advantage of
* the specified behavior of underlying {@link Object} methods wherever the
* implementor deems it appropriate.
*
* <p>This interface is a member of the
* <a href="{@docRoot}/../technotes/guides/collections/index.html">
* Java Collections Framework</a> {@description.close}.
*
* {@property.open} A propertyized property is that for all Collections and
* {@link Iterator Iterators}, said Collection should not be modified
* between the creation of an associated Iterator and any of said Iterator's
* uses {@property.shortcut UnsafeIterator}. Additionally, the
* {@link Iterator#hasNext() hasNext} method of Iterator should always be
* called and return true before the {@link Iterator#next() next} method
* may be called {@property.shortcut HasNext}. While the latter is a property
* of Iterators only, it is included here for ease of reference (and to showcase
* the new propertydocs tools).{@property.close}
*
* @property.mop {@property.name HasNext}
* // This property requires that hasnext be called before next
* // and that hasnext return true. It is a modification of the
* // HasNext property from tracematches
* // (see ECOOP'07 http://abc.comlab.ox.ac.uk/papers),
* // with the modification requiring hasnext to return true
*
* HasNext(Iterator i) {
*
* event hasnexttrue after(Iterator i) returning(boolean b) :
* call(* Iterator.hasNext())
* && target(i) && condition(b) { }
* event hasnextfalse after(Iterator i) returning(boolean b) :
* call(* Iterator.hasNext())
* && target(i) && condition(!b) { }
* event next before(Iterator i) :
* call(* Iterator.next())
* && target(i) { }
*
* ptltl: next => (*) hasnexttrue
*
* \@violation { System.out.println("ltl violated!");}
* }
*
*
* @author Josh Bloch
* @author Neal Gafter
* @see Set
* @see List
* @see Map
* @see SortedSet
* @see SortedMap
* @see HashSet
* @see TreeSet
* @see ArrayList
* @see LinkedList
* @see Vector
* @see Collections
* @see Arrays
* @see AbstractCollection
* @see Iterator
* @since 1.2
*/
public interface Collection<E> extends Iterable<E> {
// Query Operations
/**
* {@collect.stats}
* Returns the number of elements in this collection. If this collection
* contains more than <tt>Integer.MAX_VALUE</tt> elements, returns
* <tt>Integer.MAX_VALUE</tt>.
* @return the number of elements in this collection
*/
int size();
/**{@description.open}
* Returns <tt>true</tt> if this collection contains no elements.
*
* {@description.close}
* @return <tt>true</tt> if this collection contains no elements
*/
boolean isEmpty();
/**{@description.open}
* Returns <tt>true</tt> if this collection contains the specified element.
* More propertyly, returns <tt>true</tt> if and only if this collection
* contains at least one element <tt>e</tt> such that
* <tt>(o==null ? e==null : o.equals(e))</tt>.
*
* {@description.close}
* @param o element whose presence in this collection is to be tested
* @return <tt>true</tt> if this collection contains the specified
* element
* @throws ClassCastException if the type of the specified element
* is incompatible with this collection (optional)
* @throws NullPointerException if the specified element is null and this
* collection does not permit null elements (optional)
*/
boolean contains(Object o);
/**{@description.open}
* Returns an iterator over the elements in this collection. There are no
* guarantees concerning the order in which the elements are returned
* (unless this collection is an instance of some class that provides a
* guarantee).
* {@description.close}
*
* @return an <tt>Iterator</tt> over the elements in this collection
*/
Iterator<E> iterator();
/**{@description.open}
* Returns an array containing all of the elements in this collection.
* If this collection makes any guarantees as to what order its elements
* are returned by its iterator, this method must return the elements in
* the same order.
*
* <p>The returned array will be "safe" in that no references to it are
* maintained by this collection. (In other words, this method must
* allocate a new array even if this collection is backed by an array).
* The caller is thus free to modify the returned array.
*
* <p>This method acts as bridge between array-based and collection-based
* APIs.
* {@description.close}
*
* @return an array containing all of the elements in this collection
*/
Object[] toArray();
/**{@description.open}
* Returns an array containing all of the elements in this collection;
* the runtime type of the returned array is that of the specified array.
* If the collection fits in the specified array, it is returned therein.
* Otherwise, a new array is allocated with the runtime type of the
* specified array and the size of this collection.
*
* <p>If this collection fits in the specified array with room to spare
* (i.e., the array has more elements than this collection), the element
* in the array immediately following the end of the collection is set to
* <tt>null</tt>. (This is useful in determining the length of this
* collection <i>only</i> if the caller knows that this collection does
* not contain any <tt>null</tt> elements.)
* {@description.close}
*
* {@property.open}
* <p>If this collection makes any guarantees as to what order its elements
* are returned by its iterator, this method must return the elements in
* the same order.
* {@property.close}
*
*{@description.open}
* <p>Like the {@link #toArray()} method, this method acts as bridge between
* array-based and collection-based APIs. Further, this method allows
* precise control over the runtime type of the output array, and may,
* under certain circumstances, be used to save allocation costs.
*
* <p>Suppose <tt>x</tt> is a collection known to contain only strings.
* The following code can be used to dump the collection into a newly
* allocated array of <tt>String</tt>:
*
* <pre>
* String[] y = x.toArray(new String[0]);</pre>
*
* Note that <tt>toArray(new Object[0])</tt> is identical in function to
* <tt>toArray()</tt>.
*
* {@description.close}
* @param a the array into which the elements of this collection are to be
* stored, if it is big enough; otherwise, a new array of the same
* runtime type is allocated for this purpose.
* @return an array containing all of the elements in this collection
* @throws ArrayStoreException if the runtime type of the specified array
* is not a supertype of the runtime type of every element in
* this collection
* @throws NullPointerException if the specified array is null
*/
<T> T[] toArray(T[] a);
// Modification Operations
/**{@description.open}
* Ensures that this collection contains the specified element (optional
* operation). Returns <tt>true</tt> if this collection changed as a
* result of the call. (Returns <tt>false</tt> if this collection does
* not permit duplicates and already contains the specified element.)<p>
*
* Collections that support this operation may place limitations on what
* elements may be added to this collection. In particular, some
* collections will refuse to add <tt>null</tt> elements, and others will
* impose restrictions on the type of elements that may be added.
* Collection classes should clearly specify in their documentation any
* restrictions on what elements may be added.<p>
* {@description.close}
*
* {@property.open}
* If a collection refuses to add a particular element for any reason
* other than that it already contains the element, it <i>must</i> throw
* an exception (rather than returning <tt>false</tt>). This preserves
* the invariant that a collection always contains the specified element
* after this call returns.
* {@property.close}
*
* @param e element whose presence in this collection is to be ensured
* @return <tt>true</tt> if this collection changed as a result of the
* call
* @throws UnsupportedOperationException if the <tt>add</tt> operation
* is not supported by this collection
* @throws ClassCastException if the class of the specified element
* prevents it from being added to this collection
* @throws NullPointerException if the specified element is null and this
* collection does not permit null elements
* @throws IllegalArgumentException if some property of the element
* prevents it from being added to this collection
* @throws IllegalStateException if the element cannot be added at this
* time due to insertion restrictions
*/
boolean add(E e);
/**{@description.open}
* Removes a single instance of the specified element from this
* collection, if it is present (optional operation). More propertyly,
* removes an element <tt>e</tt> such that
* <tt>(o==null ? e==null : o.equals(e))</tt>, if
* this collection contains one or more such elements. Returns
* <tt>true</tt> if this collection contained the specified element (or
* equivalently, if this collection changed as a result of the call).
* {@description.close}
*
* @param o element to be removed from this collection, if present
* @return <tt>true</tt> if an element was removed as a result of this call
* @throws ClassCastException if the type of the specified element
* is incompatible with this collection (optional)
* @throws NullPointerException if the specified element is null and this
* collection does not permit null elements (optional)
* @throws UnsupportedOperationException if the <tt>remove</tt> operation
* is not supported by this collection
*/
boolean remove(Object o);
// Bulk Operations
/**{@description.open}
* Returns <tt>true</tt> if this collection contains all of the elements
* in the specified collection.
*{@description.close}
* @param c collection to be checked for containment in this collection
* @return <tt>true</tt> if this collection contains all of the elements
* in the specified collection
* @throws ClassCastException if the types of one or more elements
* in the specified collection are incompatible with this
* collection (optional)
* @throws NullPointerException if the specified collection contains one
* or more null elements and this collection does not permit null
* elements (optional), or if the specified collection is null
* @see #contains(Object)
*/
boolean containsAll(Collection<?> c);
/**{@description.open}
* Adds all of the elements in the specified collection to this collection
* (optional operation). The behavior of this operation is undefined if
* the specified collection is modified while the operation is in progress.
* (This implies that the behavior of this call is undefined if the
* specified collection is this collection, and this collection is
* nonempty.)
*{@description.close}
*
* @param c collection containing elements to be added to this collection
* @return <tt>true</tt> if this collection changed as a result of the call
* @throws UnsupportedOperationException if the <tt>addAll</tt> operation
* is not supported by this collection
* @throws ClassCastException if the class of an element of the specified
* collection prevents it from being added to this collection
* @throws NullPointerException if the specified collection contains a
* null element and this collection does not permit null elements,
* or if the specified collection is null
* @throws IllegalArgumentException if some property of an element of the
* specified collection prevents it from being added to this
* collection
* @throws IllegalStateException if not all the elements can be added at
* this time due to insertion restrictions
* @see #add(Object)
*/
boolean addAll(Collection<? extends E> c);
/**{@description.open}
* Removes all of this collection's elements that are also contained in the
* specified collection (optional operation). After this call returns,
* this collection will contain no elements in common with the specified
* collection.
* {@description.close}
*
* @param c collection containing elements to be removed from this collection
* @return <tt>true</tt> if this collection changed as a result of the
* call
* @throws UnsupportedOperationException if the <tt>removeAll</tt> method
* is not supported by this collection
* @throws ClassCastException if the types of one or more elements
* in this collection are incompatible with the specified
* collection (optional)
* @throws NullPointerException if this collection contains one or more
* null elements and the specified collection does not support
* null elements (optional), or if the specified collection is null
* @see #remove(Object)
* @see #contains(Object)
*/
boolean removeAll(Collection<?> c);
/**{@description.open}
* Retains only the elements in this collection that are contained in the
* specified collection (optional operation). In other words, removes from
* this collection all of its elements that are not contained in the
* specified collection.
* {@description.close}
*
* @param c collection containing elements to be retained in this collection
* @return <tt>true</tt> if this collection changed as a result of the call
* @throws UnsupportedOperationException if the <tt>retainAll</tt> operation
* is not supported by this collection
* @throws ClassCastException if the types of one or more elements
* in this collection are incompatible with the specified
* collection (optional)
* @throws NullPointerException if this collection contains one or more
* null elements and the specified collection does not permit null
* elements (optional), or if the specified collection is null
* @see #remove(Object)
* @see #contains(Object)
*/
boolean retainAll(Collection<?> c);
/**{@description.open}
* Removes all of the elements from this collection (optional operation).
* The collection will be empty after this method returns.
* {@description.close}
*
* @throws UnsupportedOperationException if the <tt>clear</tt> operation
* is not supported by this collection
*/
void clear();
// Comparison and hashing
/**{@description.open}
* Compares the specified object with this collection for equality. <p>
*
* While the <tt>Collection</tt> interface adds no stipulations to the
* general contract for the <tt>Object.equals</tt>, programmers who
* implement the <tt>Collection</tt> interface "directly" (in other words,
* create a class that is a <tt>Collection</tt> but is not a <tt>Set</tt>
* or a <tt>List</tt>) must exercise care if they choose to override the
* <tt>Object.equals</tt>. It is not necessary to do so, and the simplest
* course of action is to rely on <tt>Object</tt>'s implementation, but
* the implementor may wish to implement a "value comparison" in place of
* the default "reference comparison." (The <tt>List</tt> and
* <tt>Set</tt> interfaces mandate such value comparisons.)<p>
* {@description.close}
* {@property.open}
* The general contract for the <tt>Object.equals</tt> method states that
* equals must be symmetric (in other words, <tt>a.equals(b)</tt> if and
* only if <tt>b.equals(a)</tt>). The contracts for <tt>List.equals</tt>
* and <tt>Set.equals</tt> state that lists are only equal to other lists,
* and sets to other sets. Thus, a custom <tt>equals</tt> method for a
* collection class that implements neither the <tt>List</tt> nor
* <tt>Set</tt> interface must return <tt>false</tt> when this collection
* is compared to any list or set. (By the same logic, it is not possible
* to write a class that correctly implements both the <tt>Set</tt> and
* <tt>List</tt> interfaces.)
* {@property.close}
*
* {@description.close}
* @param o object to be compared for equality with this collection
* @return <tt>true</tt> if the specified object is equal to this
* collection
*
* @see Object#equals(Object)
* @see Set#equals(Object)
* @see List#equals(Object)
*/
boolean equals(Object o);
/**{@description.open}
* Returns the hash code value for this collection. While the
* <tt>Collection</tt> interface adds no stipulations to the general
* contract for the <tt>Object.hashCode</tt> method, programmers should
* take note that any class that overrides the <tt>Object.equals</tt>
* method must also override the <tt>Object.hashCode</tt> method in order
* to satisfy the general contract for the <tt>Object.hashCode</tt>method.
* {@description.close}
* {@property.open}
* In particular, <tt>c1.equals(c2)</tt> implies that
* <tt>c1.hashCode()==c2.hashCode()</tt>.
*{@property.close}
* @return the hash code value for this collection
*
* @see Object#hashCode()
* @see Object#equals(Object)
*/
int hashCode();
}
| Java |
/*
* Copyright (c) 1997, 2006, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation. Oracle designates this
* particular file as subject to the "Classpath" exception as provided
* by Oracle in the LICENSE file that accompanied this code.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
package java.util;
/**
* {@undecided.open}
* An iterator over a collection. {@code Iterator} takes the place of
* {@link Enumeration} in the Java Collections Framework. Iterators
* differ from enumerations in two ways:
*
* <ul>
* <li> Iterators allow the caller to remove elements from the
* underlying collection during the iteration with well-defined
* semantics.
* <li> Method names have been improved.
* </ul>
*
* <p>This interface is a member of the
* <a href="{@docRoot}/../technotes/guides/collections/index.html">
* Java Collections Framework</a>.
* {@undecided.close}
*
* @author Josh Bloch
* @see Collection
* @see ListIterator
* @see Iterable
* @since 1.2
*/
public interface Iterator<E> {
/**
* {@undecided.open}
* Returns {@code true} if the iteration has more elements.
* (In other words, returns {@code true} if {@link #next} would
* return an element rather than throwing an exception.)
* {@undecided.close}
*
* @return {@code true} if the iteration has more elements
*/
boolean hasNext();
/**
* {@undecided.open}
* Returns the next element in the iteration.
* {@undecided.close}
*
* @return the next element in the iteration
* @throws NoSuchElementException if the iteration has no more elements
*/
E next();
/**
* {@undecided.open}
* Removes from the underlying collection the last element returned
* by this iterator (optional operation). This method can be called
* only once per call to {@link #next}. The behavior of an iterator
* is unspecified if the underlying collection is modified while the
* iteration is in progress in any way other than by calling this
* method.
* {@undecided.close}
*
* @throws UnsupportedOperationException if the {@code remove}
* operation is not supported by this iterator
*
* @throws IllegalStateException if the {@code next} method has not
* yet been called, or the {@code remove} method has already
* been called after the last call to the {@code next}
* method
*/
void remove();
}
| Java |
package edu.uiuc.cs.fsl.propertydocs.util;
import com.sun.javadoc.SourcePosition;
import java.io.File;
import java.util.Calendar;
import java.util.GregorianCalendar;
import java.util.TimeZone;
public class PositionWrapper {
private int column;
private File file;
private int line;
private int hashCode;
public String toString(){
return file.toString() + ":" + line;
}
public PositionWrapper(SourcePosition p){
column = p.column();
file = p.file();
line = p.line();
hashCode = column ^ file.hashCode() ^ line;
}
@Override public int hashCode(){
return hashCode;
}
@Override public boolean equals(Object o){
if(!(o instanceof PositionWrapper)) return false;
PositionWrapper p = (PositionWrapper) o;
return (column == p.column) && (line == p.line) && (file.equals(p.file));
}
}
| Java |
package edu.uiuc.cs.fsl.propertydocs.util;
import java.util.Calendar;
import java.util.GregorianCalendar;
import java.util.TimeZone;
public class Util{
public static String getDate(){
Calendar calendar = new GregorianCalendar();
String timezone = TimeZone.getDefault().getDisplayName();
String day = (new String[] {"Sun", "Mon", "Tue", "Wed", "Thurs", "Fri", "Sat"})
[calendar.get(Calendar.DAY_OF_WEEK) - 1];
String month = (new String[] {"Jan", "Feb", "March",
"April", "May", "Jun",
"Jul", "Aug", "Sept",
"Oct", "Nov", "Dec"})
[calendar.get(Calendar.MONTH)];
int dayOfMonth = calendar.get(Calendar.DAY_OF_MONTH);
int hour = calendar.get(Calendar.HOUR);
int minute = calendar.get(Calendar.MINUTE);
int second = calendar.get(Calendar.SECOND);
int year = calendar.get(Calendar.YEAR);
return day + " " + month + " " + dayOfMonth + " "
+ hour + ":" + minute + ":" + second + " "
+ timezone + " " + year;
}
}
| Java |
package edu.uiuc.cs.fsl.propertydocs.util;
public class DefaultMap<K,V> extends java.util.HashMap<K,V> implements java.io.Serializable {
public static final long serialVersionUID = 0L;
protected final V defaultValue;
public DefaultMap(V defaultValue){
this.defaultValue = defaultValue;
}
@Override
public V get(Object key){
V val = super.get(key);
if(val == null) return defaultValue;
return val;
}
}
| Java |
package edu.uiuc.cs.fsl.propertydocs.util;
public class Pair<T1, T2> implements java.io.Serializable {
public static final long serialVersionUID = 0L;
public T1 first;
public T2 second;
public Pair(T1 first, T2 ssecond){
this.first = first;
this.second = second;
}
@Override
public String toString(){
return "<" + first.toString() + ", " + second.toString() + ">";
}
}
| Java |
package edu.uiuc.cs.fsl.propertydocs.util;
import java.io.File;
import java.io.FilenameFilter;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.ObjectInputStream;
import java.io.PrintStream;
import java.util.Map;
import java.util.HashMap;
public class FinishUp {
// This is the scale factor for scaling all percentages. E.g., 1e2f will scale to 2 decimal places
// 1e3f would scale to 3, etc.
private final static float FACTOR = 1e2f;
private static String propertiesDir;
//TODO? should probably really be defined in Util or something instead of in multiple places
private static final String GLOBAL = "<global>";
private static final String ALLATTRIBUTES = " <all> ";
private static Map<String, Integer> undecidedDB;
private static Map<String, Integer> descriptionDB;
private static Map<String, Integer> newDB;
private static PropertyMap propertyDB;
public static void main(String[] args){
propertiesDir = args[0] + File.separator + "__properties";
File propertiesList = new File(propertiesDir + File.separator + "property-list.html");
File undecidedStats = new File(propertiesDir + File.separator + "undecided.stats");
File descriptionStats = new File(propertiesDir + File.separator + "description.stats");
File newStats = new File(propertiesDir + File.separator + "new.stats");
File propertyStats = new File(propertiesDir + File.separator + "property.stats");
try {
(new PrintStream(new FileOutputStream(new File(args[0] + File.separator + "stylesheet.css"), true)))
.println( ".Red { background-color:#EE0000; color:#FFFFFF }"
+ "\n.HLon { color:#0000E2 }"
+ "\n.HLoff { color:#450082 }"
+ "\np { color:inherit;background-color:inherit }"
+ "\nul { color:inherit;background-color:inherit }"
+ "\nol { color:inherit;background-color:inherit }"
+ "\ndl { color:inherit;background-color:inherit }"
+ "\npre { color:inherit;background-color:inherit }"
+ "\nh1 { color:inherit;background-color:inherit }"
+ "\nh2 { color:inherit;background-color:inherit }"
+ "\nh3 { color:inherit;background-color:inherit }"
+ "\nh4 { color:inherit;background-color:inherit }"
+ "\ncode { color:inherit;background-color:inherit }"
+ "\ntable { color:inherit;background-color:inherit }"
+ "\ntr { color:inherit;background-color:inherit }"
+ "\ntd { color:inherit;background-color:inherit }"
+ "\nth { color:inherit;background-color:inherit }"
);
} catch (java.io.IOException e){
throw new RuntimeException(e);
}
undecidedDB = getDB(undecidedStats);
descriptionDB = getDB(descriptionStats);
newDB = getDB(newStats);
propertyDB = getAttributedDB(propertyStats);
//System.out.println("undecided: " + undecidedDB);
//System.out.println("description: " + descriptionDB);
//System.out.println("new: " + newDB);
//System.out.println("property: " + propertyDB);
StringBuilder table
= new StringBuilder();
table.append("<H2> MOP Coverage Statistics and Property Links</H2><HR />");
makeTableForPackage("Global", GLOBAL, table);
//this assumes that {@collect.stats} is seen in every package that uses our tags!
for(String packageName : undecidedDB.keySet()){
if(packageName.equals(GLOBAL)) continue;
makeTableForPackage(packageName, table);
}
generatePropertiesList(table, propertiesDir + File.separator + "html");
try {
FileOutputStream fos = new FileOutputStream(propertiesList);
PrintStream ps = new PrintStream(fos);
ps.println(HTMLHEADER);
ps.println(table);
ps.println(HTMLFOOTER);
} catch (java.io.IOException e){
throw new RuntimeException("Cannot create properties-list.html?");
}
}
@SuppressWarnings("unchecked")
private static Map<String, Integer> getDB(File file){
Map<String, Integer> ret = null;
try {
FileInputStream fis = new FileInputStream(file);
ObjectInputStream ois = new ObjectInputStream(fis);
try {
ret = (Map<String, Integer>)ois.readObject();
} catch (ClassNotFoundException cnfe) {
throw new RuntimeException(cnfe);
}
return ret;
} catch (java.io.IOException e){
//if there is an IOException we assume that the file isn't there which means the tag wasn't seen
return new DefaultMap<String, Integer>(0);
}
}
@SuppressWarnings("unchecked")
private static PropertyMap getAttributedDB(File file){
PropertyMap ret = null;
try {
FileInputStream fis = new FileInputStream(file);
ObjectInputStream ois = new ObjectInputStream(fis);
try {
ret = (PropertyMap)ois.readObject();
} catch (ClassNotFoundException cnfe) {
throw new RuntimeException(cnfe);
}
return ret;
} catch (java.io.IOException e){
//if there is an IOException we assume that the file isn't there which means the tag wasn't seen
return new PropertyMap(0);
}
}
private static void makeTableForPackage(String name, StringBuilder table){
makeTableForPackage(name, name, table);
}
private static void makeTableForPackage(String prettyName, String packageName, StringBuilder table){
table.append("<TABLE BORDER=\"1\" WIDTH=\"100%\" CELLPADDING=\"3\" CELLSPACING=\"0\" SUMMARY=\"\">");
table.append("<TR BGCOLOR=\"#CCCCFF\" CLASS=\"TableHeadingColor\">");
table.append("<TH ALIGN=\"left\" COLSPAN=\"4\"><FONT SIZE=\"+2\">");
table.append("<B>" + prettyName + " MOP Coverage Statistics </B></FONT></TH></TR>");
int undecidedW = undecidedDB.get(packageName);
int descriptionW = descriptionDB.get(packageName);
int newW = newDB.get(packageName);
int propertyW = propertyDB.get(packageName).get(ALLATTRIBUTES);
int totalW = undecidedW + descriptionW + newW + propertyW;
table.append(formatStat("Undecided Text",
undecidedW , totalW));
table.append(formatStat("Description Text",
descriptionW, totalW));
table.append(formatStat("New Text",
newW , totalW));
table.append(formatAttributedStat("Property Text",
propertyW, totalW, "Property Text",
propertyDB.get(packageName)));
table.append("</TABLE><BR /><BR />");
}
private static StringBuilder formatStat(String name, int w, float totalW){
return formatStat(name, w, totalW, "", "Total Text");
}
private static StringBuilder formatStat(String name, int w, float totalW, String padding, String total){
StringBuilder ret = new StringBuilder();
ret.append("<TR BGCOLOR=\"white\" CLASS=\"TableRowColor\">");
ret.append("<TD WIDTH=\"15%\">");
ret.append(name);
ret.append("</TD>\n");
ret.append("<TD WIDTH=\"15%\">" + padding + "Words: ");
ret.append(w);
ret.append("</TD><TD WIDTH=\"15%\">" + padding + "Percent of " + total + ": ");
ret.append(scale(w, totalW));
ret.append("%</TD>\n");
ret.append("</TR>\n");
return ret;
}
private static StringBuilder formatAttributedStat(String name, int w, float totalW,
String total, Map<String, Integer> attributeMap){
StringBuilder ret = new StringBuilder();
ret.append(formatStat(name, w, totalW));
for(String key : attributeMap.keySet()){
if(key.equals(ALLATTRIBUTES)) continue;
ret.append(formatStat(" "
+ key, attributeMap.get(key), w, " ", total));
}
return ret;
}
private static float scale(int num, float den){
return Math.round(num / den * 100f * FACTOR) / FACTOR;
}
private static String chop(String name){
StringBuilder ret = new StringBuilder();
String[] parts = name.split("[.]");
for(int i = 0; i < parts.length - 1; ++i){
ret.append(parts[i]);
}
return ret.toString();
}
private static void generatePropertiesList(StringBuilder table, final String dir){
System.out.println("Generating " + propertiesDir + File.separator + "property-list.html...");
generatePropertiesList(table, dir, "");
}
private static void generatePropertiesList(StringBuilder table, final String dir, String prefix){
// System.out.println("------------" + dir + "-------------" + prefix);
String linkPrefix = prefix.replaceAll("[.]", "/");
File dirFile = new File(dir);
//find all html files at this level
boolean tableHeadingAdded = false;
for(String fn :
dirFile.list(new FilenameFilter() {
public boolean accept(File dir, String name){
return name.endsWith(".html") && !(name.equals("property-list.html"));
}
})
){
if(!tableHeadingAdded){
table.append("<TABLE BORDER=\"1\" WIDTH=\"100%\" CELLPADDING=\"3\" CELLSPACING=\"0\" SUMMARY=\"\">");
table.append("<TR BGCOLOR=\"#CCCCFF\" CLASS=\"TableHeadingColor\">");
table.append("<TH ALIGN=\"left\" COLSPAN=\"1\"><FONT SIZE=\"+2\">");
table.append("<B>MOP Property Links for the " + ((prefix.equals(""))? "<Unnamed>":prefix)
+ " Package </B></FONT></TH></TR>\n");
tableHeadingAdded = true;
}
table.append("<TR BGCOLOR=\"white\" CLASS=\"TableRowColor\"><TD WIDTH=\"15%\">");
table.append("<B><A HREF='");
String link = "html/" + ((linkPrefix.equals(""))? "" : (linkPrefix + "/")) + fn;
// System.out.println("link: " + link);
table.append(link);
table.append("'>");
table.append(chop(fn));
table.append("</A></B></TD></TR>\n");
}
//if we added a heading, add a footing
if(tableHeadingAdded) {
table.append("</TABLE>");
table.append("<BR /><BR />\n");
}
//recurse to subdirectories
for(String fn :
dirFile.list(new FilenameFilter() {
public boolean accept(File dir, String name) {
String test = dir + File.separator + name;
return (new File(test)).isDirectory();
}
})
){
String subDir = dir + File.separator + fn;
generatePropertiesList(table, subDir, (prefix.equals(""))? fn : (prefix + "." + fn));
}
}
//////////////////////
// HEADER
//
//////////////////////
private static final String HTMLHEADER =
"<!DOCTYPE HTML PUBLIC \"-//W3C//DTD HTML 4.01 Transitional//EN\" \"http://www.w3.org/TR/html4/loose.dtd\">\n"
+ "<!--NewPage-->\n"
+ "<HTML>\n"
+ "<HEAD>\n"
+ "<!-- Generated by docsp on " + Util.getDate() + " -->\n"
+ "<TITLE>\n"
+ "Test\n"
+ "</TITLE>\n"
+ "\n"
+ "<META NAME=\"date\" CONTENT=\"2011-07-13\">\n"
+ "\n"
+ "<LINK REL =\"stylesheet\" TYPE=\"text/css\" HREF=\"stylesheet.css\" TITLE=\"Style\">\n"
+ "\n"
+ "<SCRIPT type=\"text/javascript\">\n"
+ "function windowTitle()\n"
+ "{\n"
+ " if (location.href.indexOf('is-external=true') == -1) {\n"
+ " parent.document.title=\"Test\";\n"
+ " }\n"
+ "}\n"
+ "</SCRIPT>\n"
+ "<NOSCRIPT>\n"
+ "</NOSCRIPT>\n"
+ "\n"
+ "</HEAD>\n"
+ "\n"
+ "<BODY BGCOLOR=\"white\" onload=\"windowTitle();\">\n"
+ "<HR>\n"
+ "\n"
+ "\n"
+ "<!-- ========= START OF TOP NAVBAR ======= -->\n"
+ "<A NAME=\"navbar_top\"><!-- --></A>\n"
+ "<A HREF=\"#skip-navbar_top\" title=\"Skip navigation links\"></A>\n"
+ "<TABLE BORDER=\"0\" WIDTH=\"100%\" CELLPADDING=\"1\" CELLSPACING=\"0\" SUMMARY=\"\">\n"
+ "<TR>\n"
+ "<TD COLSPAN=2 BGCOLOR=\"#EEEEFF\" CLASS=\"NavBarCell1\">\n"
+ "<A NAME=\"navbar_top_firstrow\"><!-- --></A>\n"
+ "<TABLE BORDER=\"0\" CELLPADDING=\"0\" CELLSPACING=\"3\" SUMMARY=\"\">\n"
+ " <TR ALIGN=\"center\" VALIGN=\"top\">\n"
+ " <TD BGCOLOR=\"#EEEEFF\" CLASS=\"NavBarCell1\"> <A HREF=\"package-summary.html\"><FONT CLASS=\"NavBarFont1\"><B>Package</B></FONT></A> </TD>\n"
+ " <TD BGCOLOR=\"#EEEEFF\" CLASS=\"NavBarCell1Rev\"> <FONT CLASS=\"NavBarFont1Rev\"><B>Class</B></FONT> </TD>\n"
+ " <TD BGCOLOR=\"#EEEEFF\" CLASS=\"NavBarCell1\"> <A HREF=\"package-tree.html\"><FONT CLASS=\"NavBarFont1\"><B>Tree</B></FONT></A> </TD>\n"
+ " <TD BGCOLOR=\"#EEEEFF\" CLASS=\"NavBarCell1\"> <A HREF=\"deprecated-list.html\"><FONT CLASS=\"NavBarFont1\"><B>Deprecated</B></FONT></A> </TD>\n"
+ " <TD BGCOLOR=\"#EEEEFF\" CLASS=\"NavBarCell1\"> <A HREF=\"index-all.html\"><FONT CLASS=\"NavBarFont1\"><B>Index</B></FONT></A> </TD>\n"
+ " <TD BGCOLOR=\"#EEEEFF\" CLASS=\"NavBarCell1\"> <A HREF=\"help-doc.html\"><FONT CLASS=\"NavBarFont1\"><B>Help</B></FONT></A> </TD>\n"
+ " </TR>\n"
+ "</TABLE>\n"
+ "</TD>\n"
+ "<TD ALIGN=\"right\" VALIGN=\"top\" ROWSPAN=3><EM>\n"
+ "<TD BGCOLOR=#FFFFFF CLASS=\"NavBarCell1Rev\"> <A HREF='property-list.html'><FONT CLASS=NavBarFont1Rev><B>Properties</B></FONT></EM>\n"
+ "</TR>\n"
+ "\n"
// + "<TD BGCOLOR=\"white\" CLASS=\"NavBarCell2\"><FONT SIZE=\"-2\">\n"
// + " <A HREF=\"index.html?Test.html\" target=\"_top\"><B>FRAMES</B></A> \n"
// + " <A HREF=\"Test.html\" target=\"_top\"><B>NO FRAMES</B></A> \n"
+ " <SCRIPT type=\"text/javascript\">\n"
+ " <!--\n"
+ " if(window==top) {\n"
+ " document.writeln('<A HREF=\"allclasses-noframe.html\"><B>All Classes</B></A>');\n"
+ " }\n"
+ " //-->\n"
+ "</SCRIPT>\n"
+ "<NOSCRIPT>\n"
+ " <A HREF=\"allclasses-noframe.html\"><B>All Classes</B></A>\n"
+ "</NOSCRIPT>\n"
+ "\n"
+ "\n"
+ "</FONT></TD>\n"
+ "</TR>\n"
+ "</TABLE>\n"
+ "<A NAME=\"skip-navbar_top\"></A>\n"
+ "<!-- ========= END OF TOP NAVBAR ========= -->\n"
+ "<HR>\n";
//////////////////////
// FOOTER
//
//////////////////////
private static final String HTMLFOOTER =
"<!-- ======= START OF BOTTOM NAVBAR ====== -->\n"
+ "<A NAME=\"navbar_bottom\"><!-- --></A>\n"
+ "<A HREF=\"#skip-navbar_bottom\" title=\"Skip navigation links\"></A>\n"
+ "<TABLE BORDER=\"0\" WIDTH=\"100%\" CELLPADDING=\"1\" CELLSPACING=\"0\" SUMMARY=\"\">\n"
+ "<TR>\n"
+ "<TD COLSPAN=2 BGCOLOR=\"#EEEEFF\" CLASS=\"NavBarCell1\">\n"
+ "<A NAME=\"navbar_bottom_firstrow\"><!-- --></A>\n"
+ "<TABLE BORDER=\"0\" CELLPADDING=\"0\" CELLSPACING=\"3\" SUMMARY=\"\">\n"
+ " <TR ALIGN=\"center\" VALIGN=\"top\">\n"
+ " <TD BGCOLOR=\"#EEEEFF\" CLASS=\"NavBarCell1\"> <A HREF=\"package-summary.html\"><FONT CLASS=\"NavBarFont1\"><B>Package</B></FONT></A> </TD>\n"
+ " <TD BGCOLOR=\"#EEEEFF\" CLASS=\"NavBarCell1Rev\"> <FONT CLASS=\"NavBarFont1Rev\"><B>Class</B></FONT> </TD>\n"
+ " <TD BGCOLOR=\"#EEEEFF\" CLASS=\"NavBarCell1\"> <A HREF=\"package-tree.html\"><FONT CLASS=\"NavBarFont1\"><B>Tree</B></FONT></A> </TD>\n"
+ " <TD BGCOLOR=\"#EEEEFF\" CLASS=\"NavBarCell1\"> <A HREF=\"deprecated-list.html\"><FONT CLASS=\"NavBarFont1\"><B>Deprecated</B></FONT></A> </TD>\n"
+ " <TD BGCOLOR=\"#EEEEFF\" CLASS=\"NavBarCell1\"> <A HREF=\"index-all.html\"><FONT CLASS=\"NavBarFont1\"><B>Index</B></FONT></A> </TD>\n"
+ " <TD BGCOLOR=\"#EEEEFF\" CLASS=\"NavBarCell1\"> <A HREF=\"help-doc.html\"><FONT CLASS=\"NavBarFont1\"><B>Help</B></FONT></A> </TD>\n"
+ " </TR>\n"
+ "</TABLE>\n"
+ "</TD>\n"
+ "<TD ALIGN=\"right\" VALIGN=\"top\" ROWSPAN=3><EM>\n"
+ "<TD BGCOLOR=#FFFFFF CLASS=\"NavBarCell1Rev\"> <A HREF='property-list.html'><FONT CLASS=NavBarFont1Rev><B>Properties</B></FONT></EM>\n"
+ "</TD>\n"
+ "</TR>\n"
// + "<TD BGCOLOR=\"white\" CLASS=\"NavBarCell2\"><FONT SIZE=\"-2\">\n"
// + " <A HREF=\"index.html?Test.html\" target=\"_top\"><B>FRAMES</B></A> \n"
// + " <A HREF=\"Test.html\" target=\"_top\"><B>NO FRAMES</B></A> \n"
+ " <SCRIPT type=\"text/javascript\">\n"
+ " <!--\n"
+ " if(window==top) {\n"
+ " document.writeln('<A HREF=\"allclasses-noframe.html\"><B>All Classes</B></A>');\n"
+ " }\n"
+ " //-->\n"
+ "</SCRIPT>\n"
+ "<NOSCRIPT>\n"
+ " <A HREF=\"allclasses-noframe.html\"><B>All Classes</B></A>\n"
+ "</NOSCRIPT>\n"
+ "\n"
+ "\n"
+ "</FONT></TD>\n"
+ "</TR>\n"
+ "</TABLE>\n"
+ "<A NAME=\"skip-navbar_bottom\"></A>\n"
+ "<!-- ======== END OF BOTTOM NAVBAR ======= -->\n"
+ "\n"
+ "<HR>\n"
+ "\n"
+ "</BODY>\n"
+ "</HTML>\n";
}
| Java |
/* Copyright 2011 Patrick Meredith
* getPackageDoc, getTopLevelClassDoc, findClass, most of buildRelativeUrl Copyright 2010 Chad Retz
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may not
* use this file except in compliance with the License. You may obtain a copy of
* the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
* WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
* License for the specific language governing permissions and limitations under
* the License.
*/
package edu.uiuc.cs.fsl.propertydocs.util;
import com.sun.javadoc.ClassDoc;
import com.sun.javadoc.Doc;
import com.sun.javadoc.PackageDoc;
import com.sun.javadoc.ProgramElementDoc;
import com.sun.javadoc.Tag;
import com.sun.tools.doclets.Taglet;
public class GenerateUrls {
public static PackageDoc getPackageDoc(Tag tag) {
Doc holder = tag.holder();
if (holder instanceof ProgramElementDoc) {
return ((ProgramElementDoc) holder).containingPackage();
} else if (holder instanceof PackageDoc) {
return (PackageDoc) holder;
} else {
throw new RuntimeException("Unrecognized holder: " + holder);
}
}
private static ClassDoc getTopLevelClassDoc(ClassDoc classDoc) {
if (classDoc.containingClass() == null) {
return classDoc;
} else {
return getTopLevelClassDoc(classDoc);
}
}
private static ClassDoc getTopLevelClassDoc(Tag tag) {
Doc holder = tag.holder();
if (holder instanceof PackageDoc) {
return null;
} else if (holder instanceof ClassDoc) {
return getTopLevelClassDoc((ClassDoc) holder);
} else if (holder instanceof ProgramElementDoc) {
return getTopLevelClassDoc(((ProgramElementDoc) holder)
.containingClass());
} else {
throw new RuntimeException("Unrecognized holder: " + holder);
}
}
private static ClassDoc findClass(String className, ClassDoc[] classImports) {
for (ClassDoc classDoc : classImports) {
if (classDoc.name().equals(className)) {
return classDoc;
}
}
return null;
}
private static ClassDoc findClass(String className, PackageDoc... packageImports) {
for (PackageDoc packageDoc : packageImports) {
for (ClassDoc found : packageDoc.allClasses(true)) {
if (found.name().equals(className)) {
return found;
}
}
}
return null;
}
public static String buildRelativeUrl(Tag tag){
PackageDoc packageDoc = getPackageDoc(tag);
ClassDoc topLevelClassDoc = getTopLevelClassDoc(tag);
StringBuilder href = new StringBuilder();
//here we are attempting to find the root directory of the
//generated documents so that we can add the proper number of ".."
//to any generated links
int dotIndex = packageDoc.name().indexOf('.');
while (dotIndex != -1) {
href.append("../");
dotIndex = packageDoc.name().indexOf('.', dotIndex + 1);
}
//package name is empty when it is the root package
if (!(packageDoc.name().length() == 0)) {
href.append("../");
}
return href.toString();
}
//Anything that gets its own webpage in javadoc
private static String classNameToUrl(String name){
return name.replaceAll("[.]","/") + ".html";
}
//this is for turning a method to a url.
//this will generate a url that points to the middle of a webpage somewhere
private static String methodNameToUrl(String name){
String[] toplevel = name.split("[(]");
String[] pieces = toplevel[0].split("[.]");
StringBuilder ret = new StringBuilder();
{ int i = 0;
for(; i < pieces.length - 2; ++i){
ret.append(pieces[i]);
ret.append("/");
}
ret.append(pieces[i]);
}
ret.append(".html#");
ret.append(pieces[pieces.length - 1]);
ret.append("(");
ret.append(toplevel[1]);
return ret.toString();
}
//this is for class elements that are not methods.
//these are easier to handle because they do not have possible
//arguments, as arguments to methods do NOT have their "."'s changed
//to "/". Everything is convoluted here, /sigh
private static String elementNameToUrl(String name){
String[] pieces = name.split("[.]");
StringBuilder ret = new StringBuilder();
for(int i = 0; i < pieces.length - 2; ++i){
ret.append(pieces[i]);
ret.append("/");
}
ret.append(pieces[pieces.length - 2]);
ret.append(".html#");
ret.append(pieces[pieces.length - 1]);
return ret.toString();
}
public static String getUrl(Tag tag){
Doc doc = tag.holder();
String name = doc.toString();
//remove anything between nested < and >
{
StringBuilder nameFixer = new StringBuilder();
int nestedDepth = 0;
for(int i = 0; i < name.length(); ++i){
char c = name.charAt(i);
if(c == '<'){
++nestedDepth;
}
else if(c == '>'){
--nestedDepth;
}
else if(nestedDepth == 0){
nameFixer.append(c);
}
}
name = nameFixer.toString();
}
//If the document is a class, interface, or annotation it has its
//own file, and the url to the file is constructed by classNameToUrl
if(doc.isClass() || doc.isInterface() || doc.isAnnotationType()
|| doc.isError() || doc.isException()){
return classNameToUrl(name);
}
//Methods must be handled specially
if(doc.isMethod() || doc.isConstructor() || doc.isAnnotationTypeElement()){
return methodNameToUrl(name);
}
//Non-method elements, such as fields, are handled with a simpler method:
//elementNameToUrl
if(doc.isField() || doc.isEnumConstant()){
return elementNameToUrl(name);
}
throw new RuntimeException("Type of tag: " + tag + " could not be handled!");
}
private static String[] getUrlAndName(Tag tag){
String text = tag.text().trim();
//I'm tired of java and it's uninitialized ERROR. Make it a warning. Total dumbassery
String urlPart, namePart = null;
String[] args = text.split("\\s+");
urlPart = args[0];
if(args.length == 1) namePart = text;
else if(args.length > 1) {
StringBuilder nameBuilder = new StringBuilder();
for(int i = 1; i < args.length; ++i){
nameBuilder.append(args[i] + " ");
}
namePart = nameBuilder.toString().trim();
}
String[] ret = new String[3];
ret[0] = buildRelativeUrl(tag);
ret[1] = classNameToUrl(urlPart);
ret[2] = namePart;
return ret;
}
public static String processLinkTag(Tag tag){
if(!tag.name().equals("@link")) throw new RuntimeException("Not a link tag: " + tag.name());
String[] urlAndName = getUrlAndName(tag);
return "<A HREF=\"" + urlAndName[0] + urlAndName[1] + "\"><CODE>" + urlAndName[2] + "</CODE></A>";
}
public static String processLinkPlainTag(Tag tag){
if(!tag.name().equals("@linkplain")) throw new RuntimeException("Not a linkplain tag" + tag.name());
String[] urlAndName = getUrlAndName(tag);
return "<A HREF=\"" + urlAndName[0] + urlAndName[1] + "\">" + urlAndName[2] + "</A>";
}
public static String processPropertyLinkTag(Tag tag){
if(!tag.name().equals("@property.link"))
throw new RuntimeException("Not a property.link tag" + tag.name());
String[] urlAndName = getUrlAndName(tag);
return "<A HREF=\"" + urlAndName[0] + "__properties/" + urlAndName[1] + "\">" + urlAndName[2] + "</A>";
}
public static String processPropertyShortcutTag(Tag tag){
if(!tag.name().equals("@property.shortcut"))
throw new RuntimeException("Not a property.shortcut tag" + tag.name());
String[] urlAndName = getUrlAndName(tag);
return "<A HREF=\\'" + urlAndName[0] + "__properties/" + urlAndName[1] + "\\'>" + urlAndName[2] + "</A>";
}
}
| Java |
package edu.uiuc.cs.fsl.propertydocs.util;
import java.io.File;
import java.io.FileOutputStream;
import java.io.PrintStream;
import java.io.FileReader;
import java.io.BufferedReader;
import java.util.HashSet;
import com.sun.tools.doclets.standard.Standard;
import com.sun.javadoc.Tag;
public class CreatePropertyFile {
private static final String dir = Standard.htmlDoclet.configuration().destDirName;
private static HashSet<String> seenPositions
= new HashSet<String> (); //this is to ensure that we don't link back
//to the same location multiple times
private static HashSet<String> seenNames
= new HashSet<String>(); //since we modify property files in place, we need this to
//ensure that we delete the files on a fresh run
public static final String PROPDIR = "__ANNOTATED_DOC_PROPERTY_PATH__";
static {
File propertyDir = new File(dir + File.separator + "__properties");
if(!propertyDir.exists()) propertyDir.mkdir();
File htmlDir = new File(dir + File.separator + "__properties" + File.separator + "html");
if(!htmlDir.exists()) htmlDir.mkdir();
File mopDir = new File(dir + File.separator + "__properties" + File.separator + "mop");
if(!mopDir.exists()) mopDir.mkdir();
}
public static void forceInit() { /* call this method to force this class to be initialized */ }
//Name is the name of the property
//tag is the PropertyOpen Tag referencing the property
//depth is the depth of the Property File, e.g., the depth of java.io.UnsafeIterator.mop
// is 4 (3 + 1, + 1 because of __properties dir)
public static void createOrModifyPropertyFile(String name, PositionWrapper p, Tag tag, int depth){
if(seenPositions.contains(p.toString() + name)) return;
seenPositions.add(p.toString() + name);
String pathifiedName = name.replaceAll("[.]","/");
StringBuilder relativeUrlPrefix = new StringBuilder();
for(int i = 0; i < depth; ++i){
relativeUrlPrefix.append("../");
}
String linkBack = relativeUrlPrefix.append(GenerateUrls.getUrl(tag)).toString();
String nameBack = tag.holder().toString().replaceAll("<","<").replaceAll(">",">");
String htmlOutName = dir + File.separator + "__properties" + File.separator
+ "html" + File.separator + pathifiedName + ".html";
try {
//copy specified mop file
File in = new File(System.getenv().get(PROPDIR) + File.separator + pathifiedName + ".mop");
File htmlOut = new File(htmlOutName);
//create the HTML file that will link to the given mop file
populate(htmlOutName);
String outName = dir + "__properties" + File.separator
+ "mop" + File.separator + pathifiedName + ".mop";
populate(outName);
File out = new File(outName);
if(!seenNames.contains(name)){
out.delete();
htmlOut.delete();
seenNames.add(name);
}
if(out.exists()) {
modifyPropertyFile(htmlOutName, linkBack, nameBack);
return;
}
FileReader fr = new FileReader(in);
FileOutputStream fos = new FileOutputStream(out);
BufferedReader br = new BufferedReader(fr);
PrintStream ps = new PrintStream(fos);
String s;
while (true) {
s = br.readLine();
if(s == null) break;
ps.println(s);
}
br.close();
ps.close();
FileOutputStream htmlfos = new FileOutputStream(htmlOut);
PrintStream htmlps = new PrintStream(htmlfos);
htmlps.print(getHtmlHeader(pathifiedName));
htmlps.print("<P><IFRAME SRC='" + buildRelativeUrlFromName(pathifiedName)
+ "/mop/" + pathifiedName + ".mop' WIDTH='100%' HEIGHT='600'></IFRAME></P>\n");
htmlps.print("<P>This property is referenced in the following locations:</P>\n");
htmlps.print("<UL>\n<LI><A HREF='" + linkBack +"'>" + nameBack + "</A></LI></UL>\n");
htmlps.print(getHtmlFooter(pathifiedName));
htmlps.close();
}
catch (Exception e){
throw new RuntimeException(e);
}
}
//This is for adding a link on an already existing HTML file. Because I don't want to
//deal with collecting a list and generating the HTML property file at the end... because
//such would require using a finalizer or some such thanks to how JavaDoc works (sigh),
//I, instead, modify the HTML files as each new link is found. This is sort of ugly,
//but it's better than messing with finalizers that may or may not get called
private static void modifyPropertyFile(String htmlOutName, String linkBack, String nameBack)
throws java.io.FileNotFoundException, java.io.IOException{
FileReader htmlReader = new FileReader(htmlOutName);
StringBuilder htmlText = new StringBuilder();
int b;
while((b = htmlReader.read()) != -1){
htmlText.append((char) b);
}
String[] parts = htmlText.toString().split("</UL>");
FileOutputStream htmlfos = new FileOutputStream(htmlOutName);
PrintStream htmlps = new PrintStream(htmlfos);
htmlps.print(parts[0]);
htmlps.print(linkBackItem(linkBack, nameBack));
htmlps.print("</UL>");
htmlps.print(parts[1]);
}
//Simple helper method, see usage points in this file
private static String linkBackItem(String linkBack, String nameBack){
return "<LI><A HREF='" + linkBack + "'>" + nameBack + "</A></LI>";
}
//This method generates the necessary directory structure for a deeply
//nested file, like java/util/concurrent/Foo.java
//
//Why the hell doesn't the standard library do this if you try to create
//a long path with non-existent intervening directories already?
public static void populate(String path){
String[] dirs = path.split(File.separator.equals("/")?"[/]":"\\\\");
String currPath = dirs[0];
for(int i = 1; i < dirs.length; ++i) {
File f = new File(currPath);
if(!f.exists()) f.mkdir();
if(!dirs[i].equals("")) currPath += File.separator + dirs[i];
}
}
//perhaps put this in GenerateUrls? Lazy
public static String buildRelativeUrlFromName(String path){
String[] dirs = path.split(File.separator.equals("/")?"[/]":"\\\\");
String ret = "..";
for(int i = 0; i < dirs.length - 1; ++i) {
ret += "/..";
}
return ret;
}
private static String getHtmlHeader(String name) {
return
"<!DOCTYPE HTML PUBLIC \"-//W3C//DTD HTML 4.01 Transitional//EN\" \"http://www.w3.org/TR/html4/loose.dtd\">\n"
+ "<!--NewPage-->\n"
+ "<HTML>\n"
+ "<HEAD>\n"
+ "<!-- Generated by docsp on " + Util.getDate() + " -->\n"
+ "<TITLE>\n"
+ "Test\n"
+ "</TITLE>\n"
+ "\n"
+ "<META NAME=\"date\" CONTENT=\"2011-07-13\">\n"
+ "\n"
+ "<LINK REL =\"stylesheet\" TYPE=\"text/css\" HREF=\"stylesheet.css\" TITLE=\"Style\">\n"
+ "\n"
+ "<SCRIPT type=\"text/javascript\">\n"
+ "function windowTitle()\n"
+ "{\n"
+ " if (location.href.indexOf('is-external=true') == -1) {\n"
+ " parent.document.title=\"Test\";\n"
+ " }\n"
+ "}\n"
+ "</SCRIPT>\n"
+ "<NOSCRIPT>\n"
+ "</NOSCRIPT>\n"
+ "\n"
+ "</HEAD>\n"
+ "\n"
+ "<BODY BGCOLOR=\"white\" onload=\"windowTitle();\">\n"
+ "<HR>\n"
+ "\n"
+ "\n"
+ "<!-- ========= START OF TOP NAVBAR ======= -->\n"
+ "<A NAME=\"navbar_top\"><!-- --></A>\n"
+ "<A HREF=\"#skip-navbar_top\" title=\"Skip navigation links\"></A>\n"
+ "<TABLE BORDER=\"0\" WNAMETH=\"100%\" CELLPADDING=\"1\" CELLSPACING=\"0\" SUMMARY=\"\">\n"
+ "<TR>\n"
+ "<TD COLSPAN=2 BGCOLOR=\"#EEEEFF\" CLASS=\"NavBarCell1\">\n"
+ "<A NAME=\"navbar_top_firstrow\"><!-- --></A>\n"
+ "<TABLE BORDER=\"0\" CELLPADDING=\"0\" CELLSPACING=\"3\" SUMMARY=\"\">\n"
+ " <TR ALIGN=\"center\" VALIGN=\"top\">\n"
+ " <TD BGCOLOR=\"#EEEEFF\" CLASS=\"NavBarCell1\"> <A HREF=\"package-summary.html\"><FONT CLASS=\"NavBarFont1\"><B>Package</B></FONT></A> </TD>\n"
+ " <TD BGCOLOR=\"#EEEEFF\" CLASS=\"NavBarCell1Rev\"> <FONT CLASS=\"NavBarFont1Rev\"><B>Class</B></FONT> </TD>\n"
+ " <TD BGCOLOR=\"#EEEEFF\" CLASS=\"NavBarCell1\"> <A HREF=\"package-tree.html\"><FONT CLASS=\"NavBarFont1\"><B>Tree</B></FONT></A> </TD>\n"
+ " <TD BGCOLOR=\"#EEEEFF\" CLASS=\"NavBarCell1\"> <A HREF=\"deprecated-list.html\"><FONT CLASS=\"NavBarFont1\"><B>Deprecated</B></FONT></A> </TD>\n"
+ " <TD BGCOLOR=\"#EEEEFF\" CLASS=\"NavBarCell1\"> <A HREF=\"index-all.html\"><FONT CLASS=\"NavBarFont1\"><B>Index</B></FONT></A> </TD>\n"
+ " <TD BGCOLOR=\"#EEEEFF\" CLASS=\"NavBarCell1\"> <A HREF=\"help-doc.html\"><FONT CLASS=\"NavBarFont1\"><B>Help</B></FONT></A> </TD>\n"
+ " </TR>\n"
+ "</TABLE>\n"
+ "</TD>\n"
+ "<TD ALIGN=\"right\" VALIGN=\"top\" ROWSPAN=3><EM>\n"
+ "<TD BGCOLOR=#FFFFFF CLASS=\"NavBarCell\"> <A HREF='" + buildRelativeUrlFromName(name) + "/property-list.html"
+ "'><FONT CLASS=NavBarFont1><B>Properties</B></FONT></EM>\n"
+ "</TR>\n"
+ "\n"
// + "<TD BGCOLOR=\"white\" CLASS=\"NavBarCell2\"><FONT SIZE=\"-2\">\n"
// + " <A HREF=\"index.html?Test.html\" target=\"_top\"><B>FRAMES</B></A> \n"
// + " <A HREF=\"Test.html\" target=\"_top\"><B>NO FRAMES</B></A> \n"
+ " <SCRIPT type=\"text/javascript\">\n"
+ " <!--\n"
+ " if(window==top) {\n"
+ " document.writeln('<A HREF=\"allclasses-noframe.html\"><B>All Classes</B></A>');\n"
+ " }\n"
+ " //-->\n"
+ "</SCRIPT>\n"
+ "<NOSCRIPT>\n"
+ " <A HREF=\"allclasses-noframe.html\"><B>All Classes</B></A>\n"
+ "</NOSCRIPT>\n"
+ "\n"
+ "\n"
+ "</FONT></TD>\n"
+ "</TR>\n"
+ "</TABLE>\n"
+ "<A NAME=\"skip-navbar_top\"></A>\n"
+ "<!-- ========= END OF TOP NAVBAR ========= -->\n"
+ "<HR>\n";
}
private static String getHtmlFooter(String name){
return
"<!-- ======= START OF BOTTOM NAVBAR ====== -->\n"
+ "<A NAME=\"navbar_bottom\"><!-- --></A>\n"
+ "<A HREF=\"#skip-navbar_bottom\" title=\"Skip navigation links\"></A>\n"
+ "<TABLE BORDER=\"0\" WNAMETH=\"100%\" CELLPADDING=\"1\" CELLSPACING=\"0\" SUMMARY=\"\">\n"
+ "<TR>\n"
+ "<TD COLSPAN=2 BGCOLOR=\"#EEEEFF\" CLASS=\"NavBarCell1\">\n"
+ "<A NAME=\"navbar_bottom_firstrow\"><!-- --></A>\n"
+ "<TABLE BORDER=\"0\" CELLPADDING=\"0\" CELLSPACING=\"3\" SUMMARY=\"\">\n"
+ " <TR ALIGN=\"center\" VALIGN=\"top\">\n"
+ " <TD BGCOLOR=\"#EEEEFF\" CLASS=\"NavBarCell1\"> <A HREF=\"package-summary.html\"><FONT CLASS=\"NavBarFont1\"><B>Package</B></FONT></A> </TD>\n"
+ " <TD BGCOLOR=\"#EEEEFF\" CLASS=\"NavBarCell1Rev\"> <FONT CLASS=\"NavBarFont1Rev\"><B>Class</B></FONT> </TD>\n"
+ " <TD BGCOLOR=\"#EEEEFF\" CLASS=\"NavBarCell1\"> <A HREF=\"package-tree.html\"><FONT CLASS=\"NavBarFont1\"><B>Tree</B></FONT></A> </TD>\n"
+ " <TD BGCOLOR=\"#EEEEFF\" CLASS=\"NavBarCell1\"> <A HREF=\"deprecated-list.html\"><FONT CLASS=\"NavBarFont1\"><B>Deprecated</B></FONT></A> </TD>\n"
+ " <TD BGCOLOR=\"#EEEEFF\" CLASS=\"NavBarCell1\"> <A HREF=\"index-all.html\"><FONT CLASS=\"NavBarFont1\"><B>Index</B></FONT></A> </TD>\n"
+ " <TD BGCOLOR=\"#EEEEFF\" CLASS=\"NavBarCell1\"> <A HREF=\"help-doc.html\"><FONT CLASS=\"NavBarFont1\"><B>Help</B></FONT></A> </TD>\n"
+ " </TR>\n"
+ "</TABLE>\n"
+ "</TD>\n"
+ "<TD ALIGN=\"right\" VALIGN=\"top\" ROWSPAN=3><EM>\n"
+ "<TD BGCOLOR=#FFFFFF CLASS=\"NavBarCell\"> <A HREF='" + buildRelativeUrlFromName(name) + "/property-list.html" +
"'><FONT CLASS=NavBarFont1><B>Properties</B></FONT></EM>\n"
+ "</TD>\n"
+ "</TR>\n"
+ " <SCRIPT type=\"text/javascript\">\n"
+ " <!--\n"
+ " if(window==top) {\n"
+ " document.writeln('<A HREF=\"allclasses-noframe.html\"><B>All Classes</B></A>');\n"
+ " }\n"
+ " //-->\n"
+ "</SCRIPT>\n"
+ "<NOSCRIPT>\n"
+ " <A HREF=\"allclasses-noframe.html\"><B>All Classes</B></A>\n"
+ "</NOSCRIPT>\n"
+ "\n"
+ "\n"
+ "</FONT></TD>\n"
+ "</TR>\n"
+ "</TABLE>\n"
+ "<A NAME=\"skip-navbar_bottom\"></A>\n"
+ "<!-- ======== END OF BOTTOM NAVBAR ======= -->\n"
+ "\n"
+ "<HR>\n"
+ "\n"
+ "</BODY>\n"
+ "</HTML>\n";
}
}
| Java |
package edu.uiuc.cs.fsl.propertydocs.util;
public class PropertyMap extends java.util.HashMap<String, DefaultMap<String, Integer>>{
private final Integer defaultValue;
public PropertyMap(Integer i){
defaultValue = i;
}
@Override
@SuppressWarnings("unchecked")
public DefaultMap<String, Integer> get(Object key){
DefaultMap<String, Integer> val = super.get(key);
if(val == null){
val = new DefaultMap<String, Integer>(defaultValue);
put((String) key, val);
}
return val;
}
}
| Java |
package edu.uiuc.cs.fsl.propertydocs.taglets;
import com.sun.javadoc.Tag;
import com.sun.tools.doclets.Taglet;
import com.sun.tools.doclets.standard.Standard;
import java.io.File;
import java.io.FileOutputStream;
import java.io.ObjectOutputStream;
import java.util.HashSet;
import java.util.Map;
import java.util.Set;
import edu.uiuc.cs.fsl.propertydocs.util.DefaultMap;
import edu.uiuc.cs.fsl.propertydocs.util.GenerateUrls;
import edu.uiuc.cs.fsl.propertydocs.util.PositionWrapper;
/**
* This Taglet allows for marking the beginning of an new property specification
*
* @author Patrick Meredith
*
*/
public class NewOpenTaglet implements Taglet {
private static final String NAME = "new.open";
private static final String dir = Standard.htmlDoclet.configuration().destDirName;
private File stats = new File(dir + File.separator + "__properties" + File.separator + "new.stats");
private static final String GLOBAL = "<global>";
private Set<PositionWrapper> seenDocs = new HashSet<PositionWrapper>();
private Map<String, Integer> statsDB = new DefaultMap<String, Integer>(0);
public String getName() { return NAME; }
/** can be used in a field comment*/
public boolean inField() { return true; }
/**can be used in a constructor comment*/
public boolean inConstructor() { return true; }
/**can be used in a method comment*/
public boolean inMethod() { return true; }
/**can be used in overview comment*/
public boolean inOverview() { return true; }
/**can be used in package comment*/
public boolean inPackage() { return true; }
/**can be used in type comment (classes or interfaces)*/
public boolean inType() { return true; }
/**this IS an inline tag*/
public boolean isInlineTag() { return true; }
// private int words = 0; //number of new text words
/**
* Register this Taglet.
* @param tagletMap the map to register this tag to.
*/
@SuppressWarnings("unchecked")
public static void register(Map tagletMap) {
NewOpenTaglet tag = new NewOpenTaglet();
Taglet t = (Taglet) tagletMap.get(tag.getName());
if (t != null) {
tagletMap.remove(tag.getName());
}
tagletMap.put(tag.getName(), tag);
}
/**
* Given the <code>Tag</code> representation of this custom
* tag, return its string representation.
*
* Here we have to do some annoying garbage because you there is no
* way short of file io to share info between Taglets. Instead
* I am going to parse all the inline tags if the whole document
* and collect statistics on <b>all</b> the new sections in the
* document.
*
* Statistics will only be collected if we have not already seen an
* new.open tag for this document. We keep track of the document
* by hashing its SourcePosition. The PositionWrapper makes these
* hashable.
*
* @param tag he <code>Tag</code> representation of this custom tag.
*/
public String toString(Tag tag) {
PositionWrapper p = new PositionWrapper(tag.holder().position());
if(!(seenDocs.contains(p))){
seenDocs.add(p);
handleTags(tag);
}
// This part is always executed, but for new we simply return the
// empty String. For other tags we will output fancy html/javascript
return "<DIV CLASS=\"NavBarCell1\" NAME=\"new\""
+ " ONMOUSEOVER=\"balloon.showTooltip(event,'This is text that has been added to the API.')\""
+ " STYLE=\"display:inline\">";
}
private void handleTags(Tag t){
Tag[] tags = t.holder().inlineTags();
boolean inNew = false;
//not sure if trim() is necessary. I doubt it is, but speed isn't
//an issue here
String packageName = GenerateUrls.getPackageDoc(t).toString().trim();
int w = 0; //word count
for(Tag tag : tags){
if(tag.name().equals("@new.open")){
inNew = true;
}
else if(tag.name().equals("@new.close")){
inNew = false;
}
else if(tag.name().equals("Text") && inNew){
String text = tag.text().trim();
if(text.length() == 0) continue;
w += text.split("\\s+").length;
}
}
if(inNew) {
System.err.println("ERROR: @new.open tag in comment near "
+ tags[0].holder().position() + " was not closed");
System.exit(1);
}
Integer globalWords = statsDB.get(GLOBAL);
Integer packageWords = statsDB.get(packageName);
statsDB.put(GLOBAL, globalWords + w);
statsDB.put(packageName, packageWords + w);
try {
FileOutputStream fos = new FileOutputStream(stats);
ObjectOutputStream ps = new ObjectOutputStream(fos);
ps.writeObject(statsDB);
ps.close();
} catch (java.io.IOException e){
throw new RuntimeException(e);
}
}
/**
* This method should not be called since arrays of inline tags do not
* exist. Method {@link #tostring(Tag)} should be used to convert this
* inline tag to a string.
* @param tags the array of <code>Tag</code>s representing of this custom tag.
*/
public String toString(Tag[] tags) {
return null;
}
}
| Java |
package edu.uiuc.cs.fsl.propertydocs.taglets;
import com.sun.javadoc.Tag;
import com.sun.tools.doclets.Taglet;
import com.sun.tools.doclets.standard.Standard;
import java.io.File;
import java.io.FileOutputStream;
import java.io.ObjectOutputStream;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Map;
import java.util.Set;
import edu.uiuc.cs.fsl.propertydocs.util.CreatePropertyFile;
import edu.uiuc.cs.fsl.propertydocs.util.DefaultMap;
import edu.uiuc.cs.fsl.propertydocs.util.GenerateUrls;
import edu.uiuc.cs.fsl.propertydocs.util.PositionWrapper;
import edu.uiuc.cs.fsl.propertydocs.util.PropertyMap;
/**
* This Taglet allows for opening a property property section in
* a javadoc comment
*
* @author Patrick Meredith
*
*/
public class PropertyOpenTaglet implements Taglet {
static {
CreatePropertyFile.forceInit();
}
private static final String NAME = "property.open";
private static final String dir = Standard.htmlDoclet.configuration().destDirName;
private File stats = new File(dir + File.separator + "__properties" + File.separator + "property.stats");
private static final String GLOBAL = "<global>";
private static final String ALLATTRIBUTES = " <all> ";
private Set<PositionWrapper> seenDocs = new HashSet<PositionWrapper>();
private PropertyMap statsDB =
new PropertyMap(0);
public String getName() { return NAME; }
/** can be used in a field comment*/
public boolean inField() { return true; }
/**can be used in a constructor comment*/
public boolean inConstructor() { return true; }
/**can be used in a method comment*/
public boolean inMethod() { return true; }
/**can be used in overview comment*/
public boolean inOverview() { return true; }
/**can be used in package comment*/
public boolean inPackage() { return true; }
/**can be used in type comment (classes or interfaces)*/
public boolean inType() { return true; }
/**this IS an inline tag*/
public boolean isInlineTag() { return true; }
/**
* Register this Taglet.
* @param tagletMap the map to register this tag to.
*/
@SuppressWarnings("unchecked")
public static void register(Map tagletMap) {
PropertyOpenTaglet tag = new PropertyOpenTaglet();
Taglet t = (Taglet) tagletMap.get(tag.getName());
if (t != null) {
tagletMap.remove(tag.getName());
}
tagletMap.put(tag.getName(), tag);
}
/**
* Given the <code>Tag</code> representation of this custom
* tag, return its string representation.
*
* Here we have to do some annoying garbage because you there is no
* way short of file io to share info between Taglets. Instead
* I am going to parse all the inline tags if the whole document
* and collect statistics on <b>all</b> the property sections in the
* document.
*
* Statistics will only be collected if we have not already seen an
* property.open tag for this document. We keep track of the document
* by hashing its SourcePosition. The PositionWrapper makes these
* hashable.
*
* @param tag he <code>Tag</code> representation of this custom tag.
*/
public String toString(Tag tag) {
//System.out.println(tag.position());
PositionWrapper p = new PositionWrapper(tag.holder().position());
if(!(seenDocs.contains(p))){
seenDocs.add(p);
handleTags(tag);
}
String[] arguments = tag.text().trim().split("\\s+");
int num = numLinks(arguments);
String links = handleLinks(arguments, p, tag);
if(num == 0){
return "<DIV CLASS=\"Red\" NAME=\"brokenproperty\""
+ " ONMOUSEOVER=\"balloon.showTooltip(event, 'This is a property with no "
+ "formalizations.')\""
+ " STYLE=\"display:inline\">";
}
else if(num == 1){
return "<DIV CLASS=\"NavBarCell1Rev\" NAME=\"property\" ONMOUSEOVER="
+ "\"balloon.showTooltip(event,'This describes a formalized property. "
+ "The property may be viewed by clicking on the link below:<br/>" + links + " ',1)\""
+ " STYLE=\"display:inline\">";
}
return "<DIV CLASS=\"NavBarCell1Rev\" NAME=\"property\" ONMOUSEOVER="
+ "\"balloon.showTooltip(event,'This describes several formalized properties. "
+ "The properties may be viewed by clicking on the links below:<br/>" + links + " ',1)\""
+ " STYLE=\"display:inline\">";
}
private boolean isLink(String arg){
return arg.startsWith("Property:") ||
arg.startsWith("property:") ||
arg.startsWith("Formal:") ||
arg.startsWith("formal:");
}
private int numLinks(String[] args){
int i = 0;
for(String arg : args){
if(isLink(arg)) ++i;
if(i > 1) return i;
}
return i;
}
private String handleLinks(String[] args, PositionWrapper p, Tag tag){
String ret = "";
for(String arg : args){
if(isLink(arg)) {
String[] parts = arg.split(":");
if(parts.length != 2) throw new RuntimeException("too many ':''s in Property specification in comment at " + p);
int depth = parts[1].split("[.]").length + 1;
CreatePropertyFile.createOrModifyPropertyFile(parts[1], p, tag, depth);
ret += "<A HREF=\\'" + GenerateUrls.buildRelativeUrl(tag)
+ "__properties/html/" + parts[1].replaceAll("[.]","/") + ".html\\'>" + parts[1] + "</A> <BR />";
}
}
//System.out.println("***********" + ret);
return ret;
}
private void handleTags(Tag t){
Tag[] tags = t.holder().inlineTags();
boolean inProperty = false;
//not sure if trim() is necessary. I doubt it is, but speed isn't
//an issue here
String packageName = GenerateUrls.getPackageDoc(t).toString().trim();
DefaultMap<String, Integer> globalStats = statsDB.get(GLOBAL);
DefaultMap<String, Integer> packageStats = statsDB.get(packageName);
//int c = 0; //character count
int localW = 0; //word count for a given property tag pair
//int l = 0; //line count
String[] arguments = null;
for(Tag tag: tags){
if(tag.name().equals("@property.open")){
arguments = tag.text().trim().split("\\s+");
localW = 0;
inProperty = true;
}
else if(tag.name().equals("@property.close")){
Integer allGlobalW = globalStats.get(ALLATTRIBUTES);
Integer allPackageW = packageStats.get(ALLATTRIBUTES);
globalStats.put(ALLATTRIBUTES, allGlobalW + localW);
packageStats.put(ALLATTRIBUTES, allPackageW + localW);
for(String arg : arguments){
if(isLink(arg)) continue;
if(arg.equals("")) continue;
Integer argGlobalW = globalStats.get(arg);
Integer argPacakgeW = packageStats.get(arg);
globalStats.put(arg, argGlobalW + localW);
packageStats.put(arg, argPacakgeW + localW);
}
inProperty = false;
}
else if(tag.name().equals("Text") && inProperty){
String text = tag.text().trim();
if(text.length() == 0) continue;
localW += text.split("\\s+").length;
}
else if(
(tag.name().equals("@description.close")
|| tag.name().equals("@description.open")
|| tag.name().equals("@inheritDoc")) && inProperty){
System.err.println("ERROR: " + tag.name() + " inside property environment in comment near "
+ tag.holder().position() + " is not allowed");
System.exit(1);
}
}
if(inProperty) {
System.err.println("ERROR: @property.open tag in comment near "
+ tags[0].holder().position() + " was not closed");
System.exit(1);
}
try {
FileOutputStream fos = new FileOutputStream(stats);
ObjectOutputStream ps = new ObjectOutputStream(fos);
ps.writeObject(statsDB);
ps.close();
} catch (java.io.IOException e){
throw new RuntimeException(e);
}
}
/**
* This method should not be called since arrays of inline tags do not
* exist. Method {@link #tostring(Tag)} should be used to convert this
* inline tag to a string.
* @param tags the array of <code>Tag</code>s representing of this custom tag.
*/
public String toString(Tag[] tags) {
return null;
}
}
| Java |
package edu.uiuc.cs.fsl.propertydocs.taglets;
import com.sun.tools.doclets.Taglet;
import com.sun.javadoc.Tag;
import java.util.Map;
import edu.uiuc.cs.fsl.propertydocs.util.GenerateUrls;
import edu.uiuc.cs.fsl.propertydocs.util.PositionWrapper;
/**
* This Taglet allows for the inline specification of links to
* properties
*
* @author Patrick Meredith
*
*/
public class PropertyCloseTaglet implements Taglet {
private static final String NAME = "property.close";
public String getName() { return NAME; }
/** can be used in a field comment*/
public boolean inField() { return true; }
/**can be used in a constructor comment*/
public boolean inConstructor() { return true; }
/**can be used in a method comment*/
public boolean inMethod() { return true; }
/**can be used in overview comment*/
public boolean inOverview() { return true; }
/**can be used in package comment*/
public boolean inPackage() { return true; }
/**can be used in type comment (classes or interfaces)*/
public boolean inType() { return true; }
/**this IS an inline tag*/
public boolean isInlineTag() { return true; }
/**
* Register this Taglet.
* @param tagletMap the map to register this tag to.
*/
@SuppressWarnings("unchecked")
public static void register(Map tagletMap) {
PropertyCloseTaglet tag = new PropertyCloseTaglet();
Taglet t = (Taglet) tagletMap.get(tag.getName());
if (t != null) {
tagletMap.remove(tag.getName());
}
tagletMap.put(tag.getName(), tag);
}
/**
* Given the <code>Tag</code> representation of this custom
* tag, return its string representation.
* @param tag he <code>Tag</code> representation of this custom tag.
*/
public String toString(Tag tag) {
return "</DIV>";
}
/**
* This method should not be called since arrays of inline tags do not
* exist. Method {@link #tostring(Tag)} should be used to convert this
* inline tag to a string.
* @param tags the array of <code>Tag</code>s representing of this custom tag.
*/
public String toString(Tag[] tags) {
return null;
}
}
| Java |
package edu.uiuc.cs.fsl.propertydocs.taglets;
import com.sun.javadoc.Tag;
import com.sun.tools.doclets.Taglet;
import com.sun.tools.doclets.standard.Standard;
import java.io.File;
import java.io.FileOutputStream;
import java.io.ObjectOutputStream;
import java.util.HashSet;
import java.util.Map;
import java.util.Set;
import edu.uiuc.cs.fsl.propertydocs.util.DefaultMap;
import edu.uiuc.cs.fsl.propertydocs.util.GenerateUrls;
import edu.uiuc.cs.fsl.propertydocs.util.PositionWrapper;
/**
* This Taglet allows for specifying the beginning of undecided text
*
* @author Patrick Meredith
*
*/
public class CollectTaglet implements Taglet {
private static final String NAME = "collect.stats";
private static final String dir = Standard.htmlDoclet.configuration().destDirName;
private File stats = new File(dir + File.separator + "__properties" + File.separator + "undecided.stats");
private Set<PositionWrapper> seenDocs = new HashSet<PositionWrapper>();
// private int chars = 0; //number of undecided chars
// private int words = 0; //number of undecided words
// private int lines = 0; //number of undecided lines
private final String GLOBAL = "<global>";
private Map<String, Integer> statsDB = new DefaultMap<String, Integer>(0);
public String getName() { return NAME; }
/** can be used in a field comment*/
public boolean inField() { return true; }
/**can be used in a constructor comment*/
public boolean inConstructor() { return true; }
/**can be used in a method comment*/
public boolean inMethod() { return true; }
/**can be used in overview comment*/
public boolean inOverview() { return true; }
/**can be used in package comment*/
public boolean inPackage() { return true; }
/**can be used in type comment (classes or interfaces)*/
public boolean inType() { return true; }
/**this IS an inline tag*/
public boolean isInlineTag() { return true; }
/**
* Register this Taglet.
* @param tagletMap the map to register this tag to.
*/
@SuppressWarnings("unchecked")
public static void register(Map tagletMap) {
CollectTaglet tag = new CollectTaglet();
Taglet t = (Taglet) tagletMap.get(tag.getName());
if (t != null) {
tagletMap.remove(tag.getName());
}
tagletMap.put(tag.getName(), tag);
}
/**
* Given the <code>Tag</code> representation of this custom
* tag, return its string representation.
*
* Here we have to do some annoying garbage because you there is no
* way short of file io to share info between Taglets. Instead
* I am going to parse all the inline tags if the whole document
* and collect statistics on <b>all</b> the undecided sections in the
* document.
*
* Statistics will only be collected if we have not already seen an
* undecided.open tag for this document. We keep track of the document
* by hashing its SourcePosition. The PositionWrapper makes these
* hashable.
*
* @param tag he <code>Tag</code> representation of this custom tag.
*/
public String toString(Tag tag) {
PositionWrapper p = new PositionWrapper(tag.holder().position());
if(!(seenDocs.contains(p))){
seenDocs.add(p);
handleTags(tag);
}
// This part is always executed, but for undecided we simply return the
// empty String. For other tags we will output fancy html/javascript
return "";
}
private void handleTags(Tag t){
Tag[] tags = t.holder().inlineTags();
boolean inUndecided = true;
//not sure if trim() is necessary. I doubt it is, but speed isn't
//an issue here
String packageName = GenerateUrls.getPackageDoc(t).toString().trim();
// int c = 0; //character count
int w = 0; //word count
// int l = 0; //lines count
for(Tag tag : tags){
if(
(tag.name().equals("@property.open")
|| tag.name().equals("@description.open")) ){
inUndecided = false;
}
else if(
(tag.name().equals("@property.close")
|| tag.name().equals("@description.close")) ){
inUndecided = true;
}
else if(tag.name().equals("Text") && inUndecided){
String text = tag.text().trim();
if(text.length() == 0) continue;
w += text.split("\\s+").length;
String printUnd = System.getenv("PRINT_UNDECIDED");
if(printUnd != null && printUnd.equals("TRUE")){
System.out.println("UNDECIDED TEXT={" + text + "}");
}
}
}
Integer globalWords = statsDB.get(GLOBAL);
Integer packageWords = statsDB.get(packageName);
statsDB.put(GLOBAL, globalWords + w);
statsDB.put(packageName, packageWords + w);
try {
FileOutputStream fos = new FileOutputStream(stats);
ObjectOutputStream ps = new ObjectOutputStream(fos);
// ps.writeInt(chars);
ps.writeObject(statsDB);
// ps.writeInt(lines);
ps.close();
} catch (java.io.IOException e){
throw new RuntimeException(e);
}
}
/**
* This method should not be called since arrays of inline tags do not
* exist. Method {@link #tostring(Tag)} should be used to convert this
* inline tag to a string.
* @param tags the array of <code>Tag</code>s representing of this custom tag.
*/
public String toString(Tag[] tags) {
return null;
}
}
| Java |
package edu.uiuc.cs.fsl.propertydocs.taglets;
import com.sun.tools.doclets.Taglet;
import com.sun.javadoc.Tag;
import java.util.Map;
import edu.uiuc.cs.fsl.propertydocs.util.GenerateUrls;
import edu.uiuc.cs.fsl.propertydocs.util.PositionWrapper;
/**
* This Taglet allows for the inline specification of links to
* properties
*
* @author Patrick Meredith
*
*/
public class DescriptionCloseTaglet implements Taglet {
private static final String NAME = "description.close";
public String getName() { return NAME; }
/** can be used in a field comment*/
public boolean inField() { return true; }
/**can be used in a constructor comment*/
public boolean inConstructor() { return true; }
/**can be used in a method comment*/
public boolean inMethod() { return true; }
/**can be used in overview comment*/
public boolean inOverview() { return true; }
/**can be used in package comment*/
public boolean inPackage() { return true; }
/**can be used in type comment (classes or interfaces)*/
public boolean inType() { return true; }
/**this IS an inline tag*/
public boolean isInlineTag() { return true; }
/**
* Register this Taglet.
* @param tagletMap the map to register this tag to.
*/
@SuppressWarnings("unchecked")
public static void register(Map tagletMap) {
DescriptionCloseTaglet tag = new DescriptionCloseTaglet();
Taglet t = (Taglet) tagletMap.get(tag.getName());
if (t != null) {
tagletMap.remove(tag.getName());
}
tagletMap.put(tag.getName(), tag);
}
/**
* Given the <code>Tag</code> representation of this custom
* tag, return its string representation.
* @param tag he <code>Tag</code> representation of this custom tag.
*/
public String toString(Tag tag) {
return "</DIV>";
}
/**
* This method should not be called since arrays of inline tags do not
* exist. Method {@link #tostring(Tag)} should be used to convert this
* inline tag to a string.
* @param tags the array of <code>Tag</code>s representing of this custom tag.
*/
public String toString(Tag[] tags) {
return null;
}
}
| Java |
package edu.uiuc.cs.fsl.propertydocs.taglets;
import com.sun.tools.doclets.Taglet;
import com.sun.javadoc.Tag;
import java.util.Map;
import edu.uiuc.cs.fsl.propertydocs.util.GenerateUrls;
import edu.uiuc.cs.fsl.propertydocs.util.PositionWrapper;
/**
* This Taglet allows for the inline specification of links to
* properties
*
* @author Patrick Meredith
*
*/
public class NewCloseTaglet implements Taglet {
private static final String NAME = "new.close";
public String getName() { return NAME; }
/** can be used in a field comment*/
public boolean inField() { return true; }
/**can be used in a constructor comment*/
public boolean inConstructor() { return true; }
/**can be used in a method comment*/
public boolean inMethod() { return true; }
/**can be used in overview comment*/
public boolean inOverview() { return true; }
/**can be used in package comment*/
public boolean inPackage() { return true; }
/**can be used in type comment (classes or interfaces)*/
public boolean inType() { return true; }
/**this IS an inline tag*/
public boolean isInlineTag() { return true; }
/**
* Register this Taglet.
* @param tagletMap the map to register this tag to.
*/
@SuppressWarnings("unchecked")
public static void register(Map tagletMap) {
NewCloseTaglet tag = new NewCloseTaglet();
Taglet t = (Taglet) tagletMap.get(tag.getName());
if (t != null) {
tagletMap.remove(tag.getName());
}
tagletMap.put(tag.getName(), tag);
}
/**
* Given the <code>Tag</code> representation of this custom
* tag, return its string representation.
* @param tag he <code>Tag</code> representation of this custom tag.
*/
public String toString(Tag tag) {
return "</DIV>";
}
/**
* This method should not be called since arrays of inline tags do not
* exist. Method {@link #tostring(Tag)} should be used to convert this
* inline tag to a string.
* @param tags the array of <code>Tag</code>s representing of this custom tag.
*/
public String toString(Tag[] tags) {
return null;
}
}
| Java |
package edu.uiuc.cs.fsl.propertydocs.taglets;
import com.sun.javadoc.Tag;
import com.sun.tools.doclets.Taglet;
import com.sun.tools.doclets.standard.Standard;
import java.io.File;
import java.io.FileOutputStream;
import java.io.ObjectOutputStream;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Map;
import java.util.Set;
import edu.uiuc.cs.fsl.propertydocs.util.DefaultMap;
import edu.uiuc.cs.fsl.propertydocs.util.GenerateUrls;
import edu.uiuc.cs.fsl.propertydocs.util.PositionWrapper;
/**
* This Taglet handles to opening of Description text comments
*
* @author Patrick Meredith
*
*/
public class DescriptionOpenTaglet implements Taglet {
private static final String NAME = "description.open";
private static final String dir = Standard.htmlDoclet.configuration().destDirName;
private File stats = new File(dir + File.separator + "__properties" + File.separator + "description.stats");
private final String GLOBAL = "<global>";
private Set<PositionWrapper> seenDocs = new HashSet<PositionWrapper>();
private Map<String, Integer> statsDB = new DefaultMap<String, Integer>(0);
// private int chars = 0; //number of description chars
// private int words = 0; //number of description words
// private int lines = 0; //number of description lines
public String getName() { return NAME; }
/** can be used in a field comment*/
public boolean inField() { return true; }
/**can be used in a constructor comment*/
public boolean inConstructor() { return true; }
/**can be used in a method comment*/
public boolean inMethod() { return true; }
/**can be used in overview comment*/
public boolean inOverview() { return true; }
/**can be used in package comment*/
public boolean inPackage() { return true; }
/**can be used in type comment (classes or interfaces)*/
public boolean inType() { return true; }
/**this IS an inline tag*/
public boolean isInlineTag() { return true; }
/**
* Register this Taglet.
* @param tagletMap the map to register this tag to.
*/
@SuppressWarnings("unchecked")
public static void register(Map tagletMap) {
DescriptionOpenTaglet tag = new DescriptionOpenTaglet();
Taglet t = (Taglet) tagletMap.get(tag.getName());
if (t != null) {
tagletMap.remove(tag.getName());
}
tagletMap.put(tag.getName(), tag);
}
/**
* Given the <code>Tag</code> representation of this custom
* tag, return its string representation.
*
* Here we have to do some annoying garbage because you there is no
* way short of file io to share info between Taglets. Instead
* I am going to parse all the inline tags if the whole document
* and collect statistics on <b>all</b> the description sections in the
* document.
*
* Statistics will only be collected if we have not already seen an
* description.open tag for this document. We keep track of the document
* by hashing its SourcePosition. The PositionWrapper makes these
* hashable.
*
* @param tag he <code>Tag</code> representation of this custom tag.
*/
public String toString(Tag tag) {
PositionWrapper p = new PositionWrapper(tag.holder().position());
if(!(seenDocs.contains(p))){
seenDocs.add(p);
handleTags(tag);
}
// This part is always executed, but for description we simply return the
// empty String. For other tags we will output fancy html/javascript
return "<DIV CLASS=\"TableHeadingColor\" NAME=\"description\""
+" ONMOUSEOVER=\"balloon.showTooltip(event,'This is description text.')\""
+" STYLE=\"display:inline\">";
}
private void handleTags(Tag t){
Tag[] tags = t.holder().inlineTags();
boolean inDescription = false;
//not sure if trim() is necessary. I doubt it is, but speed isn't
//an issue here
String packageName = GenerateUrls.getPackageDoc(t).toString().trim();
// int c = 0; //character count
int w = 0; //word count
// int l = 0; //line count
for(Tag tag : tags){
if(tag.name().equals("@description.open")){
inDescription = true;
}
else if(tag.name().equals("@description.close")){
inDescription = false;
}
else if(tag.name().equals("Text") && inDescription){
String text = tag.text().trim();
if(text.length() == 0) continue;
w += text.split("\\s+").length;
}
else if(
(tag.name().equals("@property.close")
|| tag.name().equals("@property.open")
|| tag.name().equals("@inheritDoc")) && inDescription){
System.err.println("ERROR: " + tag.name() + " inside description environment in comment near "
+ tag.holder().position() + " is not allowed");
System.exit(1);
}
}
if(inDescription) {
System.err.println("ERROR: @description.open tag in comment near "
+ tags[0].holder().position() + " was not closed");
System.exit(1);
}
Integer globalWords = statsDB.get(GLOBAL);
Integer packageWords = statsDB.get(packageName);
statsDB.put(GLOBAL, globalWords + w);
statsDB.put(packageName, packageWords + w);
//System.out.println("!!!!!!!!" + statsDB);
try {
FileOutputStream fos = new FileOutputStream(stats);
ObjectOutputStream ps = new ObjectOutputStream(fos);
ps.writeObject(statsDB);
ps.close();
} catch (java.io.IOException e){
throw new RuntimeException(e);
}
}
/**
* This method should not be called since arrays of inline tags do not
* exist. Method {@link #tostring(Tag)} should be used to convert this
* inline tag to a string.
* @param tags the array of <code>Tag</code>s representing of this custom tag.
*/
public String toString(Tag[] tags) {
return null;
}
}
| Java |
import java.io.*;
public class PushbackInputStream_UnreadAheadLimit_1 {
public static void main(String[] args) throws IOException {
byte[] buffer = { 1, 2, 3, 4, 5};
ByteArrayInputStream bais = new ByteArrayInputStream(buffer);
PushbackInputStream pis = new PushbackInputStream(bais);
pis.unread(1);
// Since the internal buffer can hold only one byte, the above
// unread(1) already filled the buffer.
pis.unread(2);
}
}
| Java |
import java.io.*;
public class BufferedInputStreamTest {
public static void main(String[] args) throws Exception {
BufferedInputStream stream = new BufferedInputStream(new StringBufferInputStream("1234567890"), 1);
stream.mark(1);
stream.read();
stream.read();
stream.reset();
stream.read();
stream.read();
}
}
| Java |
import java.io.*;
public class LineNumberInputStreamTest {
public static void main(String[] args) throws Exception {
LineNumberInputStream stream = new LineNumberInputStream(new StringBufferInputStream("1234567890"));
stream.mark(1);
stream.read();
stream.read();
stream.reset();
stream.read();
stream.read();
}
}
| Java |
import java.io.*;
public class DataInputStreamTest {
public static void main(String[] args) throws Exception {
DataInputStream stream = new DataInputStream(new StringBufferInputStream("1234567890"));
stream.mark(1);
stream.read();
stream.read();
stream.reset();
stream.read();
stream.read();
}
}
| Java |
import java.io.*;
public class BufferedInputStreamTest {
public static void main(String[] args) throws Exception {
BufferedInputStream stream = new BufferedInputStream(new StringBufferInputStream("1234567890"));
stream.reset();
int c = stream.read();
}
}
| Java |
import java.io.*;
public class LineNumberInputStreamTest {
public static void main(String[] args) throws Exception {
LineNumberInputStream stream = new LineNumberInputStream(new StringBufferInputStream("1234567890"));
stream.reset();
int c = stream.read();
}
}
| Java |
import java.io.*;
public class DataInputStreamTest {
public static void main(String[] args) throws Exception {
DataInputStream stream = new DataInputStream(new StringBufferInputStream("1234567890"));
stream.reset();
int c = stream.read();
}
}
| Java |
import java.io.*;
public class ByteArrayOutputStream_FlushBeforeRetrieve_1 {
public static void main(String[] args) throws IOException {
ByteArrayOutputStream underlying = new ByteArrayOutputStream();
BufferedOutputStream buffered = new BufferedOutputStream(underlying, 10);
buffered.write(1);
// flush() is needed to make the above write() operation effective.
// buffered.flush();
byte[] contents = underlying.toByteArray();
}
}
| Java |
import java.io.*;
public class ByteArrayInputStream_Close_1 {
public static void main(String[] args) throws IOException {
byte[] buffer = { 1, 2, 3, 4, 5};
InputStream input = new ByteArrayInputStream(buffer);
// close() has no effect.
input.close();
}
}
| Java |
import java.io.*;
public class StringWriter_Close_1 {
public static void main(String[] args) throws IOException {
Writer writer = new StringWriter();
// close() has no effect.
writer.close();
}
}
| Java |
import java.io.*;
public class ByteArrayOutputStream_Close_1 {
public static void main(String[] args) throws IOException {
OutputStream output = new ByteArrayOutputStream();
// close() has no effect.
output.close();
}
}
| Java |
import java.io.*;
public class CharArrayWriter_Close_1 {
public static void main(String[] args) throws IOException {
Writer writer = new CharArrayWriter();
// close() has no effect.
writer.close();
}
}
| Java |
import java.io.*;
public class InputStream_MarkAfterClose_1 {
public static void main(String[] args) throws IOException {
byte[] buffer = { 1, 2, 3, 4, 5};
ByteArrayInputStream input = new ByteArrayInputStream(buffer);
int i = input.read();
input.close();
// After a stream is closed, mark() has no effect on the stream.
input.mark(8);
}
}
| Java |
import java.io.*;
public class OutputStream_ManipulateAfterClose_1 {
public static void main(String[] args) throws IOException {
File file = File.createTempFile("javamoptest1", ".tmp");
file.deleteOnExit();
OutputStream output = new FileOutputStream(file);
output.write(1);
output.close();
// A closed stream cannot perform output operations.
output.write(2);
}
}
| Java |
import java.io.*;
public class OutputStream_ManipulateAfterClose_2 {
public static void main(String[] args) throws IOException {
OutputStream output = new ByteArrayOutputStream();
output.write(1);
output.close();
// ByteArrayOutputStream is an exceptional subclass of OutputStream;
// write() after close() is valid.
output.write(2);
}
}
| Java |
import java.io.*;
public class Closeable_MultipleClose_1 {
public static void main(String[] args) {
CharArrayWriter writer = new CharArrayWriter();
writer.write(100);
writer.close();
// Closing a previously closed stream has no effect.
writer.close();
}
}
| Java |
import java.io.*;
public class PipedInputStream_UnconnectedRead_2 {
public static void main(String[] args) throws IOException {
PipedInputStream pis = new PipedInputStream();
// A pipe should be connected first in order to read.
PipedOutputStream pos = new PipedOutputStream();
// PipedOutputStream pos = new PipedOutputStream(pis);
int i = pis.read();
}
}
| Java |
import java.io.*;
public class PipedInputStream_UnconnectedRead_1 {
public static void main(String[] args) throws IOException {
PipedInputStream pis = new PipedInputStream();
PipedOutputStream pos = new PipedOutputStream();
// A pipe should be connected first in order to read.
// pos.connect(pis);
int i = pis.read();
}
}
| Java |
import java.io.*;
public class File_LengthOnDirectory_1 {
public static void main(String[] args) {
File f = new File(".");
long filesize = 0;
if (f.isFile())
filesize = f.length();
else {
// The return value of the following is unspecified because a File
// object represents a directory.
filesize = f.length();
}
}
}
| Java |
import java.io.*;
public class FileReaderTest {
public static void main(String[] args) throws Exception {
File file = File.createTempFile("javamoptest1", ".tmp");
FileWriter writer = new FileWriter(file);
writer.write("0123456789");
writer.close();
file.deleteOnExit();
try{
Reader reader = new FileReader(file);
reader.mark(1);
int c = reader.read();
reader.reset();
int d = reader.read();
reader.reset();
int e = reader.read();
if (c == d && d == e)
System.out.println("reset() was properly used.");
else
throw new Exception("reset() did not preserve the value.");
} catch (Exception e){
System.err.println(e.getMessage());
}
}
}
| Java |
import java.io.*;
public class PushbackReaderTest {
public static void main(String[] args) throws Exception {
try{
Reader reader = new PushbackReader(new StringReader("1234567890"), 1);
reader.mark(1);
int c = reader.read();
reader.reset();
int d = reader.read();
reader.reset();
int e = reader.read();
if (c == d && d == e)
System.out.println("reset() was properly used.");
else
throw new Exception("reset() did not preserve the value.");
} catch (Exception e){
System.err.println(e.getMessage());
}
}
}
| Java |
import java.io.*;
public class PipedReaderTest {
public static void main(String[] args) throws Exception {
try{
Reader reader = new PipedReader(new PipedWriter(), 1);
reader.mark(1);
int c = reader.read();
reader.reset();
int d = reader.read();
reader.reset();
int e = reader.read();
if (c == d && d == e)
System.out.println("reset() was properly used.");
else
throw new Exception("reset() did not preserve the value.");
} catch (Exception e){
System.err.println(e.getMessage());
}
}
}
| Java |
import java.io.*;
public class InputStreamReaderTest {
public static void main(String[] args) throws Exception {
try{
Reader reader = new InputStreamReader(new ByteArrayInputStream("1234567890".getBytes()));
reader.mark(1);
int c = reader.read();
reader.reset();
int d = reader.read();
reader.reset();
int e = reader.read();
if (c == d && d == e)
System.out.println("reset() was properly used.");
else
throw new Exception("reset() did not preserve the value.");
} catch (Exception e){
System.err.println(e.getMessage());
}
}
}
| Java |
import java.io.*;
public class Writer_ManipulateAfterClose_2 {
public static void main(String[] args) throws IOException {
Writer writer = new StringWriter();
writer.write(100);
writer.close();
// StringWriter is an exceptional subclass of Writer;
// write() after close() is valid.
writer.write(101);
}
}
| Java |
import java.io.*;
public class Writer_ManipulateAfterClose_1 {
public static void main(String[] args) throws IOException {
File file = File.createTempFile("javamoptest1", ".tmp");
file.deleteOnExit();
Writer writer = new FileWriter(file);
writer.write(100);
writer.close();
// A closed stream cannot perform output operations.
writer.write(101);
}
}
| Java |
import java.io.*;
public class LineNumberReaderTest {
public static void main(String[] args) throws Exception {
Reader reader = new LineNumberReader(new StringReader("1234567890"), 1);
reader.mark(1);
reader.read();
reader.read();
reader.reset();
reader.read();
reader.read();
}
}
| Java |
import java.io.*;
public class BufferedReaderTest {
public static void main(String[] args) throws Exception {
Reader reader = new BufferedReader(new StringReader("1234567890"), 1);
reader.mark(1);
// We read only one byte; so, reset() is valid.
reader.read();
reader.reset();
// The buffer cannot hold two bytes; so, reset() is invalid.
reader.read();
reader.read();
reader.reset();
reader.read();
reader.read();
}
}
| Java |
import java.io.*;
public class Serializable_NoArgConstructor_1 {
static class Super_1 {
// The following hides the compiler-generating no-arg constructor,
// violating the Serializable_NoArgConstructor property.
private Super_1() {
}
}
static class Sub_1 extends Super_1 implements Serializable {
}
public static void main(String[] args) {
Object o1 = new Sub_1();
}
}
| Java |
import java.io.*;
public class Reader_ManipulateAfterClose_1 {
public static void main(String[] args) throws IOException {
StringReader reader = new StringReader("hello");
int i = reader.read();
reader.close();
// After a reader is closed, most operations, such as read() and reset(), are banned.
int j = reader.read();
}
}
| Java |
import java.io.*;
public class StreamTokenizer_AccessInvalidField_1 {
public static void main(String[] args) throws IOException {
StringReader reader = new StringReader("abc");
StreamTokenizer tokenizer = new StreamTokenizer(reader);
for (boolean readeof = false; !readeof; ) {
int type = tokenizer.nextToken();
switch (type) {
case StreamTokenizer.TT_WORD:
{
// In case of TT_WORD, sval should be accessed.
double nval = tokenizer.nval;
// String sval = tokenizer.sval;
}
break;
case StreamTokenizer.TT_NUMBER:
{
// In case of TT_NUMBER, nval should be accessed.
// double nval = tokenizer.nval;
String sval = tokenizer.sval;
}
break;
case StreamTokenizer.TT_EOL:
break;
case StreamTokenizer.TT_EOF:
readeof = true;
break;
}
}
}
}
| Java |
import java.io.*;
public class RandomAccessFile_ManipulateAfterClose_1 {
public static void main(String[] args) throws FileNotFoundException, IOException {
File file = File.createTempFile("tmp", ".tmp");
RandomAccessFile raf = new RandomAccessFile(file, "rw");
raf.writeByte(100);
raf.close();
// A closed random access file cannot perform input or output operations.
raf.writeByte(101);
}
}
| Java |
import java.io.*;
public class Console_CloseReader_1 {
public static void main(String[] args) throws IOException {
Console cons = System.console();
Reader reader = cons.reader();
// Invoking close() on the reader from the console will not close the
// underlying stream.
reader.close();
}
}
| Java |
import java.io.*;
public class InputStream_ManipulateAfterClose_2 {
public static void main(String[] args) throws IOException {
byte[] buffer = { 1, 2, 3, 4, 5};
ByteArrayInputStream input = new ByteArrayInputStream(buffer);
int i = input.read();
input.close();
// Although ByteArrayInputStream is a subclass of InputStream, calling
// read() after close() is allowed.
int j = input.read();
}
}
| Java |
import java.io.*;
public class InputStream_ManipulateAfterClose_1 {
public static void main(String[] args) throws IOException {
File file = File.createTempFile("javamoptest1", ".tmp");
FileWriter writer = new FileWriter(file);
writer.write("0123456789");
writer.close();
file.deleteOnExit();
InputStream input = new FileInputStream(file);
byte[] buf = new byte[5];
int i = input.read(buf);
input.close();
// After a stream is closed, most operations, such as read() and reset(), are banned.
int j = input.read(buf);
}
}
| Java |
import java.io.*;
public class InputStream_ManipulateAfterClose_3 {
public static void main(String[] args) throws IOException {
File file = File.createTempFile("javamoptest1", ".tmp");
FileWriter writer = new FileWriter(file);
writer.write("0123456789");
writer.close();
file.deleteOnExit();
FileInputStream fis = new FileInputStream(file);
BufferedInputStream bis = new BufferedInputStream(fis);
int i = bis.read();
// This will close not only 'bis' but also 'fis'.
bis.close();
// Since 'fis' has been also closed, the following should be caught by
// the handler of the InputStream_ManipulateAfterClose property. However,
// the property handler will not be triggered if the property is not
// thoroughly applied to all the necessary class files. For example,
// unless rt.jar is weaved, the following call will not fire any event,
// causing the property handler not to be triggered.
byte[] buf = new byte[5];
int j = fis.read(buf);
}
}
| Java |
import java.io.*;
public class PipedStream_SingleThread_3 {
private static PipedOutputStream pos;
private static PipedInputStream pis;
public static void main(String[] args) throws IOException, InterruptedException {
pos = new PipedOutputStream();
pis = new PipedInputStream(pos);
Thread thr2 = new Thread(new Runnable()
{
@Override
public void run() {
try {
pos.write(1);
}
catch (IOException ignored) {
}
}
});
thr2.start();
int i = pis.read();
thr2.join();
// The main thread reads data from the pipe in the above code, and then
// relay it to another thread by reusing the same pipe. Although it does
// not deadlock in this case, it's still bad practice.
Thread thr3 = new Thread(new Runnable()
{
@Override
public void run() {
try {
int i = pis.read();
}
catch (IOException ignored) {
}
}
});
thr3.start();
pos.write(i);
thr3.join();
}
}
| Java |
import java.io.*;
public class PipedStream_SingleThread_2 {
private static PipedOutputStream pos;
private static PipedInputStream pis;
public static void main(String[] args) throws IOException, InterruptedException {
pos = new PipedOutputStream();
pis = new PipedInputStream(pos);
Runnable r = new Runnable()
{
@Override
public void run() {
try {
int i = pis.read();
// It is recommended not to read ad write in a thread.
pos.write(2);
}
catch (IOException ignored) {
}
}
};
Thread thr2 = new Thread(r);
thr2.start();
pos.write(1);
thr2.join();
}
}
| Java |
import java.io.*;
public class PipedStream_SingleThread_1 {
public static void main(String[] args) throws IOException {
PipedOutputStream pos = new PipedOutputStream();
PipedInputStream pis = new PipedInputStream(pos);
pos.write(1);
int i = pis.read();
}
}
| Java |
import java.io.*;
public class File_DeleteTempFile_1 {
public static void main(String[] args) throws IOException {
File file = File.createTempFile("pre", ".tmp");
// A temporary file can be deleted either explicitly or automatically.
// file.delete();
// file.deleteOnExit();
}
}
| Java |
import java.io.*;
public class ObjectInput_Close_1 {
public static void main(String[] args) throws IOException {
byte[] buffer = generateBuffer();
ByteArrayInputStream bais = new ByteArrayInputStream(buffer);
ObjectInputStream ois = new ObjectInputStream(bais);
byte b = ois.readByte();
// close() must be called to release the resources.
// ois.close();
}
private static byte[] generateBuffer() throws IOException {
ByteArrayOutputStream baos = new ByteArrayOutputStream();
ObjectOutputStream oos = new ObjectOutputStream(baos);
oos.writeInt(1);
oos.close();
return baos.toByteArray();
}
}
| Java |
import java.io.*;
public class PipedInputStreamTest {
public static void main(String[] args) throws Exception {
PipedOutputStream output = new PipedOutputStream();
try {
InputStream stream = new PipedInputStream(output);
output.write(1);
output.write(2);
output.write(3);
output.write(4);
output.write(5);
stream.mark(1);
int c = stream.read();
stream.reset();
int d = stream.read();
stream.reset();
int e = stream.read();
if (c == d && d == e)
System.out.println("PipedInputStream.reset() was properly used.");
else
throw new Exception("PipedInputStream.reset() did not preserve the value.");
}
catch (Exception e) {
System.err.println(e.getMessage());
}
}
}
| Java |
import java.io.*;
public class ObjectInputStreamTest {
public static void main(String[] args) throws Exception {
File file = File.createTempFile("javamoptest1", ".tmp");
{
FileOutputStream fos = new FileOutputStream(file);
ObjectOutputStream oos = new ObjectOutputStream(fos);
oos.writeInt(12345);
oos.close();
}
FileInputStream fis = new FileInputStream(file);
try {
ObjectInputStream stream = new ObjectInputStream(fis);
stream.mark(1);
int c = stream.read();
stream.reset();
int d = stream.read();
stream.reset();
int e = stream.read();
if (c == d && d == e)
System.out.println("ObjectInputStream.reset() was properly used.");
else
throw new Exception("ObjectInputStream.reset() did not preserve the value.");
}
catch (Exception e) {
System.err.println(e.getMessage());
}
}
}
| Java |
import java.io.*;
public class SequenceInputStreamTest {
public static void main(String[] args) throws Exception {
try {
SequenceInputStream stream = new SequenceInputStream(new StringBufferInputStream("12345"), new StringBufferInputStream("67890"));
stream.mark(1);
int c = stream.read();
stream.reset();
int d = stream.read();
stream.reset();
int e = stream.read();
if (c == d && d == e)
System.out.println("SequenceInputStream.reset() was properly used.");
else
throw new Exception("SequenceInputStream.reset() did not preserve the value.");
}
catch (Exception e) {
System.err.println(e.getMessage());
}
}
}
| Java |
import java.io.*;
public class FileInputStreamTest {
public static void main(String[] args) throws Exception {
File file = File.createTempFile("javamoptest1", ".tmp");
FileWriter writer = new FileWriter(file);
writer.write("0123456789");
writer.close();
file.deleteOnExit();
try {
InputStream stream = new FileInputStream(file);
stream.mark(1);
int c = stream.read();
stream.reset();
int d = stream.read();
stream.reset();
int e = stream.read();
if (c == d && d == e)
System.out.println("FileInputStream.reset() was properly used.");
else
throw new Exception("FileInputStream.reset() did not preserve the value.");
}
catch (Exception e) {
System.err.println(e.getMessage());
}
}
}
| Java |
import java.io.*;
public class PushbackInputStreamTest {
public static void main(String[] args) throws Exception {
try {
PushbackInputStream stream = new PushbackInputStream(new StringBufferInputStream("1234567890"));
stream.mark(1);
int c = stream.read();
stream.reset();
int d = stream.read();
stream.reset();
int e = stream.read();
if (c == d && d == e)
System.out.println("PushbackInputStream.reset() was properly used.");
else
throw new Exception("PushbackInputStream.reset() did not preserve the value.");
}
catch (Exception e) {
System.err.println(e.getMessage());
}
}
}
| Java |
import java.io.*;
public class PipedOutputStream_UnconnectedWrite_1 {
public static void main(String[] args) throws IOException {
PipedOutputStream pos = new PipedOutputStream();
PipedInputStream pis = new PipedInputStream();
// A pipe should be connected first in order to write.
// pis.connect(pos);
pos.write(1);
}
}
| Java |
import java.io.*;
public class PipedOutputStream_UnconnectedWrite_2 {
public static void main(String[] args) throws IOException {
PipedOutputStream pos = new PipedOutputStream();
// A pipe should be connected first in order to write.
PipedInputStream pis = new PipedInputStream();
// PipedInputStream pis = new PipedInputStream(pos);
pos.write(1);
}
}
| Java |
import java.io.*;
public class LineNumberReaderTest {
public static void main(String[] args) throws Exception {
Reader reader = new LineNumberReader(new StringReader("1234567890"), 1);
reader.reset();
int c = reader.read();
}
}
| Java |
import java.io.*;
public class BufferedReaderTest {
public static void main(String[] args) throws Exception {
Reader reader = new BufferedReader(new StringReader("1234567890"), 1);
reader.reset();
int c = reader.read();
}
}
| Java |
import java.io.*;
public class Console_CloseWriter_1 {
public static void main(String[] args) throws IOException {
Console cons = System.console();
Writer writer = cons.writer();
// Invoking close() on the writer from the console will not close the
// underlying stream.
writer.close();
}
}
| Java |
import java.io.*;
public class Console_FillZeroPassword_1 {
public static void main(String[] args) {
Console cons = System.console();
char[] passwd = cons.readPassword();
// Zeroing the returned password is recommended to minimize the lifetime
// of sensitive data in memory.
// java.util.Arrays.fill(passwd, ' ');
}
}
| Java |
import java.io.*;
public class ObjectOutput_Close_1 {
public static void main(String[] args) throws IOException {
ByteArrayOutputStream baos = new ByteArrayOutputStream();
ObjectOutputStream oos = new ObjectOutputStream(baos);
oos.writeInt(1);
// close() must be called to release the resources.
// oos.close();
}
}
| Java |
import java.io.*;
public class Serializable_UID_1 implements Serializable {
// It is strongly recommended that all serializable classes explicitly
// declare serialVersionUID values.
// private static final long serialVersionUID = 62L;
public static void main(String[] args) {
Object o1 = new Inner_1();
Object o2 = new Inner_2();
Object o3 = new Inner_3();
}
static class Inner_1 implements Serializable {
// A serialVersionUID must be static, final, and of type long.
private final long serialVersionUID = 63L;
}
static class Inner_2 implements Serializable {
// A serialVersionUID must be static, final, and of type long.
private static long serialVersionUID = 64L;
}
static class Inner_3 implements Serializable {
// A serialVersionUID must be static, final, and of type long.
private static final int serialVersionUID = 65;
}
}
| Java |
import java.util.*;
public class Arrays_Comparable_1 {
static class Noncomparable {
public int i;
Noncomparable(int i) {
this.i = i;
}
}
public static void main(String[] args) {
Object[] objs = new Object[3];
objs[0] = new Noncomparable(0);
objs[1] = new Noncomparable(1);
objs[2] = new Noncomparable(2);
Arrays.sort(objs);
}
}
| Java |
import java.util.*;
public class Arrays_Comparable_2 {
public static void main(String[] args) {
Object[] objs = new Object[3];
objs[0] = "Hello";
objs[1] = 62;
objs[2] = 2.52;
Arrays.sort(objs);
}
}
| Java |
import java.util.*;
public class Arrays_SortBeforeBinarySearch_1 {
public static void main(String[] args) {
Object[] arr = new Object[5];
for (int i = 0; i < arr.length; ++i)
arr[i] = arr.length - i;
// 'arr' has not been sorted.
{
Arrays.binarySearch(arr, 3);
}
// Now, 'arr' is sorted.
{
Arrays.sort(arr);
Arrays.binarySearch(arr, 3);
}
// 'arr' is no longer sorted.
{
arr[2] = 4;
Arrays.binarySearch(arr, 3);
}
}
}
| Java |
import java.util.*;
public class Map_StandardConstructors_1 {
// BadMap0 does not define any of the 'standard' constructors.
static class BadMap0<K, V> extends AbstractMap<K, V> {
public Set<Map.Entry<K, V>> entrySet() {
return null;
}
}
// BadMap1 defines only one of the 'standard' constructors.
static class BadMap1 extends BadMap0 {
public BadMap1() {
}
}
// BadMap2 defines only one of the 'standard' constructors.
static class BadMap2 extends BadMap0 {
public BadMap2(Map src) {
}
}
// GoodMap defines both of the 'standard' constructors.
static class GoodMap extends BadMap0 {
public GoodMap() {
}
public GoodMap(Map src) {
}
}
public static void main(String[] args) {
Map c1 = new GoodMap();
Map c2 = new BadMap1();
Map c3 = new BadMap2(c1);
}
}
| Java |
import java.util.*;
public class SortedSet_Comparable_1 {
public static void main(String[] args) throws Exception {
SortedSet backing = new TreeSet();
backing.add(new Integer(1));
backing.add(new Integer(2));
backing.add(new Integer(3));
// SortedSet cannot have element which is not comparable.
backing.add(new Object());
}
}
| Java |
import java.util.*;
public class Collections_CopySize_1 {
public static void main(String[] args) throws Exception {
ArrayList<Integer> dest = new ArrayList<Integer>();
dest.add(1);
dest.add(2);
ArrayList<Integer> src = new ArrayList<Integer>();
src.add(1);
src.add(2);
src.add(3);
// The length of destination is not as long as source.
Collections.copy(dest, src);
}
}
| Java |
import java.util.*;
public class Collection_StandardConstructors_1 {
// BadCollection0 does not define any of the 'standard' constructors.
static class BadCollection0 extends AbstractCollection {
public int size() {
return 0;
}
public Iterator iterator() {
return null;
}
}
// BadCollection1 defines only one of the 'standard' constructors.
static class BadCollection1 extends BadCollection0 {
public BadCollection1() {
}
}
// BadCollection2 defines only one of the 'standard' constructors.
static class BadCollection2 extends BadCollection0 {
public BadCollection2(Collection src) {
}
}
// GoodCollection defines both of the 'standard' constructors.
static class GoodCollection extends BadCollection0 {
public GoodCollection() {
}
public GoodCollection(Collection src) {
}
}
public static void main(String[] args) {
Collection c1 = new GoodCollection();
Collection c2 = new BadCollection1();
Collection c3 = new BadCollection2(c1);
}
}
| Java |
import java.util.*;
public class ArrayDeque_NonNull_1 {
public static void main(String[] args) {
ArrayDeque<Integer> q = new ArrayDeque<Integer>();
// null is not permitted; so, any of these will fail.
q.add(null);
q.offer(null);
q.push(null);
}
}
| Java |
import java.util.*;
import java.util.concurrent.ArrayBlockingQueue;
public class Collection_UnsynchronizedAddAll_1 {
static final int numelem = 100000;
private static void modify(Collection<Integer> c) {
c.clear();
for (int i = 0; i < numelem; ++i)
c.add(i);
}
private static void test(Collection<Integer> col) throws Exception {
final Vector<Integer> src = new Vector<Integer>();
modify(src);
Runnable r = new Runnable()
{
@Override
public void run() {
modify(src);
}
};
Thread modifying = new Thread(r);
// The other thread will be likely modifying the shared collection 'src',
// while addAll() is accessing 'src'.
modifying.start();
col.addAll(src);
modifying.join();
}
public static void main(String[] args) {
try {
ArrayBlockingQueue<Integer> que = new ArrayBlockingQueue<Integer>(numelem);
test(que);
}
catch (Exception ignored) {
}
try {
ArrayList<Integer> list = new ArrayList<Integer>(numelem);
test(list);
}
catch (Exception ignored) {
}
}
}
| Java |
import java.util.*;
public class ArrayDeque_Iterator_1 {
public static void main(String[] args) throws Exception {
ArrayDeque<Integer> q = new ArrayDeque<Integer>();
q.add(1);
q.add(2);
Iterator i = q.iterator();
i.hasNext();
q.add(3);
// The iterator is not valid anymore because the deque has been modified above.
i.next();
}
}
| Java |
import java.util.*;
public class List_UnsynchronizedSubList_1 {
public static void main(String[] args) throws Exception {
ArrayList<Integer> backing = new ArrayList<Integer>();
backing.add(1);
backing.add(2);
backing.add(3);
List<Integer> sub = backing.subList(0, 2);
int i0 = sub.get(0);
backing.add(4);
// Since the backing list was modified by the above line, the sublist was
// invalidated.
int i1 = sub.get(1);
}
}
| Java |
import java.net.*;
public class URL_SetURLStreamHandlerFactory_1 {
public static void main(String[] args) {
URL.setURLStreamHandlerFactory(null);
// URL.setURLStreamHandlerFactory() can be called at most once.
URL.setURLStreamHandlerFactory(null);
}
}
| Java |
import java.net.*;
import java.io.IOException;
public class Socket_ReuseAddress_1 {
public static void main(String[] args) throws IOException, SocketException {
Socket sock = new Socket();
// The following call is fine.
sock.setReuseAddress(true);
sock.bind(null);
// Now that the socket is bound, the behavior of the following call is
// not defined. The property handler should be triggered.
sock.setReuseAddress(true);
}
}
| Java |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.