repo_name
stringlengths 7
104
| file_path
stringlengths 13
198
| context
stringlengths 67
7.15k
| import_statement
stringlengths 16
4.43k
| code
stringlengths 40
6.98k
| prompt
stringlengths 227
8.27k
| next_line
stringlengths 8
795
|
---|---|---|---|---|---|---|
Tyde/TuCanMobile | app/src/main/java/com/dalthed/tucan/ui/ApplyEvent.java | // Path: app/src/main/java/com/dalthed/tucan/Connection/AnswerObject.java
// public class AnswerObject {
// private String HTML_text;
// private String redirectURL;
// private String lastcalledURL;
// private CookieManager Cookies;
// /**
// * RückgabeObjekt der BrowseMethods
// * @param HTML HTML-Code
// * @param redirect Redirect-URL aus dem HTTP-Header
// * @param myCookies CookieManager mit relevanten Cookies
// * @param lastcalledURL Zuletzt aufgerufene URL
// */
// public AnswerObject(String HTML,String redirect,CookieManager myCookies,String lastcalledURL){
// this.HTML_text=HTML;
// this.redirectURL=redirect;
// this.Cookies=myCookies;
// this.lastcalledURL=lastcalledURL;
// }
// public String getHTML(){
// return this.HTML_text;
// }
// public String getRedirectURLString() {
// return this.redirectURL;
// }
// public String getLastCalledURL() {
// return this.lastcalledURL;
// }
// public CookieManager getCookieManager() {
// return this.Cookies;
// }
//
// }
//
// Path: app/src/main/java/com/dalthed/tucan/util/ConfigurationChangeStorage.java
// public class ConfigurationChangeStorage {
//
// private ArrayList<BasicScraper> scrapers;
// private ArrayList<SimpleSecureBrowser> browser;
// public ArrayList<ListAdapter> adapters;
//
// public int mode;
//
// public ConfigurationChangeStorage() {
// scrapers = new ArrayList<BasicScraper>();
// adapters = new ArrayList<ListAdapter>();
// browser = new ArrayList<SimpleSecureBrowser>();
// }
//
// /**
// * Gibt den Scraper mit angepassten Context zurück
// *
// * @param index
// * @param context
// * @return
// */
// public BasicScraper getScraper(int index, Context context) {
// if (scrapers.size() > index) {
// BasicScraper returnScraper = scrapers.get(index);
// if (returnScraper != null) {
//
// returnScraper.renewContext(context);
// return returnScraper;
// }
// }
// return null;
//
// }
//
// public void addScraper(BasicScraper scrape) {
// scrapers.add(scrape);
// }
//
// public void addBrowser(List<SimpleSecureBrowser> browser) {
// if (browser != null) {
// this.browser.addAll(browser);
// }
// }
//
// public void addBrowser(SimpleSecureBrowser browser) {
// if (browser != null) {
// this.browser.add(browser);
// }
// }
//
// public void dismissDialogs() {
// if(browser!=null){
// for(SimpleSecureBrowser singleBrowser: browser) {
// if(singleBrowser.dialog!=null) {
// singleBrowser.dialog.dismiss();
// singleBrowser.dialog = null;
// }
// }
// }
// }
//
// public void updateBrowser(BrowserAnswerReciever context) {
// for (SimpleSecureBrowser singleBrowser : browser) {
// singleBrowser.renewContext(context);
// singleBrowser.dialog = null;
// if (!(singleBrowser.getStatus().equals(AsyncTask.Status.FINISHED))) {
// Log.i(TucanMobile.LOG_TAG,
// "Configuration Change at unfinished Browser, show Dialog");
//
// singleBrowser.showDialog();
//
// }
// }
// }
//
// }
| import android.os.Bundle;
import com.dalthed.tucan.Connection.AnswerObject;
import com.dalthed.tucan.util.ConfigurationChangeStorage; | /**
* This file is part of TuCan Mobile.
*
* TuCan Mobile is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* TuCan Mobile is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with TuCan Mobile. If not, see <http://www.gnu.org/licenses/>.
*/
package com.dalthed.tucan.ui;
public class ApplyEvent extends SimpleWebListActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
/*
BugSenseHandler.setup(this, "ed5c1682");
String CookieHTTPString = getIntent().getExtras().getString("Cookie");
URLStringtoCall = getIntent().getExtras().getString("URL");
URL URLtoCall;
try {
URLtoCall = new URL(URLStringtoCall);
localCookieManager = new CookieManager();
localCookieManager.generateManagerfromHTTPString(
URLtoCall.getHost(), CookieHTTPString);
callResultBrowser = new SimpleSecureBrowser(this);
RequestObject thisRequest = new RequestObject(URLStringtoCall,
localCookieManager, RequestObject.METHOD_GET, "");
callResultBrowser.execute(thisRequest);
} catch (MalformedURLException e) {
Log.e(LOG_TAG, e.getMessage());
}*/
}
public void onPostExecute(AnswerObject result) {
}
@Override | // Path: app/src/main/java/com/dalthed/tucan/Connection/AnswerObject.java
// public class AnswerObject {
// private String HTML_text;
// private String redirectURL;
// private String lastcalledURL;
// private CookieManager Cookies;
// /**
// * RückgabeObjekt der BrowseMethods
// * @param HTML HTML-Code
// * @param redirect Redirect-URL aus dem HTTP-Header
// * @param myCookies CookieManager mit relevanten Cookies
// * @param lastcalledURL Zuletzt aufgerufene URL
// */
// public AnswerObject(String HTML,String redirect,CookieManager myCookies,String lastcalledURL){
// this.HTML_text=HTML;
// this.redirectURL=redirect;
// this.Cookies=myCookies;
// this.lastcalledURL=lastcalledURL;
// }
// public String getHTML(){
// return this.HTML_text;
// }
// public String getRedirectURLString() {
// return this.redirectURL;
// }
// public String getLastCalledURL() {
// return this.lastcalledURL;
// }
// public CookieManager getCookieManager() {
// return this.Cookies;
// }
//
// }
//
// Path: app/src/main/java/com/dalthed/tucan/util/ConfigurationChangeStorage.java
// public class ConfigurationChangeStorage {
//
// private ArrayList<BasicScraper> scrapers;
// private ArrayList<SimpleSecureBrowser> browser;
// public ArrayList<ListAdapter> adapters;
//
// public int mode;
//
// public ConfigurationChangeStorage() {
// scrapers = new ArrayList<BasicScraper>();
// adapters = new ArrayList<ListAdapter>();
// browser = new ArrayList<SimpleSecureBrowser>();
// }
//
// /**
// * Gibt den Scraper mit angepassten Context zurück
// *
// * @param index
// * @param context
// * @return
// */
// public BasicScraper getScraper(int index, Context context) {
// if (scrapers.size() > index) {
// BasicScraper returnScraper = scrapers.get(index);
// if (returnScraper != null) {
//
// returnScraper.renewContext(context);
// return returnScraper;
// }
// }
// return null;
//
// }
//
// public void addScraper(BasicScraper scrape) {
// scrapers.add(scrape);
// }
//
// public void addBrowser(List<SimpleSecureBrowser> browser) {
// if (browser != null) {
// this.browser.addAll(browser);
// }
// }
//
// public void addBrowser(SimpleSecureBrowser browser) {
// if (browser != null) {
// this.browser.add(browser);
// }
// }
//
// public void dismissDialogs() {
// if(browser!=null){
// for(SimpleSecureBrowser singleBrowser: browser) {
// if(singleBrowser.dialog!=null) {
// singleBrowser.dialog.dismiss();
// singleBrowser.dialog = null;
// }
// }
// }
// }
//
// public void updateBrowser(BrowserAnswerReciever context) {
// for (SimpleSecureBrowser singleBrowser : browser) {
// singleBrowser.renewContext(context);
// singleBrowser.dialog = null;
// if (!(singleBrowser.getStatus().equals(AsyncTask.Status.FINISHED))) {
// Log.i(TucanMobile.LOG_TAG,
// "Configuration Change at unfinished Browser, show Dialog");
//
// singleBrowser.showDialog();
//
// }
// }
// }
//
// }
// Path: app/src/main/java/com/dalthed/tucan/ui/ApplyEvent.java
import android.os.Bundle;
import com.dalthed.tucan.Connection.AnswerObject;
import com.dalthed.tucan.util.ConfigurationChangeStorage;
/**
* This file is part of TuCan Mobile.
*
* TuCan Mobile is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* TuCan Mobile is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with TuCan Mobile. If not, see <http://www.gnu.org/licenses/>.
*/
package com.dalthed.tucan.ui;
public class ApplyEvent extends SimpleWebListActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
/*
BugSenseHandler.setup(this, "ed5c1682");
String CookieHTTPString = getIntent().getExtras().getString("Cookie");
URLStringtoCall = getIntent().getExtras().getString("URL");
URL URLtoCall;
try {
URLtoCall = new URL(URLStringtoCall);
localCookieManager = new CookieManager();
localCookieManager.generateManagerfromHTTPString(
URLtoCall.getHost(), CookieHTTPString);
callResultBrowser = new SimpleSecureBrowser(this);
RequestObject thisRequest = new RequestObject(URLStringtoCall,
localCookieManager, RequestObject.METHOD_GET, "");
callResultBrowser.execute(thisRequest);
} catch (MalformedURLException e) {
Log.e(LOG_TAG, e.getMessage());
}*/
}
public void onPostExecute(AnswerObject result) {
}
@Override | public ConfigurationChangeStorage saveConfiguration() { |
Tyde/TuCanMobile | app/src/main/java/com/dalthed/tucan/scraper/UniApplicationScraper.java | // Path: app/src/main/java/com/dalthed/tucan/Connection/AnswerObject.java
// public class AnswerObject {
// private String HTML_text;
// private String redirectURL;
// private String lastcalledURL;
// private CookieManager Cookies;
// /**
// * RückgabeObjekt der BrowseMethods
// * @param HTML HTML-Code
// * @param redirect Redirect-URL aus dem HTTP-Header
// * @param myCookies CookieManager mit relevanten Cookies
// * @param lastcalledURL Zuletzt aufgerufene URL
// */
// public AnswerObject(String HTML,String redirect,CookieManager myCookies,String lastcalledURL){
// this.HTML_text=HTML;
// this.redirectURL=redirect;
// this.Cookies=myCookies;
// this.lastcalledURL=lastcalledURL;
// }
// public String getHTML(){
// return this.HTML_text;
// }
// public String getRedirectURLString() {
// return this.redirectURL;
// }
// public String getLastCalledURL() {
// return this.lastcalledURL;
// }
// public CookieManager getCookieManager() {
// return this.Cookies;
// }
//
// }
//
// Path: app/src/main/java/com/dalthed/tucan/adapters/UniApplicationAdapter.java
// public class UniApplicationAdapter extends ArrayAdapter<String> {
//
// public final HashMap<Integer, ArrayList<String>> contentMap;
//
// public static HashMap<Integer, ArrayList<String>> getEmptyContentMap() {
// return new HashMap<Integer, ArrayList<String>>() {
// {
// put(R.id.application_type, new ArrayList<String>());
// put(R.id.application_field, new ArrayList<String>());
// put(R.id.application_semester, new ArrayList<String>());
// put(R.id.application_status, new ArrayList<String>());
// put(R.id.application_begin, new ArrayList<String>());
// put(R.id.application_sent, new ArrayList<String>());
// }
// };
// }
//
// public UniApplicationAdapter(Context context,
// HashMap<Integer, ArrayList<String>> contentMap) {
//
// super(context, R.layout.application_row, R.id.application_field,
// contentMap.get(R.id.application_field));
// this.contentMap = contentMap;
// }
//
// @Override
// public View getView(int position, View convertView, ViewGroup parent) {
//
// View tempView = super.getView(position, convertView, parent);
// updateTextViewById(position, R.id.application_begin, tempView);
// updateTextViewById(position, R.id.application_semester, tempView);
// updateTextViewById(position, R.id.application_type, tempView);
// updateTextViewById(position, R.id.application_sent, tempView);
// updateTextViewById(position, R.id.application_status, tempView);
// return tempView;
// }
//
// private void updateTextViewById(int position, int id, View parentView) {
// TextView tViewToUpdate = (TextView) parentView.findViewById(id);
// tViewToUpdate.setText(contentMap.get(id).get(position));
// }
//
// }
//
// Path: app/src/main/java/com/dalthed/tucan/exceptions/LostSessionException.java
// public class LostSessionException extends Exception {
//
// public LostSessionException() {
// super();
// }
//
// public LostSessionException(String detailMessage, Throwable throwable) {
// super(detailMessage, throwable);
// }
//
// public LostSessionException(String detailMessage) {
// super(detailMessage);
// }
//
// public LostSessionException(Throwable throwable) {
// super(throwable);
// }
//
// }
//
// Path: app/src/main/java/com/dalthed/tucan/exceptions/TucanDownException.java
// public class TucanDownException extends Exception {
//
// /**
// *
// */
// private static final long serialVersionUID = 1L;
// public TucanDownException() {
// super();
// }
//
// public TucanDownException(String ErrorMessage) {
// super(ErrorMessage);
// }
//
// }
| import com.dalthed.tucan.exceptions.LostSessionException;
import com.dalthed.tucan.exceptions.TucanDownException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import org.jsoup.nodes.Element;
import org.jsoup.select.Elements;
import android.content.Context;
import android.widget.ListAdapter;
import com.dalthed.tucan.R;
import com.dalthed.tucan.Connection.AnswerObject;
import com.dalthed.tucan.adapters.UniApplicationAdapter; | /**
* This file is part of TuCan Mobile.
*
* TuCan Mobile is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* TuCan Mobile is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with TuCan Mobile. If not, see <http://www.gnu.org/licenses/>.
*/
package com.dalthed.tucan.scraper;
public class UniApplicationScraper extends BasicScraper {
private static final ArrayList<Integer> orderList = new ArrayList<Integer>() {
{
add(R.id.application_type);
add(R.id.application_field);
add(R.id.application_semester);
add(R.id.application_status);
add(R.id.application_begin);
add(R.id.application_sent);
}
};
| // Path: app/src/main/java/com/dalthed/tucan/Connection/AnswerObject.java
// public class AnswerObject {
// private String HTML_text;
// private String redirectURL;
// private String lastcalledURL;
// private CookieManager Cookies;
// /**
// * RückgabeObjekt der BrowseMethods
// * @param HTML HTML-Code
// * @param redirect Redirect-URL aus dem HTTP-Header
// * @param myCookies CookieManager mit relevanten Cookies
// * @param lastcalledURL Zuletzt aufgerufene URL
// */
// public AnswerObject(String HTML,String redirect,CookieManager myCookies,String lastcalledURL){
// this.HTML_text=HTML;
// this.redirectURL=redirect;
// this.Cookies=myCookies;
// this.lastcalledURL=lastcalledURL;
// }
// public String getHTML(){
// return this.HTML_text;
// }
// public String getRedirectURLString() {
// return this.redirectURL;
// }
// public String getLastCalledURL() {
// return this.lastcalledURL;
// }
// public CookieManager getCookieManager() {
// return this.Cookies;
// }
//
// }
//
// Path: app/src/main/java/com/dalthed/tucan/adapters/UniApplicationAdapter.java
// public class UniApplicationAdapter extends ArrayAdapter<String> {
//
// public final HashMap<Integer, ArrayList<String>> contentMap;
//
// public static HashMap<Integer, ArrayList<String>> getEmptyContentMap() {
// return new HashMap<Integer, ArrayList<String>>() {
// {
// put(R.id.application_type, new ArrayList<String>());
// put(R.id.application_field, new ArrayList<String>());
// put(R.id.application_semester, new ArrayList<String>());
// put(R.id.application_status, new ArrayList<String>());
// put(R.id.application_begin, new ArrayList<String>());
// put(R.id.application_sent, new ArrayList<String>());
// }
// };
// }
//
// public UniApplicationAdapter(Context context,
// HashMap<Integer, ArrayList<String>> contentMap) {
//
// super(context, R.layout.application_row, R.id.application_field,
// contentMap.get(R.id.application_field));
// this.contentMap = contentMap;
// }
//
// @Override
// public View getView(int position, View convertView, ViewGroup parent) {
//
// View tempView = super.getView(position, convertView, parent);
// updateTextViewById(position, R.id.application_begin, tempView);
// updateTextViewById(position, R.id.application_semester, tempView);
// updateTextViewById(position, R.id.application_type, tempView);
// updateTextViewById(position, R.id.application_sent, tempView);
// updateTextViewById(position, R.id.application_status, tempView);
// return tempView;
// }
//
// private void updateTextViewById(int position, int id, View parentView) {
// TextView tViewToUpdate = (TextView) parentView.findViewById(id);
// tViewToUpdate.setText(contentMap.get(id).get(position));
// }
//
// }
//
// Path: app/src/main/java/com/dalthed/tucan/exceptions/LostSessionException.java
// public class LostSessionException extends Exception {
//
// public LostSessionException() {
// super();
// }
//
// public LostSessionException(String detailMessage, Throwable throwable) {
// super(detailMessage, throwable);
// }
//
// public LostSessionException(String detailMessage) {
// super(detailMessage);
// }
//
// public LostSessionException(Throwable throwable) {
// super(throwable);
// }
//
// }
//
// Path: app/src/main/java/com/dalthed/tucan/exceptions/TucanDownException.java
// public class TucanDownException extends Exception {
//
// /**
// *
// */
// private static final long serialVersionUID = 1L;
// public TucanDownException() {
// super();
// }
//
// public TucanDownException(String ErrorMessage) {
// super(ErrorMessage);
// }
//
// }
// Path: app/src/main/java/com/dalthed/tucan/scraper/UniApplicationScraper.java
import com.dalthed.tucan.exceptions.LostSessionException;
import com.dalthed.tucan.exceptions.TucanDownException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import org.jsoup.nodes.Element;
import org.jsoup.select.Elements;
import android.content.Context;
import android.widget.ListAdapter;
import com.dalthed.tucan.R;
import com.dalthed.tucan.Connection.AnswerObject;
import com.dalthed.tucan.adapters.UniApplicationAdapter;
/**
* This file is part of TuCan Mobile.
*
* TuCan Mobile is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* TuCan Mobile is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with TuCan Mobile. If not, see <http://www.gnu.org/licenses/>.
*/
package com.dalthed.tucan.scraper;
public class UniApplicationScraper extends BasicScraper {
private static final ArrayList<Integer> orderList = new ArrayList<Integer>() {
{
add(R.id.application_type);
add(R.id.application_field);
add(R.id.application_semester);
add(R.id.application_status);
add(R.id.application_begin);
add(R.id.application_sent);
}
};
| public UniApplicationScraper(Context context, AnswerObject result) { |
Tyde/TuCanMobile | app/src/main/java/com/dalthed/tucan/scraper/UniApplicationScraper.java | // Path: app/src/main/java/com/dalthed/tucan/Connection/AnswerObject.java
// public class AnswerObject {
// private String HTML_text;
// private String redirectURL;
// private String lastcalledURL;
// private CookieManager Cookies;
// /**
// * RückgabeObjekt der BrowseMethods
// * @param HTML HTML-Code
// * @param redirect Redirect-URL aus dem HTTP-Header
// * @param myCookies CookieManager mit relevanten Cookies
// * @param lastcalledURL Zuletzt aufgerufene URL
// */
// public AnswerObject(String HTML,String redirect,CookieManager myCookies,String lastcalledURL){
// this.HTML_text=HTML;
// this.redirectURL=redirect;
// this.Cookies=myCookies;
// this.lastcalledURL=lastcalledURL;
// }
// public String getHTML(){
// return this.HTML_text;
// }
// public String getRedirectURLString() {
// return this.redirectURL;
// }
// public String getLastCalledURL() {
// return this.lastcalledURL;
// }
// public CookieManager getCookieManager() {
// return this.Cookies;
// }
//
// }
//
// Path: app/src/main/java/com/dalthed/tucan/adapters/UniApplicationAdapter.java
// public class UniApplicationAdapter extends ArrayAdapter<String> {
//
// public final HashMap<Integer, ArrayList<String>> contentMap;
//
// public static HashMap<Integer, ArrayList<String>> getEmptyContentMap() {
// return new HashMap<Integer, ArrayList<String>>() {
// {
// put(R.id.application_type, new ArrayList<String>());
// put(R.id.application_field, new ArrayList<String>());
// put(R.id.application_semester, new ArrayList<String>());
// put(R.id.application_status, new ArrayList<String>());
// put(R.id.application_begin, new ArrayList<String>());
// put(R.id.application_sent, new ArrayList<String>());
// }
// };
// }
//
// public UniApplicationAdapter(Context context,
// HashMap<Integer, ArrayList<String>> contentMap) {
//
// super(context, R.layout.application_row, R.id.application_field,
// contentMap.get(R.id.application_field));
// this.contentMap = contentMap;
// }
//
// @Override
// public View getView(int position, View convertView, ViewGroup parent) {
//
// View tempView = super.getView(position, convertView, parent);
// updateTextViewById(position, R.id.application_begin, tempView);
// updateTextViewById(position, R.id.application_semester, tempView);
// updateTextViewById(position, R.id.application_type, tempView);
// updateTextViewById(position, R.id.application_sent, tempView);
// updateTextViewById(position, R.id.application_status, tempView);
// return tempView;
// }
//
// private void updateTextViewById(int position, int id, View parentView) {
// TextView tViewToUpdate = (TextView) parentView.findViewById(id);
// tViewToUpdate.setText(contentMap.get(id).get(position));
// }
//
// }
//
// Path: app/src/main/java/com/dalthed/tucan/exceptions/LostSessionException.java
// public class LostSessionException extends Exception {
//
// public LostSessionException() {
// super();
// }
//
// public LostSessionException(String detailMessage, Throwable throwable) {
// super(detailMessage, throwable);
// }
//
// public LostSessionException(String detailMessage) {
// super(detailMessage);
// }
//
// public LostSessionException(Throwable throwable) {
// super(throwable);
// }
//
// }
//
// Path: app/src/main/java/com/dalthed/tucan/exceptions/TucanDownException.java
// public class TucanDownException extends Exception {
//
// /**
// *
// */
// private static final long serialVersionUID = 1L;
// public TucanDownException() {
// super();
// }
//
// public TucanDownException(String ErrorMessage) {
// super(ErrorMessage);
// }
//
// }
| import com.dalthed.tucan.exceptions.LostSessionException;
import com.dalthed.tucan.exceptions.TucanDownException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import org.jsoup.nodes.Element;
import org.jsoup.select.Elements;
import android.content.Context;
import android.widget.ListAdapter;
import com.dalthed.tucan.R;
import com.dalthed.tucan.Connection.AnswerObject;
import com.dalthed.tucan.adapters.UniApplicationAdapter; | /**
* This file is part of TuCan Mobile.
*
* TuCan Mobile is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* TuCan Mobile is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with TuCan Mobile. If not, see <http://www.gnu.org/licenses/>.
*/
package com.dalthed.tucan.scraper;
public class UniApplicationScraper extends BasicScraper {
private static final ArrayList<Integer> orderList = new ArrayList<Integer>() {
{
add(R.id.application_type);
add(R.id.application_field);
add(R.id.application_semester);
add(R.id.application_status);
add(R.id.application_begin);
add(R.id.application_sent);
}
};
public UniApplicationScraper(Context context, AnswerObject result) {
super(context, result);
}
@Override | // Path: app/src/main/java/com/dalthed/tucan/Connection/AnswerObject.java
// public class AnswerObject {
// private String HTML_text;
// private String redirectURL;
// private String lastcalledURL;
// private CookieManager Cookies;
// /**
// * RückgabeObjekt der BrowseMethods
// * @param HTML HTML-Code
// * @param redirect Redirect-URL aus dem HTTP-Header
// * @param myCookies CookieManager mit relevanten Cookies
// * @param lastcalledURL Zuletzt aufgerufene URL
// */
// public AnswerObject(String HTML,String redirect,CookieManager myCookies,String lastcalledURL){
// this.HTML_text=HTML;
// this.redirectURL=redirect;
// this.Cookies=myCookies;
// this.lastcalledURL=lastcalledURL;
// }
// public String getHTML(){
// return this.HTML_text;
// }
// public String getRedirectURLString() {
// return this.redirectURL;
// }
// public String getLastCalledURL() {
// return this.lastcalledURL;
// }
// public CookieManager getCookieManager() {
// return this.Cookies;
// }
//
// }
//
// Path: app/src/main/java/com/dalthed/tucan/adapters/UniApplicationAdapter.java
// public class UniApplicationAdapter extends ArrayAdapter<String> {
//
// public final HashMap<Integer, ArrayList<String>> contentMap;
//
// public static HashMap<Integer, ArrayList<String>> getEmptyContentMap() {
// return new HashMap<Integer, ArrayList<String>>() {
// {
// put(R.id.application_type, new ArrayList<String>());
// put(R.id.application_field, new ArrayList<String>());
// put(R.id.application_semester, new ArrayList<String>());
// put(R.id.application_status, new ArrayList<String>());
// put(R.id.application_begin, new ArrayList<String>());
// put(R.id.application_sent, new ArrayList<String>());
// }
// };
// }
//
// public UniApplicationAdapter(Context context,
// HashMap<Integer, ArrayList<String>> contentMap) {
//
// super(context, R.layout.application_row, R.id.application_field,
// contentMap.get(R.id.application_field));
// this.contentMap = contentMap;
// }
//
// @Override
// public View getView(int position, View convertView, ViewGroup parent) {
//
// View tempView = super.getView(position, convertView, parent);
// updateTextViewById(position, R.id.application_begin, tempView);
// updateTextViewById(position, R.id.application_semester, tempView);
// updateTextViewById(position, R.id.application_type, tempView);
// updateTextViewById(position, R.id.application_sent, tempView);
// updateTextViewById(position, R.id.application_status, tempView);
// return tempView;
// }
//
// private void updateTextViewById(int position, int id, View parentView) {
// TextView tViewToUpdate = (TextView) parentView.findViewById(id);
// tViewToUpdate.setText(contentMap.get(id).get(position));
// }
//
// }
//
// Path: app/src/main/java/com/dalthed/tucan/exceptions/LostSessionException.java
// public class LostSessionException extends Exception {
//
// public LostSessionException() {
// super();
// }
//
// public LostSessionException(String detailMessage, Throwable throwable) {
// super(detailMessage, throwable);
// }
//
// public LostSessionException(String detailMessage) {
// super(detailMessage);
// }
//
// public LostSessionException(Throwable throwable) {
// super(throwable);
// }
//
// }
//
// Path: app/src/main/java/com/dalthed/tucan/exceptions/TucanDownException.java
// public class TucanDownException extends Exception {
//
// /**
// *
// */
// private static final long serialVersionUID = 1L;
// public TucanDownException() {
// super();
// }
//
// public TucanDownException(String ErrorMessage) {
// super(ErrorMessage);
// }
//
// }
// Path: app/src/main/java/com/dalthed/tucan/scraper/UniApplicationScraper.java
import com.dalthed.tucan.exceptions.LostSessionException;
import com.dalthed.tucan.exceptions.TucanDownException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import org.jsoup.nodes.Element;
import org.jsoup.select.Elements;
import android.content.Context;
import android.widget.ListAdapter;
import com.dalthed.tucan.R;
import com.dalthed.tucan.Connection.AnswerObject;
import com.dalthed.tucan.adapters.UniApplicationAdapter;
/**
* This file is part of TuCan Mobile.
*
* TuCan Mobile is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* TuCan Mobile is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with TuCan Mobile. If not, see <http://www.gnu.org/licenses/>.
*/
package com.dalthed.tucan.scraper;
public class UniApplicationScraper extends BasicScraper {
private static final ArrayList<Integer> orderList = new ArrayList<Integer>() {
{
add(R.id.application_type);
add(R.id.application_field);
add(R.id.application_semester);
add(R.id.application_status);
add(R.id.application_begin);
add(R.id.application_sent);
}
};
public UniApplicationScraper(Context context, AnswerObject result) {
super(context, result);
}
@Override | public ListAdapter scrapeAdapter(int mode) throws LostSessionException, |
Tyde/TuCanMobile | app/src/main/java/com/dalthed/tucan/scraper/UniApplicationScraper.java | // Path: app/src/main/java/com/dalthed/tucan/Connection/AnswerObject.java
// public class AnswerObject {
// private String HTML_text;
// private String redirectURL;
// private String lastcalledURL;
// private CookieManager Cookies;
// /**
// * RückgabeObjekt der BrowseMethods
// * @param HTML HTML-Code
// * @param redirect Redirect-URL aus dem HTTP-Header
// * @param myCookies CookieManager mit relevanten Cookies
// * @param lastcalledURL Zuletzt aufgerufene URL
// */
// public AnswerObject(String HTML,String redirect,CookieManager myCookies,String lastcalledURL){
// this.HTML_text=HTML;
// this.redirectURL=redirect;
// this.Cookies=myCookies;
// this.lastcalledURL=lastcalledURL;
// }
// public String getHTML(){
// return this.HTML_text;
// }
// public String getRedirectURLString() {
// return this.redirectURL;
// }
// public String getLastCalledURL() {
// return this.lastcalledURL;
// }
// public CookieManager getCookieManager() {
// return this.Cookies;
// }
//
// }
//
// Path: app/src/main/java/com/dalthed/tucan/adapters/UniApplicationAdapter.java
// public class UniApplicationAdapter extends ArrayAdapter<String> {
//
// public final HashMap<Integer, ArrayList<String>> contentMap;
//
// public static HashMap<Integer, ArrayList<String>> getEmptyContentMap() {
// return new HashMap<Integer, ArrayList<String>>() {
// {
// put(R.id.application_type, new ArrayList<String>());
// put(R.id.application_field, new ArrayList<String>());
// put(R.id.application_semester, new ArrayList<String>());
// put(R.id.application_status, new ArrayList<String>());
// put(R.id.application_begin, new ArrayList<String>());
// put(R.id.application_sent, new ArrayList<String>());
// }
// };
// }
//
// public UniApplicationAdapter(Context context,
// HashMap<Integer, ArrayList<String>> contentMap) {
//
// super(context, R.layout.application_row, R.id.application_field,
// contentMap.get(R.id.application_field));
// this.contentMap = contentMap;
// }
//
// @Override
// public View getView(int position, View convertView, ViewGroup parent) {
//
// View tempView = super.getView(position, convertView, parent);
// updateTextViewById(position, R.id.application_begin, tempView);
// updateTextViewById(position, R.id.application_semester, tempView);
// updateTextViewById(position, R.id.application_type, tempView);
// updateTextViewById(position, R.id.application_sent, tempView);
// updateTextViewById(position, R.id.application_status, tempView);
// return tempView;
// }
//
// private void updateTextViewById(int position, int id, View parentView) {
// TextView tViewToUpdate = (TextView) parentView.findViewById(id);
// tViewToUpdate.setText(contentMap.get(id).get(position));
// }
//
// }
//
// Path: app/src/main/java/com/dalthed/tucan/exceptions/LostSessionException.java
// public class LostSessionException extends Exception {
//
// public LostSessionException() {
// super();
// }
//
// public LostSessionException(String detailMessage, Throwable throwable) {
// super(detailMessage, throwable);
// }
//
// public LostSessionException(String detailMessage) {
// super(detailMessage);
// }
//
// public LostSessionException(Throwable throwable) {
// super(throwable);
// }
//
// }
//
// Path: app/src/main/java/com/dalthed/tucan/exceptions/TucanDownException.java
// public class TucanDownException extends Exception {
//
// /**
// *
// */
// private static final long serialVersionUID = 1L;
// public TucanDownException() {
// super();
// }
//
// public TucanDownException(String ErrorMessage) {
// super(ErrorMessage);
// }
//
// }
| import com.dalthed.tucan.exceptions.LostSessionException;
import com.dalthed.tucan.exceptions.TucanDownException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import org.jsoup.nodes.Element;
import org.jsoup.select.Elements;
import android.content.Context;
import android.widget.ListAdapter;
import com.dalthed.tucan.R;
import com.dalthed.tucan.Connection.AnswerObject;
import com.dalthed.tucan.adapters.UniApplicationAdapter; | /**
* This file is part of TuCan Mobile.
*
* TuCan Mobile is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* TuCan Mobile is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with TuCan Mobile. If not, see <http://www.gnu.org/licenses/>.
*/
package com.dalthed.tucan.scraper;
public class UniApplicationScraper extends BasicScraper {
private static final ArrayList<Integer> orderList = new ArrayList<Integer>() {
{
add(R.id.application_type);
add(R.id.application_field);
add(R.id.application_semester);
add(R.id.application_status);
add(R.id.application_begin);
add(R.id.application_sent);
}
};
public UniApplicationScraper(Context context, AnswerObject result) {
super(context, result);
}
@Override
public ListAdapter scrapeAdapter(int mode) throws LostSessionException, | // Path: app/src/main/java/com/dalthed/tucan/Connection/AnswerObject.java
// public class AnswerObject {
// private String HTML_text;
// private String redirectURL;
// private String lastcalledURL;
// private CookieManager Cookies;
// /**
// * RückgabeObjekt der BrowseMethods
// * @param HTML HTML-Code
// * @param redirect Redirect-URL aus dem HTTP-Header
// * @param myCookies CookieManager mit relevanten Cookies
// * @param lastcalledURL Zuletzt aufgerufene URL
// */
// public AnswerObject(String HTML,String redirect,CookieManager myCookies,String lastcalledURL){
// this.HTML_text=HTML;
// this.redirectURL=redirect;
// this.Cookies=myCookies;
// this.lastcalledURL=lastcalledURL;
// }
// public String getHTML(){
// return this.HTML_text;
// }
// public String getRedirectURLString() {
// return this.redirectURL;
// }
// public String getLastCalledURL() {
// return this.lastcalledURL;
// }
// public CookieManager getCookieManager() {
// return this.Cookies;
// }
//
// }
//
// Path: app/src/main/java/com/dalthed/tucan/adapters/UniApplicationAdapter.java
// public class UniApplicationAdapter extends ArrayAdapter<String> {
//
// public final HashMap<Integer, ArrayList<String>> contentMap;
//
// public static HashMap<Integer, ArrayList<String>> getEmptyContentMap() {
// return new HashMap<Integer, ArrayList<String>>() {
// {
// put(R.id.application_type, new ArrayList<String>());
// put(R.id.application_field, new ArrayList<String>());
// put(R.id.application_semester, new ArrayList<String>());
// put(R.id.application_status, new ArrayList<String>());
// put(R.id.application_begin, new ArrayList<String>());
// put(R.id.application_sent, new ArrayList<String>());
// }
// };
// }
//
// public UniApplicationAdapter(Context context,
// HashMap<Integer, ArrayList<String>> contentMap) {
//
// super(context, R.layout.application_row, R.id.application_field,
// contentMap.get(R.id.application_field));
// this.contentMap = contentMap;
// }
//
// @Override
// public View getView(int position, View convertView, ViewGroup parent) {
//
// View tempView = super.getView(position, convertView, parent);
// updateTextViewById(position, R.id.application_begin, tempView);
// updateTextViewById(position, R.id.application_semester, tempView);
// updateTextViewById(position, R.id.application_type, tempView);
// updateTextViewById(position, R.id.application_sent, tempView);
// updateTextViewById(position, R.id.application_status, tempView);
// return tempView;
// }
//
// private void updateTextViewById(int position, int id, View parentView) {
// TextView tViewToUpdate = (TextView) parentView.findViewById(id);
// tViewToUpdate.setText(contentMap.get(id).get(position));
// }
//
// }
//
// Path: app/src/main/java/com/dalthed/tucan/exceptions/LostSessionException.java
// public class LostSessionException extends Exception {
//
// public LostSessionException() {
// super();
// }
//
// public LostSessionException(String detailMessage, Throwable throwable) {
// super(detailMessage, throwable);
// }
//
// public LostSessionException(String detailMessage) {
// super(detailMessage);
// }
//
// public LostSessionException(Throwable throwable) {
// super(throwable);
// }
//
// }
//
// Path: app/src/main/java/com/dalthed/tucan/exceptions/TucanDownException.java
// public class TucanDownException extends Exception {
//
// /**
// *
// */
// private static final long serialVersionUID = 1L;
// public TucanDownException() {
// super();
// }
//
// public TucanDownException(String ErrorMessage) {
// super(ErrorMessage);
// }
//
// }
// Path: app/src/main/java/com/dalthed/tucan/scraper/UniApplicationScraper.java
import com.dalthed.tucan.exceptions.LostSessionException;
import com.dalthed.tucan.exceptions.TucanDownException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import org.jsoup.nodes.Element;
import org.jsoup.select.Elements;
import android.content.Context;
import android.widget.ListAdapter;
import com.dalthed.tucan.R;
import com.dalthed.tucan.Connection.AnswerObject;
import com.dalthed.tucan.adapters.UniApplicationAdapter;
/**
* This file is part of TuCan Mobile.
*
* TuCan Mobile is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* TuCan Mobile is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with TuCan Mobile. If not, see <http://www.gnu.org/licenses/>.
*/
package com.dalthed.tucan.scraper;
public class UniApplicationScraper extends BasicScraper {
private static final ArrayList<Integer> orderList = new ArrayList<Integer>() {
{
add(R.id.application_type);
add(R.id.application_field);
add(R.id.application_semester);
add(R.id.application_status);
add(R.id.application_begin);
add(R.id.application_sent);
}
};
public UniApplicationScraper(Context context, AnswerObject result) {
super(context, result);
}
@Override
public ListAdapter scrapeAdapter(int mode) throws LostSessionException, | TucanDownException { |
Tyde/TuCanMobile | app/src/main/java/com/dalthed/tucan/scraper/SingleMessageScraper.java | // Path: app/src/main/java/com/dalthed/tucan/Connection/AnswerObject.java
// public class AnswerObject {
// private String HTML_text;
// private String redirectURL;
// private String lastcalledURL;
// private CookieManager Cookies;
// /**
// * RückgabeObjekt der BrowseMethods
// * @param HTML HTML-Code
// * @param redirect Redirect-URL aus dem HTTP-Header
// * @param myCookies CookieManager mit relevanten Cookies
// * @param lastcalledURL Zuletzt aufgerufene URL
// */
// public AnswerObject(String HTML,String redirect,CookieManager myCookies,String lastcalledURL){
// this.HTML_text=HTML;
// this.redirectURL=redirect;
// this.Cookies=myCookies;
// this.lastcalledURL=lastcalledURL;
// }
// public String getHTML(){
// return this.HTML_text;
// }
// public String getRedirectURLString() {
// return this.redirectURL;
// }
// public String getLastCalledURL() {
// return this.lastcalledURL;
// }
// public CookieManager getCookieManager() {
// return this.Cookies;
// }
//
// }
//
// Path: app/src/main/java/com/dalthed/tucan/exceptions/LostSessionException.java
// public class LostSessionException extends Exception {
//
// public LostSessionException() {
// super();
// }
//
// public LostSessionException(String detailMessage, Throwable throwable) {
// super(detailMessage, throwable);
// }
//
// public LostSessionException(String detailMessage) {
// super(detailMessage);
// }
//
// public LostSessionException(Throwable throwable) {
// super(throwable);
// }
//
// }
//
// Path: app/src/main/java/com/dalthed/tucan/exceptions/TucanDownException.java
// public class TucanDownException extends Exception {
//
// /**
// *
// */
// private static final long serialVersionUID = 1L;
// public TucanDownException() {
// super();
// }
//
// public TucanDownException(String ErrorMessage) {
// super(ErrorMessage);
// }
//
// }
| import com.dalthed.tucan.exceptions.TucanDownException;
import java.util.ArrayList;
import org.jsoup.select.Elements;
import android.content.Context;
import android.text.Html;
import android.text.Spanned;
import android.widget.ArrayAdapter;
import android.widget.ListAdapter;
import com.dalthed.tucan.R;
import com.dalthed.tucan.Connection.AnswerObject;
import com.dalthed.tucan.exceptions.LostSessionException; | /**
* This file is part of TuCan Mobile.
*
* TuCan Mobile is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* TuCan Mobile is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with TuCan Mobile. If not, see <http://www.gnu.org/licenses/>.
*/
package com.dalthed.tucan.scraper;
public class SingleMessageScraper extends BasicScraper {
public SingleMessageScraper(Context context, AnswerObject result) {
super(context, result);
}
@Override | // Path: app/src/main/java/com/dalthed/tucan/Connection/AnswerObject.java
// public class AnswerObject {
// private String HTML_text;
// private String redirectURL;
// private String lastcalledURL;
// private CookieManager Cookies;
// /**
// * RückgabeObjekt der BrowseMethods
// * @param HTML HTML-Code
// * @param redirect Redirect-URL aus dem HTTP-Header
// * @param myCookies CookieManager mit relevanten Cookies
// * @param lastcalledURL Zuletzt aufgerufene URL
// */
// public AnswerObject(String HTML,String redirect,CookieManager myCookies,String lastcalledURL){
// this.HTML_text=HTML;
// this.redirectURL=redirect;
// this.Cookies=myCookies;
// this.lastcalledURL=lastcalledURL;
// }
// public String getHTML(){
// return this.HTML_text;
// }
// public String getRedirectURLString() {
// return this.redirectURL;
// }
// public String getLastCalledURL() {
// return this.lastcalledURL;
// }
// public CookieManager getCookieManager() {
// return this.Cookies;
// }
//
// }
//
// Path: app/src/main/java/com/dalthed/tucan/exceptions/LostSessionException.java
// public class LostSessionException extends Exception {
//
// public LostSessionException() {
// super();
// }
//
// public LostSessionException(String detailMessage, Throwable throwable) {
// super(detailMessage, throwable);
// }
//
// public LostSessionException(String detailMessage) {
// super(detailMessage);
// }
//
// public LostSessionException(Throwable throwable) {
// super(throwable);
// }
//
// }
//
// Path: app/src/main/java/com/dalthed/tucan/exceptions/TucanDownException.java
// public class TucanDownException extends Exception {
//
// /**
// *
// */
// private static final long serialVersionUID = 1L;
// public TucanDownException() {
// super();
// }
//
// public TucanDownException(String ErrorMessage) {
// super(ErrorMessage);
// }
//
// }
// Path: app/src/main/java/com/dalthed/tucan/scraper/SingleMessageScraper.java
import com.dalthed.tucan.exceptions.TucanDownException;
import java.util.ArrayList;
import org.jsoup.select.Elements;
import android.content.Context;
import android.text.Html;
import android.text.Spanned;
import android.widget.ArrayAdapter;
import android.widget.ListAdapter;
import com.dalthed.tucan.R;
import com.dalthed.tucan.Connection.AnswerObject;
import com.dalthed.tucan.exceptions.LostSessionException;
/**
* This file is part of TuCan Mobile.
*
* TuCan Mobile is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* TuCan Mobile is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with TuCan Mobile. If not, see <http://www.gnu.org/licenses/>.
*/
package com.dalthed.tucan.scraper;
public class SingleMessageScraper extends BasicScraper {
public SingleMessageScraper(Context context, AnswerObject result) {
super(context, result);
}
@Override | public ListAdapter scrapeAdapter(int mode) throws LostSessionException, TucanDownException { |
Tyde/TuCanMobile | app/src/main/java/com/dalthed/tucan/scraper/SingleMessageScraper.java | // Path: app/src/main/java/com/dalthed/tucan/Connection/AnswerObject.java
// public class AnswerObject {
// private String HTML_text;
// private String redirectURL;
// private String lastcalledURL;
// private CookieManager Cookies;
// /**
// * RückgabeObjekt der BrowseMethods
// * @param HTML HTML-Code
// * @param redirect Redirect-URL aus dem HTTP-Header
// * @param myCookies CookieManager mit relevanten Cookies
// * @param lastcalledURL Zuletzt aufgerufene URL
// */
// public AnswerObject(String HTML,String redirect,CookieManager myCookies,String lastcalledURL){
// this.HTML_text=HTML;
// this.redirectURL=redirect;
// this.Cookies=myCookies;
// this.lastcalledURL=lastcalledURL;
// }
// public String getHTML(){
// return this.HTML_text;
// }
// public String getRedirectURLString() {
// return this.redirectURL;
// }
// public String getLastCalledURL() {
// return this.lastcalledURL;
// }
// public CookieManager getCookieManager() {
// return this.Cookies;
// }
//
// }
//
// Path: app/src/main/java/com/dalthed/tucan/exceptions/LostSessionException.java
// public class LostSessionException extends Exception {
//
// public LostSessionException() {
// super();
// }
//
// public LostSessionException(String detailMessage, Throwable throwable) {
// super(detailMessage, throwable);
// }
//
// public LostSessionException(String detailMessage) {
// super(detailMessage);
// }
//
// public LostSessionException(Throwable throwable) {
// super(throwable);
// }
//
// }
//
// Path: app/src/main/java/com/dalthed/tucan/exceptions/TucanDownException.java
// public class TucanDownException extends Exception {
//
// /**
// *
// */
// private static final long serialVersionUID = 1L;
// public TucanDownException() {
// super();
// }
//
// public TucanDownException(String ErrorMessage) {
// super(ErrorMessage);
// }
//
// }
| import com.dalthed.tucan.exceptions.TucanDownException;
import java.util.ArrayList;
import org.jsoup.select.Elements;
import android.content.Context;
import android.text.Html;
import android.text.Spanned;
import android.widget.ArrayAdapter;
import android.widget.ListAdapter;
import com.dalthed.tucan.R;
import com.dalthed.tucan.Connection.AnswerObject;
import com.dalthed.tucan.exceptions.LostSessionException; | /**
* This file is part of TuCan Mobile.
*
* TuCan Mobile is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* TuCan Mobile is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with TuCan Mobile. If not, see <http://www.gnu.org/licenses/>.
*/
package com.dalthed.tucan.scraper;
public class SingleMessageScraper extends BasicScraper {
public SingleMessageScraper(Context context, AnswerObject result) {
super(context, result);
}
@Override | // Path: app/src/main/java/com/dalthed/tucan/Connection/AnswerObject.java
// public class AnswerObject {
// private String HTML_text;
// private String redirectURL;
// private String lastcalledURL;
// private CookieManager Cookies;
// /**
// * RückgabeObjekt der BrowseMethods
// * @param HTML HTML-Code
// * @param redirect Redirect-URL aus dem HTTP-Header
// * @param myCookies CookieManager mit relevanten Cookies
// * @param lastcalledURL Zuletzt aufgerufene URL
// */
// public AnswerObject(String HTML,String redirect,CookieManager myCookies,String lastcalledURL){
// this.HTML_text=HTML;
// this.redirectURL=redirect;
// this.Cookies=myCookies;
// this.lastcalledURL=lastcalledURL;
// }
// public String getHTML(){
// return this.HTML_text;
// }
// public String getRedirectURLString() {
// return this.redirectURL;
// }
// public String getLastCalledURL() {
// return this.lastcalledURL;
// }
// public CookieManager getCookieManager() {
// return this.Cookies;
// }
//
// }
//
// Path: app/src/main/java/com/dalthed/tucan/exceptions/LostSessionException.java
// public class LostSessionException extends Exception {
//
// public LostSessionException() {
// super();
// }
//
// public LostSessionException(String detailMessage, Throwable throwable) {
// super(detailMessage, throwable);
// }
//
// public LostSessionException(String detailMessage) {
// super(detailMessage);
// }
//
// public LostSessionException(Throwable throwable) {
// super(throwable);
// }
//
// }
//
// Path: app/src/main/java/com/dalthed/tucan/exceptions/TucanDownException.java
// public class TucanDownException extends Exception {
//
// /**
// *
// */
// private static final long serialVersionUID = 1L;
// public TucanDownException() {
// super();
// }
//
// public TucanDownException(String ErrorMessage) {
// super(ErrorMessage);
// }
//
// }
// Path: app/src/main/java/com/dalthed/tucan/scraper/SingleMessageScraper.java
import com.dalthed.tucan.exceptions.TucanDownException;
import java.util.ArrayList;
import org.jsoup.select.Elements;
import android.content.Context;
import android.text.Html;
import android.text.Spanned;
import android.widget.ArrayAdapter;
import android.widget.ListAdapter;
import com.dalthed.tucan.R;
import com.dalthed.tucan.Connection.AnswerObject;
import com.dalthed.tucan.exceptions.LostSessionException;
/**
* This file is part of TuCan Mobile.
*
* TuCan Mobile is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* TuCan Mobile is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with TuCan Mobile. If not, see <http://www.gnu.org/licenses/>.
*/
package com.dalthed.tucan.scraper;
public class SingleMessageScraper extends BasicScraper {
public SingleMessageScraper(Context context, AnswerObject result) {
super(context, result);
}
@Override | public ListAdapter scrapeAdapter(int mode) throws LostSessionException, TucanDownException { |
Tyde/TuCanMobile | app/src/main/java/com/dalthed/tucan/scraper/ModuleScraper.java | // Path: app/src/main/java/com/dalthed/tucan/Connection/AnswerObject.java
// public class AnswerObject {
// private String HTML_text;
// private String redirectURL;
// private String lastcalledURL;
// private CookieManager Cookies;
// /**
// * RückgabeObjekt der BrowseMethods
// * @param HTML HTML-Code
// * @param redirect Redirect-URL aus dem HTTP-Header
// * @param myCookies CookieManager mit relevanten Cookies
// * @param lastcalledURL Zuletzt aufgerufene URL
// */
// public AnswerObject(String HTML,String redirect,CookieManager myCookies,String lastcalledURL){
// this.HTML_text=HTML;
// this.redirectURL=redirect;
// this.Cookies=myCookies;
// this.lastcalledURL=lastcalledURL;
// }
// public String getHTML(){
// return this.HTML_text;
// }
// public String getRedirectURLString() {
// return this.redirectURL;
// }
// public String getLastCalledURL() {
// return this.lastcalledURL;
// }
// public CookieManager getCookieManager() {
// return this.Cookies;
// }
//
// }
//
// Path: app/src/main/java/com/dalthed/tucan/exceptions/LostSessionException.java
// public class LostSessionException extends Exception {
//
// public LostSessionException() {
// super();
// }
//
// public LostSessionException(String detailMessage, Throwable throwable) {
// super(detailMessage, throwable);
// }
//
// public LostSessionException(String detailMessage) {
// super(detailMessage);
// }
//
// public LostSessionException(Throwable throwable) {
// super(throwable);
// }
//
// }
//
// Path: app/src/main/java/com/dalthed/tucan/exceptions/TucanDownException.java
// public class TucanDownException extends Exception {
//
// /**
// *
// */
// private static final long serialVersionUID = 1L;
// public TucanDownException() {
// super();
// }
//
// public TucanDownException(String ErrorMessage) {
// super(ErrorMessage);
// }
//
// }
| import java.util.ArrayList;
import org.jsoup.select.Elements;
import android.content.Context;
import android.widget.ArrayAdapter;
import android.widget.ListAdapter;
import com.dalthed.tucan.Connection.AnswerObject;
import com.dalthed.tucan.exceptions.LostSessionException;
import com.dalthed.tucan.exceptions.TucanDownException; | /**
* This file is part of TuCan Mobile.
*
* TuCan Mobile is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* TuCan Mobile is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with TuCan Mobile. If not, see <http://www.gnu.org/licenses/>.
*/
package com.dalthed.tucan.scraper;
public class ModuleScraper extends BasicScraper {
public ArrayList<String> eventLinks;
public String title;
| // Path: app/src/main/java/com/dalthed/tucan/Connection/AnswerObject.java
// public class AnswerObject {
// private String HTML_text;
// private String redirectURL;
// private String lastcalledURL;
// private CookieManager Cookies;
// /**
// * RückgabeObjekt der BrowseMethods
// * @param HTML HTML-Code
// * @param redirect Redirect-URL aus dem HTTP-Header
// * @param myCookies CookieManager mit relevanten Cookies
// * @param lastcalledURL Zuletzt aufgerufene URL
// */
// public AnswerObject(String HTML,String redirect,CookieManager myCookies,String lastcalledURL){
// this.HTML_text=HTML;
// this.redirectURL=redirect;
// this.Cookies=myCookies;
// this.lastcalledURL=lastcalledURL;
// }
// public String getHTML(){
// return this.HTML_text;
// }
// public String getRedirectURLString() {
// return this.redirectURL;
// }
// public String getLastCalledURL() {
// return this.lastcalledURL;
// }
// public CookieManager getCookieManager() {
// return this.Cookies;
// }
//
// }
//
// Path: app/src/main/java/com/dalthed/tucan/exceptions/LostSessionException.java
// public class LostSessionException extends Exception {
//
// public LostSessionException() {
// super();
// }
//
// public LostSessionException(String detailMessage, Throwable throwable) {
// super(detailMessage, throwable);
// }
//
// public LostSessionException(String detailMessage) {
// super(detailMessage);
// }
//
// public LostSessionException(Throwable throwable) {
// super(throwable);
// }
//
// }
//
// Path: app/src/main/java/com/dalthed/tucan/exceptions/TucanDownException.java
// public class TucanDownException extends Exception {
//
// /**
// *
// */
// private static final long serialVersionUID = 1L;
// public TucanDownException() {
// super();
// }
//
// public TucanDownException(String ErrorMessage) {
// super(ErrorMessage);
// }
//
// }
// Path: app/src/main/java/com/dalthed/tucan/scraper/ModuleScraper.java
import java.util.ArrayList;
import org.jsoup.select.Elements;
import android.content.Context;
import android.widget.ArrayAdapter;
import android.widget.ListAdapter;
import com.dalthed.tucan.Connection.AnswerObject;
import com.dalthed.tucan.exceptions.LostSessionException;
import com.dalthed.tucan.exceptions.TucanDownException;
/**
* This file is part of TuCan Mobile.
*
* TuCan Mobile is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* TuCan Mobile is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with TuCan Mobile. If not, see <http://www.gnu.org/licenses/>.
*/
package com.dalthed.tucan.scraper;
public class ModuleScraper extends BasicScraper {
public ArrayList<String> eventLinks;
public String title;
| public ModuleScraper(Context context, AnswerObject result) { |
Tyde/TuCanMobile | app/src/main/java/com/dalthed/tucan/scraper/ModuleScraper.java | // Path: app/src/main/java/com/dalthed/tucan/Connection/AnswerObject.java
// public class AnswerObject {
// private String HTML_text;
// private String redirectURL;
// private String lastcalledURL;
// private CookieManager Cookies;
// /**
// * RückgabeObjekt der BrowseMethods
// * @param HTML HTML-Code
// * @param redirect Redirect-URL aus dem HTTP-Header
// * @param myCookies CookieManager mit relevanten Cookies
// * @param lastcalledURL Zuletzt aufgerufene URL
// */
// public AnswerObject(String HTML,String redirect,CookieManager myCookies,String lastcalledURL){
// this.HTML_text=HTML;
// this.redirectURL=redirect;
// this.Cookies=myCookies;
// this.lastcalledURL=lastcalledURL;
// }
// public String getHTML(){
// return this.HTML_text;
// }
// public String getRedirectURLString() {
// return this.redirectURL;
// }
// public String getLastCalledURL() {
// return this.lastcalledURL;
// }
// public CookieManager getCookieManager() {
// return this.Cookies;
// }
//
// }
//
// Path: app/src/main/java/com/dalthed/tucan/exceptions/LostSessionException.java
// public class LostSessionException extends Exception {
//
// public LostSessionException() {
// super();
// }
//
// public LostSessionException(String detailMessage, Throwable throwable) {
// super(detailMessage, throwable);
// }
//
// public LostSessionException(String detailMessage) {
// super(detailMessage);
// }
//
// public LostSessionException(Throwable throwable) {
// super(throwable);
// }
//
// }
//
// Path: app/src/main/java/com/dalthed/tucan/exceptions/TucanDownException.java
// public class TucanDownException extends Exception {
//
// /**
// *
// */
// private static final long serialVersionUID = 1L;
// public TucanDownException() {
// super();
// }
//
// public TucanDownException(String ErrorMessage) {
// super(ErrorMessage);
// }
//
// }
| import java.util.ArrayList;
import org.jsoup.select.Elements;
import android.content.Context;
import android.widget.ArrayAdapter;
import android.widget.ListAdapter;
import com.dalthed.tucan.Connection.AnswerObject;
import com.dalthed.tucan.exceptions.LostSessionException;
import com.dalthed.tucan.exceptions.TucanDownException; | /**
* This file is part of TuCan Mobile.
*
* TuCan Mobile is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* TuCan Mobile is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with TuCan Mobile. If not, see <http://www.gnu.org/licenses/>.
*/
package com.dalthed.tucan.scraper;
public class ModuleScraper extends BasicScraper {
public ArrayList<String> eventLinks;
public String title;
public ModuleScraper(Context context, AnswerObject result) {
super(context, result);
}
@Override | // Path: app/src/main/java/com/dalthed/tucan/Connection/AnswerObject.java
// public class AnswerObject {
// private String HTML_text;
// private String redirectURL;
// private String lastcalledURL;
// private CookieManager Cookies;
// /**
// * RückgabeObjekt der BrowseMethods
// * @param HTML HTML-Code
// * @param redirect Redirect-URL aus dem HTTP-Header
// * @param myCookies CookieManager mit relevanten Cookies
// * @param lastcalledURL Zuletzt aufgerufene URL
// */
// public AnswerObject(String HTML,String redirect,CookieManager myCookies,String lastcalledURL){
// this.HTML_text=HTML;
// this.redirectURL=redirect;
// this.Cookies=myCookies;
// this.lastcalledURL=lastcalledURL;
// }
// public String getHTML(){
// return this.HTML_text;
// }
// public String getRedirectURLString() {
// return this.redirectURL;
// }
// public String getLastCalledURL() {
// return this.lastcalledURL;
// }
// public CookieManager getCookieManager() {
// return this.Cookies;
// }
//
// }
//
// Path: app/src/main/java/com/dalthed/tucan/exceptions/LostSessionException.java
// public class LostSessionException extends Exception {
//
// public LostSessionException() {
// super();
// }
//
// public LostSessionException(String detailMessage, Throwable throwable) {
// super(detailMessage, throwable);
// }
//
// public LostSessionException(String detailMessage) {
// super(detailMessage);
// }
//
// public LostSessionException(Throwable throwable) {
// super(throwable);
// }
//
// }
//
// Path: app/src/main/java/com/dalthed/tucan/exceptions/TucanDownException.java
// public class TucanDownException extends Exception {
//
// /**
// *
// */
// private static final long serialVersionUID = 1L;
// public TucanDownException() {
// super();
// }
//
// public TucanDownException(String ErrorMessage) {
// super(ErrorMessage);
// }
//
// }
// Path: app/src/main/java/com/dalthed/tucan/scraper/ModuleScraper.java
import java.util.ArrayList;
import org.jsoup.select.Elements;
import android.content.Context;
import android.widget.ArrayAdapter;
import android.widget.ListAdapter;
import com.dalthed.tucan.Connection.AnswerObject;
import com.dalthed.tucan.exceptions.LostSessionException;
import com.dalthed.tucan.exceptions.TucanDownException;
/**
* This file is part of TuCan Mobile.
*
* TuCan Mobile is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* TuCan Mobile is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with TuCan Mobile. If not, see <http://www.gnu.org/licenses/>.
*/
package com.dalthed.tucan.scraper;
public class ModuleScraper extends BasicScraper {
public ArrayList<String> eventLinks;
public String title;
public ModuleScraper(Context context, AnswerObject result) {
super(context, result);
}
@Override | public ListAdapter scrapeAdapter(int mode) throws LostSessionException, TucanDownException { |
Tyde/TuCanMobile | app/src/main/java/com/dalthed/tucan/scraper/ModuleScraper.java | // Path: app/src/main/java/com/dalthed/tucan/Connection/AnswerObject.java
// public class AnswerObject {
// private String HTML_text;
// private String redirectURL;
// private String lastcalledURL;
// private CookieManager Cookies;
// /**
// * RückgabeObjekt der BrowseMethods
// * @param HTML HTML-Code
// * @param redirect Redirect-URL aus dem HTTP-Header
// * @param myCookies CookieManager mit relevanten Cookies
// * @param lastcalledURL Zuletzt aufgerufene URL
// */
// public AnswerObject(String HTML,String redirect,CookieManager myCookies,String lastcalledURL){
// this.HTML_text=HTML;
// this.redirectURL=redirect;
// this.Cookies=myCookies;
// this.lastcalledURL=lastcalledURL;
// }
// public String getHTML(){
// return this.HTML_text;
// }
// public String getRedirectURLString() {
// return this.redirectURL;
// }
// public String getLastCalledURL() {
// return this.lastcalledURL;
// }
// public CookieManager getCookieManager() {
// return this.Cookies;
// }
//
// }
//
// Path: app/src/main/java/com/dalthed/tucan/exceptions/LostSessionException.java
// public class LostSessionException extends Exception {
//
// public LostSessionException() {
// super();
// }
//
// public LostSessionException(String detailMessage, Throwable throwable) {
// super(detailMessage, throwable);
// }
//
// public LostSessionException(String detailMessage) {
// super(detailMessage);
// }
//
// public LostSessionException(Throwable throwable) {
// super(throwable);
// }
//
// }
//
// Path: app/src/main/java/com/dalthed/tucan/exceptions/TucanDownException.java
// public class TucanDownException extends Exception {
//
// /**
// *
// */
// private static final long serialVersionUID = 1L;
// public TucanDownException() {
// super();
// }
//
// public TucanDownException(String ErrorMessage) {
// super(ErrorMessage);
// }
//
// }
| import java.util.ArrayList;
import org.jsoup.select.Elements;
import android.content.Context;
import android.widget.ArrayAdapter;
import android.widget.ListAdapter;
import com.dalthed.tucan.Connection.AnswerObject;
import com.dalthed.tucan.exceptions.LostSessionException;
import com.dalthed.tucan.exceptions.TucanDownException; | /**
* This file is part of TuCan Mobile.
*
* TuCan Mobile is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* TuCan Mobile is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with TuCan Mobile. If not, see <http://www.gnu.org/licenses/>.
*/
package com.dalthed.tucan.scraper;
public class ModuleScraper extends BasicScraper {
public ArrayList<String> eventLinks;
public String title;
public ModuleScraper(Context context, AnswerObject result) {
super(context, result);
}
@Override | // Path: app/src/main/java/com/dalthed/tucan/Connection/AnswerObject.java
// public class AnswerObject {
// private String HTML_text;
// private String redirectURL;
// private String lastcalledURL;
// private CookieManager Cookies;
// /**
// * RückgabeObjekt der BrowseMethods
// * @param HTML HTML-Code
// * @param redirect Redirect-URL aus dem HTTP-Header
// * @param myCookies CookieManager mit relevanten Cookies
// * @param lastcalledURL Zuletzt aufgerufene URL
// */
// public AnswerObject(String HTML,String redirect,CookieManager myCookies,String lastcalledURL){
// this.HTML_text=HTML;
// this.redirectURL=redirect;
// this.Cookies=myCookies;
// this.lastcalledURL=lastcalledURL;
// }
// public String getHTML(){
// return this.HTML_text;
// }
// public String getRedirectURLString() {
// return this.redirectURL;
// }
// public String getLastCalledURL() {
// return this.lastcalledURL;
// }
// public CookieManager getCookieManager() {
// return this.Cookies;
// }
//
// }
//
// Path: app/src/main/java/com/dalthed/tucan/exceptions/LostSessionException.java
// public class LostSessionException extends Exception {
//
// public LostSessionException() {
// super();
// }
//
// public LostSessionException(String detailMessage, Throwable throwable) {
// super(detailMessage, throwable);
// }
//
// public LostSessionException(String detailMessage) {
// super(detailMessage);
// }
//
// public LostSessionException(Throwable throwable) {
// super(throwable);
// }
//
// }
//
// Path: app/src/main/java/com/dalthed/tucan/exceptions/TucanDownException.java
// public class TucanDownException extends Exception {
//
// /**
// *
// */
// private static final long serialVersionUID = 1L;
// public TucanDownException() {
// super();
// }
//
// public TucanDownException(String ErrorMessage) {
// super(ErrorMessage);
// }
//
// }
// Path: app/src/main/java/com/dalthed/tucan/scraper/ModuleScraper.java
import java.util.ArrayList;
import org.jsoup.select.Elements;
import android.content.Context;
import android.widget.ArrayAdapter;
import android.widget.ListAdapter;
import com.dalthed.tucan.Connection.AnswerObject;
import com.dalthed.tucan.exceptions.LostSessionException;
import com.dalthed.tucan.exceptions.TucanDownException;
/**
* This file is part of TuCan Mobile.
*
* TuCan Mobile is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* TuCan Mobile is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with TuCan Mobile. If not, see <http://www.gnu.org/licenses/>.
*/
package com.dalthed.tucan.scraper;
public class ModuleScraper extends BasicScraper {
public ArrayList<String> eventLinks;
public String title;
public ModuleScraper(Context context, AnswerObject result) {
super(context, result);
}
@Override | public ListAdapter scrapeAdapter(int mode) throws LostSessionException, TucanDownException { |
siemens/omniproperties | src/main/java/com/siemens/oss/omniproperties/MapOmniProperties.java | // Path: src/main/java/com/siemens/oss/omniproperties/exceptions/PropertyNotFoundException.java
// public class PropertyNotFoundException extends RuntimeException {
//
// private static final long serialVersionUID = 1L;
//
// public PropertyNotFoundException(String arg0) {
// super(arg0);
// }
//
// public PropertyNotFoundException(Throwable arg0) {
// super(arg0);
// }
//
// public PropertyNotFoundException(String arg0, Throwable arg1) {
// super(arg0, arg1);
// }
//
//
// }
//
// Path: src/main/java/com/siemens/oss/omniproperties/exceptions/WrongClassException.java
// public class WrongClassException extends RuntimeException {
//
// private static final long serialVersionUID = 1L;
//
// public WrongClassException(String arg0) {
// super(arg0);
// }
//
// public WrongClassException(Throwable arg0) {
// super(arg0);
// }
//
// public WrongClassException(String arg0, Throwable arg1) {
// super(arg0, arg1);
// }
//
// }
| import java.util.ArrayList;
import java.util.Collection;
import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Set;
import com.siemens.oss.omniproperties.exceptions.PropertyNotFoundException;
import com.siemens.oss.omniproperties.exceptions.WrongClassException; | public String getString(final String key, final String def) {
return getObject(key, def, String.class);
}
/* (non-Javadoc)
* @see com.siemens.oss.omniproperties.OmniProperties#getBoolean(java.lang.String)
*/
@Override
public boolean getBoolean(String key) {
return getObject(key, Boolean.class).booleanValue();
}
/* (non-Javadoc)
* @see com.siemens.oss.omniproperties.OmniProperties#getBoolean(java.lang.String, java.lang.String)
*/
@Override
public boolean getBoolean(String key, boolean def) {
return getObject(key, Boolean.valueOf(def), Boolean.class).booleanValue();
}
/* (non-Javadoc)
* @see com.siemens.oss.omniproperties.IOmniProperties#getObject(java.lang.String, java.lang.Class)
*/
@Override
public <T> T getObject(final String key, final Class<T> type) {
final T result = getObject(key, null, type);
if (result == null) { | // Path: src/main/java/com/siemens/oss/omniproperties/exceptions/PropertyNotFoundException.java
// public class PropertyNotFoundException extends RuntimeException {
//
// private static final long serialVersionUID = 1L;
//
// public PropertyNotFoundException(String arg0) {
// super(arg0);
// }
//
// public PropertyNotFoundException(Throwable arg0) {
// super(arg0);
// }
//
// public PropertyNotFoundException(String arg0, Throwable arg1) {
// super(arg0, arg1);
// }
//
//
// }
//
// Path: src/main/java/com/siemens/oss/omniproperties/exceptions/WrongClassException.java
// public class WrongClassException extends RuntimeException {
//
// private static final long serialVersionUID = 1L;
//
// public WrongClassException(String arg0) {
// super(arg0);
// }
//
// public WrongClassException(Throwable arg0) {
// super(arg0);
// }
//
// public WrongClassException(String arg0, Throwable arg1) {
// super(arg0, arg1);
// }
//
// }
// Path: src/main/java/com/siemens/oss/omniproperties/MapOmniProperties.java
import java.util.ArrayList;
import java.util.Collection;
import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Set;
import com.siemens.oss.omniproperties.exceptions.PropertyNotFoundException;
import com.siemens.oss.omniproperties.exceptions.WrongClassException;
public String getString(final String key, final String def) {
return getObject(key, def, String.class);
}
/* (non-Javadoc)
* @see com.siemens.oss.omniproperties.OmniProperties#getBoolean(java.lang.String)
*/
@Override
public boolean getBoolean(String key) {
return getObject(key, Boolean.class).booleanValue();
}
/* (non-Javadoc)
* @see com.siemens.oss.omniproperties.OmniProperties#getBoolean(java.lang.String, java.lang.String)
*/
@Override
public boolean getBoolean(String key, boolean def) {
return getObject(key, Boolean.valueOf(def), Boolean.class).booleanValue();
}
/* (non-Javadoc)
* @see com.siemens.oss.omniproperties.IOmniProperties#getObject(java.lang.String, java.lang.Class)
*/
@Override
public <T> T getObject(final String key, final Class<T> type) {
final T result = getObject(key, null, type);
if (result == null) { | throw new PropertyNotFoundException("No property '" + key |
siemens/omniproperties | src/main/java/com/siemens/oss/omniproperties/MapOmniProperties.java | // Path: src/main/java/com/siemens/oss/omniproperties/exceptions/PropertyNotFoundException.java
// public class PropertyNotFoundException extends RuntimeException {
//
// private static final long serialVersionUID = 1L;
//
// public PropertyNotFoundException(String arg0) {
// super(arg0);
// }
//
// public PropertyNotFoundException(Throwable arg0) {
// super(arg0);
// }
//
// public PropertyNotFoundException(String arg0, Throwable arg1) {
// super(arg0, arg1);
// }
//
//
// }
//
// Path: src/main/java/com/siemens/oss/omniproperties/exceptions/WrongClassException.java
// public class WrongClassException extends RuntimeException {
//
// private static final long serialVersionUID = 1L;
//
// public WrongClassException(String arg0) {
// super(arg0);
// }
//
// public WrongClassException(Throwable arg0) {
// super(arg0);
// }
//
// public WrongClassException(String arg0, Throwable arg1) {
// super(arg0, arg1);
// }
//
// }
| import java.util.ArrayList;
import java.util.Collection;
import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Set;
import com.siemens.oss.omniproperties.exceptions.PropertyNotFoundException;
import com.siemens.oss.omniproperties.exceptions.WrongClassException; | return getObject(key, Boolean.valueOf(def), Boolean.class).booleanValue();
}
/* (non-Javadoc)
* @see com.siemens.oss.omniproperties.IOmniProperties#getObject(java.lang.String, java.lang.Class)
*/
@Override
public <T> T getObject(final String key, final Class<T> type) {
final T result = getObject(key, null, type);
if (result == null) {
throw new PropertyNotFoundException("No property '" + key
+ "' of type " + type.getSimpleName() + " found");
}
return result;
}
/* (non-Javadoc)
* @see com.siemens.oss.omniproperties.IOmniProperties#getObject(java.lang.String, T, java.lang.Class)
*/
@Override
public <T> T getObject(final String key, final T def, final Class<T> type) {
final Object value = map.get(key);
if (value == null) {
return def;
} else if (type.isAssignableFrom(value.getClass())) {
return type.cast(value);
} else { | // Path: src/main/java/com/siemens/oss/omniproperties/exceptions/PropertyNotFoundException.java
// public class PropertyNotFoundException extends RuntimeException {
//
// private static final long serialVersionUID = 1L;
//
// public PropertyNotFoundException(String arg0) {
// super(arg0);
// }
//
// public PropertyNotFoundException(Throwable arg0) {
// super(arg0);
// }
//
// public PropertyNotFoundException(String arg0, Throwable arg1) {
// super(arg0, arg1);
// }
//
//
// }
//
// Path: src/main/java/com/siemens/oss/omniproperties/exceptions/WrongClassException.java
// public class WrongClassException extends RuntimeException {
//
// private static final long serialVersionUID = 1L;
//
// public WrongClassException(String arg0) {
// super(arg0);
// }
//
// public WrongClassException(Throwable arg0) {
// super(arg0);
// }
//
// public WrongClassException(String arg0, Throwable arg1) {
// super(arg0, arg1);
// }
//
// }
// Path: src/main/java/com/siemens/oss/omniproperties/MapOmniProperties.java
import java.util.ArrayList;
import java.util.Collection;
import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Set;
import com.siemens.oss.omniproperties.exceptions.PropertyNotFoundException;
import com.siemens.oss.omniproperties.exceptions.WrongClassException;
return getObject(key, Boolean.valueOf(def), Boolean.class).booleanValue();
}
/* (non-Javadoc)
* @see com.siemens.oss.omniproperties.IOmniProperties#getObject(java.lang.String, java.lang.Class)
*/
@Override
public <T> T getObject(final String key, final Class<T> type) {
final T result = getObject(key, null, type);
if (result == null) {
throw new PropertyNotFoundException("No property '" + key
+ "' of type " + type.getSimpleName() + " found");
}
return result;
}
/* (non-Javadoc)
* @see com.siemens.oss.omniproperties.IOmniProperties#getObject(java.lang.String, T, java.lang.Class)
*/
@Override
public <T> T getObject(final String key, final T def, final Class<T> type) {
final Object value = map.get(key);
if (value == null) {
return def;
} else if (type.isAssignableFrom(value.getClass())) {
return type.cast(value);
} else { | throw new WrongClassException("Property '" + key |
thasmin/Podax | src/main/java/com/axelby/gpodder/NoAuthClient.java | // Path: src/main/java/com/axelby/gpodder/dto/Podcast.java
// public class Podcast {
// private Uri website;
// private String description;
// private String title;
// private String url;
// private String logoUrl;
// private Integer positionLastWeek;
// private Integer subscribersLastWeek;
// private Integer subscribers;
// private String mygpoLink;
// private String scaledLogoUrl;
//
// private Podcast() {
// }
//
// @Override
// public String toString() {
// return getTitle();
// }
//
// public Uri getWebsite() {
// return website;
// }
// private void setWebsite(Uri website) {
// this.website = website;
// }
//
// public String getDescription() {
// return description;
// }
// private void setDescription(String description) {
// this.description = description;
// }
//
// public String getTitle() {
// return title;
// }
// private void setTitle(String title) {
// this.title = title;
// }
//
// public String getUrl() {
// return url;
// }
// private void setUrl(String url) {
// this.url = url;
// }
//
// public String getLogoUrl() {
// return logoUrl;
// }
// private void setLogoUrl(String logoUrl) {
// this.logoUrl = logoUrl;
// }
//
// public Integer getPositionLastWeek() {
// return positionLastWeek;
// }
// private void setPositionLastWeek(int positionLastWeek) {
// this.positionLastWeek = positionLastWeek;
// }
//
// public Integer getSubscribersLastWeek() {
// return subscribersLastWeek;
// }
// private void setSubscribersLastWeek(int subscribersLastWeek) {
// this.subscribersLastWeek = subscribersLastWeek;
// }
//
// public Integer getSubscribers() {
// return subscribers;
// }
// private void setSubscribers(int subscribers) {
// this.subscribers = subscribers;
// }
//
// public String getMygpoLink() {
// return mygpoLink;
// }
// private void setMygpoLink(String mygpoLink) {
// this.mygpoLink = mygpoLink;
// }
//
// public String getScaledLogoUrl() {
// return scaledLogoUrl;
// }
// private void setScaledLogoUrl(String scaledLogoUrl) {
// this.scaledLogoUrl = scaledLogoUrl;
// }
//
// public static Podcast readJson(JsonReader reader) throws IOException {
// Podcast podcast = new Podcast();
// reader.beginObject();
// while (reader.hasNext()) {
// String k = reader.nextName();
// if (reader.peek() == JsonToken.NULL)
// reader.skipValue();
// else if (k.equals("website"))
// podcast.setWebsite(Uri.parse(reader.nextString()));
// else if (k.equals("description"))
// podcast.setDescription(reader.nextString());
// else if (k.equals("title"))
// podcast.setTitle(reader.nextString());
// else if (k.equals("url"))
// podcast.setUrl(reader.nextString());
// else if (k.equals("logo_url"))
// podcast.setLogoUrl(reader.nextString());
// else if (k.equals("mygpo_link"))
// podcast.setMygpoLink(reader.nextString());
// else if (k.equals("position_last_week"))
// podcast.setPositionLastWeek(reader.nextInt());
// else if (k.equals("subscribers"))
// podcast.setSubscribers(reader.nextInt());
// else if (k.equals("subscribers_last_week"))
// podcast.setSubscribersLastWeek(reader.nextInt());
// else if (k.equals("scaled_logo_url"))
// podcast.setScaledLogoUrl(reader.nextString());
// else
// reader.skipValue();
// }
// reader.endObject();
// return podcast;
// }
// }
| import android.content.Context;
import android.net.Uri;
import android.util.Log;
import com.axelby.gpodder.dto.Podcast;
import com.google.gson.stream.JsonReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.GregorianCalendar;
import java.util.List;
import javax.net.ssl.HttpsURLConnection; | reader.nextName();
config.mygpo = reader.nextString();
reader.endObject();
} else if (name.equals("mygpo-feedservice")) {
reader.beginObject();
reader.nextName();
config.mygpo_feedservice = reader.nextString();
reader.endObject();
} else if (name.equals("update_timeout")) {
config.update_timeout = reader.nextLong();
}
}
reader.endObject();
return config;
} catch (IOException e) {
Log.e("Podax", "io exception while retrieving gpodder config", e);
} finally {
if (conn != null)
conn.disconnect();
}
return config;
}
protected HttpsURLConnection createConnection(URL url) throws IOException {
HttpsURLConnection conn = (HttpsURLConnection) url.openConnection();
conn.setRequestProperty("User-Agent", "podax/6.0");
return conn;
}
| // Path: src/main/java/com/axelby/gpodder/dto/Podcast.java
// public class Podcast {
// private Uri website;
// private String description;
// private String title;
// private String url;
// private String logoUrl;
// private Integer positionLastWeek;
// private Integer subscribersLastWeek;
// private Integer subscribers;
// private String mygpoLink;
// private String scaledLogoUrl;
//
// private Podcast() {
// }
//
// @Override
// public String toString() {
// return getTitle();
// }
//
// public Uri getWebsite() {
// return website;
// }
// private void setWebsite(Uri website) {
// this.website = website;
// }
//
// public String getDescription() {
// return description;
// }
// private void setDescription(String description) {
// this.description = description;
// }
//
// public String getTitle() {
// return title;
// }
// private void setTitle(String title) {
// this.title = title;
// }
//
// public String getUrl() {
// return url;
// }
// private void setUrl(String url) {
// this.url = url;
// }
//
// public String getLogoUrl() {
// return logoUrl;
// }
// private void setLogoUrl(String logoUrl) {
// this.logoUrl = logoUrl;
// }
//
// public Integer getPositionLastWeek() {
// return positionLastWeek;
// }
// private void setPositionLastWeek(int positionLastWeek) {
// this.positionLastWeek = positionLastWeek;
// }
//
// public Integer getSubscribersLastWeek() {
// return subscribersLastWeek;
// }
// private void setSubscribersLastWeek(int subscribersLastWeek) {
// this.subscribersLastWeek = subscribersLastWeek;
// }
//
// public Integer getSubscribers() {
// return subscribers;
// }
// private void setSubscribers(int subscribers) {
// this.subscribers = subscribers;
// }
//
// public String getMygpoLink() {
// return mygpoLink;
// }
// private void setMygpoLink(String mygpoLink) {
// this.mygpoLink = mygpoLink;
// }
//
// public String getScaledLogoUrl() {
// return scaledLogoUrl;
// }
// private void setScaledLogoUrl(String scaledLogoUrl) {
// this.scaledLogoUrl = scaledLogoUrl;
// }
//
// public static Podcast readJson(JsonReader reader) throws IOException {
// Podcast podcast = new Podcast();
// reader.beginObject();
// while (reader.hasNext()) {
// String k = reader.nextName();
// if (reader.peek() == JsonToken.NULL)
// reader.skipValue();
// else if (k.equals("website"))
// podcast.setWebsite(Uri.parse(reader.nextString()));
// else if (k.equals("description"))
// podcast.setDescription(reader.nextString());
// else if (k.equals("title"))
// podcast.setTitle(reader.nextString());
// else if (k.equals("url"))
// podcast.setUrl(reader.nextString());
// else if (k.equals("logo_url"))
// podcast.setLogoUrl(reader.nextString());
// else if (k.equals("mygpo_link"))
// podcast.setMygpoLink(reader.nextString());
// else if (k.equals("position_last_week"))
// podcast.setPositionLastWeek(reader.nextInt());
// else if (k.equals("subscribers"))
// podcast.setSubscribers(reader.nextInt());
// else if (k.equals("subscribers_last_week"))
// podcast.setSubscribersLastWeek(reader.nextInt());
// else if (k.equals("scaled_logo_url"))
// podcast.setScaledLogoUrl(reader.nextString());
// else
// reader.skipValue();
// }
// reader.endObject();
// return podcast;
// }
// }
// Path: src/main/java/com/axelby/gpodder/NoAuthClient.java
import android.content.Context;
import android.net.Uri;
import android.util.Log;
import com.axelby.gpodder.dto.Podcast;
import com.google.gson.stream.JsonReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.GregorianCalendar;
import java.util.List;
import javax.net.ssl.HttpsURLConnection;
reader.nextName();
config.mygpo = reader.nextString();
reader.endObject();
} else if (name.equals("mygpo-feedservice")) {
reader.beginObject();
reader.nextName();
config.mygpo_feedservice = reader.nextString();
reader.endObject();
} else if (name.equals("update_timeout")) {
config.update_timeout = reader.nextLong();
}
}
reader.endObject();
return config;
} catch (IOException e) {
Log.e("Podax", "io exception while retrieving gpodder config", e);
} finally {
if (conn != null)
conn.disconnect();
}
return config;
}
protected HttpsURLConnection createConnection(URL url) throws IOException {
HttpsURLConnection conn = (HttpsURLConnection) url.openConnection();
conn.setRequestProperty("User-Agent", "podax/6.0");
return conn;
}
| public List<Podcast> getPodcastToplist() { |
thasmin/Podax | src/main/java/com/axelby/podax/ui/ITunesPopularListFragment.java | // Path: src/main/java/com/axelby/podax/Constants.java
// public class Constants {
// public static final int NOTIFICATION_UPDATE = 1;
// public static final int SUBSCRIPTION_UPDATE_ERROR = 2;
// public static final int NOTIFICATION_PLAYING = 3;
// public static final int NOTIFICATION_GPODDER_ERROR = 4;
// public static final int NOTIFICATION_DOWNLOAD_ERROR = 5;
//
// // active podcast related
// public static final Uri ACTIVE_PODCAST_DATA_RESTART = Uri.parse("podax://activepodcast/restart");
// public static final Uri ACTIVE_PODCAST_DATA_BACK = Uri.parse("podax://activepodcast/back");
// public static final Uri ACTIVE_PODCAST_DATA_FORWARD = Uri.parse("podax://activepodcast/forward");
// public static final Uri ACTIVE_PODCAST_DATA_END = Uri.parse("podax://activepodcast/end");
//
// public static final String ACTION_REFRESH_ALL_SUBSCRIPTIONS = "com.axelby.podax.REFRESH_ALL_SUBSCRIPTIONS";
// public static final String ACTION_REFRESH_SUBSCRIPTION = "com.axelby.podax.REFRESH_SUBSCRIPTION";
// public static final String ACTION_DOWNLOAD_PODCAST = "com.axelby.podax.DOWNLOAD_PODCAST";
// public static final String ACTION_DOWNLOAD_PODCASTS = "com.axelby.podax.DOWNLOAD_PODCASTS";
//
// public static final String EXTRA_PODCAST_ID = "com.axelby.podax.podcastId";
// public static final String EXTRA_SUBSCRIPTION_ID = "com.axelby.podax.subscriptionId";
// public static final String EXTRA_TITLE = "com.axelby.podax.title";
// public static final String EXTRA_URL = "com.axelby.podax.url";
// public static final String EXTRA_MANUAL_REFRESH = "com.axelby.podax.manual_refresh";
// public static final String EXTRA_FRAGMENT = "com.axelby.podax.fragmentId";
//
// public static final String EXTRA_PLAYER_COMMAND = "com.axelby.podax.player_command";
// public static final String EXTRA_PLAYER_COMMAND_ARG = "com.axelby.podax.player_command_arg";
// public static final int PLAYER_COMMAND_PLAYPAUSE = 0;
// public static final int PLAYER_COMMAND_PLAY = 1;
// public static final int PLAYER_COMMAND_PAUSE = 2;
// public static final int PLAYER_COMMAND_STOP = 3;
// public static final int PLAYER_COMMAND_PLAYSTOP = 4;
// public static final int PLAYER_COMMAND_RESUME = 5;
// public static final int PLAYER_COMMAND_REFRESHPODCAST = 6;
//
// // reasons for pausing
// public static final int PAUSE_AUDIOFOCUS = 0;
// public static final int PAUSE_MEDIABUTTON = 1;
// public static final int PAUSE_COUNT = 2;
//
// // gpodder constants
// public static final String GPODDER_ACCOUNT_TYPE = "com.axelby.gpodder";
// public static final int GPODDER_UPDATE_NONE = 0;
// public static final int GPODDER_UPDATE_POSITION = 1;
// // podax automatically downloads and deletes
// // so it doesn't make sense to send these events to gpodder
// public static final int GPODDER_UPDATE_DOWNLOAD = 2;
// public static final int GPODDER_UPDATE_DELETE = 4;
// public static final int GPODDER_UPDATE_NEW = 8;
// }
| import android.os.AsyncTask;
import android.os.Bundle;
import android.sax.RootElement;
import android.sax.StartElementListener;
import android.support.v4.app.FragmentTransaction;
import android.support.v4.app.ListFragment;
import android.util.Xml;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.ListView;
import com.axelby.podax.Constants;
import com.axelby.podax.R;
import org.apache.http.HttpResponse;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.DefaultHttpClient;
import org.xml.sax.Attributes;
import org.xml.sax.SAXException;
import java.io.IOException;
import java.util.ArrayList; | } catch (IllegalStateException e) {
e.printStackTrace();
} catch (SAXException e) {
e.printStackTrace();
}
return feeds;
}
@Override
protected void onPostExecute(ArrayList<PodaxFeed> result) {
// make sure the activity still exists
if (getActivity() != null) {
setListAdapter(new ArrayAdapter<PodaxFeed>(getActivity(), android.R.layout.simple_list_item_1, result));
_loaded = true;
}
super.onPostExecute(result);
}
}.execute((Void) null);
}
@Override
public void onListItemClick(ListView l, View v, int position, long id) {
if (!_loaded)
return;
PodaxFeed feed = (PodaxFeed) l.getItemAtPosition(position);
if (feed == null)
return;
Bundle args = new Bundle(); | // Path: src/main/java/com/axelby/podax/Constants.java
// public class Constants {
// public static final int NOTIFICATION_UPDATE = 1;
// public static final int SUBSCRIPTION_UPDATE_ERROR = 2;
// public static final int NOTIFICATION_PLAYING = 3;
// public static final int NOTIFICATION_GPODDER_ERROR = 4;
// public static final int NOTIFICATION_DOWNLOAD_ERROR = 5;
//
// // active podcast related
// public static final Uri ACTIVE_PODCAST_DATA_RESTART = Uri.parse("podax://activepodcast/restart");
// public static final Uri ACTIVE_PODCAST_DATA_BACK = Uri.parse("podax://activepodcast/back");
// public static final Uri ACTIVE_PODCAST_DATA_FORWARD = Uri.parse("podax://activepodcast/forward");
// public static final Uri ACTIVE_PODCAST_DATA_END = Uri.parse("podax://activepodcast/end");
//
// public static final String ACTION_REFRESH_ALL_SUBSCRIPTIONS = "com.axelby.podax.REFRESH_ALL_SUBSCRIPTIONS";
// public static final String ACTION_REFRESH_SUBSCRIPTION = "com.axelby.podax.REFRESH_SUBSCRIPTION";
// public static final String ACTION_DOWNLOAD_PODCAST = "com.axelby.podax.DOWNLOAD_PODCAST";
// public static final String ACTION_DOWNLOAD_PODCASTS = "com.axelby.podax.DOWNLOAD_PODCASTS";
//
// public static final String EXTRA_PODCAST_ID = "com.axelby.podax.podcastId";
// public static final String EXTRA_SUBSCRIPTION_ID = "com.axelby.podax.subscriptionId";
// public static final String EXTRA_TITLE = "com.axelby.podax.title";
// public static final String EXTRA_URL = "com.axelby.podax.url";
// public static final String EXTRA_MANUAL_REFRESH = "com.axelby.podax.manual_refresh";
// public static final String EXTRA_FRAGMENT = "com.axelby.podax.fragmentId";
//
// public static final String EXTRA_PLAYER_COMMAND = "com.axelby.podax.player_command";
// public static final String EXTRA_PLAYER_COMMAND_ARG = "com.axelby.podax.player_command_arg";
// public static final int PLAYER_COMMAND_PLAYPAUSE = 0;
// public static final int PLAYER_COMMAND_PLAY = 1;
// public static final int PLAYER_COMMAND_PAUSE = 2;
// public static final int PLAYER_COMMAND_STOP = 3;
// public static final int PLAYER_COMMAND_PLAYSTOP = 4;
// public static final int PLAYER_COMMAND_RESUME = 5;
// public static final int PLAYER_COMMAND_REFRESHPODCAST = 6;
//
// // reasons for pausing
// public static final int PAUSE_AUDIOFOCUS = 0;
// public static final int PAUSE_MEDIABUTTON = 1;
// public static final int PAUSE_COUNT = 2;
//
// // gpodder constants
// public static final String GPODDER_ACCOUNT_TYPE = "com.axelby.gpodder";
// public static final int GPODDER_UPDATE_NONE = 0;
// public static final int GPODDER_UPDATE_POSITION = 1;
// // podax automatically downloads and deletes
// // so it doesn't make sense to send these events to gpodder
// public static final int GPODDER_UPDATE_DOWNLOAD = 2;
// public static final int GPODDER_UPDATE_DELETE = 4;
// public static final int GPODDER_UPDATE_NEW = 8;
// }
// Path: src/main/java/com/axelby/podax/ui/ITunesPopularListFragment.java
import android.os.AsyncTask;
import android.os.Bundle;
import android.sax.RootElement;
import android.sax.StartElementListener;
import android.support.v4.app.FragmentTransaction;
import android.support.v4.app.ListFragment;
import android.util.Xml;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.ListView;
import com.axelby.podax.Constants;
import com.axelby.podax.R;
import org.apache.http.HttpResponse;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.DefaultHttpClient;
import org.xml.sax.Attributes;
import org.xml.sax.SAXException;
import java.io.IOException;
import java.util.ArrayList;
} catch (IllegalStateException e) {
e.printStackTrace();
} catch (SAXException e) {
e.printStackTrace();
}
return feeds;
}
@Override
protected void onPostExecute(ArrayList<PodaxFeed> result) {
// make sure the activity still exists
if (getActivity() != null) {
setListAdapter(new ArrayAdapter<PodaxFeed>(getActivity(), android.R.layout.simple_list_item_1, result));
_loaded = true;
}
super.onPostExecute(result);
}
}.execute((Void) null);
}
@Override
public void onListItemClick(ListView l, View v, int position, long id) {
if (!_loaded)
return;
PodaxFeed feed = (PodaxFeed) l.getItemAtPosition(position);
if (feed == null)
return;
Bundle args = new Bundle(); | args.putString(Constants.EXTRA_TITLE, feed.title); |
thasmin/Podax | src/main/java/com/axelby/podax/ui/PodaxPreferenceFragment.java | // Path: src/main/java/com/axelby/podax/Storage.java
// public class Storage {
// public static File getExternalStorageDirectory(Context context) {
// SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(context);
// String storageCard = prefs.getString("storageCard", "/storage/sdcard0");
// if (new File(storageCard).exists())
// return new File(storageCard);
// return Environment.getExternalStorageDirectory();
// }
// }
| import android.os.Bundle;
import android.preference.ListPreference;
import android.preference.Preference;
import android.preference.PreferenceScreen;
import com.axelby.podax.R;
import com.axelby.podax.Storage;
import java.io.File;
import java.util.ArrayList; |
setPreferenceScreen(screen);
}
private CharSequence getEntryText(ListPreference listPreference, String value) {
if (listPreference.getEntries() == null)
return "";
int index = listPreference.findIndexOfValue(value);
return listPreference.getEntries()[index];
}
@Override
public boolean onPreferenceChange(Preference preference, Object newValue) {
if (preference == null || preference.getKey() == null)
return false;
if (preference.getKey().equals("storageCard")) {
ListPreference sdcard = (ListPreference) preference;
moveFilesToNewStorage(newValue.toString());
String title = getString(R.string.pref_sdcard_title) + ": " + getEntryText(sdcard, newValue.toString());
sdcard.setTitle(title);
return true;
}
return false;
}
private boolean moveFilesToNewStorage(String newStorage) { | // Path: src/main/java/com/axelby/podax/Storage.java
// public class Storage {
// public static File getExternalStorageDirectory(Context context) {
// SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(context);
// String storageCard = prefs.getString("storageCard", "/storage/sdcard0");
// if (new File(storageCard).exists())
// return new File(storageCard);
// return Environment.getExternalStorageDirectory();
// }
// }
// Path: src/main/java/com/axelby/podax/ui/PodaxPreferenceFragment.java
import android.os.Bundle;
import android.preference.ListPreference;
import android.preference.Preference;
import android.preference.PreferenceScreen;
import com.axelby.podax.R;
import com.axelby.podax.Storage;
import java.io.File;
import java.util.ArrayList;
setPreferenceScreen(screen);
}
private CharSequence getEntryText(ListPreference listPreference, String value) {
if (listPreference.getEntries() == null)
return "";
int index = listPreference.findIndexOfValue(value);
return listPreference.getEntries()[index];
}
@Override
public boolean onPreferenceChange(Preference preference, Object newValue) {
if (preference == null || preference.getKey() == null)
return false;
if (preference.getKey().equals("storageCard")) {
ListPreference sdcard = (ListPreference) preference;
moveFilesToNewStorage(newValue.toString());
String title = getString(R.string.pref_sdcard_title) + ": " + getEntryText(sdcard, newValue.toString());
sdcard.setTitle(title);
return true;
}
return false;
}
private boolean moveFilesToNewStorage(String newStorage) { | File oldStorage = Storage.getExternalStorageDirectory(getActivity()); |
thasmin/Podax | src/main/java/com/axelby/podax/ui/StatsFragment.java | // Path: src/main/java/com/axelby/podax/Stats.java
// public class Stats {
// private Stats() { }
//
// public static void addTime(Context context, float seconds) {
// SharedPreferences statsPrefs = context.getSharedPreferences("stats", Context.MODE_PRIVATE);
// float listenTime = statsPrefs.getFloat("listenTime", 0f) + seconds;
// statsPrefs.edit().putFloat("listenTime", listenTime).commit();
// }
//
// public static float getTime(Context context) {
// SharedPreferences statsPrefs = context.getSharedPreferences("stats", Context.MODE_PRIVATE);
// return statsPrefs.getFloat("listenTime", 0f);
// }
//
// public static String getTimeString(Context context) {
// float listenSeconds = Stats.getTime(context);
// final int secondsPerMinute = 60;
// final int secondsPerHour = secondsPerMinute * 60;
// final int secondsPerDay = secondsPerHour * 24;
//
// StringBuilder listenText = new StringBuilder();
// if (listenSeconds > secondsPerDay) {
// int days = (int) Math.floor(listenSeconds / secondsPerDay);
// listenText.append(days);
// listenText.append(" ");
// listenText.append(context.getResources().getQuantityString(R.plurals.days, days));
// listenSeconds = listenSeconds % secondsPerDay;
// }
// if (listenSeconds > secondsPerHour) {
// int hours = (int) Math.floor(listenSeconds / secondsPerHour);
// if (listenText.length() > 0)
// listenText.append(" ");
// listenText.append(hours);
// listenText.append(" ");
// listenText.append(context.getResources().getQuantityString(R.plurals.hours, hours));
// listenSeconds = listenSeconds % secondsPerHour;
// }
// if (listenSeconds > secondsPerMinute) {
// int minutes = (int) Math.floor(listenSeconds / secondsPerMinute);
// if (listenText.length() > 0)
// listenText.append(" ");
// listenText.append(minutes);
// listenText.append(" ");
// listenText.append(context.getResources().getQuantityString(R.plurals.minutes, minutes));
// }
// if (listenText.length() == 0)
// listenText.append(context.getString(R.string.none));
// return listenText.toString();
// }
//
// public static void addCompletion(Context context) {
// SharedPreferences statsPrefs = context.getSharedPreferences("stats", Context.MODE_PRIVATE);
// int completions = statsPrefs.getInt("completions", 0) + 1;
// statsPrefs.edit().putInt("completions", completions).commit();
// }
//
// public static int getCompletions(Context context) {
// SharedPreferences statsPrefs = context.getSharedPreferences("stats", Context.MODE_PRIVATE);
// return statsPrefs.getInt("completions", 0);
// }
// }
| import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;
import com.axelby.podax.R;
import com.axelby.podax.Stats; | package com.axelby.podax.ui;
// todo: fragment doesn't update when stats change
public class StatsFragment extends Fragment {
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
return inflater.inflate(R.layout.stats, container, false);
}
@Override
public void onActivityCreated(Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
TextView listenTime = (TextView) getActivity().findViewById(R.id.listen_time); | // Path: src/main/java/com/axelby/podax/Stats.java
// public class Stats {
// private Stats() { }
//
// public static void addTime(Context context, float seconds) {
// SharedPreferences statsPrefs = context.getSharedPreferences("stats", Context.MODE_PRIVATE);
// float listenTime = statsPrefs.getFloat("listenTime", 0f) + seconds;
// statsPrefs.edit().putFloat("listenTime", listenTime).commit();
// }
//
// public static float getTime(Context context) {
// SharedPreferences statsPrefs = context.getSharedPreferences("stats", Context.MODE_PRIVATE);
// return statsPrefs.getFloat("listenTime", 0f);
// }
//
// public static String getTimeString(Context context) {
// float listenSeconds = Stats.getTime(context);
// final int secondsPerMinute = 60;
// final int secondsPerHour = secondsPerMinute * 60;
// final int secondsPerDay = secondsPerHour * 24;
//
// StringBuilder listenText = new StringBuilder();
// if (listenSeconds > secondsPerDay) {
// int days = (int) Math.floor(listenSeconds / secondsPerDay);
// listenText.append(days);
// listenText.append(" ");
// listenText.append(context.getResources().getQuantityString(R.plurals.days, days));
// listenSeconds = listenSeconds % secondsPerDay;
// }
// if (listenSeconds > secondsPerHour) {
// int hours = (int) Math.floor(listenSeconds / secondsPerHour);
// if (listenText.length() > 0)
// listenText.append(" ");
// listenText.append(hours);
// listenText.append(" ");
// listenText.append(context.getResources().getQuantityString(R.plurals.hours, hours));
// listenSeconds = listenSeconds % secondsPerHour;
// }
// if (listenSeconds > secondsPerMinute) {
// int minutes = (int) Math.floor(listenSeconds / secondsPerMinute);
// if (listenText.length() > 0)
// listenText.append(" ");
// listenText.append(minutes);
// listenText.append(" ");
// listenText.append(context.getResources().getQuantityString(R.plurals.minutes, minutes));
// }
// if (listenText.length() == 0)
// listenText.append(context.getString(R.string.none));
// return listenText.toString();
// }
//
// public static void addCompletion(Context context) {
// SharedPreferences statsPrefs = context.getSharedPreferences("stats", Context.MODE_PRIVATE);
// int completions = statsPrefs.getInt("completions", 0) + 1;
// statsPrefs.edit().putInt("completions", completions).commit();
// }
//
// public static int getCompletions(Context context) {
// SharedPreferences statsPrefs = context.getSharedPreferences("stats", Context.MODE_PRIVATE);
// return statsPrefs.getInt("completions", 0);
// }
// }
// Path: src/main/java/com/axelby/podax/ui/StatsFragment.java
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;
import com.axelby.podax.R;
import com.axelby.podax.Stats;
package com.axelby.podax.ui;
// todo: fragment doesn't update when stats change
public class StatsFragment extends Fragment {
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
return inflater.inflate(R.layout.stats, container, false);
}
@Override
public void onActivityCreated(Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
TextView listenTime = (TextView) getActivity().findViewById(R.id.listen_time); | listenTime.setText(Stats.getTimeString(getActivity())); |
thasmin/Podax | src/main/java/com/axelby/podax/ui/PodaxFragmentActivity.java | // Path: src/main/java/com/axelby/podax/Helper.java
// public class Helper {
//
// private static RequestQueue _requestQueue = null;
// private static ImageLoader _imageLoader = null;
// private static LruCache<String, Bitmap> _imageCache = new LruCache<String, Bitmap>(10);
// private static DiskBasedCache _diskCache = null;
//
// public static boolean ensureWifi(Context context) {
// ConnectivityManager cm = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
// NetworkInfo netInfo = cm.getActiveNetworkInfo();
// if (netInfo == null || !netInfo.isConnectedOrConnecting())
// return false;
// // always OK if we're on wifi
// if (netInfo.getType() == ConnectivityManager.TYPE_WIFI)
// return true;
// // check for wifi only pref
// if (PreferenceManager.getDefaultSharedPreferences(context).getBoolean("wifiPref", true))
// return false;
// // check for 3g data turned off
// return netInfo.isConnected();
// }
//
// public static String getTimeString(int milliseconds) {
// int seconds = milliseconds / 1000;
// final int SECONDSPERHOUR = 60 * 60;
// final int SECONDSPERMINUTE = 60;
// int hours = seconds / SECONDSPERHOUR;
// int minutes = seconds % SECONDSPERHOUR / SECONDSPERMINUTE;
// seconds = seconds % SECONDSPERMINUTE;
//
// StringBuilder builder = new StringBuilder();
// if (hours > 0) {
// builder.append(hours);
// builder.append(":");
// if (minutes < 10)
// builder.append("0");
// }
// builder.append(minutes);
// builder.append(":");
// if (seconds < 10)
// builder.append("0");
// builder.append(seconds);
// return builder.toString();
// }
//
// public static void registerMediaButtons(Context context) {
// AudioManager audioManager = (AudioManager) context.getSystemService(Context.AUDIO_SERVICE);
// audioManager.registerMediaButtonEventReceiver(new ComponentName(context, MediaButtonIntentReceiver.class));
// }
//
// public static void unregisterMediaButtons(Context context) {
// AudioManager audioManager = (AudioManager) context.getSystemService(Context.AUDIO_SERVICE);
// audioManager.unregisterMediaButtonEventReceiver(new ComponentName(context, MediaButtonIntentReceiver.class));
// }
//
// public static RequestQueue getRequestQueue(Context context) {
// if (_requestQueue == null)
// _requestQueue = Volley.newRequestQueue(context);
// return _requestQueue;
// }
//
// public static ImageLoader getImageLoader(Context context) {
// if (_diskCache == null)
// _diskCache = new DiskBasedCache(context.getExternalCacheDir());
// if (_imageLoader == null) {
// _imageLoader = new ImageLoader(getRequestQueue(context), new ImageLoader.ImageCache() {
// @Override
// public Bitmap getBitmap(String key) {
// if (_imageCache.get(key) != null)
// return _imageCache.get(key);
// if (_diskCache.getFileForKey(key).exists())
// return BitmapFactory.decodeFile(_diskCache.getFileForKey(key).getAbsolutePath());
// return null;
// }
//
// @Override
// public void putBitmap(String key, Bitmap bitmap) {
// _imageCache.put(key, bitmap);
//
// Cache.Entry entry = new Cache.Entry();
// // only put a max 512x512 image in the disk cache
// if (bitmap.getWidth() > 512 && bitmap.getHeight() > 512)
// bitmap = Bitmap.createScaledBitmap(bitmap, 512, 512, false);
// ByteBuffer buffer = ByteBuffer.allocate(bitmap.getRowBytes() * bitmap.getHeight());
// bitmap.copyPixelsToBuffer(buffer);
// entry.data = buffer.array();
// _diskCache.put(key, entry);
// }
// });
// }
// return _imageLoader;
// }
//
// public static Bitmap getCachedImage(Context context, String url) {
// if (_diskCache == null)
// _diskCache = new DiskBasedCache(context.getExternalCacheDir());
// String key = "#W0#H0" + url;
// if (_imageCache.get(key) != null)
// return _imageCache.get(key);
// if (_diskCache.getFileForKey(key).exists())
// return BitmapFactory.decodeFile(_diskCache.getFileForKey(url).getAbsolutePath());
// return null;
// }
//
// public static Bitmap getCachedImage(Context context, String url, int width, int height) {
// if (_diskCache == null)
// _diskCache = new DiskBasedCache(context.getExternalCacheDir());
//
// String key = "#W" + width + "#H" + height + url;
// if (_imageCache.get(key) != null)
// return _imageCache.get(key);
//
// Bitmap fullSize = getCachedImage(context, url);
// if (fullSize == null)
// return null;
//
// Bitmap scaled = Bitmap.createScaledBitmap(fullSize, width, height, false);
// _imageCache.put(key, scaled);
// return scaled;
// }
//
// public static boolean isTablet(Context context) {
// return (context.getResources().getConfiguration().screenLayout
// & Configuration.SCREENLAYOUT_SIZE_MASK)
// >= Configuration.SCREENLAYOUT_SIZE_LARGE;
// }
// }
| import android.app.Activity;
import android.app.Fragment;
import android.app.FragmentManager;
import android.app.FragmentTransaction;
import android.os.Bundle;
import android.view.MenuItem;
import android.widget.FrameLayout;
import android.widget.FrameLayout.LayoutParams;
import com.axelby.podax.Helper;
import com.axelby.podax.R; | package com.axelby.podax.ui;
public class PodaxFragmentActivity extends Activity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
getActionBar().setDisplayHomeAsUpEnabled(true);
}
@Override
protected void onResume() {
super.onResume();
| // Path: src/main/java/com/axelby/podax/Helper.java
// public class Helper {
//
// private static RequestQueue _requestQueue = null;
// private static ImageLoader _imageLoader = null;
// private static LruCache<String, Bitmap> _imageCache = new LruCache<String, Bitmap>(10);
// private static DiskBasedCache _diskCache = null;
//
// public static boolean ensureWifi(Context context) {
// ConnectivityManager cm = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
// NetworkInfo netInfo = cm.getActiveNetworkInfo();
// if (netInfo == null || !netInfo.isConnectedOrConnecting())
// return false;
// // always OK if we're on wifi
// if (netInfo.getType() == ConnectivityManager.TYPE_WIFI)
// return true;
// // check for wifi only pref
// if (PreferenceManager.getDefaultSharedPreferences(context).getBoolean("wifiPref", true))
// return false;
// // check for 3g data turned off
// return netInfo.isConnected();
// }
//
// public static String getTimeString(int milliseconds) {
// int seconds = milliseconds / 1000;
// final int SECONDSPERHOUR = 60 * 60;
// final int SECONDSPERMINUTE = 60;
// int hours = seconds / SECONDSPERHOUR;
// int minutes = seconds % SECONDSPERHOUR / SECONDSPERMINUTE;
// seconds = seconds % SECONDSPERMINUTE;
//
// StringBuilder builder = new StringBuilder();
// if (hours > 0) {
// builder.append(hours);
// builder.append(":");
// if (minutes < 10)
// builder.append("0");
// }
// builder.append(minutes);
// builder.append(":");
// if (seconds < 10)
// builder.append("0");
// builder.append(seconds);
// return builder.toString();
// }
//
// public static void registerMediaButtons(Context context) {
// AudioManager audioManager = (AudioManager) context.getSystemService(Context.AUDIO_SERVICE);
// audioManager.registerMediaButtonEventReceiver(new ComponentName(context, MediaButtonIntentReceiver.class));
// }
//
// public static void unregisterMediaButtons(Context context) {
// AudioManager audioManager = (AudioManager) context.getSystemService(Context.AUDIO_SERVICE);
// audioManager.unregisterMediaButtonEventReceiver(new ComponentName(context, MediaButtonIntentReceiver.class));
// }
//
// public static RequestQueue getRequestQueue(Context context) {
// if (_requestQueue == null)
// _requestQueue = Volley.newRequestQueue(context);
// return _requestQueue;
// }
//
// public static ImageLoader getImageLoader(Context context) {
// if (_diskCache == null)
// _diskCache = new DiskBasedCache(context.getExternalCacheDir());
// if (_imageLoader == null) {
// _imageLoader = new ImageLoader(getRequestQueue(context), new ImageLoader.ImageCache() {
// @Override
// public Bitmap getBitmap(String key) {
// if (_imageCache.get(key) != null)
// return _imageCache.get(key);
// if (_diskCache.getFileForKey(key).exists())
// return BitmapFactory.decodeFile(_diskCache.getFileForKey(key).getAbsolutePath());
// return null;
// }
//
// @Override
// public void putBitmap(String key, Bitmap bitmap) {
// _imageCache.put(key, bitmap);
//
// Cache.Entry entry = new Cache.Entry();
// // only put a max 512x512 image in the disk cache
// if (bitmap.getWidth() > 512 && bitmap.getHeight() > 512)
// bitmap = Bitmap.createScaledBitmap(bitmap, 512, 512, false);
// ByteBuffer buffer = ByteBuffer.allocate(bitmap.getRowBytes() * bitmap.getHeight());
// bitmap.copyPixelsToBuffer(buffer);
// entry.data = buffer.array();
// _diskCache.put(key, entry);
// }
// });
// }
// return _imageLoader;
// }
//
// public static Bitmap getCachedImage(Context context, String url) {
// if (_diskCache == null)
// _diskCache = new DiskBasedCache(context.getExternalCacheDir());
// String key = "#W0#H0" + url;
// if (_imageCache.get(key) != null)
// return _imageCache.get(key);
// if (_diskCache.getFileForKey(key).exists())
// return BitmapFactory.decodeFile(_diskCache.getFileForKey(url).getAbsolutePath());
// return null;
// }
//
// public static Bitmap getCachedImage(Context context, String url, int width, int height) {
// if (_diskCache == null)
// _diskCache = new DiskBasedCache(context.getExternalCacheDir());
//
// String key = "#W" + width + "#H" + height + url;
// if (_imageCache.get(key) != null)
// return _imageCache.get(key);
//
// Bitmap fullSize = getCachedImage(context, url);
// if (fullSize == null)
// return null;
//
// Bitmap scaled = Bitmap.createScaledBitmap(fullSize, width, height, false);
// _imageCache.put(key, scaled);
// return scaled;
// }
//
// public static boolean isTablet(Context context) {
// return (context.getResources().getConfiguration().screenLayout
// & Configuration.SCREENLAYOUT_SIZE_MASK)
// >= Configuration.SCREENLAYOUT_SIZE_LARGE;
// }
// }
// Path: src/main/java/com/axelby/podax/ui/PodaxFragmentActivity.java
import android.app.Activity;
import android.app.Fragment;
import android.app.FragmentManager;
import android.app.FragmentTransaction;
import android.os.Bundle;
import android.view.MenuItem;
import android.widget.FrameLayout;
import android.widget.FrameLayout.LayoutParams;
import com.axelby.podax.Helper;
import com.axelby.podax.R;
package com.axelby.podax.ui;
public class PodaxFragmentActivity extends Activity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
getActionBar().setDisplayHomeAsUpEnabled(true);
}
@Override
protected void onResume() {
super.onResume();
| Helper.registerMediaButtons(this); |
pajikos/java-examples | spring-rest-api-client-auth/src/main/java/com/pavelsklenar/rest/controller/CustomerController.java | // Path: spring-rest-api-client-auth/src/main/java/com/pavelsklenar/rest/pojo/Customer.java
// public class Customer {
//
// private Long id;
// private String name;
//
// public Customer(Long id, String name) {
// this.id = id;
// this.name = name;
// }
//
// public Long getId() {
// return id;
// }
//
// public void setId(Long id) {
// this.id = id;
// }
//
// public String getName() {
// return name;
// }
//
// public void setName(String name) {
// this.name = name;
// }
// }
| import org.springframework.security.access.annotation.Secured;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import com.pavelsklenar.rest.pojo.Customer; | package com.pavelsklenar.rest.controller;
@RestController
@RequestMapping("/customer")
public class CustomerController {
@GetMapping("/{id}")
@Secured("ROLE_USER") | // Path: spring-rest-api-client-auth/src/main/java/com/pavelsklenar/rest/pojo/Customer.java
// public class Customer {
//
// private Long id;
// private String name;
//
// public Customer(Long id, String name) {
// this.id = id;
// this.name = name;
// }
//
// public Long getId() {
// return id;
// }
//
// public void setId(Long id) {
// this.id = id;
// }
//
// public String getName() {
// return name;
// }
//
// public void setName(String name) {
// this.name = name;
// }
// }
// Path: spring-rest-api-client-auth/src/main/java/com/pavelsklenar/rest/controller/CustomerController.java
import org.springframework.security.access.annotation.Secured;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import com.pavelsklenar.rest.pojo.Customer;
package com.pavelsklenar.rest.controller;
@RestController
@RequestMapping("/customer")
public class CustomerController {
@GetMapping("/{id}")
@Secured("ROLE_USER") | public Customer GetCustomer(@PathVariable Long id) { |
pajikos/java-examples | spring-sftp-upload-demo/src/test/java/com/pavelsklenar/SpringSftpUploadDemoApplicationTests.java | // Path: spring-sftp-upload-demo/src/main/java/com/pavelsklenar/SftpConfig.java
// @MessagingGateway
// public interface UploadGateway {
//
// @Gateway(requestChannel = "toSftpChannel")
// void upload(File file);
//
// }
| import static org.junit.Assert.assertEquals;
import java.io.File;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.util.List;
import java.util.stream.Collectors;
import org.junit.After;
import org.junit.AfterClass;
import org.junit.Before;
import org.junit.BeforeClass;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.test.context.TestPropertySource;
import org.springframework.test.context.junit4.SpringRunner;
import com.pavelsklenar.SftpConfig.UploadGateway; | package com.pavelsklenar;
@RunWith(SpringRunner.class)
@SpringBootTest
@TestPropertySource(properties = { "sftp.port = 10022" })
public class SpringSftpUploadDemoApplicationTests {
@Autowired | // Path: spring-sftp-upload-demo/src/main/java/com/pavelsklenar/SftpConfig.java
// @MessagingGateway
// public interface UploadGateway {
//
// @Gateway(requestChannel = "toSftpChannel")
// void upload(File file);
//
// }
// Path: spring-sftp-upload-demo/src/test/java/com/pavelsklenar/SpringSftpUploadDemoApplicationTests.java
import static org.junit.Assert.assertEquals;
import java.io.File;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.util.List;
import java.util.stream.Collectors;
import org.junit.After;
import org.junit.AfterClass;
import org.junit.Before;
import org.junit.BeforeClass;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.test.context.TestPropertySource;
import org.springframework.test.context.junit4.SpringRunner;
import com.pavelsklenar.SftpConfig.UploadGateway;
package com.pavelsklenar;
@RunWith(SpringRunner.class)
@SpringBootTest
@TestPropertySource(properties = { "sftp.port = 10022" })
public class SpringSftpUploadDemoApplicationTests {
@Autowired | private UploadGateway gateway; |
pajikos/java-examples | spring-boot-docker-build/src/main/java/com/pavelsklenar/rest/controller/CustomerController.java | // Path: spring-rest-api-client-auth/src/main/java/com/pavelsklenar/rest/pojo/Customer.java
// public class Customer {
//
// private Long id;
// private String name;
//
// public Customer(Long id, String name) {
// this.id = id;
// this.name = name;
// }
//
// public Long getId() {
// return id;
// }
//
// public void setId(Long id) {
// this.id = id;
// }
//
// public String getName() {
// return name;
// }
//
// public void setName(String name) {
// this.name = name;
// }
// }
| import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import com.pavelsklenar.rest.pojo.Customer; | package com.pavelsklenar.rest.controller;
@RestController
@RequestMapping("/customer")
public class CustomerController {
@GetMapping("/{id}") | // Path: spring-rest-api-client-auth/src/main/java/com/pavelsklenar/rest/pojo/Customer.java
// public class Customer {
//
// private Long id;
// private String name;
//
// public Customer(Long id, String name) {
// this.id = id;
// this.name = name;
// }
//
// public Long getId() {
// return id;
// }
//
// public void setId(Long id) {
// this.id = id;
// }
//
// public String getName() {
// return name;
// }
//
// public void setName(String name) {
// this.name = name;
// }
// }
// Path: spring-boot-docker-build/src/main/java/com/pavelsklenar/rest/controller/CustomerController.java
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import com.pavelsklenar.rest.pojo.Customer;
package com.pavelsklenar.rest.controller;
@RestController
@RequestMapping("/customer")
public class CustomerController {
@GetMapping("/{id}") | public Customer GetCustomer(@PathVariable Long id) { |
pajikos/java-examples | spring-security-radius-login/src/main/java/com/pavelsklenar/radiuslogin/bootstrap/WebSecurityConfig.java | // Path: spring-security-radius-login/src/main/java/com/pavelsklenar/radiuslogin/authentication/RadiusAuthenticationProvider.java
// public class RadiusAuthenticationProvider implements AuthenticationProvider {
//
// private static final Logger logger = LoggerFactory.getLogger(RadiusAuthenticationProvider.class);
//
// @Value("${com.pavelsklenar.radius.server}")
// private String serverConfigurationToken;
//
// private List<NetworkAccessServer> clients = new ArrayList<>();
//
// @PostConstruct
// public void initServers() {
// List<RadiusServer> servers = RadiusUtil.parseServerConfigurationToken(serverConfigurationToken);
// servers.forEach(it -> {
// clients.add(new NetworkAccessServer(it));
// });
// }
//
// @Override
// public Authentication authenticate(Authentication authentication) throws AuthenticationException {
// String username = authentication.getName();
// RadiusPacket response = null;
// int attemptCount = 0;
// while (response == null && attemptCount++ < clients.size()) {
// response = authenticateInternally(clients.get(attemptCount - 1), username,
// authentication.getCredentials().toString());
// }
// if (response == null) {
// logger.warn("User {}, calling radius does not return any value.", username);
// return null;
// }
// if (response.getPacketType() == RadiusPacket.ACCESS_ACCEPT) {
// logger.info("User {} successfully authenticated using radius", username);
// return new UsernamePasswordAuthenticationToken(username, "", new ArrayList<>());
// } else {
// logger.warn("User {}, returned response {}", username, response);
// return null;
// }
// }
//
// private RadiusPacket authenticateInternally(NetworkAccessServer client, String username, String password) {
// logger.info("Calling radius server to authenticate user {}", username);
// try {
// return client.authenticate(username, password);
// } catch (Exception e) {
// logger.error("Exception when calling remote radius server.", e);
// return null;
// }
// }
//
// @Override
// public boolean supports(Class<?> authentication) {
// return authentication.equals(UsernamePasswordAuthenticationToken.class);
// }
//
// }
| import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import com.pavelsklenar.radiuslogin.authentication.RadiusAuthenticationProvider; | package com.pavelsklenar.radiuslogin.bootstrap;
@Configuration
@EnableWebSecurity
public class WebSecurityConfig extends WebSecurityConfigurerAdapter {
@Override
protected void configure(HttpSecurity http) throws Exception {
http
.authorizeRequests()
.anyRequest().authenticated()
.and()
.formLogin()
.loginPage("/login")
.permitAll()
.and()
.logout()
.permitAll();
}
@Autowired
public void configureGlobal(AuthenticationManagerBuilder auth) throws Exception {
auth.authenticationProvider(radiusAuthenticationProvider());
}
@Bean | // Path: spring-security-radius-login/src/main/java/com/pavelsklenar/radiuslogin/authentication/RadiusAuthenticationProvider.java
// public class RadiusAuthenticationProvider implements AuthenticationProvider {
//
// private static final Logger logger = LoggerFactory.getLogger(RadiusAuthenticationProvider.class);
//
// @Value("${com.pavelsklenar.radius.server}")
// private String serverConfigurationToken;
//
// private List<NetworkAccessServer> clients = new ArrayList<>();
//
// @PostConstruct
// public void initServers() {
// List<RadiusServer> servers = RadiusUtil.parseServerConfigurationToken(serverConfigurationToken);
// servers.forEach(it -> {
// clients.add(new NetworkAccessServer(it));
// });
// }
//
// @Override
// public Authentication authenticate(Authentication authentication) throws AuthenticationException {
// String username = authentication.getName();
// RadiusPacket response = null;
// int attemptCount = 0;
// while (response == null && attemptCount++ < clients.size()) {
// response = authenticateInternally(clients.get(attemptCount - 1), username,
// authentication.getCredentials().toString());
// }
// if (response == null) {
// logger.warn("User {}, calling radius does not return any value.", username);
// return null;
// }
// if (response.getPacketType() == RadiusPacket.ACCESS_ACCEPT) {
// logger.info("User {} successfully authenticated using radius", username);
// return new UsernamePasswordAuthenticationToken(username, "", new ArrayList<>());
// } else {
// logger.warn("User {}, returned response {}", username, response);
// return null;
// }
// }
//
// private RadiusPacket authenticateInternally(NetworkAccessServer client, String username, String password) {
// logger.info("Calling radius server to authenticate user {}", username);
// try {
// return client.authenticate(username, password);
// } catch (Exception e) {
// logger.error("Exception when calling remote radius server.", e);
// return null;
// }
// }
//
// @Override
// public boolean supports(Class<?> authentication) {
// return authentication.equals(UsernamePasswordAuthenticationToken.class);
// }
//
// }
// Path: spring-security-radius-login/src/main/java/com/pavelsklenar/radiuslogin/bootstrap/WebSecurityConfig.java
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import com.pavelsklenar.radiuslogin.authentication.RadiusAuthenticationProvider;
package com.pavelsklenar.radiuslogin.bootstrap;
@Configuration
@EnableWebSecurity
public class WebSecurityConfig extends WebSecurityConfigurerAdapter {
@Override
protected void configure(HttpSecurity http) throws Exception {
http
.authorizeRequests()
.anyRequest().authenticated()
.and()
.formLogin()
.loginPage("/login")
.permitAll()
.and()
.logout()
.permitAll();
}
@Autowired
public void configureGlobal(AuthenticationManagerBuilder auth) throws Exception {
auth.authenticationProvider(radiusAuthenticationProvider());
}
@Bean | public RadiusAuthenticationProvider radiusAuthenticationProvider() { |
AlexeyDmitriev/JHelper | src/name/admitriev/jhelper/ui/ConfigurationDialog.java | // Path: src/name/admitriev/jhelper/components/Configurator.java
// @State(name = "Configurator", storages = @Storage("JHelper.xml"))
// @Service(Service.Level.PROJECT)
// public final class Configurator implements PersistentStateComponent<Configurator.State> {
// public Configurator() {
// state = new Configurator.State();
// }
//
// @Override
// public @NotNull Configurator.State getState() {
// return state;
// }
//
// @SuppressWarnings("ParameterHidesMemberVariable")
// @Override
// public void loadState(@NotNull Configurator.State state) {
// this.state = state;
// }
//
// private Configurator.State state;
//
// public static class State {
// private String author;
// private String tasksDirectory;
// private String outputFile;
// private String runFile;
// private boolean codeEliminationOn;
// private boolean codeReformattingOn;
//
// public State(
// String author,
// String tasksDirectory,
// String outputFile,
// String runFile,
// boolean codeEliminationOn,
// boolean codeReformattingOn
// ) {
// this.author = author;
// this.tasksDirectory = tasksDirectory;
// this.outputFile = outputFile;
// this.runFile = runFile;
// this.codeEliminationOn = codeEliminationOn;
// this.codeReformattingOn = codeReformattingOn;
// }
//
// public State() {
// this("", "tasks", "output/main.cpp", "testrunner/main.cpp", false, false);
// }
//
// public String getAuthor() {
// return author;
// }
//
// public String getTasksDirectory() {
// return tasksDirectory;
// }
//
// public String getOutputFile() {
// return outputFile;
// }
//
// public String getRunFile() {
// return runFile;
// }
//
// public boolean isCodeEliminationOn() {
// return codeEliminationOn;
// }
//
// public boolean isCodeReformattingOn() {
// return codeReformattingOn;
// }
//
// @Deprecated
// public void setAuthor(String author) {
// this.author = author;
// }
//
// @Deprecated
// public void setTasksDirectory(String tasksDirectory) {
// this.tasksDirectory = tasksDirectory;
// }
//
// @Deprecated
// public void setOutputFile(String outputFile) {
// this.outputFile = outputFile;
// }
//
// @Deprecated
// public void setRunFile(String runFile) {
// this.runFile = runFile;
// }
//
// @Deprecated
// public void setCodeEliminationOn(boolean codeEliminationOn) {
// this.codeEliminationOn = codeEliminationOn;
// }
//
// @Deprecated
// public void setCodeReformattingOn(boolean codeReformattingOn) {
// this.codeReformattingOn = codeReformattingOn;
// }
// }
// }
| import com.intellij.openapi.project.Project;
import com.intellij.openapi.ui.DialogWrapper;
import com.intellij.openapi.ui.LabeledComponent;
import name.admitriev.jhelper.components.Configurator;
import org.jdesktop.swingx.VerticalLayout;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
import javax.swing.*; | package name.admitriev.jhelper.ui;
public class ConfigurationDialog extends DialogWrapper {
private final JComponent component;
private JTextField author;
private FileSelector tasksDirectory;
private FileSelector outputFile;
private FileSelector runFile;
private JCheckBox codeEliminationOn;
private JCheckBox codeReformattingOn;
| // Path: src/name/admitriev/jhelper/components/Configurator.java
// @State(name = "Configurator", storages = @Storage("JHelper.xml"))
// @Service(Service.Level.PROJECT)
// public final class Configurator implements PersistentStateComponent<Configurator.State> {
// public Configurator() {
// state = new Configurator.State();
// }
//
// @Override
// public @NotNull Configurator.State getState() {
// return state;
// }
//
// @SuppressWarnings("ParameterHidesMemberVariable")
// @Override
// public void loadState(@NotNull Configurator.State state) {
// this.state = state;
// }
//
// private Configurator.State state;
//
// public static class State {
// private String author;
// private String tasksDirectory;
// private String outputFile;
// private String runFile;
// private boolean codeEliminationOn;
// private boolean codeReformattingOn;
//
// public State(
// String author,
// String tasksDirectory,
// String outputFile,
// String runFile,
// boolean codeEliminationOn,
// boolean codeReformattingOn
// ) {
// this.author = author;
// this.tasksDirectory = tasksDirectory;
// this.outputFile = outputFile;
// this.runFile = runFile;
// this.codeEliminationOn = codeEliminationOn;
// this.codeReformattingOn = codeReformattingOn;
// }
//
// public State() {
// this("", "tasks", "output/main.cpp", "testrunner/main.cpp", false, false);
// }
//
// public String getAuthor() {
// return author;
// }
//
// public String getTasksDirectory() {
// return tasksDirectory;
// }
//
// public String getOutputFile() {
// return outputFile;
// }
//
// public String getRunFile() {
// return runFile;
// }
//
// public boolean isCodeEliminationOn() {
// return codeEliminationOn;
// }
//
// public boolean isCodeReformattingOn() {
// return codeReformattingOn;
// }
//
// @Deprecated
// public void setAuthor(String author) {
// this.author = author;
// }
//
// @Deprecated
// public void setTasksDirectory(String tasksDirectory) {
// this.tasksDirectory = tasksDirectory;
// }
//
// @Deprecated
// public void setOutputFile(String outputFile) {
// this.outputFile = outputFile;
// }
//
// @Deprecated
// public void setRunFile(String runFile) {
// this.runFile = runFile;
// }
//
// @Deprecated
// public void setCodeEliminationOn(boolean codeEliminationOn) {
// this.codeEliminationOn = codeEliminationOn;
// }
//
// @Deprecated
// public void setCodeReformattingOn(boolean codeReformattingOn) {
// this.codeReformattingOn = codeReformattingOn;
// }
// }
// }
// Path: src/name/admitriev/jhelper/ui/ConfigurationDialog.java
import com.intellij.openapi.project.Project;
import com.intellij.openapi.ui.DialogWrapper;
import com.intellij.openapi.ui.LabeledComponent;
import name.admitriev.jhelper.components.Configurator;
import org.jdesktop.swingx.VerticalLayout;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
import javax.swing.*;
package name.admitriev.jhelper.ui;
public class ConfigurationDialog extends DialogWrapper {
private final JComponent component;
private JTextField author;
private FileSelector tasksDirectory;
private FileSelector outputFile;
private FileSelector runFile;
private JCheckBox codeEliminationOn;
private JCheckBox codeReformattingOn;
| public ConfigurationDialog(@NotNull Project project, Configurator.State configuration) { |
AlexeyDmitriev/JHelper | src/name/admitriev/jhelper/ui/AddTaskDialog.java | // Path: src/name/admitriev/jhelper/task/TaskData.java
// public class TaskData {
// private final String name;
// private final String className;
// private final String cppPath;
// private final StreamConfiguration input;
// private final StreamConfiguration output;
// private final TestType testType;
// private final Test[] tests;
//
// public TaskData(
// String name,
// String className,
// String cppPath,
// StreamConfiguration input,
// StreamConfiguration output,
// TestType testType,
// Test[] tests
// ) {
// this.input = input;
// this.output = output;
// this.name = name;
// this.className = className;
// this.cppPath = cppPath;
// this.testType = testType;
// this.tests = Arrays.copyOf(tests, tests.length);
// }
//
// public TaskData(TaskData task) {
// this(task.name, task.className, task.cppPath, task.input, task.output, task.testType, task.tests);
// }
//
// public String getName() {
// return name;
// }
//
// public String getClassName() {
// return className;
// }
//
// public String getCppPath() {
// return cppPath;
// }
//
// public StreamConfiguration getInput() {
// return input;
// }
//
// public StreamConfiguration getOutput() {
// return output;
// }
//
// public Test[] getTests() {
// return Arrays.copyOf(tests, tests.length);
// }
//
// public static TaskData emptyTaskData(Project project) {
// return new TaskData(
// "",
// "",
// String.format(defaultCppPathFormat(project), ""),
// StreamConfiguration.STANDARD,
// StreamConfiguration.STANDARD,
// TestType.SINGLE,
// new Test[0]
// );
// }
//
// public static String defaultCppPathFormat(Project project) {
// Configurator configurator = project.getService(Configurator.class);
// Configurator.State configuration = configurator.getState();
// String path = configuration.getTasksDirectory();
// return path + "/%s.cpp";
// }
//
// public TestType getTestType() {
// return testType;
// }
//
// }
| import com.intellij.openapi.project.Project;
import com.intellij.openapi.ui.DialogWrapper;
import name.admitriev.jhelper.task.TaskData;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
import javax.swing.*; | package name.admitriev.jhelper.ui;
public class AddTaskDialog extends DialogWrapper {
private TaskSettingsComponent component;
public AddTaskDialog(@NotNull Project project) {
super(project);
setTitle("Add Task");
component = new TaskSettingsComponent(
project,
true,
this::pack
);
init();
}
@Nullable
@Override
protected JComponent createCenterPanel() {
return component;
}
| // Path: src/name/admitriev/jhelper/task/TaskData.java
// public class TaskData {
// private final String name;
// private final String className;
// private final String cppPath;
// private final StreamConfiguration input;
// private final StreamConfiguration output;
// private final TestType testType;
// private final Test[] tests;
//
// public TaskData(
// String name,
// String className,
// String cppPath,
// StreamConfiguration input,
// StreamConfiguration output,
// TestType testType,
// Test[] tests
// ) {
// this.input = input;
// this.output = output;
// this.name = name;
// this.className = className;
// this.cppPath = cppPath;
// this.testType = testType;
// this.tests = Arrays.copyOf(tests, tests.length);
// }
//
// public TaskData(TaskData task) {
// this(task.name, task.className, task.cppPath, task.input, task.output, task.testType, task.tests);
// }
//
// public String getName() {
// return name;
// }
//
// public String getClassName() {
// return className;
// }
//
// public String getCppPath() {
// return cppPath;
// }
//
// public StreamConfiguration getInput() {
// return input;
// }
//
// public StreamConfiguration getOutput() {
// return output;
// }
//
// public Test[] getTests() {
// return Arrays.copyOf(tests, tests.length);
// }
//
// public static TaskData emptyTaskData(Project project) {
// return new TaskData(
// "",
// "",
// String.format(defaultCppPathFormat(project), ""),
// StreamConfiguration.STANDARD,
// StreamConfiguration.STANDARD,
// TestType.SINGLE,
// new Test[0]
// );
// }
//
// public static String defaultCppPathFormat(Project project) {
// Configurator configurator = project.getService(Configurator.class);
// Configurator.State configuration = configurator.getState();
// String path = configuration.getTasksDirectory();
// return path + "/%s.cpp";
// }
//
// public TestType getTestType() {
// return testType;
// }
//
// }
// Path: src/name/admitriev/jhelper/ui/AddTaskDialog.java
import com.intellij.openapi.project.Project;
import com.intellij.openapi.ui.DialogWrapper;
import name.admitriev.jhelper.task.TaskData;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
import javax.swing.*;
package name.admitriev.jhelper.ui;
public class AddTaskDialog extends DialogWrapper {
private TaskSettingsComponent component;
public AddTaskDialog(@NotNull Project project) {
super(project);
setTitle("Add Task");
component = new TaskSettingsComponent(
project,
true,
this::pack
);
init();
}
@Nullable
@Override
protected JComponent createCenterPanel() {
return component;
}
| public TaskData getTask() { |
AlexeyDmitriev/JHelper | src/name/admitriev/jhelper/actions/BaseAction.java | // Path: src/name/admitriev/jhelper/exceptions/JHelperException.java
// public class JHelperException extends RuntimeException {
//
// public JHelperException(String message, Throwable cause) {
// super(message, cause);
// }
//
// public JHelperException(String message) {
// super(message);
// }
//
// @Override
// public String getMessage() {
// return "Please, report that bug to issue tracker on https://github.com/AlexeyDmitriev/JHelper . Attach your code and this stack trace. "
// + super.getMessage();
// }
// }
//
// Path: src/name/admitriev/jhelper/exceptions/NotificationException.java
// public class NotificationException extends RuntimeException {
// private final String title;
// private final String content;
//
// public NotificationException(String content) {
// this(content, (Throwable) null);
// }
//
// public NotificationException(String content, Throwable cause) {
// super(content, cause);
// title = "";
// this.content = content;
// }
//
// public NotificationException(String title, String content) {
// this(title, content, null);
// }
//
// public NotificationException(String title, String content, Throwable cause) {
// super(title + ": " + content, cause);
// this.title = title;
// this.content = content;
// }
//
// public String getTitle() {
// return title;
// }
//
// public String getContent() {
// return content;
// }
// }
//
// Path: src/name/admitriev/jhelper/ui/Notificator.java
// public class Notificator {
// private static final NotificationGroup GROUP = NotificationGroupManager.getInstance().getNotificationGroup("JHelper");
//
// private Notificator() {
// }
//
// public static void showNotification(String title, String content, NotificationType notificationType) {
// GROUP.createNotification(title, content, notificationType, null).notify(null);
// }
//
// public static void showNotification(String content, NotificationType notificationType) {
// showNotification("", content, notificationType);
// }
// }
| import com.intellij.notification.NotificationType;
import com.intellij.openapi.actionSystem.AnAction;
import com.intellij.openapi.actionSystem.AnActionEvent;
import name.admitriev.jhelper.exceptions.JHelperException;
import name.admitriev.jhelper.exceptions.NotificationException;
import name.admitriev.jhelper.ui.Notificator;
import org.jetbrains.annotations.NotNull; | package name.admitriev.jhelper.actions;
public abstract class BaseAction extends AnAction {
@Override
public void actionPerformed(@NotNull AnActionEvent e) {
try {
performAction(e);
} | // Path: src/name/admitriev/jhelper/exceptions/JHelperException.java
// public class JHelperException extends RuntimeException {
//
// public JHelperException(String message, Throwable cause) {
// super(message, cause);
// }
//
// public JHelperException(String message) {
// super(message);
// }
//
// @Override
// public String getMessage() {
// return "Please, report that bug to issue tracker on https://github.com/AlexeyDmitriev/JHelper . Attach your code and this stack trace. "
// + super.getMessage();
// }
// }
//
// Path: src/name/admitriev/jhelper/exceptions/NotificationException.java
// public class NotificationException extends RuntimeException {
// private final String title;
// private final String content;
//
// public NotificationException(String content) {
// this(content, (Throwable) null);
// }
//
// public NotificationException(String content, Throwable cause) {
// super(content, cause);
// title = "";
// this.content = content;
// }
//
// public NotificationException(String title, String content) {
// this(title, content, null);
// }
//
// public NotificationException(String title, String content, Throwable cause) {
// super(title + ": " + content, cause);
// this.title = title;
// this.content = content;
// }
//
// public String getTitle() {
// return title;
// }
//
// public String getContent() {
// return content;
// }
// }
//
// Path: src/name/admitriev/jhelper/ui/Notificator.java
// public class Notificator {
// private static final NotificationGroup GROUP = NotificationGroupManager.getInstance().getNotificationGroup("JHelper");
//
// private Notificator() {
// }
//
// public static void showNotification(String title, String content, NotificationType notificationType) {
// GROUP.createNotification(title, content, notificationType, null).notify(null);
// }
//
// public static void showNotification(String content, NotificationType notificationType) {
// showNotification("", content, notificationType);
// }
// }
// Path: src/name/admitriev/jhelper/actions/BaseAction.java
import com.intellij.notification.NotificationType;
import com.intellij.openapi.actionSystem.AnAction;
import com.intellij.openapi.actionSystem.AnActionEvent;
import name.admitriev.jhelper.exceptions.JHelperException;
import name.admitriev.jhelper.exceptions.NotificationException;
import name.admitriev.jhelper.ui.Notificator;
import org.jetbrains.annotations.NotNull;
package name.admitriev.jhelper.actions;
public abstract class BaseAction extends AnAction {
@Override
public void actionPerformed(@NotNull AnActionEvent e) {
try {
performAction(e);
} | catch (NotificationException exception) { |
AlexeyDmitriev/JHelper | src/name/admitriev/jhelper/actions/BaseAction.java | // Path: src/name/admitriev/jhelper/exceptions/JHelperException.java
// public class JHelperException extends RuntimeException {
//
// public JHelperException(String message, Throwable cause) {
// super(message, cause);
// }
//
// public JHelperException(String message) {
// super(message);
// }
//
// @Override
// public String getMessage() {
// return "Please, report that bug to issue tracker on https://github.com/AlexeyDmitriev/JHelper . Attach your code and this stack trace. "
// + super.getMessage();
// }
// }
//
// Path: src/name/admitriev/jhelper/exceptions/NotificationException.java
// public class NotificationException extends RuntimeException {
// private final String title;
// private final String content;
//
// public NotificationException(String content) {
// this(content, (Throwable) null);
// }
//
// public NotificationException(String content, Throwable cause) {
// super(content, cause);
// title = "";
// this.content = content;
// }
//
// public NotificationException(String title, String content) {
// this(title, content, null);
// }
//
// public NotificationException(String title, String content, Throwable cause) {
// super(title + ": " + content, cause);
// this.title = title;
// this.content = content;
// }
//
// public String getTitle() {
// return title;
// }
//
// public String getContent() {
// return content;
// }
// }
//
// Path: src/name/admitriev/jhelper/ui/Notificator.java
// public class Notificator {
// private static final NotificationGroup GROUP = NotificationGroupManager.getInstance().getNotificationGroup("JHelper");
//
// private Notificator() {
// }
//
// public static void showNotification(String title, String content, NotificationType notificationType) {
// GROUP.createNotification(title, content, notificationType, null).notify(null);
// }
//
// public static void showNotification(String content, NotificationType notificationType) {
// showNotification("", content, notificationType);
// }
// }
| import com.intellij.notification.NotificationType;
import com.intellij.openapi.actionSystem.AnAction;
import com.intellij.openapi.actionSystem.AnActionEvent;
import name.admitriev.jhelper.exceptions.JHelperException;
import name.admitriev.jhelper.exceptions.NotificationException;
import name.admitriev.jhelper.ui.Notificator;
import org.jetbrains.annotations.NotNull; | package name.admitriev.jhelper.actions;
public abstract class BaseAction extends AnAction {
@Override
public void actionPerformed(@NotNull AnActionEvent e) {
try {
performAction(e);
}
catch (NotificationException exception) { | // Path: src/name/admitriev/jhelper/exceptions/JHelperException.java
// public class JHelperException extends RuntimeException {
//
// public JHelperException(String message, Throwable cause) {
// super(message, cause);
// }
//
// public JHelperException(String message) {
// super(message);
// }
//
// @Override
// public String getMessage() {
// return "Please, report that bug to issue tracker on https://github.com/AlexeyDmitriev/JHelper . Attach your code and this stack trace. "
// + super.getMessage();
// }
// }
//
// Path: src/name/admitriev/jhelper/exceptions/NotificationException.java
// public class NotificationException extends RuntimeException {
// private final String title;
// private final String content;
//
// public NotificationException(String content) {
// this(content, (Throwable) null);
// }
//
// public NotificationException(String content, Throwable cause) {
// super(content, cause);
// title = "";
// this.content = content;
// }
//
// public NotificationException(String title, String content) {
// this(title, content, null);
// }
//
// public NotificationException(String title, String content, Throwable cause) {
// super(title + ": " + content, cause);
// this.title = title;
// this.content = content;
// }
//
// public String getTitle() {
// return title;
// }
//
// public String getContent() {
// return content;
// }
// }
//
// Path: src/name/admitriev/jhelper/ui/Notificator.java
// public class Notificator {
// private static final NotificationGroup GROUP = NotificationGroupManager.getInstance().getNotificationGroup("JHelper");
//
// private Notificator() {
// }
//
// public static void showNotification(String title, String content, NotificationType notificationType) {
// GROUP.createNotification(title, content, notificationType, null).notify(null);
// }
//
// public static void showNotification(String content, NotificationType notificationType) {
// showNotification("", content, notificationType);
// }
// }
// Path: src/name/admitriev/jhelper/actions/BaseAction.java
import com.intellij.notification.NotificationType;
import com.intellij.openapi.actionSystem.AnAction;
import com.intellij.openapi.actionSystem.AnActionEvent;
import name.admitriev.jhelper.exceptions.JHelperException;
import name.admitriev.jhelper.exceptions.NotificationException;
import name.admitriev.jhelper.ui.Notificator;
import org.jetbrains.annotations.NotNull;
package name.admitriev.jhelper.actions;
public abstract class BaseAction extends AnAction {
@Override
public void actionPerformed(@NotNull AnActionEvent e) {
try {
performAction(e);
}
catch (NotificationException exception) { | Notificator.showNotification( |
AlexeyDmitriev/JHelper | src/name/admitriev/jhelper/actions/BaseAction.java | // Path: src/name/admitriev/jhelper/exceptions/JHelperException.java
// public class JHelperException extends RuntimeException {
//
// public JHelperException(String message, Throwable cause) {
// super(message, cause);
// }
//
// public JHelperException(String message) {
// super(message);
// }
//
// @Override
// public String getMessage() {
// return "Please, report that bug to issue tracker on https://github.com/AlexeyDmitriev/JHelper . Attach your code and this stack trace. "
// + super.getMessage();
// }
// }
//
// Path: src/name/admitriev/jhelper/exceptions/NotificationException.java
// public class NotificationException extends RuntimeException {
// private final String title;
// private final String content;
//
// public NotificationException(String content) {
// this(content, (Throwable) null);
// }
//
// public NotificationException(String content, Throwable cause) {
// super(content, cause);
// title = "";
// this.content = content;
// }
//
// public NotificationException(String title, String content) {
// this(title, content, null);
// }
//
// public NotificationException(String title, String content, Throwable cause) {
// super(title + ": " + content, cause);
// this.title = title;
// this.content = content;
// }
//
// public String getTitle() {
// return title;
// }
//
// public String getContent() {
// return content;
// }
// }
//
// Path: src/name/admitriev/jhelper/ui/Notificator.java
// public class Notificator {
// private static final NotificationGroup GROUP = NotificationGroupManager.getInstance().getNotificationGroup("JHelper");
//
// private Notificator() {
// }
//
// public static void showNotification(String title, String content, NotificationType notificationType) {
// GROUP.createNotification(title, content, notificationType, null).notify(null);
// }
//
// public static void showNotification(String content, NotificationType notificationType) {
// showNotification("", content, notificationType);
// }
// }
| import com.intellij.notification.NotificationType;
import com.intellij.openapi.actionSystem.AnAction;
import com.intellij.openapi.actionSystem.AnActionEvent;
import name.admitriev.jhelper.exceptions.JHelperException;
import name.admitriev.jhelper.exceptions.NotificationException;
import name.admitriev.jhelper.ui.Notificator;
import org.jetbrains.annotations.NotNull; | package name.admitriev.jhelper.actions;
public abstract class BaseAction extends AnAction {
@Override
public void actionPerformed(@NotNull AnActionEvent e) {
try {
performAction(e);
}
catch (NotificationException exception) {
Notificator.showNotification(
exception.getTitle(),
exception.getContent(),
NotificationType.ERROR
);
} | // Path: src/name/admitriev/jhelper/exceptions/JHelperException.java
// public class JHelperException extends RuntimeException {
//
// public JHelperException(String message, Throwable cause) {
// super(message, cause);
// }
//
// public JHelperException(String message) {
// super(message);
// }
//
// @Override
// public String getMessage() {
// return "Please, report that bug to issue tracker on https://github.com/AlexeyDmitriev/JHelper . Attach your code and this stack trace. "
// + super.getMessage();
// }
// }
//
// Path: src/name/admitriev/jhelper/exceptions/NotificationException.java
// public class NotificationException extends RuntimeException {
// private final String title;
// private final String content;
//
// public NotificationException(String content) {
// this(content, (Throwable) null);
// }
//
// public NotificationException(String content, Throwable cause) {
// super(content, cause);
// title = "";
// this.content = content;
// }
//
// public NotificationException(String title, String content) {
// this(title, content, null);
// }
//
// public NotificationException(String title, String content, Throwable cause) {
// super(title + ": " + content, cause);
// this.title = title;
// this.content = content;
// }
//
// public String getTitle() {
// return title;
// }
//
// public String getContent() {
// return content;
// }
// }
//
// Path: src/name/admitriev/jhelper/ui/Notificator.java
// public class Notificator {
// private static final NotificationGroup GROUP = NotificationGroupManager.getInstance().getNotificationGroup("JHelper");
//
// private Notificator() {
// }
//
// public static void showNotification(String title, String content, NotificationType notificationType) {
// GROUP.createNotification(title, content, notificationType, null).notify(null);
// }
//
// public static void showNotification(String content, NotificationType notificationType) {
// showNotification("", content, notificationType);
// }
// }
// Path: src/name/admitriev/jhelper/actions/BaseAction.java
import com.intellij.notification.NotificationType;
import com.intellij.openapi.actionSystem.AnAction;
import com.intellij.openapi.actionSystem.AnActionEvent;
import name.admitriev.jhelper.exceptions.JHelperException;
import name.admitriev.jhelper.exceptions.NotificationException;
import name.admitriev.jhelper.ui.Notificator;
import org.jetbrains.annotations.NotNull;
package name.admitriev.jhelper.actions;
public abstract class BaseAction extends AnAction {
@Override
public void actionPerformed(@NotNull AnActionEvent e) {
try {
performAction(e);
}
catch (NotificationException exception) {
Notificator.showNotification(
exception.getTitle(),
exception.getContent(),
NotificationType.ERROR
);
} | catch (JHelperException exception) { |
AlexeyDmitriev/JHelper | src/name/admitriev/jhelper/generation/FileUtils.java | // Path: src/name/admitriev/jhelper/exceptions/NotificationException.java
// public class NotificationException extends RuntimeException {
// private final String title;
// private final String content;
//
// public NotificationException(String content) {
// this(content, (Throwable) null);
// }
//
// public NotificationException(String content, Throwable cause) {
// super(content, cause);
// title = "";
// this.content = content;
// }
//
// public NotificationException(String title, String content) {
// this(title, content, null);
// }
//
// public NotificationException(String title, String content, Throwable cause) {
// super(title + ": " + content, cause);
// this.title = title;
// this.content = content;
// }
//
// public String getTitle() {
// return title;
// }
//
// public String getContent() {
// return content;
// }
// }
| import com.intellij.openapi.application.ApplicationManager;
import com.intellij.openapi.command.WriteCommandAction;
import com.intellij.openapi.editor.Document;
import com.intellij.openapi.fileEditor.FileDocumentManager;
import com.intellij.openapi.project.Project;
import com.intellij.openapi.util.Computable;
import com.intellij.openapi.util.text.StringUtil;
import com.intellij.openapi.vfs.VirtualFile;
import com.intellij.psi.PsiDocumentManager;
import com.intellij.psi.PsiFile;
import name.admitriev.jhelper.exceptions.NotificationException;
import net.egork.chelper.util.OutputWriter;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
import java.io.IOException; | package name.admitriev.jhelper.generation;
public class FileUtils {
private FileUtils() {
}
public static OutputWriter getOutputWriter(VirtualFile virtualFile, Object requestor) {
try {
return new OutputWriter(virtualFile.getOutputStream(requestor));
}
catch (IOException e) { | // Path: src/name/admitriev/jhelper/exceptions/NotificationException.java
// public class NotificationException extends RuntimeException {
// private final String title;
// private final String content;
//
// public NotificationException(String content) {
// this(content, (Throwable) null);
// }
//
// public NotificationException(String content, Throwable cause) {
// super(content, cause);
// title = "";
// this.content = content;
// }
//
// public NotificationException(String title, String content) {
// this(title, content, null);
// }
//
// public NotificationException(String title, String content, Throwable cause) {
// super(title + ": " + content, cause);
// this.title = title;
// this.content = content;
// }
//
// public String getTitle() {
// return title;
// }
//
// public String getContent() {
// return content;
// }
// }
// Path: src/name/admitriev/jhelper/generation/FileUtils.java
import com.intellij.openapi.application.ApplicationManager;
import com.intellij.openapi.command.WriteCommandAction;
import com.intellij.openapi.editor.Document;
import com.intellij.openapi.fileEditor.FileDocumentManager;
import com.intellij.openapi.project.Project;
import com.intellij.openapi.util.Computable;
import com.intellij.openapi.util.text.StringUtil;
import com.intellij.openapi.vfs.VirtualFile;
import com.intellij.psi.PsiDocumentManager;
import com.intellij.psi.PsiFile;
import name.admitriev.jhelper.exceptions.NotificationException;
import net.egork.chelper.util.OutputWriter;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
import java.io.IOException;
package name.admitriev.jhelper.generation;
public class FileUtils {
private FileUtils() {
}
public static OutputWriter getOutputWriter(VirtualFile virtualFile, Object requestor) {
try {
return new OutputWriter(virtualFile.getOutputStream(requestor));
}
catch (IOException e) { | throw new NotificationException("Couldn't open virtual file to write", e); |
AlexeyDmitriev/JHelper | src/name/admitriev/jhelper/network/SimpleHttpServer.java | // Path: src/name/admitriev/jhelper/ui/Notificator.java
// public class Notificator {
// private static final NotificationGroup GROUP = NotificationGroupManager.getInstance().getNotificationGroup("JHelper");
//
// private Notificator() {
// }
//
// public static void showNotification(String title, String content, NotificationType notificationType) {
// GROUP.createNotification(title, content, notificationType, null).notify(null);
// }
//
// public static void showNotification(String content, NotificationType notificationType) {
// showNotification("", content, notificationType);
// }
// }
| import com.intellij.notification.NotificationType;
import com.intellij.openapi.application.ApplicationManager;
import com.intellij.openapi.application.ModalityState;
import com.intellij.util.Consumer;
import name.admitriev.jhelper.ui.Notificator;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.ServerSocket;
import java.net.Socket;
import java.net.SocketAddress; | package name.admitriev.jhelper.network;
/**
* Simple HTTP Server.
* Passes every request without headers to given Consumer
*/
public class SimpleHttpServer implements Runnable {
private Consumer<String> consumer;
private ServerSocket serverSocket = null;
public SimpleHttpServer(SocketAddress endpoint, Consumer<String> consumer) throws IOException {
serverSocket = new ServerSocket();
serverSocket.bind(endpoint);
this.consumer = consumer;
}
@Override
public void run() {
while (true) {
try {
if (serverSocket.isClosed()) {
return;
}
try (Socket socket = serverSocket.accept()) {
InputStream inputStream = socket.getInputStream();
String request = readFromStream(inputStream);
String[] strings = request.split("\n\n", 2);
//ignore headers
if (strings.length < 2) { | // Path: src/name/admitriev/jhelper/ui/Notificator.java
// public class Notificator {
// private static final NotificationGroup GROUP = NotificationGroupManager.getInstance().getNotificationGroup("JHelper");
//
// private Notificator() {
// }
//
// public static void showNotification(String title, String content, NotificationType notificationType) {
// GROUP.createNotification(title, content, notificationType, null).notify(null);
// }
//
// public static void showNotification(String content, NotificationType notificationType) {
// showNotification("", content, notificationType);
// }
// }
// Path: src/name/admitriev/jhelper/network/SimpleHttpServer.java
import com.intellij.notification.NotificationType;
import com.intellij.openapi.application.ApplicationManager;
import com.intellij.openapi.application.ModalityState;
import com.intellij.util.Consumer;
import name.admitriev.jhelper.ui.Notificator;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.ServerSocket;
import java.net.Socket;
import java.net.SocketAddress;
package name.admitriev.jhelper.network;
/**
* Simple HTTP Server.
* Passes every request without headers to given Consumer
*/
public class SimpleHttpServer implements Runnable {
private Consumer<String> consumer;
private ServerSocket serverSocket = null;
public SimpleHttpServer(SocketAddress endpoint, Consumer<String> consumer) throws IOException {
serverSocket = new ServerSocket();
serverSocket.bind(endpoint);
this.consumer = consumer;
}
@Override
public void run() {
while (true) {
try {
if (serverSocket.isClosed()) {
return;
}
try (Socket socket = serverSocket.accept()) {
InputStream inputStream = socket.getInputStream();
String request = readFromStream(inputStream);
String[] strings = request.split("\n\n", 2);
//ignore headers
if (strings.length < 2) { | Notificator.showNotification( |
AlexeyDmitriev/JHelper | src/name/admitriev/jhelper/ui/FileSelector.java | // Path: src/name/admitriev/jhelper/generation/FileUtils.java
// public class FileUtils {
// private FileUtils() {
// }
//
// public static OutputWriter getOutputWriter(VirtualFile virtualFile, Object requestor) {
// try {
// return new OutputWriter(virtualFile.getOutputStream(requestor));
// }
// catch (IOException e) {
// throw new NotificationException("Couldn't open virtual file to write", e);
// }
// }
//
// @Nullable
// private static VirtualFile findChild(VirtualFile file, @NotNull String child) {
// if (child.equals(".")) {
// return file;
// }
// if (child.equals("..")) {
// return file.getParent();
// }
// return file.findChild(child);
// }
//
// public static VirtualFile findOrCreateByRelativePath(VirtualFile root, String localPath) {
// return ApplicationManager.getApplication().runWriteAction(
// new Computable<VirtualFile>() {
// @Override
// public VirtualFile compute() {
// String path = localPath;
// path = StringUtil.trimStart(path, "/");
// if (path.isEmpty()) {
// return root;
// }
// int index = path.indexOf('/');
// if (index < 0) {
// index = path.length();
// }
// String name = path.substring(0, index);
//
// @Nullable VirtualFile child = findChild(root, name);
// if (child == null) {
// try {
// if (index == path.length()) {
// child = root.createChildData(this, name);
// }
// else {
// child = root.createChildDirectory(this, name);
// }
// }
// catch (IOException e) {
// throw new NotificationException(
// "Couldn't create directory: " + root.getPath() + '/' + name,
// e
// );
// }
// }
// assert child != null;
//
// if (index < path.length()) {
// return findOrCreateByRelativePath(child, path.substring(index + 1));
// }
// return child;
// }
// }
// );
// }
//
// /**
// * Checks if given file is a C++ file.
// * In other words checks if code may be generated for that file
// */
// public static boolean isCppFile(PsiFile file) {
// return file.getName().endsWith(".cpp");
// }
//
// public static void writeToFile(PsiFile outputFile, String... strings) {
// Project project = outputFile.getProject();
// Document document = PsiDocumentManager.getInstance(project).getDocument(outputFile);
// if (document == null) {
// throw new NotificationException("Couldn't open output file as document");
// }
//
// WriteCommandAction.writeCommandAction(project).run(
// () -> {
// document.deleteString(0, document.getTextLength());
// for (String string : strings) {
// document.insertString(document.getTextLength(), string);
// }
// FileDocumentManager.getInstance().saveDocument(document);
// PsiDocumentManager.getInstance(project).commitDocument(document);
// }
// );
// }
//
// public static String relativePath(String parentPath, String childPath) {
// if (!parentPath.endsWith("/")) {
// parentPath += "/";
// }
// if (!isChild(parentPath, childPath)) {
// throw new IllegalArgumentException("childPath should be inside a parentPath");
// }
// // Minimum is needed for case when childPath = parentPath and there's no / at the end of childPath
// return childPath.substring(Math.min(parentPath.length(), childPath.length()));
// }
//
// public static boolean isChild(String parentPath, String childPath) {
// if (!parentPath.endsWith("/")) {
// parentPath += "/";
// }
// if (!childPath.endsWith("/")) {
// childPath += "/";
// }
// return childPath.startsWith(parentPath);
// }
//
// public static String getDirectory(String filePath) {
// int index = filePath.lastIndexOf('/');
// if (index < 0) {
// return ".";
// }
// return filePath.substring(0, index + 1);
// }
//
// public static String getFilename(String filePath) {
// int index = filePath.lastIndexOf('/');
// if (index < 0) {
// return filePath;
// }
// return filePath.substring(index + 1);
// }
// }
| import com.intellij.openapi.fileChooser.FileChooserDescriptor;
import com.intellij.openapi.project.Project;
import com.intellij.openapi.ui.TextBrowseFolderListener;
import com.intellij.openapi.ui.TextFieldWithBrowseButton;
import com.intellij.openapi.vfs.VirtualFile;
import name.admitriev.jhelper.generation.FileUtils;
import org.jetbrains.annotations.NotNull;
import javax.swing.*; | package name.admitriev.jhelper.ui;
public class FileSelector extends TextFieldWithBrowseButton.NoPathCompletion {
public FileSelector(Project project, String initialValue, FileChooserDescriptor descriptor) {
super(new JTextField(initialValue));
addBrowseFolderListener(
new RelativePathBrowseListener(descriptor, project)
);
installPathCompletion(descriptor);
}
private static class RelativePathBrowseListener extends TextBrowseFolderListener {
private final String basePath;
private RelativePathBrowseListener(FileChooserDescriptor descriptor, Project project) {
super(descriptor, project);
basePath = project.getBasePath();
}
@NotNull
@Override
protected String chosenFileToResultingText(@NotNull VirtualFile chosenFile) { | // Path: src/name/admitriev/jhelper/generation/FileUtils.java
// public class FileUtils {
// private FileUtils() {
// }
//
// public static OutputWriter getOutputWriter(VirtualFile virtualFile, Object requestor) {
// try {
// return new OutputWriter(virtualFile.getOutputStream(requestor));
// }
// catch (IOException e) {
// throw new NotificationException("Couldn't open virtual file to write", e);
// }
// }
//
// @Nullable
// private static VirtualFile findChild(VirtualFile file, @NotNull String child) {
// if (child.equals(".")) {
// return file;
// }
// if (child.equals("..")) {
// return file.getParent();
// }
// return file.findChild(child);
// }
//
// public static VirtualFile findOrCreateByRelativePath(VirtualFile root, String localPath) {
// return ApplicationManager.getApplication().runWriteAction(
// new Computable<VirtualFile>() {
// @Override
// public VirtualFile compute() {
// String path = localPath;
// path = StringUtil.trimStart(path, "/");
// if (path.isEmpty()) {
// return root;
// }
// int index = path.indexOf('/');
// if (index < 0) {
// index = path.length();
// }
// String name = path.substring(0, index);
//
// @Nullable VirtualFile child = findChild(root, name);
// if (child == null) {
// try {
// if (index == path.length()) {
// child = root.createChildData(this, name);
// }
// else {
// child = root.createChildDirectory(this, name);
// }
// }
// catch (IOException e) {
// throw new NotificationException(
// "Couldn't create directory: " + root.getPath() + '/' + name,
// e
// );
// }
// }
// assert child != null;
//
// if (index < path.length()) {
// return findOrCreateByRelativePath(child, path.substring(index + 1));
// }
// return child;
// }
// }
// );
// }
//
// /**
// * Checks if given file is a C++ file.
// * In other words checks if code may be generated for that file
// */
// public static boolean isCppFile(PsiFile file) {
// return file.getName().endsWith(".cpp");
// }
//
// public static void writeToFile(PsiFile outputFile, String... strings) {
// Project project = outputFile.getProject();
// Document document = PsiDocumentManager.getInstance(project).getDocument(outputFile);
// if (document == null) {
// throw new NotificationException("Couldn't open output file as document");
// }
//
// WriteCommandAction.writeCommandAction(project).run(
// () -> {
// document.deleteString(0, document.getTextLength());
// for (String string : strings) {
// document.insertString(document.getTextLength(), string);
// }
// FileDocumentManager.getInstance().saveDocument(document);
// PsiDocumentManager.getInstance(project).commitDocument(document);
// }
// );
// }
//
// public static String relativePath(String parentPath, String childPath) {
// if (!parentPath.endsWith("/")) {
// parentPath += "/";
// }
// if (!isChild(parentPath, childPath)) {
// throw new IllegalArgumentException("childPath should be inside a parentPath");
// }
// // Minimum is needed for case when childPath = parentPath and there's no / at the end of childPath
// return childPath.substring(Math.min(parentPath.length(), childPath.length()));
// }
//
// public static boolean isChild(String parentPath, String childPath) {
// if (!parentPath.endsWith("/")) {
// parentPath += "/";
// }
// if (!childPath.endsWith("/")) {
// childPath += "/";
// }
// return childPath.startsWith(parentPath);
// }
//
// public static String getDirectory(String filePath) {
// int index = filePath.lastIndexOf('/');
// if (index < 0) {
// return ".";
// }
// return filePath.substring(0, index + 1);
// }
//
// public static String getFilename(String filePath) {
// int index = filePath.lastIndexOf('/');
// if (index < 0) {
// return filePath;
// }
// return filePath.substring(index + 1);
// }
// }
// Path: src/name/admitriev/jhelper/ui/FileSelector.java
import com.intellij.openapi.fileChooser.FileChooserDescriptor;
import com.intellij.openapi.project.Project;
import com.intellij.openapi.ui.TextBrowseFolderListener;
import com.intellij.openapi.ui.TextFieldWithBrowseButton;
import com.intellij.openapi.vfs.VirtualFile;
import name.admitriev.jhelper.generation.FileUtils;
import org.jetbrains.annotations.NotNull;
import javax.swing.*;
package name.admitriev.jhelper.ui;
public class FileSelector extends TextFieldWithBrowseButton.NoPathCompletion {
public FileSelector(Project project, String initialValue, FileChooserDescriptor descriptor) {
super(new JTextField(initialValue));
addBrowseFolderListener(
new RelativePathBrowseListener(descriptor, project)
);
installPathCompletion(descriptor);
}
private static class RelativePathBrowseListener extends TextBrowseFolderListener {
private final String basePath;
private RelativePathBrowseListener(FileChooserDescriptor descriptor, Project project) {
super(descriptor, project);
basePath = project.getBasePath();
}
@NotNull
@Override
protected String chosenFileToResultingText(@NotNull VirtualFile chosenFile) { | return FileUtils.relativePath(basePath, chosenFile.getPath()); |
AlexeyDmitriev/JHelper | src/name/admitriev/jhelper/ui/RelativeFileChooserDescriptor.java | // Path: src/name/admitriev/jhelper/generation/FileUtils.java
// public class FileUtils {
// private FileUtils() {
// }
//
// public static OutputWriter getOutputWriter(VirtualFile virtualFile, Object requestor) {
// try {
// return new OutputWriter(virtualFile.getOutputStream(requestor));
// }
// catch (IOException e) {
// throw new NotificationException("Couldn't open virtual file to write", e);
// }
// }
//
// @Nullable
// private static VirtualFile findChild(VirtualFile file, @NotNull String child) {
// if (child.equals(".")) {
// return file;
// }
// if (child.equals("..")) {
// return file.getParent();
// }
// return file.findChild(child);
// }
//
// public static VirtualFile findOrCreateByRelativePath(VirtualFile root, String localPath) {
// return ApplicationManager.getApplication().runWriteAction(
// new Computable<VirtualFile>() {
// @Override
// public VirtualFile compute() {
// String path = localPath;
// path = StringUtil.trimStart(path, "/");
// if (path.isEmpty()) {
// return root;
// }
// int index = path.indexOf('/');
// if (index < 0) {
// index = path.length();
// }
// String name = path.substring(0, index);
//
// @Nullable VirtualFile child = findChild(root, name);
// if (child == null) {
// try {
// if (index == path.length()) {
// child = root.createChildData(this, name);
// }
// else {
// child = root.createChildDirectory(this, name);
// }
// }
// catch (IOException e) {
// throw new NotificationException(
// "Couldn't create directory: " + root.getPath() + '/' + name,
// e
// );
// }
// }
// assert child != null;
//
// if (index < path.length()) {
// return findOrCreateByRelativePath(child, path.substring(index + 1));
// }
// return child;
// }
// }
// );
// }
//
// /**
// * Checks if given file is a C++ file.
// * In other words checks if code may be generated for that file
// */
// public static boolean isCppFile(PsiFile file) {
// return file.getName().endsWith(".cpp");
// }
//
// public static void writeToFile(PsiFile outputFile, String... strings) {
// Project project = outputFile.getProject();
// Document document = PsiDocumentManager.getInstance(project).getDocument(outputFile);
// if (document == null) {
// throw new NotificationException("Couldn't open output file as document");
// }
//
// WriteCommandAction.writeCommandAction(project).run(
// () -> {
// document.deleteString(0, document.getTextLength());
// for (String string : strings) {
// document.insertString(document.getTextLength(), string);
// }
// FileDocumentManager.getInstance().saveDocument(document);
// PsiDocumentManager.getInstance(project).commitDocument(document);
// }
// );
// }
//
// public static String relativePath(String parentPath, String childPath) {
// if (!parentPath.endsWith("/")) {
// parentPath += "/";
// }
// if (!isChild(parentPath, childPath)) {
// throw new IllegalArgumentException("childPath should be inside a parentPath");
// }
// // Minimum is needed for case when childPath = parentPath and there's no / at the end of childPath
// return childPath.substring(Math.min(parentPath.length(), childPath.length()));
// }
//
// public static boolean isChild(String parentPath, String childPath) {
// if (!parentPath.endsWith("/")) {
// parentPath += "/";
// }
// if (!childPath.endsWith("/")) {
// childPath += "/";
// }
// return childPath.startsWith(parentPath);
// }
//
// public static String getDirectory(String filePath) {
// int index = filePath.lastIndexOf('/');
// if (index < 0) {
// return ".";
// }
// return filePath.substring(0, index + 1);
// }
//
// public static String getFilename(String filePath) {
// int index = filePath.lastIndexOf('/');
// if (index < 0) {
// return filePath;
// }
// return filePath.substring(index + 1);
// }
// }
| import com.intellij.openapi.fileChooser.FileChooserDescriptor;
import com.intellij.openapi.vfs.VirtualFile;
import name.admitriev.jhelper.generation.FileUtils; | package name.admitriev.jhelper.ui;
public class RelativeFileChooserDescriptor extends FileChooserDescriptor {
private String basePath;
private RelativeFileChooserDescriptor(
VirtualFile baseDir,
boolean chooseFiles,
boolean chooseFolders
) {
super(chooseFiles, chooseFolders, false, false, false, false);
basePath = baseDir.getPath();
withShowHiddenFiles(true);
setRoots(baseDir);
}
@Override
public boolean isFileSelectable(VirtualFile file) { | // Path: src/name/admitriev/jhelper/generation/FileUtils.java
// public class FileUtils {
// private FileUtils() {
// }
//
// public static OutputWriter getOutputWriter(VirtualFile virtualFile, Object requestor) {
// try {
// return new OutputWriter(virtualFile.getOutputStream(requestor));
// }
// catch (IOException e) {
// throw new NotificationException("Couldn't open virtual file to write", e);
// }
// }
//
// @Nullable
// private static VirtualFile findChild(VirtualFile file, @NotNull String child) {
// if (child.equals(".")) {
// return file;
// }
// if (child.equals("..")) {
// return file.getParent();
// }
// return file.findChild(child);
// }
//
// public static VirtualFile findOrCreateByRelativePath(VirtualFile root, String localPath) {
// return ApplicationManager.getApplication().runWriteAction(
// new Computable<VirtualFile>() {
// @Override
// public VirtualFile compute() {
// String path = localPath;
// path = StringUtil.trimStart(path, "/");
// if (path.isEmpty()) {
// return root;
// }
// int index = path.indexOf('/');
// if (index < 0) {
// index = path.length();
// }
// String name = path.substring(0, index);
//
// @Nullable VirtualFile child = findChild(root, name);
// if (child == null) {
// try {
// if (index == path.length()) {
// child = root.createChildData(this, name);
// }
// else {
// child = root.createChildDirectory(this, name);
// }
// }
// catch (IOException e) {
// throw new NotificationException(
// "Couldn't create directory: " + root.getPath() + '/' + name,
// e
// );
// }
// }
// assert child != null;
//
// if (index < path.length()) {
// return findOrCreateByRelativePath(child, path.substring(index + 1));
// }
// return child;
// }
// }
// );
// }
//
// /**
// * Checks if given file is a C++ file.
// * In other words checks if code may be generated for that file
// */
// public static boolean isCppFile(PsiFile file) {
// return file.getName().endsWith(".cpp");
// }
//
// public static void writeToFile(PsiFile outputFile, String... strings) {
// Project project = outputFile.getProject();
// Document document = PsiDocumentManager.getInstance(project).getDocument(outputFile);
// if (document == null) {
// throw new NotificationException("Couldn't open output file as document");
// }
//
// WriteCommandAction.writeCommandAction(project).run(
// () -> {
// document.deleteString(0, document.getTextLength());
// for (String string : strings) {
// document.insertString(document.getTextLength(), string);
// }
// FileDocumentManager.getInstance().saveDocument(document);
// PsiDocumentManager.getInstance(project).commitDocument(document);
// }
// );
// }
//
// public static String relativePath(String parentPath, String childPath) {
// if (!parentPath.endsWith("/")) {
// parentPath += "/";
// }
// if (!isChild(parentPath, childPath)) {
// throw new IllegalArgumentException("childPath should be inside a parentPath");
// }
// // Minimum is needed for case when childPath = parentPath and there's no / at the end of childPath
// return childPath.substring(Math.min(parentPath.length(), childPath.length()));
// }
//
// public static boolean isChild(String parentPath, String childPath) {
// if (!parentPath.endsWith("/")) {
// parentPath += "/";
// }
// if (!childPath.endsWith("/")) {
// childPath += "/";
// }
// return childPath.startsWith(parentPath);
// }
//
// public static String getDirectory(String filePath) {
// int index = filePath.lastIndexOf('/');
// if (index < 0) {
// return ".";
// }
// return filePath.substring(0, index + 1);
// }
//
// public static String getFilename(String filePath) {
// int index = filePath.lastIndexOf('/');
// if (index < 0) {
// return filePath;
// }
// return filePath.substring(index + 1);
// }
// }
// Path: src/name/admitriev/jhelper/ui/RelativeFileChooserDescriptor.java
import com.intellij.openapi.fileChooser.FileChooserDescriptor;
import com.intellij.openapi.vfs.VirtualFile;
import name.admitriev.jhelper.generation.FileUtils;
package name.admitriev.jhelper.ui;
public class RelativeFileChooserDescriptor extends FileChooserDescriptor {
private String basePath;
private RelativeFileChooserDescriptor(
VirtualFile baseDir,
boolean chooseFiles,
boolean chooseFolders
) {
super(chooseFiles, chooseFolders, false, false, false, false);
basePath = baseDir.getPath();
withShowHiddenFiles(true);
setRoots(baseDir);
}
@Override
public boolean isFileSelectable(VirtualFile file) { | return super.isFileSelectable(file) && FileUtils.isChild( |
AlexeyDmitriev/JHelper | src/name/admitriev/jhelper/generation/TemplatesUtils.java | // Path: src/name/admitriev/jhelper/exceptions/JHelperException.java
// public class JHelperException extends RuntimeException {
//
// public JHelperException(String message, Throwable cause) {
// super(message, cause);
// }
//
// public JHelperException(String message) {
// super(message);
// }
//
// @Override
// public String getMessage() {
// return "Please, report that bug to issue tracker on https://github.com/AlexeyDmitriev/JHelper . Attach your code and this stack trace. "
// + super.getMessage();
// }
// }
//
// Path: src/name/admitriev/jhelper/exceptions/NotificationException.java
// public class NotificationException extends RuntimeException {
// private final String title;
// private final String content;
//
// public NotificationException(String content) {
// this(content, (Throwable) null);
// }
//
// public NotificationException(String content, Throwable cause) {
// super(content, cause);
// title = "";
// this.content = content;
// }
//
// public NotificationException(String title, String content) {
// this(title, content, null);
// }
//
// public NotificationException(String title, String content, Throwable cause) {
// super(title + ": " + content, cause);
// this.title = title;
// this.content = content;
// }
//
// public String getTitle() {
// return title;
// }
//
// public String getContent() {
// return content;
// }
// }
| import com.intellij.openapi.editor.Document;
import com.intellij.openapi.fileEditor.FileDocumentManager;
import com.intellij.openapi.project.Project;
import com.intellij.openapi.vfs.VirtualFile;
import com.intellij.psi.PsiFile;
import com.intellij.psi.PsiManager;
import name.admitriev.jhelper.exceptions.JHelperException;
import name.admitriev.jhelper.exceptions.NotificationException;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.regex.Matcher;
import java.util.regex.Pattern; | package name.admitriev.jhelper.generation;
/**
* Utility class for customizing templates of code
*/
public class TemplatesUtils {
public static final Pattern CLASS_NAME = Pattern.compile("%ClassName%", Pattern.LITERAL);
public static final Pattern TASK_FILE = Pattern.compile("%TaskFile%", Pattern.LITERAL);
public static final Pattern TESTS = Pattern.compile("%Tests%", Pattern.LITERAL);
public static final Pattern SOLVER_CALL = Pattern.compile("%SolverCall%", Pattern.LITERAL);
public static final Pattern INPUT = Pattern.compile("%Input%", Pattern.LITERAL);
public static final Pattern OUTPUT = Pattern.compile("%Output%", Pattern.LITERAL);
public static final Pattern CODE = Pattern.compile("%Code%", Pattern.LITERAL);
private TemplatesUtils() {
}
public static String replaceAll(String text, Pattern pattern, String replacement) {
return pattern.matcher(text).replaceAll(Matcher.quoteReplacement(replacement));
}
public static String getTemplate(Project project, String name) {
String filename = name + ".template";
VirtualFile file = project.getBaseDir().findFileByRelativePath(filename);
if (file == null) {
createTemplateFromDefault(project, name);
file = project.getBaseDir().findFileByRelativePath(filename);
if (file == null) { | // Path: src/name/admitriev/jhelper/exceptions/JHelperException.java
// public class JHelperException extends RuntimeException {
//
// public JHelperException(String message, Throwable cause) {
// super(message, cause);
// }
//
// public JHelperException(String message) {
// super(message);
// }
//
// @Override
// public String getMessage() {
// return "Please, report that bug to issue tracker on https://github.com/AlexeyDmitriev/JHelper . Attach your code and this stack trace. "
// + super.getMessage();
// }
// }
//
// Path: src/name/admitriev/jhelper/exceptions/NotificationException.java
// public class NotificationException extends RuntimeException {
// private final String title;
// private final String content;
//
// public NotificationException(String content) {
// this(content, (Throwable) null);
// }
//
// public NotificationException(String content, Throwable cause) {
// super(content, cause);
// title = "";
// this.content = content;
// }
//
// public NotificationException(String title, String content) {
// this(title, content, null);
// }
//
// public NotificationException(String title, String content, Throwable cause) {
// super(title + ": " + content, cause);
// this.title = title;
// this.content = content;
// }
//
// public String getTitle() {
// return title;
// }
//
// public String getContent() {
// return content;
// }
// }
// Path: src/name/admitriev/jhelper/generation/TemplatesUtils.java
import com.intellij.openapi.editor.Document;
import com.intellij.openapi.fileEditor.FileDocumentManager;
import com.intellij.openapi.project.Project;
import com.intellij.openapi.vfs.VirtualFile;
import com.intellij.psi.PsiFile;
import com.intellij.psi.PsiManager;
import name.admitriev.jhelper.exceptions.JHelperException;
import name.admitriev.jhelper.exceptions.NotificationException;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
package name.admitriev.jhelper.generation;
/**
* Utility class for customizing templates of code
*/
public class TemplatesUtils {
public static final Pattern CLASS_NAME = Pattern.compile("%ClassName%", Pattern.LITERAL);
public static final Pattern TASK_FILE = Pattern.compile("%TaskFile%", Pattern.LITERAL);
public static final Pattern TESTS = Pattern.compile("%Tests%", Pattern.LITERAL);
public static final Pattern SOLVER_CALL = Pattern.compile("%SolverCall%", Pattern.LITERAL);
public static final Pattern INPUT = Pattern.compile("%Input%", Pattern.LITERAL);
public static final Pattern OUTPUT = Pattern.compile("%Output%", Pattern.LITERAL);
public static final Pattern CODE = Pattern.compile("%Code%", Pattern.LITERAL);
private TemplatesUtils() {
}
public static String replaceAll(String text, Pattern pattern, String replacement) {
return pattern.matcher(text).replaceAll(Matcher.quoteReplacement(replacement));
}
public static String getTemplate(Project project, String name) {
String filename = name + ".template";
VirtualFile file = project.getBaseDir().findFileByRelativePath(filename);
if (file == null) {
createTemplateFromDefault(project, name);
file = project.getBaseDir().findFileByRelativePath(filename);
if (file == null) { | throw new JHelperException("Can't open template file(" + filename + ") after its creation"); |
AlexeyDmitriev/JHelper | src/name/admitriev/jhelper/generation/TemplatesUtils.java | // Path: src/name/admitriev/jhelper/exceptions/JHelperException.java
// public class JHelperException extends RuntimeException {
//
// public JHelperException(String message, Throwable cause) {
// super(message, cause);
// }
//
// public JHelperException(String message) {
// super(message);
// }
//
// @Override
// public String getMessage() {
// return "Please, report that bug to issue tracker on https://github.com/AlexeyDmitriev/JHelper . Attach your code and this stack trace. "
// + super.getMessage();
// }
// }
//
// Path: src/name/admitriev/jhelper/exceptions/NotificationException.java
// public class NotificationException extends RuntimeException {
// private final String title;
// private final String content;
//
// public NotificationException(String content) {
// this(content, (Throwable) null);
// }
//
// public NotificationException(String content, Throwable cause) {
// super(content, cause);
// title = "";
// this.content = content;
// }
//
// public NotificationException(String title, String content) {
// this(title, content, null);
// }
//
// public NotificationException(String title, String content, Throwable cause) {
// super(title + ": " + content, cause);
// this.title = title;
// this.content = content;
// }
//
// public String getTitle() {
// return title;
// }
//
// public String getContent() {
// return content;
// }
// }
| import com.intellij.openapi.editor.Document;
import com.intellij.openapi.fileEditor.FileDocumentManager;
import com.intellij.openapi.project.Project;
import com.intellij.openapi.vfs.VirtualFile;
import com.intellij.psi.PsiFile;
import com.intellij.psi.PsiManager;
import name.admitriev.jhelper.exceptions.JHelperException;
import name.admitriev.jhelper.exceptions.NotificationException;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.regex.Matcher;
import java.util.regex.Pattern; | package name.admitriev.jhelper.generation;
/**
* Utility class for customizing templates of code
*/
public class TemplatesUtils {
public static final Pattern CLASS_NAME = Pattern.compile("%ClassName%", Pattern.LITERAL);
public static final Pattern TASK_FILE = Pattern.compile("%TaskFile%", Pattern.LITERAL);
public static final Pattern TESTS = Pattern.compile("%Tests%", Pattern.LITERAL);
public static final Pattern SOLVER_CALL = Pattern.compile("%SolverCall%", Pattern.LITERAL);
public static final Pattern INPUT = Pattern.compile("%Input%", Pattern.LITERAL);
public static final Pattern OUTPUT = Pattern.compile("%Output%", Pattern.LITERAL);
public static final Pattern CODE = Pattern.compile("%Code%", Pattern.LITERAL);
private TemplatesUtils() {
}
public static String replaceAll(String text, Pattern pattern, String replacement) {
return pattern.matcher(text).replaceAll(Matcher.quoteReplacement(replacement));
}
public static String getTemplate(Project project, String name) {
String filename = name + ".template";
VirtualFile file = project.getBaseDir().findFileByRelativePath(filename);
if (file == null) {
createTemplateFromDefault(project, name);
file = project.getBaseDir().findFileByRelativePath(filename);
if (file == null) {
throw new JHelperException("Can't open template file(" + filename + ") after its creation");
}
}
Document document = FileDocumentManager.getInstance().getDocument(file);
if (document == null) { | // Path: src/name/admitriev/jhelper/exceptions/JHelperException.java
// public class JHelperException extends RuntimeException {
//
// public JHelperException(String message, Throwable cause) {
// super(message, cause);
// }
//
// public JHelperException(String message) {
// super(message);
// }
//
// @Override
// public String getMessage() {
// return "Please, report that bug to issue tracker on https://github.com/AlexeyDmitriev/JHelper . Attach your code and this stack trace. "
// + super.getMessage();
// }
// }
//
// Path: src/name/admitriev/jhelper/exceptions/NotificationException.java
// public class NotificationException extends RuntimeException {
// private final String title;
// private final String content;
//
// public NotificationException(String content) {
// this(content, (Throwable) null);
// }
//
// public NotificationException(String content, Throwable cause) {
// super(content, cause);
// title = "";
// this.content = content;
// }
//
// public NotificationException(String title, String content) {
// this(title, content, null);
// }
//
// public NotificationException(String title, String content, Throwable cause) {
// super(title + ": " + content, cause);
// this.title = title;
// this.content = content;
// }
//
// public String getTitle() {
// return title;
// }
//
// public String getContent() {
// return content;
// }
// }
// Path: src/name/admitriev/jhelper/generation/TemplatesUtils.java
import com.intellij.openapi.editor.Document;
import com.intellij.openapi.fileEditor.FileDocumentManager;
import com.intellij.openapi.project.Project;
import com.intellij.openapi.vfs.VirtualFile;
import com.intellij.psi.PsiFile;
import com.intellij.psi.PsiManager;
import name.admitriev.jhelper.exceptions.JHelperException;
import name.admitriev.jhelper.exceptions.NotificationException;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
package name.admitriev.jhelper.generation;
/**
* Utility class for customizing templates of code
*/
public class TemplatesUtils {
public static final Pattern CLASS_NAME = Pattern.compile("%ClassName%", Pattern.LITERAL);
public static final Pattern TASK_FILE = Pattern.compile("%TaskFile%", Pattern.LITERAL);
public static final Pattern TESTS = Pattern.compile("%Tests%", Pattern.LITERAL);
public static final Pattern SOLVER_CALL = Pattern.compile("%SolverCall%", Pattern.LITERAL);
public static final Pattern INPUT = Pattern.compile("%Input%", Pattern.LITERAL);
public static final Pattern OUTPUT = Pattern.compile("%Output%", Pattern.LITERAL);
public static final Pattern CODE = Pattern.compile("%Code%", Pattern.LITERAL);
private TemplatesUtils() {
}
public static String replaceAll(String text, Pattern pattern, String replacement) {
return pattern.matcher(text).replaceAll(Matcher.quoteReplacement(replacement));
}
public static String getTemplate(Project project, String name) {
String filename = name + ".template";
VirtualFile file = project.getBaseDir().findFileByRelativePath(filename);
if (file == null) {
createTemplateFromDefault(project, name);
file = project.getBaseDir().findFileByRelativePath(filename);
if (file == null) {
throw new JHelperException("Can't open template file(" + filename + ") after its creation");
}
}
Document document = FileDocumentManager.getInstance().getDocument(file);
if (document == null) { | throw new NotificationException("Couldn't find template \"" + name + '"'); |
AlexeyDmitriev/JHelper | src/name/admitriev/jhelper/ui/TaskSettingsComponent.java | // Path: src/name/admitriev/jhelper/task/TaskData.java
// public class TaskData {
// private final String name;
// private final String className;
// private final String cppPath;
// private final StreamConfiguration input;
// private final StreamConfiguration output;
// private final TestType testType;
// private final Test[] tests;
//
// public TaskData(
// String name,
// String className,
// String cppPath,
// StreamConfiguration input,
// StreamConfiguration output,
// TestType testType,
// Test[] tests
// ) {
// this.input = input;
// this.output = output;
// this.name = name;
// this.className = className;
// this.cppPath = cppPath;
// this.testType = testType;
// this.tests = Arrays.copyOf(tests, tests.length);
// }
//
// public TaskData(TaskData task) {
// this(task.name, task.className, task.cppPath, task.input, task.output, task.testType, task.tests);
// }
//
// public String getName() {
// return name;
// }
//
// public String getClassName() {
// return className;
// }
//
// public String getCppPath() {
// return cppPath;
// }
//
// public StreamConfiguration getInput() {
// return input;
// }
//
// public StreamConfiguration getOutput() {
// return output;
// }
//
// public Test[] getTests() {
// return Arrays.copyOf(tests, tests.length);
// }
//
// public static TaskData emptyTaskData(Project project) {
// return new TaskData(
// "",
// "",
// String.format(defaultCppPathFormat(project), ""),
// StreamConfiguration.STANDARD,
// StreamConfiguration.STANDARD,
// TestType.SINGLE,
// new Test[0]
// );
// }
//
// public static String defaultCppPathFormat(Project project) {
// Configurator configurator = project.getService(Configurator.class);
// Configurator.State configuration = configurator.getState();
// String path = configuration.getTasksDirectory();
// return path + "/%s.cpp";
// }
//
// public TestType getTestType() {
// return testType;
// }
//
// }
| import com.intellij.openapi.project.Project;
import com.intellij.openapi.ui.ComboBox;
import com.intellij.openapi.ui.LabeledComponent;
import name.admitriev.jhelper.task.TaskData;
import net.egork.chelper.task.StreamConfiguration;
import net.egork.chelper.task.Test;
import net.egork.chelper.task.TestType;
import org.jdesktop.swingx.VerticalLayout;
import javax.swing.*; | package name.admitriev.jhelper.ui;
/**
* Panel for task configuration.
*/
public final class TaskSettingsComponent extends JPanel {
private JTextField name = null;
private JTextField className = null;
private FileSelector cppPath = null;
private StreamConfigurationPanel input = null;
private StreamConfigurationPanel output = null;
private ComboBox<TestType> testType = null;
private final boolean canChangeName;
private Project project;
private StreamConfigurationPanel.SizeChangedListener listener;
public TaskSettingsComponent(Project project, boolean canChangeName) {
this(project, canChangeName, null);
}
public TaskSettingsComponent(Project project, boolean canChangeName, StreamConfigurationPanel.SizeChangedListener listener) {
super(new VerticalLayout());
this.project = project;
this.listener = listener;
this.canChangeName = canChangeName;
| // Path: src/name/admitriev/jhelper/task/TaskData.java
// public class TaskData {
// private final String name;
// private final String className;
// private final String cppPath;
// private final StreamConfiguration input;
// private final StreamConfiguration output;
// private final TestType testType;
// private final Test[] tests;
//
// public TaskData(
// String name,
// String className,
// String cppPath,
// StreamConfiguration input,
// StreamConfiguration output,
// TestType testType,
// Test[] tests
// ) {
// this.input = input;
// this.output = output;
// this.name = name;
// this.className = className;
// this.cppPath = cppPath;
// this.testType = testType;
// this.tests = Arrays.copyOf(tests, tests.length);
// }
//
// public TaskData(TaskData task) {
// this(task.name, task.className, task.cppPath, task.input, task.output, task.testType, task.tests);
// }
//
// public String getName() {
// return name;
// }
//
// public String getClassName() {
// return className;
// }
//
// public String getCppPath() {
// return cppPath;
// }
//
// public StreamConfiguration getInput() {
// return input;
// }
//
// public StreamConfiguration getOutput() {
// return output;
// }
//
// public Test[] getTests() {
// return Arrays.copyOf(tests, tests.length);
// }
//
// public static TaskData emptyTaskData(Project project) {
// return new TaskData(
// "",
// "",
// String.format(defaultCppPathFormat(project), ""),
// StreamConfiguration.STANDARD,
// StreamConfiguration.STANDARD,
// TestType.SINGLE,
// new Test[0]
// );
// }
//
// public static String defaultCppPathFormat(Project project) {
// Configurator configurator = project.getService(Configurator.class);
// Configurator.State configuration = configurator.getState();
// String path = configuration.getTasksDirectory();
// return path + "/%s.cpp";
// }
//
// public TestType getTestType() {
// return testType;
// }
//
// }
// Path: src/name/admitriev/jhelper/ui/TaskSettingsComponent.java
import com.intellij.openapi.project.Project;
import com.intellij.openapi.ui.ComboBox;
import com.intellij.openapi.ui.LabeledComponent;
import name.admitriev.jhelper.task.TaskData;
import net.egork.chelper.task.StreamConfiguration;
import net.egork.chelper.task.Test;
import net.egork.chelper.task.TestType;
import org.jdesktop.swingx.VerticalLayout;
import javax.swing.*;
package name.admitriev.jhelper.ui;
/**
* Panel for task configuration.
*/
public final class TaskSettingsComponent extends JPanel {
private JTextField name = null;
private JTextField className = null;
private FileSelector cppPath = null;
private StreamConfigurationPanel input = null;
private StreamConfigurationPanel output = null;
private ComboBox<TestType> testType = null;
private final boolean canChangeName;
private Project project;
private StreamConfigurationPanel.SizeChangedListener listener;
public TaskSettingsComponent(Project project, boolean canChangeName) {
this(project, canChangeName, null);
}
public TaskSettingsComponent(Project project, boolean canChangeName, StreamConfigurationPanel.SizeChangedListener listener) {
super(new VerticalLayout());
this.project = project;
this.listener = listener;
this.canChangeName = canChangeName;
| setTaskData(TaskData.emptyTaskData(project)); |
AlexeyDmitriev/JHelper | src/name/admitriev/jhelper/task/TaskData.java | // Path: src/name/admitriev/jhelper/components/Configurator.java
// @State(name = "Configurator", storages = @Storage("JHelper.xml"))
// @Service(Service.Level.PROJECT)
// public final class Configurator implements PersistentStateComponent<Configurator.State> {
// public Configurator() {
// state = new Configurator.State();
// }
//
// @Override
// public @NotNull Configurator.State getState() {
// return state;
// }
//
// @SuppressWarnings("ParameterHidesMemberVariable")
// @Override
// public void loadState(@NotNull Configurator.State state) {
// this.state = state;
// }
//
// private Configurator.State state;
//
// public static class State {
// private String author;
// private String tasksDirectory;
// private String outputFile;
// private String runFile;
// private boolean codeEliminationOn;
// private boolean codeReformattingOn;
//
// public State(
// String author,
// String tasksDirectory,
// String outputFile,
// String runFile,
// boolean codeEliminationOn,
// boolean codeReformattingOn
// ) {
// this.author = author;
// this.tasksDirectory = tasksDirectory;
// this.outputFile = outputFile;
// this.runFile = runFile;
// this.codeEliminationOn = codeEliminationOn;
// this.codeReformattingOn = codeReformattingOn;
// }
//
// public State() {
// this("", "tasks", "output/main.cpp", "testrunner/main.cpp", false, false);
// }
//
// public String getAuthor() {
// return author;
// }
//
// public String getTasksDirectory() {
// return tasksDirectory;
// }
//
// public String getOutputFile() {
// return outputFile;
// }
//
// public String getRunFile() {
// return runFile;
// }
//
// public boolean isCodeEliminationOn() {
// return codeEliminationOn;
// }
//
// public boolean isCodeReformattingOn() {
// return codeReformattingOn;
// }
//
// @Deprecated
// public void setAuthor(String author) {
// this.author = author;
// }
//
// @Deprecated
// public void setTasksDirectory(String tasksDirectory) {
// this.tasksDirectory = tasksDirectory;
// }
//
// @Deprecated
// public void setOutputFile(String outputFile) {
// this.outputFile = outputFile;
// }
//
// @Deprecated
// public void setRunFile(String runFile) {
// this.runFile = runFile;
// }
//
// @Deprecated
// public void setCodeEliminationOn(boolean codeEliminationOn) {
// this.codeEliminationOn = codeEliminationOn;
// }
//
// @Deprecated
// public void setCodeReformattingOn(boolean codeReformattingOn) {
// this.codeReformattingOn = codeReformattingOn;
// }
// }
// }
| import com.intellij.openapi.project.Project;
import name.admitriev.jhelper.components.Configurator;
import net.egork.chelper.task.StreamConfiguration;
import net.egork.chelper.task.Test;
import net.egork.chelper.task.TestType;
import java.util.Arrays; |
public String getCppPath() {
return cppPath;
}
public StreamConfiguration getInput() {
return input;
}
public StreamConfiguration getOutput() {
return output;
}
public Test[] getTests() {
return Arrays.copyOf(tests, tests.length);
}
public static TaskData emptyTaskData(Project project) {
return new TaskData(
"",
"",
String.format(defaultCppPathFormat(project), ""),
StreamConfiguration.STANDARD,
StreamConfiguration.STANDARD,
TestType.SINGLE,
new Test[0]
);
}
public static String defaultCppPathFormat(Project project) { | // Path: src/name/admitriev/jhelper/components/Configurator.java
// @State(name = "Configurator", storages = @Storage("JHelper.xml"))
// @Service(Service.Level.PROJECT)
// public final class Configurator implements PersistentStateComponent<Configurator.State> {
// public Configurator() {
// state = new Configurator.State();
// }
//
// @Override
// public @NotNull Configurator.State getState() {
// return state;
// }
//
// @SuppressWarnings("ParameterHidesMemberVariable")
// @Override
// public void loadState(@NotNull Configurator.State state) {
// this.state = state;
// }
//
// private Configurator.State state;
//
// public static class State {
// private String author;
// private String tasksDirectory;
// private String outputFile;
// private String runFile;
// private boolean codeEliminationOn;
// private boolean codeReformattingOn;
//
// public State(
// String author,
// String tasksDirectory,
// String outputFile,
// String runFile,
// boolean codeEliminationOn,
// boolean codeReformattingOn
// ) {
// this.author = author;
// this.tasksDirectory = tasksDirectory;
// this.outputFile = outputFile;
// this.runFile = runFile;
// this.codeEliminationOn = codeEliminationOn;
// this.codeReformattingOn = codeReformattingOn;
// }
//
// public State() {
// this("", "tasks", "output/main.cpp", "testrunner/main.cpp", false, false);
// }
//
// public String getAuthor() {
// return author;
// }
//
// public String getTasksDirectory() {
// return tasksDirectory;
// }
//
// public String getOutputFile() {
// return outputFile;
// }
//
// public String getRunFile() {
// return runFile;
// }
//
// public boolean isCodeEliminationOn() {
// return codeEliminationOn;
// }
//
// public boolean isCodeReformattingOn() {
// return codeReformattingOn;
// }
//
// @Deprecated
// public void setAuthor(String author) {
// this.author = author;
// }
//
// @Deprecated
// public void setTasksDirectory(String tasksDirectory) {
// this.tasksDirectory = tasksDirectory;
// }
//
// @Deprecated
// public void setOutputFile(String outputFile) {
// this.outputFile = outputFile;
// }
//
// @Deprecated
// public void setRunFile(String runFile) {
// this.runFile = runFile;
// }
//
// @Deprecated
// public void setCodeEliminationOn(boolean codeEliminationOn) {
// this.codeEliminationOn = codeEliminationOn;
// }
//
// @Deprecated
// public void setCodeReformattingOn(boolean codeReformattingOn) {
// this.codeReformattingOn = codeReformattingOn;
// }
// }
// }
// Path: src/name/admitriev/jhelper/task/TaskData.java
import com.intellij.openapi.project.Project;
import name.admitriev.jhelper.components.Configurator;
import net.egork.chelper.task.StreamConfiguration;
import net.egork.chelper.task.Test;
import net.egork.chelper.task.TestType;
import java.util.Arrays;
public String getCppPath() {
return cppPath;
}
public StreamConfiguration getInput() {
return input;
}
public StreamConfiguration getOutput() {
return output;
}
public Test[] getTests() {
return Arrays.copyOf(tests, tests.length);
}
public static TaskData emptyTaskData(Project project) {
return new TaskData(
"",
"",
String.format(defaultCppPathFormat(project), ""),
StreamConfiguration.STANDARD,
StreamConfiguration.STANDARD,
TestType.SINGLE,
new Test[0]
);
}
public static String defaultCppPathFormat(Project project) { | Configurator configurator = project.getService(Configurator.class); |
zhengxiaopeng/AndroidUtils | old-library-with-sample/src/main/java/com/rocko/update/UpdateService.java | // Path: old-library-with-sample/src/main/java/com/rocko/common/DebugLog.java
// public class DebugLog {
// /**
// * Log输出所在类
// */
// private static String className;
// /**
// * Log输出所在方法
// */
// private static String methodName;
// /**
// * Log输出所行号
// */
// private static int lineNumber;
//
// private DebugLog() {
// }
//
// /**
// * 是否可Debug状态
// *
// * @return
// */
// public static boolean isDebuggable() {
// return BuildConfig.DEBUG;
// }
//
// /**
// * 创建Log输出的基本信息
// *
// * @param log
// * @return
// */
// private static String createLog(String log) {
// StringBuffer buffer = new StringBuffer();
// buffer.append("[");
// buffer.append(methodName);
// buffer.append("()");
// buffer.append(" line:");
// buffer.append(lineNumber);
// buffer.append("] ");
// buffer.append(log);
// return buffer.toString();
// }
//
// /**
// * 取得输出所在位置的信息 className methodName lineNumber
// *
// * @param sElements
// */
// private static void getMethodNames(StackTraceElement[] sElements) {
// className = sElements[1].getFileName().split("\\.")[0];
// methodName = sElements[1].getMethodName();
// lineNumber = sElements[1].getLineNumber();
// }
//
// public static void e(String message) {
// if (!isDebuggable())
// return;
//
// getMethodNames(new Throwable().getStackTrace());
// Log.e(className, createLog(message));
// }
//
// public static void i(String message) {
// if (!isDebuggable())
// return;
//
// getMethodNames(new Throwable().getStackTrace());
// Log.i(className, createLog(message));
// }
//
// public static void d(String message) {
// if (!isDebuggable())
// return;
//
// getMethodNames(new Throwable().getStackTrace());
// Log.d(className, createLog(message));
// }
//
// public static void v(String message) {
// if (!isDebuggable())
// return;
//
// getMethodNames(new Throwable().getStackTrace());
// Log.v(className, createLog(message));
// }
//
// public static void w(String message) {
// if (!isDebuggable())
// return;
//
// getMethodNames(new Throwable().getStackTrace());
// Log.w(className, createLog(message));
// }
//
// public static void wtf(String message) {
// if (!isDebuggable())
// return;
//
// getMethodNames(new Throwable().getStackTrace());
// Log.wtf(className, createLog(message));
// }
//
// }
//
// Path: old-library-with-sample/src/main/java/com/rocko/config/Configs.java
// public class Configs {
// /**
// * 更新文件夹
// */
// public static final String UPDATE_DOWNLOAD_PATH = "RepairSystem/update";
// /**
// * 外部存储地址
// */
// public static final String EXTERNAL_STORAGE_DIRECTORY = Environment.getExternalStorageDirectory()
// .toString() + "/";
// /**
// * 更新下载后的文件名
// */
// public static final String NEW_APK_FILE_NAME = "/RepairSystem.apk";
// }
//
// Path: old-library-with-sample/src/main/java/com/rocko/config/Urls.java
// public class Urls {
// public final static String baseUrl = "http://192.168.206.1:8080/repairSys";
// public final static String update = "/Mobile/androidUpdateInfo.xml";
// public final static String downloadApk = "/Mobile/RepairSystem.apk";
// }
| import android.app.Notification;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.app.Service;
import android.content.Context;
import android.content.Intent;
import android.net.Uri;
import android.os.Handler;
import android.os.IBinder;
import android.os.Message;
import android.widget.RemoteViews;
import com.rocko.androidutils.R;
import com.rocko.common.DebugLog;
import com.rocko.config.Configs;
import com.rocko.config.Urls;
import java.io.File; | package com.rocko.update;
/**
* 更新下载服务
*
* @author Mr.Zheng
* @date 2014年7月13日21:39:49
*/
public class UpdateService extends Service {
public static final String INTENT_FILTER = "com.roc.service.UPDATE_SERVICE";
public static final int DOWNLOAD_PROGRESS = 1;
public static final int DOWNLOAD_FINISH = 2;
public static final int DOWNLOAD_FAILED = 3;
/* 通知 */
private Notification notification;
private NotificationManager notificationManager;
@Override
public IBinder onBind(Intent intent) {
return null;
}
@Override
public void onCreate() {
super.onCreate();
initUpdate();
}
@Override
public void onDestroy() {
super.onDestroy();
}
private void initUpdate() {
final DownloadHandler downloadHandler = new DownloadHandler(); | // Path: old-library-with-sample/src/main/java/com/rocko/common/DebugLog.java
// public class DebugLog {
// /**
// * Log输出所在类
// */
// private static String className;
// /**
// * Log输出所在方法
// */
// private static String methodName;
// /**
// * Log输出所行号
// */
// private static int lineNumber;
//
// private DebugLog() {
// }
//
// /**
// * 是否可Debug状态
// *
// * @return
// */
// public static boolean isDebuggable() {
// return BuildConfig.DEBUG;
// }
//
// /**
// * 创建Log输出的基本信息
// *
// * @param log
// * @return
// */
// private static String createLog(String log) {
// StringBuffer buffer = new StringBuffer();
// buffer.append("[");
// buffer.append(methodName);
// buffer.append("()");
// buffer.append(" line:");
// buffer.append(lineNumber);
// buffer.append("] ");
// buffer.append(log);
// return buffer.toString();
// }
//
// /**
// * 取得输出所在位置的信息 className methodName lineNumber
// *
// * @param sElements
// */
// private static void getMethodNames(StackTraceElement[] sElements) {
// className = sElements[1].getFileName().split("\\.")[0];
// methodName = sElements[1].getMethodName();
// lineNumber = sElements[1].getLineNumber();
// }
//
// public static void e(String message) {
// if (!isDebuggable())
// return;
//
// getMethodNames(new Throwable().getStackTrace());
// Log.e(className, createLog(message));
// }
//
// public static void i(String message) {
// if (!isDebuggable())
// return;
//
// getMethodNames(new Throwable().getStackTrace());
// Log.i(className, createLog(message));
// }
//
// public static void d(String message) {
// if (!isDebuggable())
// return;
//
// getMethodNames(new Throwable().getStackTrace());
// Log.d(className, createLog(message));
// }
//
// public static void v(String message) {
// if (!isDebuggable())
// return;
//
// getMethodNames(new Throwable().getStackTrace());
// Log.v(className, createLog(message));
// }
//
// public static void w(String message) {
// if (!isDebuggable())
// return;
//
// getMethodNames(new Throwable().getStackTrace());
// Log.w(className, createLog(message));
// }
//
// public static void wtf(String message) {
// if (!isDebuggable())
// return;
//
// getMethodNames(new Throwable().getStackTrace());
// Log.wtf(className, createLog(message));
// }
//
// }
//
// Path: old-library-with-sample/src/main/java/com/rocko/config/Configs.java
// public class Configs {
// /**
// * 更新文件夹
// */
// public static final String UPDATE_DOWNLOAD_PATH = "RepairSystem/update";
// /**
// * 外部存储地址
// */
// public static final String EXTERNAL_STORAGE_DIRECTORY = Environment.getExternalStorageDirectory()
// .toString() + "/";
// /**
// * 更新下载后的文件名
// */
// public static final String NEW_APK_FILE_NAME = "/RepairSystem.apk";
// }
//
// Path: old-library-with-sample/src/main/java/com/rocko/config/Urls.java
// public class Urls {
// public final static String baseUrl = "http://192.168.206.1:8080/repairSys";
// public final static String update = "/Mobile/androidUpdateInfo.xml";
// public final static String downloadApk = "/Mobile/RepairSystem.apk";
// }
// Path: old-library-with-sample/src/main/java/com/rocko/update/UpdateService.java
import android.app.Notification;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.app.Service;
import android.content.Context;
import android.content.Intent;
import android.net.Uri;
import android.os.Handler;
import android.os.IBinder;
import android.os.Message;
import android.widget.RemoteViews;
import com.rocko.androidutils.R;
import com.rocko.common.DebugLog;
import com.rocko.config.Configs;
import com.rocko.config.Urls;
import java.io.File;
package com.rocko.update;
/**
* 更新下载服务
*
* @author Mr.Zheng
* @date 2014年7月13日21:39:49
*/
public class UpdateService extends Service {
public static final String INTENT_FILTER = "com.roc.service.UPDATE_SERVICE";
public static final int DOWNLOAD_PROGRESS = 1;
public static final int DOWNLOAD_FINISH = 2;
public static final int DOWNLOAD_FAILED = 3;
/* 通知 */
private Notification notification;
private NotificationManager notificationManager;
@Override
public IBinder onBind(Intent intent) {
return null;
}
@Override
public void onCreate() {
super.onCreate();
initUpdate();
}
@Override
public void onDestroy() {
super.onDestroy();
}
private void initUpdate() {
final DownloadHandler downloadHandler = new DownloadHandler(); | File dir = new File(Configs.EXTERNAL_STORAGE_DIRECTORY + Configs.UPDATE_DOWNLOAD_PATH); |
zhengxiaopeng/AndroidUtils | old-library-with-sample/src/main/java/com/rocko/update/UpdateService.java | // Path: old-library-with-sample/src/main/java/com/rocko/common/DebugLog.java
// public class DebugLog {
// /**
// * Log输出所在类
// */
// private static String className;
// /**
// * Log输出所在方法
// */
// private static String methodName;
// /**
// * Log输出所行号
// */
// private static int lineNumber;
//
// private DebugLog() {
// }
//
// /**
// * 是否可Debug状态
// *
// * @return
// */
// public static boolean isDebuggable() {
// return BuildConfig.DEBUG;
// }
//
// /**
// * 创建Log输出的基本信息
// *
// * @param log
// * @return
// */
// private static String createLog(String log) {
// StringBuffer buffer = new StringBuffer();
// buffer.append("[");
// buffer.append(methodName);
// buffer.append("()");
// buffer.append(" line:");
// buffer.append(lineNumber);
// buffer.append("] ");
// buffer.append(log);
// return buffer.toString();
// }
//
// /**
// * 取得输出所在位置的信息 className methodName lineNumber
// *
// * @param sElements
// */
// private static void getMethodNames(StackTraceElement[] sElements) {
// className = sElements[1].getFileName().split("\\.")[0];
// methodName = sElements[1].getMethodName();
// lineNumber = sElements[1].getLineNumber();
// }
//
// public static void e(String message) {
// if (!isDebuggable())
// return;
//
// getMethodNames(new Throwable().getStackTrace());
// Log.e(className, createLog(message));
// }
//
// public static void i(String message) {
// if (!isDebuggable())
// return;
//
// getMethodNames(new Throwable().getStackTrace());
// Log.i(className, createLog(message));
// }
//
// public static void d(String message) {
// if (!isDebuggable())
// return;
//
// getMethodNames(new Throwable().getStackTrace());
// Log.d(className, createLog(message));
// }
//
// public static void v(String message) {
// if (!isDebuggable())
// return;
//
// getMethodNames(new Throwable().getStackTrace());
// Log.v(className, createLog(message));
// }
//
// public static void w(String message) {
// if (!isDebuggable())
// return;
//
// getMethodNames(new Throwable().getStackTrace());
// Log.w(className, createLog(message));
// }
//
// public static void wtf(String message) {
// if (!isDebuggable())
// return;
//
// getMethodNames(new Throwable().getStackTrace());
// Log.wtf(className, createLog(message));
// }
//
// }
//
// Path: old-library-with-sample/src/main/java/com/rocko/config/Configs.java
// public class Configs {
// /**
// * 更新文件夹
// */
// public static final String UPDATE_DOWNLOAD_PATH = "RepairSystem/update";
// /**
// * 外部存储地址
// */
// public static final String EXTERNAL_STORAGE_DIRECTORY = Environment.getExternalStorageDirectory()
// .toString() + "/";
// /**
// * 更新下载后的文件名
// */
// public static final String NEW_APK_FILE_NAME = "/RepairSystem.apk";
// }
//
// Path: old-library-with-sample/src/main/java/com/rocko/config/Urls.java
// public class Urls {
// public final static String baseUrl = "http://192.168.206.1:8080/repairSys";
// public final static String update = "/Mobile/androidUpdateInfo.xml";
// public final static String downloadApk = "/Mobile/RepairSystem.apk";
// }
| import android.app.Notification;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.app.Service;
import android.content.Context;
import android.content.Intent;
import android.net.Uri;
import android.os.Handler;
import android.os.IBinder;
import android.os.Message;
import android.widget.RemoteViews;
import com.rocko.androidutils.R;
import com.rocko.common.DebugLog;
import com.rocko.config.Configs;
import com.rocko.config.Urls;
import java.io.File; | package com.rocko.update;
/**
* 更新下载服务
*
* @author Mr.Zheng
* @date 2014年7月13日21:39:49
*/
public class UpdateService extends Service {
public static final String INTENT_FILTER = "com.roc.service.UPDATE_SERVICE";
public static final int DOWNLOAD_PROGRESS = 1;
public static final int DOWNLOAD_FINISH = 2;
public static final int DOWNLOAD_FAILED = 3;
/* 通知 */
private Notification notification;
private NotificationManager notificationManager;
@Override
public IBinder onBind(Intent intent) {
return null;
}
@Override
public void onCreate() {
super.onCreate();
initUpdate();
}
@Override
public void onDestroy() {
super.onDestroy();
}
private void initUpdate() {
final DownloadHandler downloadHandler = new DownloadHandler();
File dir = new File(Configs.EXTERNAL_STORAGE_DIRECTORY + Configs.UPDATE_DOWNLOAD_PATH);
if (!dir.exists()) {
// 创建文件夹
dir.mkdirs();
}
sendNotification();
final String apkSavePath = Configs.EXTERNAL_STORAGE_DIRECTORY + Configs.UPDATE_DOWNLOAD_PATH
+ Configs.NEW_APK_FILE_NAME; | // Path: old-library-with-sample/src/main/java/com/rocko/common/DebugLog.java
// public class DebugLog {
// /**
// * Log输出所在类
// */
// private static String className;
// /**
// * Log输出所在方法
// */
// private static String methodName;
// /**
// * Log输出所行号
// */
// private static int lineNumber;
//
// private DebugLog() {
// }
//
// /**
// * 是否可Debug状态
// *
// * @return
// */
// public static boolean isDebuggable() {
// return BuildConfig.DEBUG;
// }
//
// /**
// * 创建Log输出的基本信息
// *
// * @param log
// * @return
// */
// private static String createLog(String log) {
// StringBuffer buffer = new StringBuffer();
// buffer.append("[");
// buffer.append(methodName);
// buffer.append("()");
// buffer.append(" line:");
// buffer.append(lineNumber);
// buffer.append("] ");
// buffer.append(log);
// return buffer.toString();
// }
//
// /**
// * 取得输出所在位置的信息 className methodName lineNumber
// *
// * @param sElements
// */
// private static void getMethodNames(StackTraceElement[] sElements) {
// className = sElements[1].getFileName().split("\\.")[0];
// methodName = sElements[1].getMethodName();
// lineNumber = sElements[1].getLineNumber();
// }
//
// public static void e(String message) {
// if (!isDebuggable())
// return;
//
// getMethodNames(new Throwable().getStackTrace());
// Log.e(className, createLog(message));
// }
//
// public static void i(String message) {
// if (!isDebuggable())
// return;
//
// getMethodNames(new Throwable().getStackTrace());
// Log.i(className, createLog(message));
// }
//
// public static void d(String message) {
// if (!isDebuggable())
// return;
//
// getMethodNames(new Throwable().getStackTrace());
// Log.d(className, createLog(message));
// }
//
// public static void v(String message) {
// if (!isDebuggable())
// return;
//
// getMethodNames(new Throwable().getStackTrace());
// Log.v(className, createLog(message));
// }
//
// public static void w(String message) {
// if (!isDebuggable())
// return;
//
// getMethodNames(new Throwable().getStackTrace());
// Log.w(className, createLog(message));
// }
//
// public static void wtf(String message) {
// if (!isDebuggable())
// return;
//
// getMethodNames(new Throwable().getStackTrace());
// Log.wtf(className, createLog(message));
// }
//
// }
//
// Path: old-library-with-sample/src/main/java/com/rocko/config/Configs.java
// public class Configs {
// /**
// * 更新文件夹
// */
// public static final String UPDATE_DOWNLOAD_PATH = "RepairSystem/update";
// /**
// * 外部存储地址
// */
// public static final String EXTERNAL_STORAGE_DIRECTORY = Environment.getExternalStorageDirectory()
// .toString() + "/";
// /**
// * 更新下载后的文件名
// */
// public static final String NEW_APK_FILE_NAME = "/RepairSystem.apk";
// }
//
// Path: old-library-with-sample/src/main/java/com/rocko/config/Urls.java
// public class Urls {
// public final static String baseUrl = "http://192.168.206.1:8080/repairSys";
// public final static String update = "/Mobile/androidUpdateInfo.xml";
// public final static String downloadApk = "/Mobile/RepairSystem.apk";
// }
// Path: old-library-with-sample/src/main/java/com/rocko/update/UpdateService.java
import android.app.Notification;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.app.Service;
import android.content.Context;
import android.content.Intent;
import android.net.Uri;
import android.os.Handler;
import android.os.IBinder;
import android.os.Message;
import android.widget.RemoteViews;
import com.rocko.androidutils.R;
import com.rocko.common.DebugLog;
import com.rocko.config.Configs;
import com.rocko.config.Urls;
import java.io.File;
package com.rocko.update;
/**
* 更新下载服务
*
* @author Mr.Zheng
* @date 2014年7月13日21:39:49
*/
public class UpdateService extends Service {
public static final String INTENT_FILTER = "com.roc.service.UPDATE_SERVICE";
public static final int DOWNLOAD_PROGRESS = 1;
public static final int DOWNLOAD_FINISH = 2;
public static final int DOWNLOAD_FAILED = 3;
/* 通知 */
private Notification notification;
private NotificationManager notificationManager;
@Override
public IBinder onBind(Intent intent) {
return null;
}
@Override
public void onCreate() {
super.onCreate();
initUpdate();
}
@Override
public void onDestroy() {
super.onDestroy();
}
private void initUpdate() {
final DownloadHandler downloadHandler = new DownloadHandler();
File dir = new File(Configs.EXTERNAL_STORAGE_DIRECTORY + Configs.UPDATE_DOWNLOAD_PATH);
if (!dir.exists()) {
// 创建文件夹
dir.mkdirs();
}
sendNotification();
final String apkSavePath = Configs.EXTERNAL_STORAGE_DIRECTORY + Configs.UPDATE_DOWNLOAD_PATH
+ Configs.NEW_APK_FILE_NAME; | final String downloadUrl = Urls.baseUrl + Urls.downloadApk;// getResources().getString(R.string.base_url) |
zhengxiaopeng/AndroidUtils | old-library-with-sample/src/main/java/com/rocko/update/UpdateService.java | // Path: old-library-with-sample/src/main/java/com/rocko/common/DebugLog.java
// public class DebugLog {
// /**
// * Log输出所在类
// */
// private static String className;
// /**
// * Log输出所在方法
// */
// private static String methodName;
// /**
// * Log输出所行号
// */
// private static int lineNumber;
//
// private DebugLog() {
// }
//
// /**
// * 是否可Debug状态
// *
// * @return
// */
// public static boolean isDebuggable() {
// return BuildConfig.DEBUG;
// }
//
// /**
// * 创建Log输出的基本信息
// *
// * @param log
// * @return
// */
// private static String createLog(String log) {
// StringBuffer buffer = new StringBuffer();
// buffer.append("[");
// buffer.append(methodName);
// buffer.append("()");
// buffer.append(" line:");
// buffer.append(lineNumber);
// buffer.append("] ");
// buffer.append(log);
// return buffer.toString();
// }
//
// /**
// * 取得输出所在位置的信息 className methodName lineNumber
// *
// * @param sElements
// */
// private static void getMethodNames(StackTraceElement[] sElements) {
// className = sElements[1].getFileName().split("\\.")[0];
// methodName = sElements[1].getMethodName();
// lineNumber = sElements[1].getLineNumber();
// }
//
// public static void e(String message) {
// if (!isDebuggable())
// return;
//
// getMethodNames(new Throwable().getStackTrace());
// Log.e(className, createLog(message));
// }
//
// public static void i(String message) {
// if (!isDebuggable())
// return;
//
// getMethodNames(new Throwable().getStackTrace());
// Log.i(className, createLog(message));
// }
//
// public static void d(String message) {
// if (!isDebuggable())
// return;
//
// getMethodNames(new Throwable().getStackTrace());
// Log.d(className, createLog(message));
// }
//
// public static void v(String message) {
// if (!isDebuggable())
// return;
//
// getMethodNames(new Throwable().getStackTrace());
// Log.v(className, createLog(message));
// }
//
// public static void w(String message) {
// if (!isDebuggable())
// return;
//
// getMethodNames(new Throwable().getStackTrace());
// Log.w(className, createLog(message));
// }
//
// public static void wtf(String message) {
// if (!isDebuggable())
// return;
//
// getMethodNames(new Throwable().getStackTrace());
// Log.wtf(className, createLog(message));
// }
//
// }
//
// Path: old-library-with-sample/src/main/java/com/rocko/config/Configs.java
// public class Configs {
// /**
// * 更新文件夹
// */
// public static final String UPDATE_DOWNLOAD_PATH = "RepairSystem/update";
// /**
// * 外部存储地址
// */
// public static final String EXTERNAL_STORAGE_DIRECTORY = Environment.getExternalStorageDirectory()
// .toString() + "/";
// /**
// * 更新下载后的文件名
// */
// public static final String NEW_APK_FILE_NAME = "/RepairSystem.apk";
// }
//
// Path: old-library-with-sample/src/main/java/com/rocko/config/Urls.java
// public class Urls {
// public final static String baseUrl = "http://192.168.206.1:8080/repairSys";
// public final static String update = "/Mobile/androidUpdateInfo.xml";
// public final static String downloadApk = "/Mobile/RepairSystem.apk";
// }
| import android.app.Notification;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.app.Service;
import android.content.Context;
import android.content.Intent;
import android.net.Uri;
import android.os.Handler;
import android.os.IBinder;
import android.os.Message;
import android.widget.RemoteViews;
import com.rocko.androidutils.R;
import com.rocko.common.DebugLog;
import com.rocko.config.Configs;
import com.rocko.config.Urls;
import java.io.File; | package com.rocko.update;
/**
* 更新下载服务
*
* @author Mr.Zheng
* @date 2014年7月13日21:39:49
*/
public class UpdateService extends Service {
public static final String INTENT_FILTER = "com.roc.service.UPDATE_SERVICE";
public static final int DOWNLOAD_PROGRESS = 1;
public static final int DOWNLOAD_FINISH = 2;
public static final int DOWNLOAD_FAILED = 3;
/* 通知 */
private Notification notification;
private NotificationManager notificationManager;
@Override
public IBinder onBind(Intent intent) {
return null;
}
@Override
public void onCreate() {
super.onCreate();
initUpdate();
}
@Override
public void onDestroy() {
super.onDestroy();
}
private void initUpdate() {
final DownloadHandler downloadHandler = new DownloadHandler();
File dir = new File(Configs.EXTERNAL_STORAGE_DIRECTORY + Configs.UPDATE_DOWNLOAD_PATH);
if (!dir.exists()) {
// 创建文件夹
dir.mkdirs();
}
sendNotification();
final String apkSavePath = Configs.EXTERNAL_STORAGE_DIRECTORY + Configs.UPDATE_DOWNLOAD_PATH
+ Configs.NEW_APK_FILE_NAME;
final String downloadUrl = Urls.baseUrl + Urls.downloadApk;// getResources().getString(R.string.base_url)
// +
// getResources().getString(R.string.downloadApkUrl);
new Thread(new Runnable() {
public void run() {
try {
DownloadTask.downloadFile(getApplicationContext(), downloadUrl, apkSavePath, downloadHandler);
} catch (Exception e) { | // Path: old-library-with-sample/src/main/java/com/rocko/common/DebugLog.java
// public class DebugLog {
// /**
// * Log输出所在类
// */
// private static String className;
// /**
// * Log输出所在方法
// */
// private static String methodName;
// /**
// * Log输出所行号
// */
// private static int lineNumber;
//
// private DebugLog() {
// }
//
// /**
// * 是否可Debug状态
// *
// * @return
// */
// public static boolean isDebuggable() {
// return BuildConfig.DEBUG;
// }
//
// /**
// * 创建Log输出的基本信息
// *
// * @param log
// * @return
// */
// private static String createLog(String log) {
// StringBuffer buffer = new StringBuffer();
// buffer.append("[");
// buffer.append(methodName);
// buffer.append("()");
// buffer.append(" line:");
// buffer.append(lineNumber);
// buffer.append("] ");
// buffer.append(log);
// return buffer.toString();
// }
//
// /**
// * 取得输出所在位置的信息 className methodName lineNumber
// *
// * @param sElements
// */
// private static void getMethodNames(StackTraceElement[] sElements) {
// className = sElements[1].getFileName().split("\\.")[0];
// methodName = sElements[1].getMethodName();
// lineNumber = sElements[1].getLineNumber();
// }
//
// public static void e(String message) {
// if (!isDebuggable())
// return;
//
// getMethodNames(new Throwable().getStackTrace());
// Log.e(className, createLog(message));
// }
//
// public static void i(String message) {
// if (!isDebuggable())
// return;
//
// getMethodNames(new Throwable().getStackTrace());
// Log.i(className, createLog(message));
// }
//
// public static void d(String message) {
// if (!isDebuggable())
// return;
//
// getMethodNames(new Throwable().getStackTrace());
// Log.d(className, createLog(message));
// }
//
// public static void v(String message) {
// if (!isDebuggable())
// return;
//
// getMethodNames(new Throwable().getStackTrace());
// Log.v(className, createLog(message));
// }
//
// public static void w(String message) {
// if (!isDebuggable())
// return;
//
// getMethodNames(new Throwable().getStackTrace());
// Log.w(className, createLog(message));
// }
//
// public static void wtf(String message) {
// if (!isDebuggable())
// return;
//
// getMethodNames(new Throwable().getStackTrace());
// Log.wtf(className, createLog(message));
// }
//
// }
//
// Path: old-library-with-sample/src/main/java/com/rocko/config/Configs.java
// public class Configs {
// /**
// * 更新文件夹
// */
// public static final String UPDATE_DOWNLOAD_PATH = "RepairSystem/update";
// /**
// * 外部存储地址
// */
// public static final String EXTERNAL_STORAGE_DIRECTORY = Environment.getExternalStorageDirectory()
// .toString() + "/";
// /**
// * 更新下载后的文件名
// */
// public static final String NEW_APK_FILE_NAME = "/RepairSystem.apk";
// }
//
// Path: old-library-with-sample/src/main/java/com/rocko/config/Urls.java
// public class Urls {
// public final static String baseUrl = "http://192.168.206.1:8080/repairSys";
// public final static String update = "/Mobile/androidUpdateInfo.xml";
// public final static String downloadApk = "/Mobile/RepairSystem.apk";
// }
// Path: old-library-with-sample/src/main/java/com/rocko/update/UpdateService.java
import android.app.Notification;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.app.Service;
import android.content.Context;
import android.content.Intent;
import android.net.Uri;
import android.os.Handler;
import android.os.IBinder;
import android.os.Message;
import android.widget.RemoteViews;
import com.rocko.androidutils.R;
import com.rocko.common.DebugLog;
import com.rocko.config.Configs;
import com.rocko.config.Urls;
import java.io.File;
package com.rocko.update;
/**
* 更新下载服务
*
* @author Mr.Zheng
* @date 2014年7月13日21:39:49
*/
public class UpdateService extends Service {
public static final String INTENT_FILTER = "com.roc.service.UPDATE_SERVICE";
public static final int DOWNLOAD_PROGRESS = 1;
public static final int DOWNLOAD_FINISH = 2;
public static final int DOWNLOAD_FAILED = 3;
/* 通知 */
private Notification notification;
private NotificationManager notificationManager;
@Override
public IBinder onBind(Intent intent) {
return null;
}
@Override
public void onCreate() {
super.onCreate();
initUpdate();
}
@Override
public void onDestroy() {
super.onDestroy();
}
private void initUpdate() {
final DownloadHandler downloadHandler = new DownloadHandler();
File dir = new File(Configs.EXTERNAL_STORAGE_DIRECTORY + Configs.UPDATE_DOWNLOAD_PATH);
if (!dir.exists()) {
// 创建文件夹
dir.mkdirs();
}
sendNotification();
final String apkSavePath = Configs.EXTERNAL_STORAGE_DIRECTORY + Configs.UPDATE_DOWNLOAD_PATH
+ Configs.NEW_APK_FILE_NAME;
final String downloadUrl = Urls.baseUrl + Urls.downloadApk;// getResources().getString(R.string.base_url)
// +
// getResources().getString(R.string.downloadApkUrl);
new Thread(new Runnable() {
public void run() {
try {
DownloadTask.downloadFile(getApplicationContext(), downloadUrl, apkSavePath, downloadHandler);
} catch (Exception e) { | DebugLog.e(e.getMessage()); |
zhengxiaopeng/AndroidUtils | old-library-with-sample/src/main/java/com/rocko/http/CustomAsyncTask.java | // Path: old-library-with-sample/src/main/java/com/rocko/common/DebugLog.java
// public class DebugLog {
// /**
// * Log输出所在类
// */
// private static String className;
// /**
// * Log输出所在方法
// */
// private static String methodName;
// /**
// * Log输出所行号
// */
// private static int lineNumber;
//
// private DebugLog() {
// }
//
// /**
// * 是否可Debug状态
// *
// * @return
// */
// public static boolean isDebuggable() {
// return BuildConfig.DEBUG;
// }
//
// /**
// * 创建Log输出的基本信息
// *
// * @param log
// * @return
// */
// private static String createLog(String log) {
// StringBuffer buffer = new StringBuffer();
// buffer.append("[");
// buffer.append(methodName);
// buffer.append("()");
// buffer.append(" line:");
// buffer.append(lineNumber);
// buffer.append("] ");
// buffer.append(log);
// return buffer.toString();
// }
//
// /**
// * 取得输出所在位置的信息 className methodName lineNumber
// *
// * @param sElements
// */
// private static void getMethodNames(StackTraceElement[] sElements) {
// className = sElements[1].getFileName().split("\\.")[0];
// methodName = sElements[1].getMethodName();
// lineNumber = sElements[1].getLineNumber();
// }
//
// public static void e(String message) {
// if (!isDebuggable())
// return;
//
// getMethodNames(new Throwable().getStackTrace());
// Log.e(className, createLog(message));
// }
//
// public static void i(String message) {
// if (!isDebuggable())
// return;
//
// getMethodNames(new Throwable().getStackTrace());
// Log.i(className, createLog(message));
// }
//
// public static void d(String message) {
// if (!isDebuggable())
// return;
//
// getMethodNames(new Throwable().getStackTrace());
// Log.d(className, createLog(message));
// }
//
// public static void v(String message) {
// if (!isDebuggable())
// return;
//
// getMethodNames(new Throwable().getStackTrace());
// Log.v(className, createLog(message));
// }
//
// public static void w(String message) {
// if (!isDebuggable())
// return;
//
// getMethodNames(new Throwable().getStackTrace());
// Log.w(className, createLog(message));
// }
//
// public static void wtf(String message) {
// if (!isDebuggable())
// return;
//
// getMethodNames(new Throwable().getStackTrace());
// Log.wtf(className, createLog(message));
// }
//
// }
| import android.content.Context;
import android.os.AsyncTask;
import com.rocko.common.DebugLog;
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.protocol.HTTP;
import org.apache.http.util.EntityUtils;
import java.util.ArrayList;
import java.util.List; | @Override
protected void onPreExecute() {
if (mCallback != null)
mCallback.onPreExecute();
}
@Override
public String doInBackground(String... params) {
HttpResponse response = null;
String responseText = "";
try {
switch (mMode) {
case GET:
NameValuePair[] nameValuePairs = new NameValuePair[listNameValuePairs.size()];
for (int i = 0; i < listNameValuePairs.size(); i++) {
nameValuePairs[i] = listNameValuePairs.get(i);
}
response = CustomHttpClient.getHttpResponseByGET(mContext, params[0], nameValuePairs);
break;
case POST:
response = CustomHttpClient.getHttpResponseByPOST(mContext, params[0], listNameValuePairs);
break;
default:
break;
}
statusCode = response.getStatusLine().getStatusCode();
responseText = EntityUtils.toString(response.getEntity(), HTTP.UTF_8);
} catch (Exception e) { | // Path: old-library-with-sample/src/main/java/com/rocko/common/DebugLog.java
// public class DebugLog {
// /**
// * Log输出所在类
// */
// private static String className;
// /**
// * Log输出所在方法
// */
// private static String methodName;
// /**
// * Log输出所行号
// */
// private static int lineNumber;
//
// private DebugLog() {
// }
//
// /**
// * 是否可Debug状态
// *
// * @return
// */
// public static boolean isDebuggable() {
// return BuildConfig.DEBUG;
// }
//
// /**
// * 创建Log输出的基本信息
// *
// * @param log
// * @return
// */
// private static String createLog(String log) {
// StringBuffer buffer = new StringBuffer();
// buffer.append("[");
// buffer.append(methodName);
// buffer.append("()");
// buffer.append(" line:");
// buffer.append(lineNumber);
// buffer.append("] ");
// buffer.append(log);
// return buffer.toString();
// }
//
// /**
// * 取得输出所在位置的信息 className methodName lineNumber
// *
// * @param sElements
// */
// private static void getMethodNames(StackTraceElement[] sElements) {
// className = sElements[1].getFileName().split("\\.")[0];
// methodName = sElements[1].getMethodName();
// lineNumber = sElements[1].getLineNumber();
// }
//
// public static void e(String message) {
// if (!isDebuggable())
// return;
//
// getMethodNames(new Throwable().getStackTrace());
// Log.e(className, createLog(message));
// }
//
// public static void i(String message) {
// if (!isDebuggable())
// return;
//
// getMethodNames(new Throwable().getStackTrace());
// Log.i(className, createLog(message));
// }
//
// public static void d(String message) {
// if (!isDebuggable())
// return;
//
// getMethodNames(new Throwable().getStackTrace());
// Log.d(className, createLog(message));
// }
//
// public static void v(String message) {
// if (!isDebuggable())
// return;
//
// getMethodNames(new Throwable().getStackTrace());
// Log.v(className, createLog(message));
// }
//
// public static void w(String message) {
// if (!isDebuggable())
// return;
//
// getMethodNames(new Throwable().getStackTrace());
// Log.w(className, createLog(message));
// }
//
// public static void wtf(String message) {
// if (!isDebuggable())
// return;
//
// getMethodNames(new Throwable().getStackTrace());
// Log.wtf(className, createLog(message));
// }
//
// }
// Path: old-library-with-sample/src/main/java/com/rocko/http/CustomAsyncTask.java
import android.content.Context;
import android.os.AsyncTask;
import com.rocko.common.DebugLog;
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.protocol.HTTP;
import org.apache.http.util.EntityUtils;
import java.util.ArrayList;
import java.util.List;
@Override
protected void onPreExecute() {
if (mCallback != null)
mCallback.onPreExecute();
}
@Override
public String doInBackground(String... params) {
HttpResponse response = null;
String responseText = "";
try {
switch (mMode) {
case GET:
NameValuePair[] nameValuePairs = new NameValuePair[listNameValuePairs.size()];
for (int i = 0; i < listNameValuePairs.size(); i++) {
nameValuePairs[i] = listNameValuePairs.get(i);
}
response = CustomHttpClient.getHttpResponseByGET(mContext, params[0], nameValuePairs);
break;
case POST:
response = CustomHttpClient.getHttpResponseByPOST(mContext, params[0], listNameValuePairs);
break;
default:
break;
}
statusCode = response.getStatusLine().getStatusCode();
responseText = EntityUtils.toString(response.getEntity(), HTTP.UTF_8);
} catch (Exception e) { | DebugLog.e(e.getMessage()); |
zhengxiaopeng/AndroidUtils | old-library-with-sample/src/main/java/com/rocko/annotation/ViewInstaller.java | // Path: old-library-with-sample/src/main/java/com/rocko/common/DebugLog.java
// public class DebugLog {
// /**
// * Log输出所在类
// */
// private static String className;
// /**
// * Log输出所在方法
// */
// private static String methodName;
// /**
// * Log输出所行号
// */
// private static int lineNumber;
//
// private DebugLog() {
// }
//
// /**
// * 是否可Debug状态
// *
// * @return
// */
// public static boolean isDebuggable() {
// return BuildConfig.DEBUG;
// }
//
// /**
// * 创建Log输出的基本信息
// *
// * @param log
// * @return
// */
// private static String createLog(String log) {
// StringBuffer buffer = new StringBuffer();
// buffer.append("[");
// buffer.append(methodName);
// buffer.append("()");
// buffer.append(" line:");
// buffer.append(lineNumber);
// buffer.append("] ");
// buffer.append(log);
// return buffer.toString();
// }
//
// /**
// * 取得输出所在位置的信息 className methodName lineNumber
// *
// * @param sElements
// */
// private static void getMethodNames(StackTraceElement[] sElements) {
// className = sElements[1].getFileName().split("\\.")[0];
// methodName = sElements[1].getMethodName();
// lineNumber = sElements[1].getLineNumber();
// }
//
// public static void e(String message) {
// if (!isDebuggable())
// return;
//
// getMethodNames(new Throwable().getStackTrace());
// Log.e(className, createLog(message));
// }
//
// public static void i(String message) {
// if (!isDebuggable())
// return;
//
// getMethodNames(new Throwable().getStackTrace());
// Log.i(className, createLog(message));
// }
//
// public static void d(String message) {
// if (!isDebuggable())
// return;
//
// getMethodNames(new Throwable().getStackTrace());
// Log.d(className, createLog(message));
// }
//
// public static void v(String message) {
// if (!isDebuggable())
// return;
//
// getMethodNames(new Throwable().getStackTrace());
// Log.v(className, createLog(message));
// }
//
// public static void w(String message) {
// if (!isDebuggable())
// return;
//
// getMethodNames(new Throwable().getStackTrace());
// Log.w(className, createLog(message));
// }
//
// public static void wtf(String message) {
// if (!isDebuggable())
// return;
//
// getMethodNames(new Throwable().getStackTrace());
// Log.wtf(className, createLog(message));
// }
//
// }
| import android.app.Activity;
import android.os.Bundle;
import android.view.View;
import android.widget.AdapterView;
import android.widget.CompoundButton;
import android.widget.RadioGroup;
import com.rocko.common.DebugLog;
import java.lang.reflect.Field;
import java.lang.reflect.Method; | package com.rocko.annotation;
/**
* 为带InitView注解的View控件初始化并设置监听器的加载器<br>
* 主要方法: {@link #processAnnotation(Object obj)}
*
* @author Mr.Zheng
* @date 2014年8月11日21:59:01
*/
public class ViewInstaller {
public static void processAnnotation(Activity obj) {
process(obj);
}
// public static void processAnnotation(Fragment obj) {
// processAnnotation(obj);
// }
/**
* 初始化控件,处理View控件的Annotation注解
*
* @param obj Object实例对象 其或父类应有findViewById方法
*/
private static void process(Object obj) {
int viewId; // 当前Field注解的id值
View view; // 控件
InitView initView; // InitView注解
ContentView layoutView;// LayoutView注解
try {
// 获取obj对象的类
Class cl = obj.getClass();
/* 设置setContentView */
Method method = cl.getDeclaredMethod("onCreate", Bundle.class);
layoutView = method.getAnnotation(ContentView.class);
if (layoutView != null)
((Activity) obj).setContentView(layoutView.id());
// 获取指定obj对象的所有Field,并遍历每个Field
for (Field f : cl.getDeclaredFields()) {
initView = f.getAnnotation(InitView.class);
if (initView != null) { | // Path: old-library-with-sample/src/main/java/com/rocko/common/DebugLog.java
// public class DebugLog {
// /**
// * Log输出所在类
// */
// private static String className;
// /**
// * Log输出所在方法
// */
// private static String methodName;
// /**
// * Log输出所行号
// */
// private static int lineNumber;
//
// private DebugLog() {
// }
//
// /**
// * 是否可Debug状态
// *
// * @return
// */
// public static boolean isDebuggable() {
// return BuildConfig.DEBUG;
// }
//
// /**
// * 创建Log输出的基本信息
// *
// * @param log
// * @return
// */
// private static String createLog(String log) {
// StringBuffer buffer = new StringBuffer();
// buffer.append("[");
// buffer.append(methodName);
// buffer.append("()");
// buffer.append(" line:");
// buffer.append(lineNumber);
// buffer.append("] ");
// buffer.append(log);
// return buffer.toString();
// }
//
// /**
// * 取得输出所在位置的信息 className methodName lineNumber
// *
// * @param sElements
// */
// private static void getMethodNames(StackTraceElement[] sElements) {
// className = sElements[1].getFileName().split("\\.")[0];
// methodName = sElements[1].getMethodName();
// lineNumber = sElements[1].getLineNumber();
// }
//
// public static void e(String message) {
// if (!isDebuggable())
// return;
//
// getMethodNames(new Throwable().getStackTrace());
// Log.e(className, createLog(message));
// }
//
// public static void i(String message) {
// if (!isDebuggable())
// return;
//
// getMethodNames(new Throwable().getStackTrace());
// Log.i(className, createLog(message));
// }
//
// public static void d(String message) {
// if (!isDebuggable())
// return;
//
// getMethodNames(new Throwable().getStackTrace());
// Log.d(className, createLog(message));
// }
//
// public static void v(String message) {
// if (!isDebuggable())
// return;
//
// getMethodNames(new Throwable().getStackTrace());
// Log.v(className, createLog(message));
// }
//
// public static void w(String message) {
// if (!isDebuggable())
// return;
//
// getMethodNames(new Throwable().getStackTrace());
// Log.w(className, createLog(message));
// }
//
// public static void wtf(String message) {
// if (!isDebuggable())
// return;
//
// getMethodNames(new Throwable().getStackTrace());
// Log.wtf(className, createLog(message));
// }
//
// }
// Path: old-library-with-sample/src/main/java/com/rocko/annotation/ViewInstaller.java
import android.app.Activity;
import android.os.Bundle;
import android.view.View;
import android.widget.AdapterView;
import android.widget.CompoundButton;
import android.widget.RadioGroup;
import com.rocko.common.DebugLog;
import java.lang.reflect.Field;
import java.lang.reflect.Method;
package com.rocko.annotation;
/**
* 为带InitView注解的View控件初始化并设置监听器的加载器<br>
* 主要方法: {@link #processAnnotation(Object obj)}
*
* @author Mr.Zheng
* @date 2014年8月11日21:59:01
*/
public class ViewInstaller {
public static void processAnnotation(Activity obj) {
process(obj);
}
// public static void processAnnotation(Fragment obj) {
// processAnnotation(obj);
// }
/**
* 初始化控件,处理View控件的Annotation注解
*
* @param obj Object实例对象 其或父类应有findViewById方法
*/
private static void process(Object obj) {
int viewId; // 当前Field注解的id值
View view; // 控件
InitView initView; // InitView注解
ContentView layoutView;// LayoutView注解
try {
// 获取obj对象的类
Class cl = obj.getClass();
/* 设置setContentView */
Method method = cl.getDeclaredMethod("onCreate", Bundle.class);
layoutView = method.getAnnotation(ContentView.class);
if (layoutView != null)
((Activity) obj).setContentView(layoutView.id());
// 获取指定obj对象的所有Field,并遍历每个Field
for (Field f : cl.getDeclaredFields()) {
initView = f.getAnnotation(InitView.class);
if (initView != null) { | DebugLog.v(">>>>>注解的field:" + f.getName()); |
zhengxiaopeng/AndroidUtils | old-library-with-sample/src/main/java/com/rocko/utils/PhoneUtils.java | // Path: old-library-with-sample/src/main/java/com/rocko/common/DebugLog.java
// public class DebugLog {
// /**
// * Log输出所在类
// */
// private static String className;
// /**
// * Log输出所在方法
// */
// private static String methodName;
// /**
// * Log输出所行号
// */
// private static int lineNumber;
//
// private DebugLog() {
// }
//
// /**
// * 是否可Debug状态
// *
// * @return
// */
// public static boolean isDebuggable() {
// return BuildConfig.DEBUG;
// }
//
// /**
// * 创建Log输出的基本信息
// *
// * @param log
// * @return
// */
// private static String createLog(String log) {
// StringBuffer buffer = new StringBuffer();
// buffer.append("[");
// buffer.append(methodName);
// buffer.append("()");
// buffer.append(" line:");
// buffer.append(lineNumber);
// buffer.append("] ");
// buffer.append(log);
// return buffer.toString();
// }
//
// /**
// * 取得输出所在位置的信息 className methodName lineNumber
// *
// * @param sElements
// */
// private static void getMethodNames(StackTraceElement[] sElements) {
// className = sElements[1].getFileName().split("\\.")[0];
// methodName = sElements[1].getMethodName();
// lineNumber = sElements[1].getLineNumber();
// }
//
// public static void e(String message) {
// if (!isDebuggable())
// return;
//
// getMethodNames(new Throwable().getStackTrace());
// Log.e(className, createLog(message));
// }
//
// public static void i(String message) {
// if (!isDebuggable())
// return;
//
// getMethodNames(new Throwable().getStackTrace());
// Log.i(className, createLog(message));
// }
//
// public static void d(String message) {
// if (!isDebuggable())
// return;
//
// getMethodNames(new Throwable().getStackTrace());
// Log.d(className, createLog(message));
// }
//
// public static void v(String message) {
// if (!isDebuggable())
// return;
//
// getMethodNames(new Throwable().getStackTrace());
// Log.v(className, createLog(message));
// }
//
// public static void w(String message) {
// if (!isDebuggable())
// return;
//
// getMethodNames(new Throwable().getStackTrace());
// Log.w(className, createLog(message));
// }
//
// public static void wtf(String message) {
// if (!isDebuggable())
// return;
//
// getMethodNames(new Throwable().getStackTrace());
// Log.wtf(className, createLog(message));
// }
//
// }
| import android.app.Activity;
import android.content.Context;
import android.telephony.TelephonyManager;
import android.util.DisplayMetrics;
import android.view.Display;
import android.view.inputmethod.InputMethodManager;
import com.rocko.common.DebugLog;
import java.net.InetAddress;
import java.net.NetworkInterface;
import java.net.SocketException;
import java.util.Enumeration; | * @return
*/
public static int getDefaultStatusBarHeight(Context context) {
int result = 0;
int resourceId = context.getResources().getIdentifier("status_bar_height", "dimen", "android");
if (resourceId > 0) {
result = context.getResources().getDimensionPixelSize(resourceId);
}
return result;
}
/**
* 获取本机IP地址
*
* @return
*/
public static String getLocalIpAddress() {
try {
for (Enumeration<NetworkInterface> en = NetworkInterface
.getNetworkInterfaces(); en.hasMoreElements(); ) {
NetworkInterface intf = en.nextElement();
for (Enumeration<InetAddress> enumIpAddr = intf
.getInetAddresses(); enumIpAddr.hasMoreElements(); ) {
InetAddress inetAddress = enumIpAddr.nextElement();
if (!inetAddress.isLoopbackAddress()) {
return inetAddress.getHostAddress().toString();
}
}
}
} catch (SocketException ex) { | // Path: old-library-with-sample/src/main/java/com/rocko/common/DebugLog.java
// public class DebugLog {
// /**
// * Log输出所在类
// */
// private static String className;
// /**
// * Log输出所在方法
// */
// private static String methodName;
// /**
// * Log输出所行号
// */
// private static int lineNumber;
//
// private DebugLog() {
// }
//
// /**
// * 是否可Debug状态
// *
// * @return
// */
// public static boolean isDebuggable() {
// return BuildConfig.DEBUG;
// }
//
// /**
// * 创建Log输出的基本信息
// *
// * @param log
// * @return
// */
// private static String createLog(String log) {
// StringBuffer buffer = new StringBuffer();
// buffer.append("[");
// buffer.append(methodName);
// buffer.append("()");
// buffer.append(" line:");
// buffer.append(lineNumber);
// buffer.append("] ");
// buffer.append(log);
// return buffer.toString();
// }
//
// /**
// * 取得输出所在位置的信息 className methodName lineNumber
// *
// * @param sElements
// */
// private static void getMethodNames(StackTraceElement[] sElements) {
// className = sElements[1].getFileName().split("\\.")[0];
// methodName = sElements[1].getMethodName();
// lineNumber = sElements[1].getLineNumber();
// }
//
// public static void e(String message) {
// if (!isDebuggable())
// return;
//
// getMethodNames(new Throwable().getStackTrace());
// Log.e(className, createLog(message));
// }
//
// public static void i(String message) {
// if (!isDebuggable())
// return;
//
// getMethodNames(new Throwable().getStackTrace());
// Log.i(className, createLog(message));
// }
//
// public static void d(String message) {
// if (!isDebuggable())
// return;
//
// getMethodNames(new Throwable().getStackTrace());
// Log.d(className, createLog(message));
// }
//
// public static void v(String message) {
// if (!isDebuggable())
// return;
//
// getMethodNames(new Throwable().getStackTrace());
// Log.v(className, createLog(message));
// }
//
// public static void w(String message) {
// if (!isDebuggable())
// return;
//
// getMethodNames(new Throwable().getStackTrace());
// Log.w(className, createLog(message));
// }
//
// public static void wtf(String message) {
// if (!isDebuggable())
// return;
//
// getMethodNames(new Throwable().getStackTrace());
// Log.wtf(className, createLog(message));
// }
//
// }
// Path: old-library-with-sample/src/main/java/com/rocko/utils/PhoneUtils.java
import android.app.Activity;
import android.content.Context;
import android.telephony.TelephonyManager;
import android.util.DisplayMetrics;
import android.view.Display;
import android.view.inputmethod.InputMethodManager;
import com.rocko.common.DebugLog;
import java.net.InetAddress;
import java.net.NetworkInterface;
import java.net.SocketException;
import java.util.Enumeration;
* @return
*/
public static int getDefaultStatusBarHeight(Context context) {
int result = 0;
int resourceId = context.getResources().getIdentifier("status_bar_height", "dimen", "android");
if (resourceId > 0) {
result = context.getResources().getDimensionPixelSize(resourceId);
}
return result;
}
/**
* 获取本机IP地址
*
* @return
*/
public static String getLocalIpAddress() {
try {
for (Enumeration<NetworkInterface> en = NetworkInterface
.getNetworkInterfaces(); en.hasMoreElements(); ) {
NetworkInterface intf = en.nextElement();
for (Enumeration<InetAddress> enumIpAddr = intf
.getInetAddresses(); enumIpAddr.hasMoreElements(); ) {
InetAddress inetAddress = enumIpAddr.nextElement();
if (!inetAddress.isLoopbackAddress()) {
return inetAddress.getHostAddress().toString();
}
}
}
} catch (SocketException ex) { | DebugLog.e(ex.getMessage()); |
zhengxiaopeng/AndroidUtils | old-library-with-sample/src/main/java/com/rocko/http/NetWorkHelper.java | // Path: old-library-with-sample/src/main/java/com/rocko/common/DebugLog.java
// public class DebugLog {
// /**
// * Log输出所在类
// */
// private static String className;
// /**
// * Log输出所在方法
// */
// private static String methodName;
// /**
// * Log输出所行号
// */
// private static int lineNumber;
//
// private DebugLog() {
// }
//
// /**
// * 是否可Debug状态
// *
// * @return
// */
// public static boolean isDebuggable() {
// return BuildConfig.DEBUG;
// }
//
// /**
// * 创建Log输出的基本信息
// *
// * @param log
// * @return
// */
// private static String createLog(String log) {
// StringBuffer buffer = new StringBuffer();
// buffer.append("[");
// buffer.append(methodName);
// buffer.append("()");
// buffer.append(" line:");
// buffer.append(lineNumber);
// buffer.append("] ");
// buffer.append(log);
// return buffer.toString();
// }
//
// /**
// * 取得输出所在位置的信息 className methodName lineNumber
// *
// * @param sElements
// */
// private static void getMethodNames(StackTraceElement[] sElements) {
// className = sElements[1].getFileName().split("\\.")[0];
// methodName = sElements[1].getMethodName();
// lineNumber = sElements[1].getLineNumber();
// }
//
// public static void e(String message) {
// if (!isDebuggable())
// return;
//
// getMethodNames(new Throwable().getStackTrace());
// Log.e(className, createLog(message));
// }
//
// public static void i(String message) {
// if (!isDebuggable())
// return;
//
// getMethodNames(new Throwable().getStackTrace());
// Log.i(className, createLog(message));
// }
//
// public static void d(String message) {
// if (!isDebuggable())
// return;
//
// getMethodNames(new Throwable().getStackTrace());
// Log.d(className, createLog(message));
// }
//
// public static void v(String message) {
// if (!isDebuggable())
// return;
//
// getMethodNames(new Throwable().getStackTrace());
// Log.v(className, createLog(message));
// }
//
// public static void w(String message) {
// if (!isDebuggable())
// return;
//
// getMethodNames(new Throwable().getStackTrace());
// Log.w(className, createLog(message));
// }
//
// public static void wtf(String message) {
// if (!isDebuggable())
// return;
//
// getMethodNames(new Throwable().getStackTrace());
// Log.wtf(className, createLog(message));
// }
//
// }
| import android.content.ContentValues;
import android.content.Context;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.net.Uri;
import android.telephony.TelephonyManager;
import com.rocko.common.DebugLog;
import java.util.List; | package com.rocko.http;
/**
* 2014年7月13日12:06:14
*
* @author Mr.Zheng
*/
public class NetWorkHelper {
public static Uri uri = Uri.parse("content://telephony/carriers");
/**
* 判断是否有网络连接
*
* @param context ApplicationContext
*/
public static boolean isNetworkAvailable(Context context) {
ConnectivityManager connectivity = (ConnectivityManager) context
.getSystemService(Context.CONNECTIVITY_SERVICE);
if (connectivity == null) { | // Path: old-library-with-sample/src/main/java/com/rocko/common/DebugLog.java
// public class DebugLog {
// /**
// * Log输出所在类
// */
// private static String className;
// /**
// * Log输出所在方法
// */
// private static String methodName;
// /**
// * Log输出所行号
// */
// private static int lineNumber;
//
// private DebugLog() {
// }
//
// /**
// * 是否可Debug状态
// *
// * @return
// */
// public static boolean isDebuggable() {
// return BuildConfig.DEBUG;
// }
//
// /**
// * 创建Log输出的基本信息
// *
// * @param log
// * @return
// */
// private static String createLog(String log) {
// StringBuffer buffer = new StringBuffer();
// buffer.append("[");
// buffer.append(methodName);
// buffer.append("()");
// buffer.append(" line:");
// buffer.append(lineNumber);
// buffer.append("] ");
// buffer.append(log);
// return buffer.toString();
// }
//
// /**
// * 取得输出所在位置的信息 className methodName lineNumber
// *
// * @param sElements
// */
// private static void getMethodNames(StackTraceElement[] sElements) {
// className = sElements[1].getFileName().split("\\.")[0];
// methodName = sElements[1].getMethodName();
// lineNumber = sElements[1].getLineNumber();
// }
//
// public static void e(String message) {
// if (!isDebuggable())
// return;
//
// getMethodNames(new Throwable().getStackTrace());
// Log.e(className, createLog(message));
// }
//
// public static void i(String message) {
// if (!isDebuggable())
// return;
//
// getMethodNames(new Throwable().getStackTrace());
// Log.i(className, createLog(message));
// }
//
// public static void d(String message) {
// if (!isDebuggable())
// return;
//
// getMethodNames(new Throwable().getStackTrace());
// Log.d(className, createLog(message));
// }
//
// public static void v(String message) {
// if (!isDebuggable())
// return;
//
// getMethodNames(new Throwable().getStackTrace());
// Log.v(className, createLog(message));
// }
//
// public static void w(String message) {
// if (!isDebuggable())
// return;
//
// getMethodNames(new Throwable().getStackTrace());
// Log.w(className, createLog(message));
// }
//
// public static void wtf(String message) {
// if (!isDebuggable())
// return;
//
// getMethodNames(new Throwable().getStackTrace());
// Log.wtf(className, createLog(message));
// }
//
// }
// Path: old-library-with-sample/src/main/java/com/rocko/http/NetWorkHelper.java
import android.content.ContentValues;
import android.content.Context;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.net.Uri;
import android.telephony.TelephonyManager;
import com.rocko.common.DebugLog;
import java.util.List;
package com.rocko.http;
/**
* 2014年7月13日12:06:14
*
* @author Mr.Zheng
*/
public class NetWorkHelper {
public static Uri uri = Uri.parse("content://telephony/carriers");
/**
* 判断是否有网络连接
*
* @param context ApplicationContext
*/
public static boolean isNetworkAvailable(Context context) {
ConnectivityManager connectivity = (ConnectivityManager) context
.getSystemService(Context.CONNECTIVITY_SERVICE);
if (connectivity == null) { | DebugLog.v("无法获得网络连接"); |
zhengxiaopeng/AndroidUtils | old-library-with-sample/src/main/java/com/rocko/view/ViewUtils.java | // Path: old-library-with-sample/src/main/java/com/rocko/common/DebugLog.java
// public class DebugLog {
// /**
// * Log输出所在类
// */
// private static String className;
// /**
// * Log输出所在方法
// */
// private static String methodName;
// /**
// * Log输出所行号
// */
// private static int lineNumber;
//
// private DebugLog() {
// }
//
// /**
// * 是否可Debug状态
// *
// * @return
// */
// public static boolean isDebuggable() {
// return BuildConfig.DEBUG;
// }
//
// /**
// * 创建Log输出的基本信息
// *
// * @param log
// * @return
// */
// private static String createLog(String log) {
// StringBuffer buffer = new StringBuffer();
// buffer.append("[");
// buffer.append(methodName);
// buffer.append("()");
// buffer.append(" line:");
// buffer.append(lineNumber);
// buffer.append("] ");
// buffer.append(log);
// return buffer.toString();
// }
//
// /**
// * 取得输出所在位置的信息 className methodName lineNumber
// *
// * @param sElements
// */
// private static void getMethodNames(StackTraceElement[] sElements) {
// className = sElements[1].getFileName().split("\\.")[0];
// methodName = sElements[1].getMethodName();
// lineNumber = sElements[1].getLineNumber();
// }
//
// public static void e(String message) {
// if (!isDebuggable())
// return;
//
// getMethodNames(new Throwable().getStackTrace());
// Log.e(className, createLog(message));
// }
//
// public static void i(String message) {
// if (!isDebuggable())
// return;
//
// getMethodNames(new Throwable().getStackTrace());
// Log.i(className, createLog(message));
// }
//
// public static void d(String message) {
// if (!isDebuggable())
// return;
//
// getMethodNames(new Throwable().getStackTrace());
// Log.d(className, createLog(message));
// }
//
// public static void v(String message) {
// if (!isDebuggable())
// return;
//
// getMethodNames(new Throwable().getStackTrace());
// Log.v(className, createLog(message));
// }
//
// public static void w(String message) {
// if (!isDebuggable())
// return;
//
// getMethodNames(new Throwable().getStackTrace());
// Log.w(className, createLog(message));
// }
//
// public static void wtf(String message) {
// if (!isDebuggable())
// return;
//
// getMethodNames(new Throwable().getStackTrace());
// Log.wtf(className, createLog(message));
// }
//
// }
| import android.app.Activity;
import android.text.InputType;
import android.text.Selection;
import android.view.WindowManager;
import android.widget.EditText;
import com.rocko.common.DebugLog;
import java.lang.reflect.Method; | package com.rocko.view;
/**
* @author Mr.Zheng
* @date 2014年10月25日 下午11:03:39
*/
public class ViewUtils {
/**
* 设置EditText光标的位置
*
* @param editText
* @param position
*/
public static void setEditTextCursorPosition(EditText editText, int position) {
Selection.setSelection(editText.getText(), position);
}
/**
* edittext不显示软键盘,要显示光标
*/
public void initPhoneEditText(EditText numEditText) {
if (android.os.Build.VERSION.SDK_INT <= 10) {
numEditText.setInputType(InputType.TYPE_NULL);
} else {
((Activity) numEditText.getContext()).getWindow().setSoftInputMode(
WindowManager.LayoutParams.SOFT_INPUT_STATE_ALWAYS_HIDDEN);
try {
Class<EditText> cls = EditText.class;
Method setSoftInputShownOnFocus;
setSoftInputShownOnFocus = cls.getMethod("setShowSoftInputOnFocus", boolean.class);
setSoftInputShownOnFocus.setAccessible(true);
setSoftInputShownOnFocus.invoke(numEditText, false);
} catch (Exception e) { | // Path: old-library-with-sample/src/main/java/com/rocko/common/DebugLog.java
// public class DebugLog {
// /**
// * Log输出所在类
// */
// private static String className;
// /**
// * Log输出所在方法
// */
// private static String methodName;
// /**
// * Log输出所行号
// */
// private static int lineNumber;
//
// private DebugLog() {
// }
//
// /**
// * 是否可Debug状态
// *
// * @return
// */
// public static boolean isDebuggable() {
// return BuildConfig.DEBUG;
// }
//
// /**
// * 创建Log输出的基本信息
// *
// * @param log
// * @return
// */
// private static String createLog(String log) {
// StringBuffer buffer = new StringBuffer();
// buffer.append("[");
// buffer.append(methodName);
// buffer.append("()");
// buffer.append(" line:");
// buffer.append(lineNumber);
// buffer.append("] ");
// buffer.append(log);
// return buffer.toString();
// }
//
// /**
// * 取得输出所在位置的信息 className methodName lineNumber
// *
// * @param sElements
// */
// private static void getMethodNames(StackTraceElement[] sElements) {
// className = sElements[1].getFileName().split("\\.")[0];
// methodName = sElements[1].getMethodName();
// lineNumber = sElements[1].getLineNumber();
// }
//
// public static void e(String message) {
// if (!isDebuggable())
// return;
//
// getMethodNames(new Throwable().getStackTrace());
// Log.e(className, createLog(message));
// }
//
// public static void i(String message) {
// if (!isDebuggable())
// return;
//
// getMethodNames(new Throwable().getStackTrace());
// Log.i(className, createLog(message));
// }
//
// public static void d(String message) {
// if (!isDebuggable())
// return;
//
// getMethodNames(new Throwable().getStackTrace());
// Log.d(className, createLog(message));
// }
//
// public static void v(String message) {
// if (!isDebuggable())
// return;
//
// getMethodNames(new Throwable().getStackTrace());
// Log.v(className, createLog(message));
// }
//
// public static void w(String message) {
// if (!isDebuggable())
// return;
//
// getMethodNames(new Throwable().getStackTrace());
// Log.w(className, createLog(message));
// }
//
// public static void wtf(String message) {
// if (!isDebuggable())
// return;
//
// getMethodNames(new Throwable().getStackTrace());
// Log.wtf(className, createLog(message));
// }
//
// }
// Path: old-library-with-sample/src/main/java/com/rocko/view/ViewUtils.java
import android.app.Activity;
import android.text.InputType;
import android.text.Selection;
import android.view.WindowManager;
import android.widget.EditText;
import com.rocko.common.DebugLog;
import java.lang.reflect.Method;
package com.rocko.view;
/**
* @author Mr.Zheng
* @date 2014年10月25日 下午11:03:39
*/
public class ViewUtils {
/**
* 设置EditText光标的位置
*
* @param editText
* @param position
*/
public static void setEditTextCursorPosition(EditText editText, int position) {
Selection.setSelection(editText.getText(), position);
}
/**
* edittext不显示软键盘,要显示光标
*/
public void initPhoneEditText(EditText numEditText) {
if (android.os.Build.VERSION.SDK_INT <= 10) {
numEditText.setInputType(InputType.TYPE_NULL);
} else {
((Activity) numEditText.getContext()).getWindow().setSoftInputMode(
WindowManager.LayoutParams.SOFT_INPUT_STATE_ALWAYS_HIDDEN);
try {
Class<EditText> cls = EditText.class;
Method setSoftInputShownOnFocus;
setSoftInputShownOnFocus = cls.getMethod("setShowSoftInputOnFocus", boolean.class);
setSoftInputShownOnFocus.setAccessible(true);
setSoftInputShownOnFocus.invoke(numEditText, false);
} catch (Exception e) { | DebugLog.e(">>>" + e.getMessage()); |
zhengxiaopeng/AndroidUtils | old-library-with-sample/src/main/java/com/rocko/io/IOHelper.java | // Path: old-library-with-sample/src/main/java/com/rocko/utils/ApplicationUtils.java
// public class ApplicationUtils {
//
// /**
// * 备份本程序的apk安装文件到SD卡根目录下
// *
// * @param context ApplicationContext
// * @param packageName
// * @param mActivity
// * @throws java.io.IOException
// */
// public static void backupApp(Context context) throws IOException {
// // 存放位置
// String newFile = Environment.getExternalStorageDirectory().getAbsolutePath() + File.separator;
// String oldFile = null;
// try {
// // 原始位置
// oldFile = context.getPackageManager().getApplicationInfo(context.getPackageName(), 0).sourceDir;
// } catch (PackageManager.NameNotFoundException e) {
// e.printStackTrace();
// }
// System.out.println(newFile);
// System.out.println(oldFile);
//
// File in = new File(oldFile);
// File out = new File(newFile + context.getPackageName() + ".apk");
// if (!out.exists()) {
// out.createNewFile();
// } else {
// }
//
// FileInputStream fis = new FileInputStream(in);
// FileOutputStream fos = new FileOutputStream(out);
//
// int count;
// // 文件太大的话,我觉得需要修改
// byte[] buffer = new byte[256 * 1024];
// while ((count = fis.read(buffer)) > 0) {
// fos.write(buffer, 0, count);
// }
//
// fis.close();
// fos.flush();
// fos.close();
// }
//
// /**
// * 获取应用的MD5签名值
// *
// * @param context ApplicationContext
// * @return
// */
// public static String getSign(Context context) {
// PackageManager packageManager = context.getPackageManager();
// try {
// PackageInfo packageInfo = packageManager.getPackageInfo(context.getPackageName(),
// PackageManager.GET_SIGNATURES);
// Signature[] signs = packageInfo.signatures;
// Signature sign = signs[0];
// return MD5Helper.hexdigest(sign.toByteArray());
// } catch (Exception e) {
// e.printStackTrace();
// return null;
// }
// }
//
// /**
// * 获取应用版本Code
// *
// * @param context ApplicationContext
// * @return
// */
// public static int getAppVersionCode(Context context) {
// try {
// PackageInfo info = context.getPackageManager().getPackageInfo(context.getPackageName(), 0);
// return info.versionCode;
// } catch (PackageManager.NameNotFoundException e) {
// e.printStackTrace();
// }
// return 1;
// }
//
// /**
// * 获取应用版本Name
// *
// * @param context ApplicationContext
// * @return
// */
// public static String getAppVersionName(Context context) {
// try {
// PackageInfo info = context.getPackageManager().getPackageInfo(context.getPackageName(), 0);
// return info.versionName;
// } catch (PackageManager.NameNotFoundException e) {
// e.printStackTrace();
// }
// return "unkonwn";
// }
// }
| import android.content.Context;
import android.os.Environment;
import com.rocko.utils.ApplicationUtils;
import java.io.File;
import java.io.IOException; | package com.rocko.io;
/**
* @author Mr.Zheng
* @date 2014年11月2日 上午12:49:30
*/
public class IOHelper {
/**
* 获取DiskLruCache实例
*
* @param context
* @param uniqueName 对不同类型的数据进行区分而设定的一个唯一值
* @return
*/
public static DiskLruCache getDiskLruCache(Context context, String uniqueName) {
DiskLruCache mDiskLruCache = null;
try {
File cacheDir = getDiskCacheDir(context, uniqueName);
if (!cacheDir.exists()) {
cacheDir.mkdirs();
} | // Path: old-library-with-sample/src/main/java/com/rocko/utils/ApplicationUtils.java
// public class ApplicationUtils {
//
// /**
// * 备份本程序的apk安装文件到SD卡根目录下
// *
// * @param context ApplicationContext
// * @param packageName
// * @param mActivity
// * @throws java.io.IOException
// */
// public static void backupApp(Context context) throws IOException {
// // 存放位置
// String newFile = Environment.getExternalStorageDirectory().getAbsolutePath() + File.separator;
// String oldFile = null;
// try {
// // 原始位置
// oldFile = context.getPackageManager().getApplicationInfo(context.getPackageName(), 0).sourceDir;
// } catch (PackageManager.NameNotFoundException e) {
// e.printStackTrace();
// }
// System.out.println(newFile);
// System.out.println(oldFile);
//
// File in = new File(oldFile);
// File out = new File(newFile + context.getPackageName() + ".apk");
// if (!out.exists()) {
// out.createNewFile();
// } else {
// }
//
// FileInputStream fis = new FileInputStream(in);
// FileOutputStream fos = new FileOutputStream(out);
//
// int count;
// // 文件太大的话,我觉得需要修改
// byte[] buffer = new byte[256 * 1024];
// while ((count = fis.read(buffer)) > 0) {
// fos.write(buffer, 0, count);
// }
//
// fis.close();
// fos.flush();
// fos.close();
// }
//
// /**
// * 获取应用的MD5签名值
// *
// * @param context ApplicationContext
// * @return
// */
// public static String getSign(Context context) {
// PackageManager packageManager = context.getPackageManager();
// try {
// PackageInfo packageInfo = packageManager.getPackageInfo(context.getPackageName(),
// PackageManager.GET_SIGNATURES);
// Signature[] signs = packageInfo.signatures;
// Signature sign = signs[0];
// return MD5Helper.hexdigest(sign.toByteArray());
// } catch (Exception e) {
// e.printStackTrace();
// return null;
// }
// }
//
// /**
// * 获取应用版本Code
// *
// * @param context ApplicationContext
// * @return
// */
// public static int getAppVersionCode(Context context) {
// try {
// PackageInfo info = context.getPackageManager().getPackageInfo(context.getPackageName(), 0);
// return info.versionCode;
// } catch (PackageManager.NameNotFoundException e) {
// e.printStackTrace();
// }
// return 1;
// }
//
// /**
// * 获取应用版本Name
// *
// * @param context ApplicationContext
// * @return
// */
// public static String getAppVersionName(Context context) {
// try {
// PackageInfo info = context.getPackageManager().getPackageInfo(context.getPackageName(), 0);
// return info.versionName;
// } catch (PackageManager.NameNotFoundException e) {
// e.printStackTrace();
// }
// return "unkonwn";
// }
// }
// Path: old-library-with-sample/src/main/java/com/rocko/io/IOHelper.java
import android.content.Context;
import android.os.Environment;
import com.rocko.utils.ApplicationUtils;
import java.io.File;
import java.io.IOException;
package com.rocko.io;
/**
* @author Mr.Zheng
* @date 2014年11月2日 上午12:49:30
*/
public class IOHelper {
/**
* 获取DiskLruCache实例
*
* @param context
* @param uniqueName 对不同类型的数据进行区分而设定的一个唯一值
* @return
*/
public static DiskLruCache getDiskLruCache(Context context, String uniqueName) {
DiskLruCache mDiskLruCache = null;
try {
File cacheDir = getDiskCacheDir(context, uniqueName);
if (!cacheDir.exists()) {
cacheDir.mkdirs();
} | mDiskLruCache = DiskLruCache.open(cacheDir, ApplicationUtils.getAppVersionCode(context), 1, |
zhengxiaopeng/AndroidUtils | old-library-with-sample/src/main/java/com/rocko/utils/ApplicationUtils.java | // Path: old-library-with-sample/src/main/java/com/rocko/security/MD5Helper.java
// public class MD5Helper {
//
// protected final static char hexDigits[] = {'0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'a', 'b',
// 'c', 'd', 'e', 'f'};
//
// protected static MessageDigest messagedigest = null;
//
// static {
// try {
// messagedigest = MessageDigest.getInstance("MD5");
// } catch (NoSuchAlgorithmException nsaex) {
// System.err.println(MD5Helper.class.getName() + "初始化失败,MessageDigest不支持MD5Util。");
// nsaex.printStackTrace();
// }
// }
//
// /**
// * 功能:加盐版的MD5.返回格式为MD5(密码+{盐值})
// *
// * @param password 密码
// * @param salt 盐值
// * @return String
// * @author 郑晓鹏
// * @date 2014年06月24日
// */
// public static String getMD5StringWithSalt(String password, String salt) {
// if (password == null) {
// throw new IllegalArgumentException("password不能为null");
// }
// if (salt.equals("") || salt.length() == 0) {
// throw new IllegalArgumentException("salt不能为空");
// }
// if ((salt.toString().lastIndexOf("{") != -1) || (salt.toString().lastIndexOf("}") != -1)) {
// throw new IllegalArgumentException("salt中不能包含 { 或者 }");
// }
// return getMD5String(password + "{" + salt.toString() + "}");
// }
//
// /**
// * 功能:得到文件的md5值。
// *
// * @param file 文件。
// * @return String
// * @throws IOException 读取文件IO异常时。
// * @author 郑晓鹏
// * @date 2014年06月24日
// */
// public static String getFileMD5String(File file) throws IOException {
// FileInputStream in = new FileInputStream(file);
// FileChannel ch = in.getChannel();
// MappedByteBuffer byteBuffer = ch.map(FileChannel.MapMode.READ_ONLY, 0, file.length());
// messagedigest.update(byteBuffer);
// return bufferToHex(messagedigest.digest());
// }
//
// /**
// * 功能:得到一个字符串的MD5值。
// *
// * @param str 字符串
// * @return String
// * @author 郑晓鹏
// * @date 2014年06月24日
// */
// public static String getMD5String(String str) {
// return getMD5String(str.getBytes());
// }
//
// private static String getMD5String(byte[] bytes) {
// messagedigest.update(bytes);
// return bufferToHex(messagedigest.digest());
// }
//
// private static String bufferToHex(byte bytes[]) {
// return bufferToHex(bytes, 0, bytes.length);
// }
//
// private static String bufferToHex(byte bytes[], int m, int n) {
// StringBuffer stringbuffer = new StringBuffer(2 * n);
// int k = m + n;
// for (int l = m; l < k; l++) {
// appendHexPair(bytes[l], stringbuffer);
// }
// return stringbuffer.toString();
// }
//
// private static void appendHexPair(byte bt, StringBuffer stringbuffer) {
// char c0 = hexDigits[(bt & 0xf0) >> 4];
// char c1 = hexDigits[bt & 0xf];
// stringbuffer.append(c0);
// stringbuffer.append(c1);
// }
//
// /*
// * 哈希摘摘要
// */
// public static String hexdigest(byte[] paramArrayOfByte) {
// try {
// MessageDigest localMessageDigest = MessageDigest.getInstance("MD5");
// localMessageDigest.update(paramArrayOfByte);
// byte[] arrayOfByte = localMessageDigest.digest();
// char[] arrayOfChar = new char[32];
// int i = 0;
// int j = 0;
// for (; ; ) {
// if (i >= 16) {
// return new String(arrayOfChar);
// }
// int k = arrayOfByte[i];
// int m = j + 1;
// arrayOfChar[j] = hexDigits[(0xF & k >>> 4)];
// j = m + 1;
// arrayOfChar[m] = hexDigits[(k & 0xF)];
// i++;
// }
//
// } catch (Exception localException) {
// return null;
// }
// }
// }
| import android.content.Context;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.content.pm.Signature;
import android.os.Environment;
import com.rocko.security.MD5Helper;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException; | }
FileInputStream fis = new FileInputStream(in);
FileOutputStream fos = new FileOutputStream(out);
int count;
// 文件太大的话,我觉得需要修改
byte[] buffer = new byte[256 * 1024];
while ((count = fis.read(buffer)) > 0) {
fos.write(buffer, 0, count);
}
fis.close();
fos.flush();
fos.close();
}
/**
* 获取应用的MD5签名值
*
* @param context ApplicationContext
* @return
*/
public static String getSign(Context context) {
PackageManager packageManager = context.getPackageManager();
try {
PackageInfo packageInfo = packageManager.getPackageInfo(context.getPackageName(),
PackageManager.GET_SIGNATURES);
Signature[] signs = packageInfo.signatures;
Signature sign = signs[0]; | // Path: old-library-with-sample/src/main/java/com/rocko/security/MD5Helper.java
// public class MD5Helper {
//
// protected final static char hexDigits[] = {'0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'a', 'b',
// 'c', 'd', 'e', 'f'};
//
// protected static MessageDigest messagedigest = null;
//
// static {
// try {
// messagedigest = MessageDigest.getInstance("MD5");
// } catch (NoSuchAlgorithmException nsaex) {
// System.err.println(MD5Helper.class.getName() + "初始化失败,MessageDigest不支持MD5Util。");
// nsaex.printStackTrace();
// }
// }
//
// /**
// * 功能:加盐版的MD5.返回格式为MD5(密码+{盐值})
// *
// * @param password 密码
// * @param salt 盐值
// * @return String
// * @author 郑晓鹏
// * @date 2014年06月24日
// */
// public static String getMD5StringWithSalt(String password, String salt) {
// if (password == null) {
// throw new IllegalArgumentException("password不能为null");
// }
// if (salt.equals("") || salt.length() == 0) {
// throw new IllegalArgumentException("salt不能为空");
// }
// if ((salt.toString().lastIndexOf("{") != -1) || (salt.toString().lastIndexOf("}") != -1)) {
// throw new IllegalArgumentException("salt中不能包含 { 或者 }");
// }
// return getMD5String(password + "{" + salt.toString() + "}");
// }
//
// /**
// * 功能:得到文件的md5值。
// *
// * @param file 文件。
// * @return String
// * @throws IOException 读取文件IO异常时。
// * @author 郑晓鹏
// * @date 2014年06月24日
// */
// public static String getFileMD5String(File file) throws IOException {
// FileInputStream in = new FileInputStream(file);
// FileChannel ch = in.getChannel();
// MappedByteBuffer byteBuffer = ch.map(FileChannel.MapMode.READ_ONLY, 0, file.length());
// messagedigest.update(byteBuffer);
// return bufferToHex(messagedigest.digest());
// }
//
// /**
// * 功能:得到一个字符串的MD5值。
// *
// * @param str 字符串
// * @return String
// * @author 郑晓鹏
// * @date 2014年06月24日
// */
// public static String getMD5String(String str) {
// return getMD5String(str.getBytes());
// }
//
// private static String getMD5String(byte[] bytes) {
// messagedigest.update(bytes);
// return bufferToHex(messagedigest.digest());
// }
//
// private static String bufferToHex(byte bytes[]) {
// return bufferToHex(bytes, 0, bytes.length);
// }
//
// private static String bufferToHex(byte bytes[], int m, int n) {
// StringBuffer stringbuffer = new StringBuffer(2 * n);
// int k = m + n;
// for (int l = m; l < k; l++) {
// appendHexPair(bytes[l], stringbuffer);
// }
// return stringbuffer.toString();
// }
//
// private static void appendHexPair(byte bt, StringBuffer stringbuffer) {
// char c0 = hexDigits[(bt & 0xf0) >> 4];
// char c1 = hexDigits[bt & 0xf];
// stringbuffer.append(c0);
// stringbuffer.append(c1);
// }
//
// /*
// * 哈希摘摘要
// */
// public static String hexdigest(byte[] paramArrayOfByte) {
// try {
// MessageDigest localMessageDigest = MessageDigest.getInstance("MD5");
// localMessageDigest.update(paramArrayOfByte);
// byte[] arrayOfByte = localMessageDigest.digest();
// char[] arrayOfChar = new char[32];
// int i = 0;
// int j = 0;
// for (; ; ) {
// if (i >= 16) {
// return new String(arrayOfChar);
// }
// int k = arrayOfByte[i];
// int m = j + 1;
// arrayOfChar[j] = hexDigits[(0xF & k >>> 4)];
// j = m + 1;
// arrayOfChar[m] = hexDigits[(k & 0xF)];
// i++;
// }
//
// } catch (Exception localException) {
// return null;
// }
// }
// }
// Path: old-library-with-sample/src/main/java/com/rocko/utils/ApplicationUtils.java
import android.content.Context;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.content.pm.Signature;
import android.os.Environment;
import com.rocko.security.MD5Helper;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
}
FileInputStream fis = new FileInputStream(in);
FileOutputStream fos = new FileOutputStream(out);
int count;
// 文件太大的话,我觉得需要修改
byte[] buffer = new byte[256 * 1024];
while ((count = fis.read(buffer)) > 0) {
fos.write(buffer, 0, count);
}
fis.close();
fos.flush();
fos.close();
}
/**
* 获取应用的MD5签名值
*
* @param context ApplicationContext
* @return
*/
public static String getSign(Context context) {
PackageManager packageManager = context.getPackageManager();
try {
PackageInfo packageInfo = packageManager.getPackageInfo(context.getPackageName(),
PackageManager.GET_SIGNATURES);
Signature[] signs = packageInfo.signatures;
Signature sign = signs[0]; | return MD5Helper.hexdigest(sign.toByteArray()); |
zhengxiaopeng/AndroidUtils | old-library-with-sample/src/main/java/com/rocko/http/CustomHttpClient.java | // Path: old-library-with-sample/src/main/java/com/rocko/common/DebugLog.java
// public class DebugLog {
// /**
// * Log输出所在类
// */
// private static String className;
// /**
// * Log输出所在方法
// */
// private static String methodName;
// /**
// * Log输出所行号
// */
// private static int lineNumber;
//
// private DebugLog() {
// }
//
// /**
// * 是否可Debug状态
// *
// * @return
// */
// public static boolean isDebuggable() {
// return BuildConfig.DEBUG;
// }
//
// /**
// * 创建Log输出的基本信息
// *
// * @param log
// * @return
// */
// private static String createLog(String log) {
// StringBuffer buffer = new StringBuffer();
// buffer.append("[");
// buffer.append(methodName);
// buffer.append("()");
// buffer.append(" line:");
// buffer.append(lineNumber);
// buffer.append("] ");
// buffer.append(log);
// return buffer.toString();
// }
//
// /**
// * 取得输出所在位置的信息 className methodName lineNumber
// *
// * @param sElements
// */
// private static void getMethodNames(StackTraceElement[] sElements) {
// className = sElements[1].getFileName().split("\\.")[0];
// methodName = sElements[1].getMethodName();
// lineNumber = sElements[1].getLineNumber();
// }
//
// public static void e(String message) {
// if (!isDebuggable())
// return;
//
// getMethodNames(new Throwable().getStackTrace());
// Log.e(className, createLog(message));
// }
//
// public static void i(String message) {
// if (!isDebuggable())
// return;
//
// getMethodNames(new Throwable().getStackTrace());
// Log.i(className, createLog(message));
// }
//
// public static void d(String message) {
// if (!isDebuggable())
// return;
//
// getMethodNames(new Throwable().getStackTrace());
// Log.d(className, createLog(message));
// }
//
// public static void v(String message) {
// if (!isDebuggable())
// return;
//
// getMethodNames(new Throwable().getStackTrace());
// Log.v(className, createLog(message));
// }
//
// public static void w(String message) {
// if (!isDebuggable())
// return;
//
// getMethodNames(new Throwable().getStackTrace());
// Log.w(className, createLog(message));
// }
//
// public static void wtf(String message) {
// if (!isDebuggable())
// return;
//
// getMethodNames(new Throwable().getStackTrace());
// Log.wtf(className, createLog(message));
// }
//
// }
| import android.content.Context;
import com.rocko.common.DebugLog;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.HttpStatus;
import org.apache.http.HttpVersion;
import org.apache.http.NameValuePair;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.HttpClient;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.conn.ClientConnectionManager;
import org.apache.http.conn.params.ConnManagerParams;
import org.apache.http.conn.scheme.PlainSocketFactory;
import org.apache.http.conn.scheme.Scheme;
import org.apache.http.conn.scheme.SchemeRegistry;
import org.apache.http.conn.ssl.SSLSocketFactory;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.impl.conn.tsccm.ThreadSafeClientConnManager;
import org.apache.http.params.BasicHttpParams;
import org.apache.http.params.HttpConnectionParams;
import org.apache.http.params.HttpParams;
import org.apache.http.params.HttpProtocolParams;
import org.apache.http.protocol.HTTP;
import org.apache.http.util.EntityUtils;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.util.List; | package com.rocko.http;
/**
* @author Mr.Zheng
* @date 2014年7月13日12:05:00
*/
public class CustomHttpClient {
private static final String CHARSET_UTF8 = HTTP.UTF_8;
private static final String CHARSET_GB2312 = "GB2312";
private static HttpClient customerHttpClient;
private static HttpEntity urlEncoded;
private CustomHttpClient() {
}
/**
* 通过GET方式获取HttpResponse
*
* @param context ApplicationContext
* @param url
* @param nameValuePairs
* @return HttpResponse
*/
public static HttpResponse getHttpResponseByGET(Context context, String url, NameValuePair... nameValuePairs) { | // Path: old-library-with-sample/src/main/java/com/rocko/common/DebugLog.java
// public class DebugLog {
// /**
// * Log输出所在类
// */
// private static String className;
// /**
// * Log输出所在方法
// */
// private static String methodName;
// /**
// * Log输出所行号
// */
// private static int lineNumber;
//
// private DebugLog() {
// }
//
// /**
// * 是否可Debug状态
// *
// * @return
// */
// public static boolean isDebuggable() {
// return BuildConfig.DEBUG;
// }
//
// /**
// * 创建Log输出的基本信息
// *
// * @param log
// * @return
// */
// private static String createLog(String log) {
// StringBuffer buffer = new StringBuffer();
// buffer.append("[");
// buffer.append(methodName);
// buffer.append("()");
// buffer.append(" line:");
// buffer.append(lineNumber);
// buffer.append("] ");
// buffer.append(log);
// return buffer.toString();
// }
//
// /**
// * 取得输出所在位置的信息 className methodName lineNumber
// *
// * @param sElements
// */
// private static void getMethodNames(StackTraceElement[] sElements) {
// className = sElements[1].getFileName().split("\\.")[0];
// methodName = sElements[1].getMethodName();
// lineNumber = sElements[1].getLineNumber();
// }
//
// public static void e(String message) {
// if (!isDebuggable())
// return;
//
// getMethodNames(new Throwable().getStackTrace());
// Log.e(className, createLog(message));
// }
//
// public static void i(String message) {
// if (!isDebuggable())
// return;
//
// getMethodNames(new Throwable().getStackTrace());
// Log.i(className, createLog(message));
// }
//
// public static void d(String message) {
// if (!isDebuggable())
// return;
//
// getMethodNames(new Throwable().getStackTrace());
// Log.d(className, createLog(message));
// }
//
// public static void v(String message) {
// if (!isDebuggable())
// return;
//
// getMethodNames(new Throwable().getStackTrace());
// Log.v(className, createLog(message));
// }
//
// public static void w(String message) {
// if (!isDebuggable())
// return;
//
// getMethodNames(new Throwable().getStackTrace());
// Log.w(className, createLog(message));
// }
//
// public static void wtf(String message) {
// if (!isDebuggable())
// return;
//
// getMethodNames(new Throwable().getStackTrace());
// Log.wtf(className, createLog(message));
// }
//
// }
// Path: old-library-with-sample/src/main/java/com/rocko/http/CustomHttpClient.java
import android.content.Context;
import com.rocko.common.DebugLog;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.HttpStatus;
import org.apache.http.HttpVersion;
import org.apache.http.NameValuePair;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.HttpClient;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.conn.ClientConnectionManager;
import org.apache.http.conn.params.ConnManagerParams;
import org.apache.http.conn.scheme.PlainSocketFactory;
import org.apache.http.conn.scheme.Scheme;
import org.apache.http.conn.scheme.SchemeRegistry;
import org.apache.http.conn.ssl.SSLSocketFactory;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.impl.conn.tsccm.ThreadSafeClientConnManager;
import org.apache.http.params.BasicHttpParams;
import org.apache.http.params.HttpConnectionParams;
import org.apache.http.params.HttpParams;
import org.apache.http.params.HttpProtocolParams;
import org.apache.http.protocol.HTTP;
import org.apache.http.util.EntityUtils;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.util.List;
package com.rocko.http;
/**
* @author Mr.Zheng
* @date 2014年7月13日12:05:00
*/
public class CustomHttpClient {
private static final String CHARSET_UTF8 = HTTP.UTF_8;
private static final String CHARSET_GB2312 = "GB2312";
private static HttpClient customerHttpClient;
private static HttpEntity urlEncoded;
private CustomHttpClient() {
}
/**
* 通过GET方式获取HttpResponse
*
* @param context ApplicationContext
* @param url
* @param nameValuePairs
* @return HttpResponse
*/
public static HttpResponse getHttpResponseByGET(Context context, String url, NameValuePair... nameValuePairs) { | DebugLog.v(url); |
zhengxiaopeng/AndroidUtils | sample/src/main/java/com/rocko/android/common/sample/MainActivity.java | // Path: library/src/main/java/com/rocko/android/common/util/DialogUtils.java
// public class DialogUtils {
// private static Dialog mDialog = null;
// private static View mDialogView = null;
//
// /**
// * 开启全屏无进度的progress
// *
// * @param context Activity的上下文,不可为ApplicationContext
// * @param msg 显示的提示信息
// * @param cancelable 返回键是否可取消
// * @param canceledOnTouchOutside 点击边缘是否可取消
// */
// public static void stratProgressDialog(Context context, String msg, boolean cancelable,
// boolean canceledOnTouchOutside) {
// mDialog = new ProgressDialog(context, android.R.style.Theme_Material_Light_Dialog_NoActionBar_MinWidth);
// mDialog.setCancelable(cancelable);
// mDialog.setCanceledOnTouchOutside(canceledOnTouchOutside);
// mDialog.show();
// // mDialog.getWindow().setContentView(getDialogView(context, msg));
// }
//
// private static View getDialogView(Context context, String msg) {
//
// mDialogView = LayoutInflater.from(context).inflate(R.layout.dialog_progress, null);
// ((TextView) mDialogView.findViewById(R.id.txtView_dialog_show_msg)).setText(msg);
// return mDialogView;
// }
//
// /**
// * 停止显示全屏无进度的progress 确保在主(UI)线程执行
// */
// public static void stopProgressDialog() {
// if (mDialog.isShowing()) {
// mDialog.dismiss();
// // mDialog = null;
// // mDialogView.clearAnimation();
// // mDialogView = null;
// }
//
// }
//
// /**
// * 通过反射区设置默认的AlertDialog在点击确定时是否自动关闭dialog
// *
// * @param pDialog
// * @param pIsClose
// */
// public static void setAlertDialogIsClose(DialogInterface pDialog, Boolean pIsClose) {
// try {
// Field field = pDialog.getClass().getSuperclass().getDeclaredField("mShowing");
// field.setAccessible(true);
// field.set(pDialog, pIsClose);
// } catch (Exception e) {
// e.printStackTrace();
// }
// }
//
// }
| import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.v7.app.ActionBarActivity;
import android.view.Menu;
import android.view.MenuItem;
import com.rocko.android.common.util.DialogUtils; | package com.rocko.android.common.sample;
public class MainActivity extends ActionBarActivity {
@Override
protected void onCreate(final Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main); | // Path: library/src/main/java/com/rocko/android/common/util/DialogUtils.java
// public class DialogUtils {
// private static Dialog mDialog = null;
// private static View mDialogView = null;
//
// /**
// * 开启全屏无进度的progress
// *
// * @param context Activity的上下文,不可为ApplicationContext
// * @param msg 显示的提示信息
// * @param cancelable 返回键是否可取消
// * @param canceledOnTouchOutside 点击边缘是否可取消
// */
// public static void stratProgressDialog(Context context, String msg, boolean cancelable,
// boolean canceledOnTouchOutside) {
// mDialog = new ProgressDialog(context, android.R.style.Theme_Material_Light_Dialog_NoActionBar_MinWidth);
// mDialog.setCancelable(cancelable);
// mDialog.setCanceledOnTouchOutside(canceledOnTouchOutside);
// mDialog.show();
// // mDialog.getWindow().setContentView(getDialogView(context, msg));
// }
//
// private static View getDialogView(Context context, String msg) {
//
// mDialogView = LayoutInflater.from(context).inflate(R.layout.dialog_progress, null);
// ((TextView) mDialogView.findViewById(R.id.txtView_dialog_show_msg)).setText(msg);
// return mDialogView;
// }
//
// /**
// * 停止显示全屏无进度的progress 确保在主(UI)线程执行
// */
// public static void stopProgressDialog() {
// if (mDialog.isShowing()) {
// mDialog.dismiss();
// // mDialog = null;
// // mDialogView.clearAnimation();
// // mDialogView = null;
// }
//
// }
//
// /**
// * 通过反射区设置默认的AlertDialog在点击确定时是否自动关闭dialog
// *
// * @param pDialog
// * @param pIsClose
// */
// public static void setAlertDialogIsClose(DialogInterface pDialog, Boolean pIsClose) {
// try {
// Field field = pDialog.getClass().getSuperclass().getDeclaredField("mShowing");
// field.setAccessible(true);
// field.set(pDialog, pIsClose);
// } catch (Exception e) {
// e.printStackTrace();
// }
// }
//
// }
// Path: sample/src/main/java/com/rocko/android/common/sample/MainActivity.java
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.v7.app.ActionBarActivity;
import android.view.Menu;
import android.view.MenuItem;
import com.rocko.android.common.util.DialogUtils;
package com.rocko.android.common.sample;
public class MainActivity extends ActionBarActivity {
@Override
protected void onCreate(final Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main); | DialogUtils.stratProgressDialog(this, "ss", false, false); |
zhengxiaopeng/AndroidUtils | old-library-with-sample/src/main/java/com/rocko/http/HttpUtil.java | // Path: old-library-with-sample/src/main/java/com/rocko/common/DebugLog.java
// public class DebugLog {
// /**
// * Log输出所在类
// */
// private static String className;
// /**
// * Log输出所在方法
// */
// private static String methodName;
// /**
// * Log输出所行号
// */
// private static int lineNumber;
//
// private DebugLog() {
// }
//
// /**
// * 是否可Debug状态
// *
// * @return
// */
// public static boolean isDebuggable() {
// return BuildConfig.DEBUG;
// }
//
// /**
// * 创建Log输出的基本信息
// *
// * @param log
// * @return
// */
// private static String createLog(String log) {
// StringBuffer buffer = new StringBuffer();
// buffer.append("[");
// buffer.append(methodName);
// buffer.append("()");
// buffer.append(" line:");
// buffer.append(lineNumber);
// buffer.append("] ");
// buffer.append(log);
// return buffer.toString();
// }
//
// /**
// * 取得输出所在位置的信息 className methodName lineNumber
// *
// * @param sElements
// */
// private static void getMethodNames(StackTraceElement[] sElements) {
// className = sElements[1].getFileName().split("\\.")[0];
// methodName = sElements[1].getMethodName();
// lineNumber = sElements[1].getLineNumber();
// }
//
// public static void e(String message) {
// if (!isDebuggable())
// return;
//
// getMethodNames(new Throwable().getStackTrace());
// Log.e(className, createLog(message));
// }
//
// public static void i(String message) {
// if (!isDebuggable())
// return;
//
// getMethodNames(new Throwable().getStackTrace());
// Log.i(className, createLog(message));
// }
//
// public static void d(String message) {
// if (!isDebuggable())
// return;
//
// getMethodNames(new Throwable().getStackTrace());
// Log.d(className, createLog(message));
// }
//
// public static void v(String message) {
// if (!isDebuggable())
// return;
//
// getMethodNames(new Throwable().getStackTrace());
// Log.v(className, createLog(message));
// }
//
// public static void w(String message) {
// if (!isDebuggable())
// return;
//
// getMethodNames(new Throwable().getStackTrace());
// Log.w(className, createLog(message));
// }
//
// public static void wtf(String message) {
// if (!isDebuggable())
// return;
//
// getMethodNames(new Throwable().getStackTrace());
// Log.wtf(className, createLog(message));
// }
//
// }
| import java.util.List;
import android.content.Context;
import com.rocko.common.DebugLog;
import org.apache.http.NameValuePair; | package com.rocko.http;
/**
* @author Mr.Zheng
* @date 2014年7月13日12:06:00
*/
public class HttpUtil {
/**
* ****************************** 网络连接部分 ********************************
*/
public static String postByHttpURLConnection(String strUrl, NameValuePair... nameValuePairs) {
return CustomHttpURLConnection.PostFromWebByHttpURLConnection(strUrl, nameValuePairs);
}
public static String getByHttpURLConnection(String strUrl, NameValuePair... nameValuePairs) {
return CustomHttpURLConnection.GetFromWebByHttpUrlConnection(strUrl, nameValuePairs);
}
public static String postByHttpClient(Context context, String strUrl, List<NameValuePair> nameValuePairs) {
return CustomHttpClient.PostFromWebByHttpClient(context, strUrl, nameValuePairs);
}
public static String getByHttpClient(Context context, String strUrl, NameValuePair... nameValuePairs) throws Exception {
return CustomHttpClient.getFromWebByHttpClient(context, strUrl, nameValuePairs);
}
/**
* 判断mobile网络是否可用
*
* @param context ApplicationContext
* @return
*/
public static boolean isMobileDataEnable(Context context) {
try {
return NetWorkHelper.isMobileDataEnable(context);
} catch (Exception e) { | // Path: old-library-with-sample/src/main/java/com/rocko/common/DebugLog.java
// public class DebugLog {
// /**
// * Log输出所在类
// */
// private static String className;
// /**
// * Log输出所在方法
// */
// private static String methodName;
// /**
// * Log输出所行号
// */
// private static int lineNumber;
//
// private DebugLog() {
// }
//
// /**
// * 是否可Debug状态
// *
// * @return
// */
// public static boolean isDebuggable() {
// return BuildConfig.DEBUG;
// }
//
// /**
// * 创建Log输出的基本信息
// *
// * @param log
// * @return
// */
// private static String createLog(String log) {
// StringBuffer buffer = new StringBuffer();
// buffer.append("[");
// buffer.append(methodName);
// buffer.append("()");
// buffer.append(" line:");
// buffer.append(lineNumber);
// buffer.append("] ");
// buffer.append(log);
// return buffer.toString();
// }
//
// /**
// * 取得输出所在位置的信息 className methodName lineNumber
// *
// * @param sElements
// */
// private static void getMethodNames(StackTraceElement[] sElements) {
// className = sElements[1].getFileName().split("\\.")[0];
// methodName = sElements[1].getMethodName();
// lineNumber = sElements[1].getLineNumber();
// }
//
// public static void e(String message) {
// if (!isDebuggable())
// return;
//
// getMethodNames(new Throwable().getStackTrace());
// Log.e(className, createLog(message));
// }
//
// public static void i(String message) {
// if (!isDebuggable())
// return;
//
// getMethodNames(new Throwable().getStackTrace());
// Log.i(className, createLog(message));
// }
//
// public static void d(String message) {
// if (!isDebuggable())
// return;
//
// getMethodNames(new Throwable().getStackTrace());
// Log.d(className, createLog(message));
// }
//
// public static void v(String message) {
// if (!isDebuggable())
// return;
//
// getMethodNames(new Throwable().getStackTrace());
// Log.v(className, createLog(message));
// }
//
// public static void w(String message) {
// if (!isDebuggable())
// return;
//
// getMethodNames(new Throwable().getStackTrace());
// Log.w(className, createLog(message));
// }
//
// public static void wtf(String message) {
// if (!isDebuggable())
// return;
//
// getMethodNames(new Throwable().getStackTrace());
// Log.wtf(className, createLog(message));
// }
//
// }
// Path: old-library-with-sample/src/main/java/com/rocko/http/HttpUtil.java
import java.util.List;
import android.content.Context;
import com.rocko.common.DebugLog;
import org.apache.http.NameValuePair;
package com.rocko.http;
/**
* @author Mr.Zheng
* @date 2014年7月13日12:06:00
*/
public class HttpUtil {
/**
* ****************************** 网络连接部分 ********************************
*/
public static String postByHttpURLConnection(String strUrl, NameValuePair... nameValuePairs) {
return CustomHttpURLConnection.PostFromWebByHttpURLConnection(strUrl, nameValuePairs);
}
public static String getByHttpURLConnection(String strUrl, NameValuePair... nameValuePairs) {
return CustomHttpURLConnection.GetFromWebByHttpUrlConnection(strUrl, nameValuePairs);
}
public static String postByHttpClient(Context context, String strUrl, List<NameValuePair> nameValuePairs) {
return CustomHttpClient.PostFromWebByHttpClient(context, strUrl, nameValuePairs);
}
public static String getByHttpClient(Context context, String strUrl, NameValuePair... nameValuePairs) throws Exception {
return CustomHttpClient.getFromWebByHttpClient(context, strUrl, nameValuePairs);
}
/**
* 判断mobile网络是否可用
*
* @param context ApplicationContext
* @return
*/
public static boolean isMobileDataEnable(Context context) {
try {
return NetWorkHelper.isMobileDataEnable(context);
} catch (Exception e) { | DebugLog.e(e.getMessage()); |
zhengxiaopeng/AndroidUtils | old-library-with-sample/src/main/java/com/rocko/utils/DialogUtils.java | // Path: old-library-with-sample/src/main/java/com/rocko/widget/dialog/SimpleDialog.java
// public class SimpleDialog implements OnClickListener {
// private Dialog dialog = null;
// private Context mContext = null;
// private TextView txtViewTitle, txtViewMsg;
// private Button btnCancel, btnConfirm;
// private View contentView = null;
// private SimpleDialogConfirmListener l = null;
//
// /**
// * SimpleDialog确认按钮监听接口
// */
// public interface SimpleDialogConfirmListener {
// /**
// * SimpleDialog确认按钮监听回调方法
// */
// void confirm();
// // void cancel();
// }
//
// public SimpleDialog(Context context) {
// this.mContext = context;
// this.contentView = LayoutInflater.from(context).inflate(R.layout.dialog_simple, null);
//
// this.txtViewTitle = (TextView) contentView.findViewById(R.id.txtView_dialog_simple_title);
// this.txtViewMsg = (TextView) contentView.findViewById(R.id.txtView_dialog_simple_msg);
// this.btnCancel = (Button) contentView.findViewById(R.id.btn_dialog_simple_cancel);
// this.btnConfirm = (Button) contentView.findViewById(R.id.btn_dialog_simple_confirm);
//
// this.btnCancel.setOnClickListener(this);
// this.btnConfirm.setOnClickListener(this);
// }
//
// /**
// * 设置Dialog的标题
// *
// * @param title
// */
// public SimpleDialog setTitle(String title) {
// txtViewTitle.setText(title);
// return this;
// }
//
// /**
// * 设置Dialog的提示信息
// *
// * @param msg
// */
// public SimpleDialog setMsg(String msg) {
// txtViewMsg.setText(msg);
// return this;
// }
//
// /**
// * 显示Dialog
// *
// * @param canceledOnTouchOutside 点击外边缘是否可取消
// * @param cancelable 按返回键是否可取消
// */
// public void showDialog(boolean canceledOnTouchOutside, boolean cancelable) {
// if (dialog == null)
// dialog = new AlertDialog.Builder(mContext).create();
// dialog.setCanceledOnTouchOutside(canceledOnTouchOutside);
// dialog.setCancelable(cancelable);
// dialog.show();
// Window window = dialog.getWindow();
// // window.setGravity(Gravity.BOTTOM);
// window.setContentView(contentView);
// }
//
// /**
// * 取消dialog显示
// */
// public void dimissDialog() {
// if (dialog.isShowing())
// dialog.dismiss();
// }
//
// /**
// * 设置监听器
// *
// * @param l
// */
// public void setSimpleDialogConfirmListener(SimpleDialogConfirmListener l) {
// this.l = l;
// }
//
// @Override
// public void onClick(View v) {
// switch (v.getId()) {
// case R.id.btn_dialog_simple_cancel:
// break;
// case R.id.btn_dialog_simple_confirm:
// if (l != null) {
// l.confirm();
// }
// break;
// default:
// break;
// }
// dimissDialog();
// }
// }
//
// Path: old-library-with-sample/src/main/java/com/rocko/widget/dialog/SimpleDialog.java
// public interface SimpleDialogConfirmListener {
// /**
// * SimpleDialog确认按钮监听回调方法
// */
// void confirm();
// // void cancel();
// }
| import android.app.AlertDialog;
import android.app.Dialog;
import android.content.Context;
import android.content.DialogInterface;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.TextView;
import com.rocko.androidutils.R;
import com.rocko.widget.dialog.SimpleDialog;
import com.rocko.widget.dialog.SimpleDialog.SimpleDialogConfirmListener;
import java.lang.reflect.Field; | package com.rocko.utils;
/**
* 基本Dialog的工具
*
* @author Mr.Zheng
* @date 2014年7月30日11:16:53
*/
public class DialogUtils {
private static Dialog mDialog = null;
private static View mDialogView = null; | // Path: old-library-with-sample/src/main/java/com/rocko/widget/dialog/SimpleDialog.java
// public class SimpleDialog implements OnClickListener {
// private Dialog dialog = null;
// private Context mContext = null;
// private TextView txtViewTitle, txtViewMsg;
// private Button btnCancel, btnConfirm;
// private View contentView = null;
// private SimpleDialogConfirmListener l = null;
//
// /**
// * SimpleDialog确认按钮监听接口
// */
// public interface SimpleDialogConfirmListener {
// /**
// * SimpleDialog确认按钮监听回调方法
// */
// void confirm();
// // void cancel();
// }
//
// public SimpleDialog(Context context) {
// this.mContext = context;
// this.contentView = LayoutInflater.from(context).inflate(R.layout.dialog_simple, null);
//
// this.txtViewTitle = (TextView) contentView.findViewById(R.id.txtView_dialog_simple_title);
// this.txtViewMsg = (TextView) contentView.findViewById(R.id.txtView_dialog_simple_msg);
// this.btnCancel = (Button) contentView.findViewById(R.id.btn_dialog_simple_cancel);
// this.btnConfirm = (Button) contentView.findViewById(R.id.btn_dialog_simple_confirm);
//
// this.btnCancel.setOnClickListener(this);
// this.btnConfirm.setOnClickListener(this);
// }
//
// /**
// * 设置Dialog的标题
// *
// * @param title
// */
// public SimpleDialog setTitle(String title) {
// txtViewTitle.setText(title);
// return this;
// }
//
// /**
// * 设置Dialog的提示信息
// *
// * @param msg
// */
// public SimpleDialog setMsg(String msg) {
// txtViewMsg.setText(msg);
// return this;
// }
//
// /**
// * 显示Dialog
// *
// * @param canceledOnTouchOutside 点击外边缘是否可取消
// * @param cancelable 按返回键是否可取消
// */
// public void showDialog(boolean canceledOnTouchOutside, boolean cancelable) {
// if (dialog == null)
// dialog = new AlertDialog.Builder(mContext).create();
// dialog.setCanceledOnTouchOutside(canceledOnTouchOutside);
// dialog.setCancelable(cancelable);
// dialog.show();
// Window window = dialog.getWindow();
// // window.setGravity(Gravity.BOTTOM);
// window.setContentView(contentView);
// }
//
// /**
// * 取消dialog显示
// */
// public void dimissDialog() {
// if (dialog.isShowing())
// dialog.dismiss();
// }
//
// /**
// * 设置监听器
// *
// * @param l
// */
// public void setSimpleDialogConfirmListener(SimpleDialogConfirmListener l) {
// this.l = l;
// }
//
// @Override
// public void onClick(View v) {
// switch (v.getId()) {
// case R.id.btn_dialog_simple_cancel:
// break;
// case R.id.btn_dialog_simple_confirm:
// if (l != null) {
// l.confirm();
// }
// break;
// default:
// break;
// }
// dimissDialog();
// }
// }
//
// Path: old-library-with-sample/src/main/java/com/rocko/widget/dialog/SimpleDialog.java
// public interface SimpleDialogConfirmListener {
// /**
// * SimpleDialog确认按钮监听回调方法
// */
// void confirm();
// // void cancel();
// }
// Path: old-library-with-sample/src/main/java/com/rocko/utils/DialogUtils.java
import android.app.AlertDialog;
import android.app.Dialog;
import android.content.Context;
import android.content.DialogInterface;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.TextView;
import com.rocko.androidutils.R;
import com.rocko.widget.dialog.SimpleDialog;
import com.rocko.widget.dialog.SimpleDialog.SimpleDialogConfirmListener;
import java.lang.reflect.Field;
package com.rocko.utils;
/**
* 基本Dialog的工具
*
* @author Mr.Zheng
* @date 2014年7月30日11:16:53
*/
public class DialogUtils {
private static Dialog mDialog = null;
private static View mDialogView = null; | private static SimpleDialog mSimpleDialog = null; |
zhengxiaopeng/AndroidUtils | old-library-with-sample/src/main/java/com/rocko/app/MainApplication.java | // Path: old-library-with-sample/src/main/java/com/rocko/common/DebugLog.java
// public class DebugLog {
// /**
// * Log输出所在类
// */
// private static String className;
// /**
// * Log输出所在方法
// */
// private static String methodName;
// /**
// * Log输出所行号
// */
// private static int lineNumber;
//
// private DebugLog() {
// }
//
// /**
// * 是否可Debug状态
// *
// * @return
// */
// public static boolean isDebuggable() {
// return BuildConfig.DEBUG;
// }
//
// /**
// * 创建Log输出的基本信息
// *
// * @param log
// * @return
// */
// private static String createLog(String log) {
// StringBuffer buffer = new StringBuffer();
// buffer.append("[");
// buffer.append(methodName);
// buffer.append("()");
// buffer.append(" line:");
// buffer.append(lineNumber);
// buffer.append("] ");
// buffer.append(log);
// return buffer.toString();
// }
//
// /**
// * 取得输出所在位置的信息 className methodName lineNumber
// *
// * @param sElements
// */
// private static void getMethodNames(StackTraceElement[] sElements) {
// className = sElements[1].getFileName().split("\\.")[0];
// methodName = sElements[1].getMethodName();
// lineNumber = sElements[1].getLineNumber();
// }
//
// public static void e(String message) {
// if (!isDebuggable())
// return;
//
// getMethodNames(new Throwable().getStackTrace());
// Log.e(className, createLog(message));
// }
//
// public static void i(String message) {
// if (!isDebuggable())
// return;
//
// getMethodNames(new Throwable().getStackTrace());
// Log.i(className, createLog(message));
// }
//
// public static void d(String message) {
// if (!isDebuggable())
// return;
//
// getMethodNames(new Throwable().getStackTrace());
// Log.d(className, createLog(message));
// }
//
// public static void v(String message) {
// if (!isDebuggable())
// return;
//
// getMethodNames(new Throwable().getStackTrace());
// Log.v(className, createLog(message));
// }
//
// public static void w(String message) {
// if (!isDebuggable())
// return;
//
// getMethodNames(new Throwable().getStackTrace());
// Log.w(className, createLog(message));
// }
//
// public static void wtf(String message) {
// if (!isDebuggable())
// return;
//
// getMethodNames(new Throwable().getStackTrace());
// Log.wtf(className, createLog(message));
// }
//
// }
| import android.app.Activity;
import android.app.ActivityManager;
import android.app.Application;
import android.content.Context;
import com.rocko.common.DebugLog;
import java.util.Stack; | package com.rocko.app;
/**
* @author Mr.Zheng
* @date 2014年9月15日 下午6:46:32
* 注意:Application对象并不是始终在内存中的,它有可能会由于系统内存不足而被杀掉(例如Home键或任务切换退出此程序后内存不足,Application被杀)。但Android在你恢复这个应用时
* 并不是重新开始启动这个应用,它会创建一个新的Application对象并且启动上次用户离开时的activity以造成这个app从
* 来没有被kill掉得假象。
*/
public class MainApplication extends Application {
private static MainApplication mainApplication;
/**
* activity栈
*/
private Stack<Activity> activitiesStack;
/**
* 获取全局Application Context
*/
public static MainApplication getContext() {
return mainApplication;
}
public MainApplication() {
mainApplication = this;
}
@Override
public void onCreate() { | // Path: old-library-with-sample/src/main/java/com/rocko/common/DebugLog.java
// public class DebugLog {
// /**
// * Log输出所在类
// */
// private static String className;
// /**
// * Log输出所在方法
// */
// private static String methodName;
// /**
// * Log输出所行号
// */
// private static int lineNumber;
//
// private DebugLog() {
// }
//
// /**
// * 是否可Debug状态
// *
// * @return
// */
// public static boolean isDebuggable() {
// return BuildConfig.DEBUG;
// }
//
// /**
// * 创建Log输出的基本信息
// *
// * @param log
// * @return
// */
// private static String createLog(String log) {
// StringBuffer buffer = new StringBuffer();
// buffer.append("[");
// buffer.append(methodName);
// buffer.append("()");
// buffer.append(" line:");
// buffer.append(lineNumber);
// buffer.append("] ");
// buffer.append(log);
// return buffer.toString();
// }
//
// /**
// * 取得输出所在位置的信息 className methodName lineNumber
// *
// * @param sElements
// */
// private static void getMethodNames(StackTraceElement[] sElements) {
// className = sElements[1].getFileName().split("\\.")[0];
// methodName = sElements[1].getMethodName();
// lineNumber = sElements[1].getLineNumber();
// }
//
// public static void e(String message) {
// if (!isDebuggable())
// return;
//
// getMethodNames(new Throwable().getStackTrace());
// Log.e(className, createLog(message));
// }
//
// public static void i(String message) {
// if (!isDebuggable())
// return;
//
// getMethodNames(new Throwable().getStackTrace());
// Log.i(className, createLog(message));
// }
//
// public static void d(String message) {
// if (!isDebuggable())
// return;
//
// getMethodNames(new Throwable().getStackTrace());
// Log.d(className, createLog(message));
// }
//
// public static void v(String message) {
// if (!isDebuggable())
// return;
//
// getMethodNames(new Throwable().getStackTrace());
// Log.v(className, createLog(message));
// }
//
// public static void w(String message) {
// if (!isDebuggable())
// return;
//
// getMethodNames(new Throwable().getStackTrace());
// Log.w(className, createLog(message));
// }
//
// public static void wtf(String message) {
// if (!isDebuggable())
// return;
//
// getMethodNames(new Throwable().getStackTrace());
// Log.wtf(className, createLog(message));
// }
//
// }
// Path: old-library-with-sample/src/main/java/com/rocko/app/MainApplication.java
import android.app.Activity;
import android.app.ActivityManager;
import android.app.Application;
import android.content.Context;
import com.rocko.common.DebugLog;
import java.util.Stack;
package com.rocko.app;
/**
* @author Mr.Zheng
* @date 2014年9月15日 下午6:46:32
* 注意:Application对象并不是始终在内存中的,它有可能会由于系统内存不足而被杀掉(例如Home键或任务切换退出此程序后内存不足,Application被杀)。但Android在你恢复这个应用时
* 并不是重新开始启动这个应用,它会创建一个新的Application对象并且启动上次用户离开时的activity以造成这个app从
* 来没有被kill掉得假象。
*/
public class MainApplication extends Application {
private static MainApplication mainApplication;
/**
* activity栈
*/
private Stack<Activity> activitiesStack;
/**
* 获取全局Application Context
*/
public static MainApplication getContext() {
return mainApplication;
}
public MainApplication() {
mainApplication = this;
}
@Override
public void onCreate() { | DebugLog.v("<<<"); |
zhengxiaopeng/AndroidUtils | old-library-with-sample/src/main/java/com/rocko/adapter/ViewHolder.java | // Path: old-library-with-sample/src/main/java/com/rocko/adapter/ImageLoader.java
// public enum Type {
// FIFO, LIFO
// }
| import android.content.Context;
import android.graphics.Bitmap;
import android.util.SparseArray;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.TextView;
import com.rocko.adapter.ImageLoader.Type; | * @return
*/
public ViewHolder setImageResource(int viewId, int drawableId) {
ImageView view = getView(viewId);
view.setImageResource(drawableId);
return this;
}
/**
* 为ImageView设置图片
*
* @param viewId
* @param drawableId
* @return
*/
public ViewHolder setImageBitmap(int viewId, Bitmap bm) {
ImageView view = getView(viewId);
view.setImageBitmap(bm);
return this;
}
/**
* 为ImageView设置图片
*
* @param viewId
* @param drawableId
* @return
*/
public ViewHolder setImageByUrl(int viewId, String url) { | // Path: old-library-with-sample/src/main/java/com/rocko/adapter/ImageLoader.java
// public enum Type {
// FIFO, LIFO
// }
// Path: old-library-with-sample/src/main/java/com/rocko/adapter/ViewHolder.java
import android.content.Context;
import android.graphics.Bitmap;
import android.util.SparseArray;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.TextView;
import com.rocko.adapter.ImageLoader.Type;
* @return
*/
public ViewHolder setImageResource(int viewId, int drawableId) {
ImageView view = getView(viewId);
view.setImageResource(drawableId);
return this;
}
/**
* 为ImageView设置图片
*
* @param viewId
* @param drawableId
* @return
*/
public ViewHolder setImageBitmap(int viewId, Bitmap bm) {
ImageView view = getView(viewId);
view.setImageBitmap(bm);
return this;
}
/**
* 为ImageView设置图片
*
* @param viewId
* @param drawableId
* @return
*/
public ViewHolder setImageByUrl(int viewId, String url) { | ImageLoader.getInstance(3, Type.LIFO).loadImage(url, (ImageView) getView(viewId)); |
zhengxiaopeng/AndroidUtils | library/src/main/java/com/rocko/android/common/util/ApplicationUtils.java | // Path: library/src/main/java/com/rocko/android/common/security/MD5Helper.java
// public class MD5Helper {
//
// protected final static char hexDigits[] = {'0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'a', 'b',
// 'c', 'd', 'e', 'f'};
//
// protected static MessageDigest messagedigest = null;
//
// static {
// try {
// messagedigest = MessageDigest.getInstance("MD5");
// } catch (NoSuchAlgorithmException nsaex) {
// System.err.println(MD5Helper.class.getName() + "初始化失败,MessageDigest不支持MD5Util。");
// nsaex.printStackTrace();
// }
// }
//
// /**
// * 功能:加盐版的MD5.返回格式为MD5(密码+{盐值})
// *
// * @param password 密码
// * @param salt 盐值
// * @return String
// * @author 郑晓鹏
// * @date 2014年06月24日
// */
// public static String getMD5StringWithSalt(String password, String salt) {
// if (password == null) {
// throw new IllegalArgumentException("password不能为null");
// }
// if (salt.equals("") || salt.length() == 0) {
// throw new IllegalArgumentException("salt不能为空");
// }
// if ((salt.toString().lastIndexOf("{") != -1) || (salt.toString().lastIndexOf("}") != -1)) {
// throw new IllegalArgumentException("salt中不能包含 { 或者 }");
// }
// return getMD5String(password + "{" + salt.toString() + "}");
// }
//
// /**
// * 功能:得到文件的md5值。
// *
// * @param file 文件。
// * @return String
// * @throws java.io.IOException 读取文件IO异常时。
// * @author 郑晓鹏
// * @date 2014年06月24日
// */
// public static String getFileMD5String(File file) throws IOException {
// FileInputStream in = new FileInputStream(file);
// FileChannel ch = in.getChannel();
// MappedByteBuffer byteBuffer = ch.map(FileChannel.MapMode.READ_ONLY, 0, file.length());
// messagedigest.update(byteBuffer);
// return bufferToHex(messagedigest.digest());
// }
//
// /**
// * 功能:得到一个字符串的MD5值。
// *
// * @param str 字符串
// * @return String
// * @author 郑晓鹏
// * @date 2014年06月24日
// */
// public static String getMD5String(String str) {
// return getMD5String(str.getBytes());
// }
//
// private static String getMD5String(byte[] bytes) {
// messagedigest.update(bytes);
// return bufferToHex(messagedigest.digest());
// }
//
// private static String bufferToHex(byte bytes[]) {
// return bufferToHex(bytes, 0, bytes.length);
// }
//
// private static String bufferToHex(byte bytes[], int m, int n) {
// StringBuffer stringbuffer = new StringBuffer(2 * n);
// int k = m + n;
// for (int l = m; l < k; l++) {
// appendHexPair(bytes[l], stringbuffer);
// }
// return stringbuffer.toString();
// }
//
// private static void appendHexPair(byte bt, StringBuffer stringbuffer) {
// char c0 = hexDigits[(bt & 0xf0) >> 4];
// char c1 = hexDigits[bt & 0xf];
// stringbuffer.append(c0);
// stringbuffer.append(c1);
// }
//
// /*
// * 哈希摘摘要
// */
// public static String hexdigest(byte[] paramArrayOfByte) {
// try {
// MessageDigest localMessageDigest = MessageDigest.getInstance("MD5");
// localMessageDigest.update(paramArrayOfByte);
// byte[] arrayOfByte = localMessageDigest.digest();
// char[] arrayOfChar = new char[32];
// int i = 0;
// int j = 0;
// for (; ; ) {
// if (i >= 16) {
// return new String(arrayOfChar);
// }
// int k = arrayOfByte[i];
// int m = j + 1;
// arrayOfChar[j] = hexDigits[(0xF & k >>> 4)];
// j = m + 1;
// arrayOfChar[m] = hexDigits[(k & 0xF)];
// i++;
// }
//
// } catch (Exception localException) {
// return null;
// }
// }
// }
| import android.content.Context;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.content.pm.Signature;
import android.os.Environment;
import com.rocko.android.common.security.MD5Helper;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException; | }
FileInputStream fis = new FileInputStream(in);
FileOutputStream fos = new FileOutputStream(out);
int count;
// 文件太大的话,我觉得需要修改
byte[] buffer = new byte[256 * 1024];
while ((count = fis.read(buffer)) > 0) {
fos.write(buffer, 0, count);
}
fis.close();
fos.flush();
fos.close();
}
/**
* 获取应用的MD5签名值
*
* @param context ApplicationContext
* @return
*/
public static String getSign(Context context) {
PackageManager packageManager = context.getPackageManager();
try {
PackageInfo packageInfo = packageManager.getPackageInfo(context.getPackageName(),
PackageManager.GET_SIGNATURES);
Signature[] signs = packageInfo.signatures;
Signature sign = signs[0]; | // Path: library/src/main/java/com/rocko/android/common/security/MD5Helper.java
// public class MD5Helper {
//
// protected final static char hexDigits[] = {'0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'a', 'b',
// 'c', 'd', 'e', 'f'};
//
// protected static MessageDigest messagedigest = null;
//
// static {
// try {
// messagedigest = MessageDigest.getInstance("MD5");
// } catch (NoSuchAlgorithmException nsaex) {
// System.err.println(MD5Helper.class.getName() + "初始化失败,MessageDigest不支持MD5Util。");
// nsaex.printStackTrace();
// }
// }
//
// /**
// * 功能:加盐版的MD5.返回格式为MD5(密码+{盐值})
// *
// * @param password 密码
// * @param salt 盐值
// * @return String
// * @author 郑晓鹏
// * @date 2014年06月24日
// */
// public static String getMD5StringWithSalt(String password, String salt) {
// if (password == null) {
// throw new IllegalArgumentException("password不能为null");
// }
// if (salt.equals("") || salt.length() == 0) {
// throw new IllegalArgumentException("salt不能为空");
// }
// if ((salt.toString().lastIndexOf("{") != -1) || (salt.toString().lastIndexOf("}") != -1)) {
// throw new IllegalArgumentException("salt中不能包含 { 或者 }");
// }
// return getMD5String(password + "{" + salt.toString() + "}");
// }
//
// /**
// * 功能:得到文件的md5值。
// *
// * @param file 文件。
// * @return String
// * @throws java.io.IOException 读取文件IO异常时。
// * @author 郑晓鹏
// * @date 2014年06月24日
// */
// public static String getFileMD5String(File file) throws IOException {
// FileInputStream in = new FileInputStream(file);
// FileChannel ch = in.getChannel();
// MappedByteBuffer byteBuffer = ch.map(FileChannel.MapMode.READ_ONLY, 0, file.length());
// messagedigest.update(byteBuffer);
// return bufferToHex(messagedigest.digest());
// }
//
// /**
// * 功能:得到一个字符串的MD5值。
// *
// * @param str 字符串
// * @return String
// * @author 郑晓鹏
// * @date 2014年06月24日
// */
// public static String getMD5String(String str) {
// return getMD5String(str.getBytes());
// }
//
// private static String getMD5String(byte[] bytes) {
// messagedigest.update(bytes);
// return bufferToHex(messagedigest.digest());
// }
//
// private static String bufferToHex(byte bytes[]) {
// return bufferToHex(bytes, 0, bytes.length);
// }
//
// private static String bufferToHex(byte bytes[], int m, int n) {
// StringBuffer stringbuffer = new StringBuffer(2 * n);
// int k = m + n;
// for (int l = m; l < k; l++) {
// appendHexPair(bytes[l], stringbuffer);
// }
// return stringbuffer.toString();
// }
//
// private static void appendHexPair(byte bt, StringBuffer stringbuffer) {
// char c0 = hexDigits[(bt & 0xf0) >> 4];
// char c1 = hexDigits[bt & 0xf];
// stringbuffer.append(c0);
// stringbuffer.append(c1);
// }
//
// /*
// * 哈希摘摘要
// */
// public static String hexdigest(byte[] paramArrayOfByte) {
// try {
// MessageDigest localMessageDigest = MessageDigest.getInstance("MD5");
// localMessageDigest.update(paramArrayOfByte);
// byte[] arrayOfByte = localMessageDigest.digest();
// char[] arrayOfChar = new char[32];
// int i = 0;
// int j = 0;
// for (; ; ) {
// if (i >= 16) {
// return new String(arrayOfChar);
// }
// int k = arrayOfByte[i];
// int m = j + 1;
// arrayOfChar[j] = hexDigits[(0xF & k >>> 4)];
// j = m + 1;
// arrayOfChar[m] = hexDigits[(k & 0xF)];
// i++;
// }
//
// } catch (Exception localException) {
// return null;
// }
// }
// }
// Path: library/src/main/java/com/rocko/android/common/util/ApplicationUtils.java
import android.content.Context;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.content.pm.Signature;
import android.os.Environment;
import com.rocko.android.common.security.MD5Helper;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
}
FileInputStream fis = new FileInputStream(in);
FileOutputStream fos = new FileOutputStream(out);
int count;
// 文件太大的话,我觉得需要修改
byte[] buffer = new byte[256 * 1024];
while ((count = fis.read(buffer)) > 0) {
fos.write(buffer, 0, count);
}
fis.close();
fos.flush();
fos.close();
}
/**
* 获取应用的MD5签名值
*
* @param context ApplicationContext
* @return
*/
public static String getSign(Context context) {
PackageManager packageManager = context.getPackageManager();
try {
PackageInfo packageInfo = packageManager.getPackageInfo(context.getPackageName(),
PackageManager.GET_SIGNATURES);
Signature[] signs = packageInfo.signatures;
Signature sign = signs[0]; | return MD5Helper.hexdigest(sign.toByteArray()); |
zhengxiaopeng/AndroidUtils | old-library-with-sample/src/main/java/com/rocko/utils/JsonUtils.java | // Path: old-library-with-sample/src/main/java/com/rocko/common/DebugLog.java
// public class DebugLog {
// /**
// * Log输出所在类
// */
// private static String className;
// /**
// * Log输出所在方法
// */
// private static String methodName;
// /**
// * Log输出所行号
// */
// private static int lineNumber;
//
// private DebugLog() {
// }
//
// /**
// * 是否可Debug状态
// *
// * @return
// */
// public static boolean isDebuggable() {
// return BuildConfig.DEBUG;
// }
//
// /**
// * 创建Log输出的基本信息
// *
// * @param log
// * @return
// */
// private static String createLog(String log) {
// StringBuffer buffer = new StringBuffer();
// buffer.append("[");
// buffer.append(methodName);
// buffer.append("()");
// buffer.append(" line:");
// buffer.append(lineNumber);
// buffer.append("] ");
// buffer.append(log);
// return buffer.toString();
// }
//
// /**
// * 取得输出所在位置的信息 className methodName lineNumber
// *
// * @param sElements
// */
// private static void getMethodNames(StackTraceElement[] sElements) {
// className = sElements[1].getFileName().split("\\.")[0];
// methodName = sElements[1].getMethodName();
// lineNumber = sElements[1].getLineNumber();
// }
//
// public static void e(String message) {
// if (!isDebuggable())
// return;
//
// getMethodNames(new Throwable().getStackTrace());
// Log.e(className, createLog(message));
// }
//
// public static void i(String message) {
// if (!isDebuggable())
// return;
//
// getMethodNames(new Throwable().getStackTrace());
// Log.i(className, createLog(message));
// }
//
// public static void d(String message) {
// if (!isDebuggable())
// return;
//
// getMethodNames(new Throwable().getStackTrace());
// Log.d(className, createLog(message));
// }
//
// public static void v(String message) {
// if (!isDebuggable())
// return;
//
// getMethodNames(new Throwable().getStackTrace());
// Log.v(className, createLog(message));
// }
//
// public static void w(String message) {
// if (!isDebuggable())
// return;
//
// getMethodNames(new Throwable().getStackTrace());
// Log.w(className, createLog(message));
// }
//
// public static void wtf(String message) {
// if (!isDebuggable())
// return;
//
// getMethodNames(new Throwable().getStackTrace());
// Log.wtf(className, createLog(message));
// }
//
// }
| import com.fasterxml.jackson.core.JsonGenerationException;
import com.fasterxml.jackson.core.JsonParseException;
import com.fasterxml.jackson.core.type.TypeReference;
import com.fasterxml.jackson.databind.JsonMappingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.type.TypeFactory;
import com.rocko.common.DebugLog;
import java.io.IOException;
import java.io.StringWriter;
import java.io.Writer; | package com.rocko.utils;
/**
* Json工具:Json数据和Java对象之间的转换
*
* @author Mr.Zheng
* @date 2014年7月15日10:24:52
*/
public class JsonUtils {
private static ObjectMapper objectMapper = new ObjectMapper();
/**
* 将对象序列化为JSON字符串
*
* @param object
* @return JSON字符串
*/
public static String serialize(Object object) {
Writer write = new StringWriter();
try {
objectMapper.writeValue(write, object);
} catch (JsonGenerationException e) { | // Path: old-library-with-sample/src/main/java/com/rocko/common/DebugLog.java
// public class DebugLog {
// /**
// * Log输出所在类
// */
// private static String className;
// /**
// * Log输出所在方法
// */
// private static String methodName;
// /**
// * Log输出所行号
// */
// private static int lineNumber;
//
// private DebugLog() {
// }
//
// /**
// * 是否可Debug状态
// *
// * @return
// */
// public static boolean isDebuggable() {
// return BuildConfig.DEBUG;
// }
//
// /**
// * 创建Log输出的基本信息
// *
// * @param log
// * @return
// */
// private static String createLog(String log) {
// StringBuffer buffer = new StringBuffer();
// buffer.append("[");
// buffer.append(methodName);
// buffer.append("()");
// buffer.append(" line:");
// buffer.append(lineNumber);
// buffer.append("] ");
// buffer.append(log);
// return buffer.toString();
// }
//
// /**
// * 取得输出所在位置的信息 className methodName lineNumber
// *
// * @param sElements
// */
// private static void getMethodNames(StackTraceElement[] sElements) {
// className = sElements[1].getFileName().split("\\.")[0];
// methodName = sElements[1].getMethodName();
// lineNumber = sElements[1].getLineNumber();
// }
//
// public static void e(String message) {
// if (!isDebuggable())
// return;
//
// getMethodNames(new Throwable().getStackTrace());
// Log.e(className, createLog(message));
// }
//
// public static void i(String message) {
// if (!isDebuggable())
// return;
//
// getMethodNames(new Throwable().getStackTrace());
// Log.i(className, createLog(message));
// }
//
// public static void d(String message) {
// if (!isDebuggable())
// return;
//
// getMethodNames(new Throwable().getStackTrace());
// Log.d(className, createLog(message));
// }
//
// public static void v(String message) {
// if (!isDebuggable())
// return;
//
// getMethodNames(new Throwable().getStackTrace());
// Log.v(className, createLog(message));
// }
//
// public static void w(String message) {
// if (!isDebuggable())
// return;
//
// getMethodNames(new Throwable().getStackTrace());
// Log.w(className, createLog(message));
// }
//
// public static void wtf(String message) {
// if (!isDebuggable())
// return;
//
// getMethodNames(new Throwable().getStackTrace());
// Log.wtf(className, createLog(message));
// }
//
// }
// Path: old-library-with-sample/src/main/java/com/rocko/utils/JsonUtils.java
import com.fasterxml.jackson.core.JsonGenerationException;
import com.fasterxml.jackson.core.JsonParseException;
import com.fasterxml.jackson.core.type.TypeReference;
import com.fasterxml.jackson.databind.JsonMappingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.type.TypeFactory;
import com.rocko.common.DebugLog;
import java.io.IOException;
import java.io.StringWriter;
import java.io.Writer;
package com.rocko.utils;
/**
* Json工具:Json数据和Java对象之间的转换
*
* @author Mr.Zheng
* @date 2014年7月15日10:24:52
*/
public class JsonUtils {
private static ObjectMapper objectMapper = new ObjectMapper();
/**
* 将对象序列化为JSON字符串
*
* @param object
* @return JSON字符串
*/
public static String serialize(Object object) {
Writer write = new StringWriter();
try {
objectMapper.writeValue(write, object);
} catch (JsonGenerationException e) { | DebugLog.e(e.getMessage()); |
pe-pan/flappy | core/src/main/java/net/panuska/tlappy/FinalScreen.java | // Path: core/src/main/java/net/panuska/tlappy/awt/Color.java
// public enum Color {
// BLACK(0xff000000),
// RED(0xffff0000),
// BLUE(0xff0000ff),
// YELLOW(0xffffff00),
// WHITE(0xffffffff),
// DARK_GRAY(0xff404040),
// LIGHT_GRAY(0xffc0c0c0),
// TRANSPARENT(0x00000000),
//
// black(0xff000000),
// red(0xffff0000),
// blue(0xff0000ff),
// yellow(0xffffff00),
// white(0xffffffff),
// dark_gray(0xff404040);
//
// private final int color;
// Color(int color) { this.color = color; }
// public int getValue() { return color; }
// }
//
// Path: core/src/main/java/net/panuska/tlappy/Device.java
// public class Device {
// private static final String TAG = Device.class.getSimpleName();
// public static Keyboard keyboard;
// public static VRAM vram;
// public static Music music;
//
// public static int displayWidth;
// public static int displayHeight;
//
// public static boolean initialized = false;
// public static void init (SurfaceView view) {
// if (initialized) {
// Log.d(TAG, "Device already initialized");
// return;
// }
// Log.d(TAG, "Init");
// Images.load(view.getResources());
// keyboard = Keyboard.getInstance();
// vram = VRAM.getInstance();
// vram.createWindow(view);
// music = Music.getInstance(view.getContext());
// WindowManager wm = (WindowManager) view.getContext().getSystemService(Context.WINDOW_SERVICE);
// Display display = wm.getDefaultDisplay();
// displayWidth = display.getWidth();
// displayHeight = display.getHeight();
// if (displayHeight > displayWidth) {
// Log.d(TAG, "Swapping display width and height "+displayWidth+", "+displayHeight);
// displayWidth = displayWidth + displayHeight;
// displayHeight = displayWidth - displayHeight;
// displayWidth = displayWidth - displayHeight;
// }
// initialized = true;
// }
//
// public static void destroy() {
// music.destroy();
// initialized = false;
// }
// }
| import net.panuska.tlappy.awt.Color;
import static net.panuska.tlappy.Device.*; | }
}
//sync
vram.refresh();
Main.wait(50);
}
vram.imageNoOfs(20, 22, Images.chickenDown);
vram.refresh();
}
private void rut(byte[] arr, int c, Chicken chicken) {
Chicken.DemoStepInfo par = new Chicken.DemoStepInfo();
int cc = 2 * c;
if (arr7C64[c + 0x3c] >= arr7C64[c]) {
return;
}
par.steps = arr;
par.pStep = arr7C64[c + 0x3c];
par.cx = arr7BEC[cc];
par.cy = arr7BEC[cc + 1];
chicken.demoDoStep1(par);
arr7BEC[cc] = (byte) par.cx;
arr7BEC[cc + 1] = (byte) par.cy;
}
void finalCertificate() {
vram.clear();
vram.refresh();
music.start();
chickenBorder(); | // Path: core/src/main/java/net/panuska/tlappy/awt/Color.java
// public enum Color {
// BLACK(0xff000000),
// RED(0xffff0000),
// BLUE(0xff0000ff),
// YELLOW(0xffffff00),
// WHITE(0xffffffff),
// DARK_GRAY(0xff404040),
// LIGHT_GRAY(0xffc0c0c0),
// TRANSPARENT(0x00000000),
//
// black(0xff000000),
// red(0xffff0000),
// blue(0xff0000ff),
// yellow(0xffffff00),
// white(0xffffffff),
// dark_gray(0xff404040);
//
// private final int color;
// Color(int color) { this.color = color; }
// public int getValue() { return color; }
// }
//
// Path: core/src/main/java/net/panuska/tlappy/Device.java
// public class Device {
// private static final String TAG = Device.class.getSimpleName();
// public static Keyboard keyboard;
// public static VRAM vram;
// public static Music music;
//
// public static int displayWidth;
// public static int displayHeight;
//
// public static boolean initialized = false;
// public static void init (SurfaceView view) {
// if (initialized) {
// Log.d(TAG, "Device already initialized");
// return;
// }
// Log.d(TAG, "Init");
// Images.load(view.getResources());
// keyboard = Keyboard.getInstance();
// vram = VRAM.getInstance();
// vram.createWindow(view);
// music = Music.getInstance(view.getContext());
// WindowManager wm = (WindowManager) view.getContext().getSystemService(Context.WINDOW_SERVICE);
// Display display = wm.getDefaultDisplay();
// displayWidth = display.getWidth();
// displayHeight = display.getHeight();
// if (displayHeight > displayWidth) {
// Log.d(TAG, "Swapping display width and height "+displayWidth+", "+displayHeight);
// displayWidth = displayWidth + displayHeight;
// displayHeight = displayWidth - displayHeight;
// displayWidth = displayWidth - displayHeight;
// }
// initialized = true;
// }
//
// public static void destroy() {
// music.destroy();
// initialized = false;
// }
// }
// Path: core/src/main/java/net/panuska/tlappy/FinalScreen.java
import net.panuska.tlappy.awt.Color;
import static net.panuska.tlappy.Device.*;
}
}
//sync
vram.refresh();
Main.wait(50);
}
vram.imageNoOfs(20, 22, Images.chickenDown);
vram.refresh();
}
private void rut(byte[] arr, int c, Chicken chicken) {
Chicken.DemoStepInfo par = new Chicken.DemoStepInfo();
int cc = 2 * c;
if (arr7C64[c + 0x3c] >= arr7C64[c]) {
return;
}
par.steps = arr;
par.pStep = arr7C64[c + 0x3c];
par.cx = arr7BEC[cc];
par.cy = arr7BEC[cc + 1];
chicken.demoDoStep1(par);
arr7BEC[cc] = (byte) par.cx;
arr7BEC[cc + 1] = (byte) par.cy;
}
void finalCertificate() {
vram.clear();
vram.refresh();
music.start();
chickenBorder(); | final Color c = Color.WHITE; |
pe-pan/flappy | core/src/main/java/net/panuska/tlappy/awt/Graphics.java | // Path: core/src/main/java/net/panuska/tlappy/Constants.java
// public class Constants {
//
// static final int SCREEN_WIDTH = 320;
// static final int SCREEN_HEIGHT = 200;
// static final int NUM_SCENES = 200;
// static final int LIVES = 5;
// public static final int SPRITE_SIZE = 16;
// public static final int SPRITE_HALF = 8;
// public static final int FONT_WIDTH = SPRITE_HALF;
//
// static final int UP = 1;
// static final int DOWN = 2;
// static final int LEFT = 3;
// static final int RIGHT = 4;
// static final int FIRE = 5;
// static final int ESC = 255;
//
// static final int INTRO = -1;
// static final int GAME = -2;
// static final int SETUP = -3;
//
// static final byte SPACE = 0;
// static final byte MUSHROOM = 0x10;
// static final byte CHICKEN = 0x20;
// static final byte BLUE_ENEMY = 0x30;
// static final byte RED_ENEMY = 0x40;
// static final byte RED_BALL = 0x50;
// static final byte BLUE_BALL = 0x60;
// static final byte WALL = 0x70;
// static final byte BLUE_WALL = 0x71; // ORIGINAL: (byte) 0x80;
//
// }
//
// Path: core/src/main/java/net/panuska/tlappy/ImageUtils.java
// public class ImageUtils {
//
// private static final int ZOOM = 1;
//
// private ImageUtils() {
// }
// static BufferedImage loadDrawable(Resources r, int drawableId) {
// BitmapDrawable d = (BitmapDrawable)r.getDrawable(drawableId);
// return new BufferedImage(d);
// }
//
// public static final int FONT_SIZE = 8;
// public static BufferedImage createLetterImage(int z, Color color, Color background) {
// BufferedImage img = new BufferedImage(FONT_SIZE * ZOOM, FONT_SIZE * ZOOM, BufferedImage.TYPE_INT_RGB);
// Graphics g = img.getGraphics();
// for (int i = 0; i < FONT_SIZE; i++) {
// int b = Fonts.bitmap[z][i];
// for (int j = 0; j < FONT_SIZE; j++) {
// boolean px = (b & 0x80) == 0x80;
// b = b << 1;
// g.setColor(px ? color : background);
// g.fillRect(j * ZOOM, i * ZOOM, ZOOM, ZOOM);
// }
// }
// return img;
// }
// }
| import android.graphics.Bitmap;
import android.graphics.Canvas;
import android.graphics.Paint;
import android.graphics.Typeface;
import net.panuska.tlappy.Constants;
import net.panuska.tlappy.ImageUtils; | package net.panuska.tlappy.awt;
/**
* Flappy:
* Original game created by dB-SOFT in 1984 for SHARP MZ-800 computer.
* Java version by Petr Slechta, 2014.
* Android version by Petr Panuska, 2015.
*/
public class Graphics {
private Canvas c;
static final private Paint p = new Paint();
public Graphics(Bitmap b) {
c = new Canvas(b);
}
public void setColor(Color c) {
p.setColor(c.getValue());
}
public void fillRect(int x, int y, int width, int height) {
p.setStyle(Paint.Style.FILL);
c.drawRect(x, y, x+width, y+height, p);
}
public void drawRect(int x, int y, int width, int height) {
p.setStyle(Paint.Style.STROKE);
c.drawRect(x, y, x+width, y+height, p);
}
public boolean drawImage(BufferedImage img, int x, int y, Paint paint) {
c.drawBitmap(img.getBitmap(), x, y, paint);
return true;
}
public void drawString(String str, int x, int y, Color color) {
Paint p = new Paint();
p.setTypeface(Typeface.DEFAULT_BOLD); | // Path: core/src/main/java/net/panuska/tlappy/Constants.java
// public class Constants {
//
// static final int SCREEN_WIDTH = 320;
// static final int SCREEN_HEIGHT = 200;
// static final int NUM_SCENES = 200;
// static final int LIVES = 5;
// public static final int SPRITE_SIZE = 16;
// public static final int SPRITE_HALF = 8;
// public static final int FONT_WIDTH = SPRITE_HALF;
//
// static final int UP = 1;
// static final int DOWN = 2;
// static final int LEFT = 3;
// static final int RIGHT = 4;
// static final int FIRE = 5;
// static final int ESC = 255;
//
// static final int INTRO = -1;
// static final int GAME = -2;
// static final int SETUP = -3;
//
// static final byte SPACE = 0;
// static final byte MUSHROOM = 0x10;
// static final byte CHICKEN = 0x20;
// static final byte BLUE_ENEMY = 0x30;
// static final byte RED_ENEMY = 0x40;
// static final byte RED_BALL = 0x50;
// static final byte BLUE_BALL = 0x60;
// static final byte WALL = 0x70;
// static final byte BLUE_WALL = 0x71; // ORIGINAL: (byte) 0x80;
//
// }
//
// Path: core/src/main/java/net/panuska/tlappy/ImageUtils.java
// public class ImageUtils {
//
// private static final int ZOOM = 1;
//
// private ImageUtils() {
// }
// static BufferedImage loadDrawable(Resources r, int drawableId) {
// BitmapDrawable d = (BitmapDrawable)r.getDrawable(drawableId);
// return new BufferedImage(d);
// }
//
// public static final int FONT_SIZE = 8;
// public static BufferedImage createLetterImage(int z, Color color, Color background) {
// BufferedImage img = new BufferedImage(FONT_SIZE * ZOOM, FONT_SIZE * ZOOM, BufferedImage.TYPE_INT_RGB);
// Graphics g = img.getGraphics();
// for (int i = 0; i < FONT_SIZE; i++) {
// int b = Fonts.bitmap[z][i];
// for (int j = 0; j < FONT_SIZE; j++) {
// boolean px = (b & 0x80) == 0x80;
// b = b << 1;
// g.setColor(px ? color : background);
// g.fillRect(j * ZOOM, i * ZOOM, ZOOM, ZOOM);
// }
// }
// return img;
// }
// }
// Path: core/src/main/java/net/panuska/tlappy/awt/Graphics.java
import android.graphics.Bitmap;
import android.graphics.Canvas;
import android.graphics.Paint;
import android.graphics.Typeface;
import net.panuska.tlappy.Constants;
import net.panuska.tlappy.ImageUtils;
package net.panuska.tlappy.awt;
/**
* Flappy:
* Original game created by dB-SOFT in 1984 for SHARP MZ-800 computer.
* Java version by Petr Slechta, 2014.
* Android version by Petr Panuska, 2015.
*/
public class Graphics {
private Canvas c;
static final private Paint p = new Paint();
public Graphics(Bitmap b) {
c = new Canvas(b);
}
public void setColor(Color c) {
p.setColor(c.getValue());
}
public void fillRect(int x, int y, int width, int height) {
p.setStyle(Paint.Style.FILL);
c.drawRect(x, y, x+width, y+height, p);
}
public void drawRect(int x, int y, int width, int height) {
p.setStyle(Paint.Style.STROKE);
c.drawRect(x, y, x+width, y+height, p);
}
public boolean drawImage(BufferedImage img, int x, int y, Paint paint) {
c.drawBitmap(img.getBitmap(), x, y, paint);
return true;
}
public void drawString(String str, int x, int y, Color color) {
Paint p = new Paint();
p.setTypeface(Typeface.DEFAULT_BOLD); | p.setTextSize(Constants.SPRITE_SIZE); |
pe-pan/flappy | core/src/main/java/net/panuska/tlappy/awt/Graphics.java | // Path: core/src/main/java/net/panuska/tlappy/Constants.java
// public class Constants {
//
// static final int SCREEN_WIDTH = 320;
// static final int SCREEN_HEIGHT = 200;
// static final int NUM_SCENES = 200;
// static final int LIVES = 5;
// public static final int SPRITE_SIZE = 16;
// public static final int SPRITE_HALF = 8;
// public static final int FONT_WIDTH = SPRITE_HALF;
//
// static final int UP = 1;
// static final int DOWN = 2;
// static final int LEFT = 3;
// static final int RIGHT = 4;
// static final int FIRE = 5;
// static final int ESC = 255;
//
// static final int INTRO = -1;
// static final int GAME = -2;
// static final int SETUP = -3;
//
// static final byte SPACE = 0;
// static final byte MUSHROOM = 0x10;
// static final byte CHICKEN = 0x20;
// static final byte BLUE_ENEMY = 0x30;
// static final byte RED_ENEMY = 0x40;
// static final byte RED_BALL = 0x50;
// static final byte BLUE_BALL = 0x60;
// static final byte WALL = 0x70;
// static final byte BLUE_WALL = 0x71; // ORIGINAL: (byte) 0x80;
//
// }
//
// Path: core/src/main/java/net/panuska/tlappy/ImageUtils.java
// public class ImageUtils {
//
// private static final int ZOOM = 1;
//
// private ImageUtils() {
// }
// static BufferedImage loadDrawable(Resources r, int drawableId) {
// BitmapDrawable d = (BitmapDrawable)r.getDrawable(drawableId);
// return new BufferedImage(d);
// }
//
// public static final int FONT_SIZE = 8;
// public static BufferedImage createLetterImage(int z, Color color, Color background) {
// BufferedImage img = new BufferedImage(FONT_SIZE * ZOOM, FONT_SIZE * ZOOM, BufferedImage.TYPE_INT_RGB);
// Graphics g = img.getGraphics();
// for (int i = 0; i < FONT_SIZE; i++) {
// int b = Fonts.bitmap[z][i];
// for (int j = 0; j < FONT_SIZE; j++) {
// boolean px = (b & 0x80) == 0x80;
// b = b << 1;
// g.setColor(px ? color : background);
// g.fillRect(j * ZOOM, i * ZOOM, ZOOM, ZOOM);
// }
// }
// return img;
// }
// }
| import android.graphics.Bitmap;
import android.graphics.Canvas;
import android.graphics.Paint;
import android.graphics.Typeface;
import net.panuska.tlappy.Constants;
import net.panuska.tlappy.ImageUtils; | }
public boolean drawImage(BufferedImage img, int x, int y, Paint paint) {
c.drawBitmap(img.getBitmap(), x, y, paint);
return true;
}
public void drawString(String str, int x, int y, Color color) {
Paint p = new Paint();
p.setTypeface(Typeface.DEFAULT_BOLD);
p.setTextSize(Constants.SPRITE_SIZE);
p.setColor(color.getValue());
c.drawText(str, x, y + Constants.SPRITE_SIZE, p);
}
/**
* Draws string using monospaced (Flappy built-in) font.
* @param text
* @param x
* @param y
* @param color
*/
public void drawText(String text, int x, int y, Color color) {
//todo copied from VRAM.printText()
for (int i = 0, maxi = text.length(); i < maxi; i++) {
int z = text.charAt(i);
if (z < 0x20 || z > 0x7a) {
z = '!';
}
z -= 0x20; | // Path: core/src/main/java/net/panuska/tlappy/Constants.java
// public class Constants {
//
// static final int SCREEN_WIDTH = 320;
// static final int SCREEN_HEIGHT = 200;
// static final int NUM_SCENES = 200;
// static final int LIVES = 5;
// public static final int SPRITE_SIZE = 16;
// public static final int SPRITE_HALF = 8;
// public static final int FONT_WIDTH = SPRITE_HALF;
//
// static final int UP = 1;
// static final int DOWN = 2;
// static final int LEFT = 3;
// static final int RIGHT = 4;
// static final int FIRE = 5;
// static final int ESC = 255;
//
// static final int INTRO = -1;
// static final int GAME = -2;
// static final int SETUP = -3;
//
// static final byte SPACE = 0;
// static final byte MUSHROOM = 0x10;
// static final byte CHICKEN = 0x20;
// static final byte BLUE_ENEMY = 0x30;
// static final byte RED_ENEMY = 0x40;
// static final byte RED_BALL = 0x50;
// static final byte BLUE_BALL = 0x60;
// static final byte WALL = 0x70;
// static final byte BLUE_WALL = 0x71; // ORIGINAL: (byte) 0x80;
//
// }
//
// Path: core/src/main/java/net/panuska/tlappy/ImageUtils.java
// public class ImageUtils {
//
// private static final int ZOOM = 1;
//
// private ImageUtils() {
// }
// static BufferedImage loadDrawable(Resources r, int drawableId) {
// BitmapDrawable d = (BitmapDrawable)r.getDrawable(drawableId);
// return new BufferedImage(d);
// }
//
// public static final int FONT_SIZE = 8;
// public static BufferedImage createLetterImage(int z, Color color, Color background) {
// BufferedImage img = new BufferedImage(FONT_SIZE * ZOOM, FONT_SIZE * ZOOM, BufferedImage.TYPE_INT_RGB);
// Graphics g = img.getGraphics();
// for (int i = 0; i < FONT_SIZE; i++) {
// int b = Fonts.bitmap[z][i];
// for (int j = 0; j < FONT_SIZE; j++) {
// boolean px = (b & 0x80) == 0x80;
// b = b << 1;
// g.setColor(px ? color : background);
// g.fillRect(j * ZOOM, i * ZOOM, ZOOM, ZOOM);
// }
// }
// return img;
// }
// }
// Path: core/src/main/java/net/panuska/tlappy/awt/Graphics.java
import android.graphics.Bitmap;
import android.graphics.Canvas;
import android.graphics.Paint;
import android.graphics.Typeface;
import net.panuska.tlappy.Constants;
import net.panuska.tlappy.ImageUtils;
}
public boolean drawImage(BufferedImage img, int x, int y, Paint paint) {
c.drawBitmap(img.getBitmap(), x, y, paint);
return true;
}
public void drawString(String str, int x, int y, Color color) {
Paint p = new Paint();
p.setTypeface(Typeface.DEFAULT_BOLD);
p.setTextSize(Constants.SPRITE_SIZE);
p.setColor(color.getValue());
c.drawText(str, x, y + Constants.SPRITE_SIZE, p);
}
/**
* Draws string using monospaced (Flappy built-in) font.
* @param text
* @param x
* @param y
* @param color
*/
public void drawText(String text, int x, int y, Color color) {
//todo copied from VRAM.printText()
for (int i = 0, maxi = text.length(); i < maxi; i++) {
int z = text.charAt(i);
if (z < 0x20 || z > 0x7a) {
z = '!';
}
z -= 0x20; | BufferedImage imgChar = ImageUtils.createLetterImage(z, color, Color.BLACK); |
pe-pan/flappy | core/src/main/java/net/panuska/tlappy/BlueEnemy.java | // Path: core/src/main/java/net/panuska/tlappy/awt/BufferedImage.java
// public class BufferedImage {
// private Bitmap b;
// private Graphics g;
// public static final int TYPE_INT_RGB = Bitmap.Config.ARGB_8888.ordinal();
//
// public BufferedImage(BitmapDrawable d) {
// Bitmap immb = d.getBitmap();
// b = immb.copy(Bitmap.Config.ARGB_8888, false);
// }
//
// public BufferedImage(int width,
// int height,
// int imageType) {
// b = Bitmap.createBitmap(width, height, Bitmap.Config.ARGB_8888);
// g = new Graphics(b);
// }
//
// private BufferedImage(Bitmap b) {
// this.b = b;
// }
//
// public Graphics getGraphics() {
// return g;
// }
//
// public Bitmap getBitmap() {
// return b;
// }
//
// public BufferedImage getSubimage (int x, int y, int w, int h) {
// Bitmap b = Bitmap.createBitmap(this.b, x, y, w, h);
// return new BufferedImage(b);
// }
//
// /**
// * Returns a copy of this image rotated by 90 degrees.
// * @return
// */
// public BufferedImage getRotatedImage() {
// Matrix matrix = new Matrix();
// matrix.postRotate(90);
// Bitmap b = Bitmap.createBitmap(this.getBitmap(), 0, 0, this.getWidth(), this.getHeight(), matrix, false);
// return new BufferedImage(b);
// }
//
// /**
// * Returns a copy of this image mirrored by vertical axis
// * @return
// */
// public BufferedImage getMirroredImage() {
// Matrix matrix = new Matrix();
// matrix.preScale(-1, 1);
// Bitmap b = Bitmap.createBitmap(this.getBitmap(), 0, 0, this.getWidth(), this.getHeight(), matrix, false);
// return new BufferedImage(b);
// }
//
// /**
// * Returns 16x16 subimage starting at x, y
// * @param x
// * @param y
// * @return
// */
// public BufferedImage getSubimage (int x, int y) {
// return getSubimage(x, y, 16, 16);
// }
//
// public int getWidth() {
// return b.getWidth();
// }
//
// public int getHeight() {
// return b.getHeight();
// }
// }
//
// Path: core/src/main/java/net/panuska/tlappy/Constants.java
// public class Constants {
//
// static final int SCREEN_WIDTH = 320;
// static final int SCREEN_HEIGHT = 200;
// static final int NUM_SCENES = 200;
// static final int LIVES = 5;
// public static final int SPRITE_SIZE = 16;
// public static final int SPRITE_HALF = 8;
// public static final int FONT_WIDTH = SPRITE_HALF;
//
// static final int UP = 1;
// static final int DOWN = 2;
// static final int LEFT = 3;
// static final int RIGHT = 4;
// static final int FIRE = 5;
// static final int ESC = 255;
//
// static final int INTRO = -1;
// static final int GAME = -2;
// static final int SETUP = -3;
//
// static final byte SPACE = 0;
// static final byte MUSHROOM = 0x10;
// static final byte CHICKEN = 0x20;
// static final byte BLUE_ENEMY = 0x30;
// static final byte RED_ENEMY = 0x40;
// static final byte RED_BALL = 0x50;
// static final byte BLUE_BALL = 0x60;
// static final byte WALL = 0x70;
// static final byte BLUE_WALL = 0x71; // ORIGINAL: (byte) 0x80;
//
// }
//
// Path: core/src/main/java/net/panuska/tlappy/Device.java
// public class Device {
// private static final String TAG = Device.class.getSimpleName();
// public static Keyboard keyboard;
// public static VRAM vram;
// public static Music music;
//
// public static int displayWidth;
// public static int displayHeight;
//
// public static boolean initialized = false;
// public static void init (SurfaceView view) {
// if (initialized) {
// Log.d(TAG, "Device already initialized");
// return;
// }
// Log.d(TAG, "Init");
// Images.load(view.getResources());
// keyboard = Keyboard.getInstance();
// vram = VRAM.getInstance();
// vram.createWindow(view);
// music = Music.getInstance(view.getContext());
// WindowManager wm = (WindowManager) view.getContext().getSystemService(Context.WINDOW_SERVICE);
// Display display = wm.getDefaultDisplay();
// displayWidth = display.getWidth();
// displayHeight = display.getHeight();
// if (displayHeight > displayWidth) {
// Log.d(TAG, "Swapping display width and height "+displayWidth+", "+displayHeight);
// displayWidth = displayWidth + displayHeight;
// displayHeight = displayWidth - displayHeight;
// displayWidth = displayWidth - displayHeight;
// }
// initialized = true;
// }
//
// public static void destroy() {
// music.destroy();
// initialized = false;
// }
// }
| import net.panuska.tlappy.awt.BufferedImage;
import static net.panuska.tlappy.Constants.*;
import static net.panuska.tlappy.Device.*; | break;
case 0xFE:
drawMe(Images.blueEnemySleep3);
break;
case 0xFF:
default:
drawMe(Images.blueEnemySleep4);
break;
}
direction++;
return;
}
n2 = (n2 >> 4) & 0x0F;
if (n2 < 1) {
drawMe(Images.blueEnemyLeft2);
direction++;
} else if (n2 > 10) {
n = n & 0xFF;
if (n < 0xAE) {
drawMe(Images.blueEnemySleep5);
direction++;
} else if (n < 0xC8) {
drawMe(Images.blueEnemyLeft2);
direction++;
} else {
drawMe(Images.blueEnemyLeft2);
direction = 0;
}
} else {
n2 = n2 >> 1; | // Path: core/src/main/java/net/panuska/tlappy/awt/BufferedImage.java
// public class BufferedImage {
// private Bitmap b;
// private Graphics g;
// public static final int TYPE_INT_RGB = Bitmap.Config.ARGB_8888.ordinal();
//
// public BufferedImage(BitmapDrawable d) {
// Bitmap immb = d.getBitmap();
// b = immb.copy(Bitmap.Config.ARGB_8888, false);
// }
//
// public BufferedImage(int width,
// int height,
// int imageType) {
// b = Bitmap.createBitmap(width, height, Bitmap.Config.ARGB_8888);
// g = new Graphics(b);
// }
//
// private BufferedImage(Bitmap b) {
// this.b = b;
// }
//
// public Graphics getGraphics() {
// return g;
// }
//
// public Bitmap getBitmap() {
// return b;
// }
//
// public BufferedImage getSubimage (int x, int y, int w, int h) {
// Bitmap b = Bitmap.createBitmap(this.b, x, y, w, h);
// return new BufferedImage(b);
// }
//
// /**
// * Returns a copy of this image rotated by 90 degrees.
// * @return
// */
// public BufferedImage getRotatedImage() {
// Matrix matrix = new Matrix();
// matrix.postRotate(90);
// Bitmap b = Bitmap.createBitmap(this.getBitmap(), 0, 0, this.getWidth(), this.getHeight(), matrix, false);
// return new BufferedImage(b);
// }
//
// /**
// * Returns a copy of this image mirrored by vertical axis
// * @return
// */
// public BufferedImage getMirroredImage() {
// Matrix matrix = new Matrix();
// matrix.preScale(-1, 1);
// Bitmap b = Bitmap.createBitmap(this.getBitmap(), 0, 0, this.getWidth(), this.getHeight(), matrix, false);
// return new BufferedImage(b);
// }
//
// /**
// * Returns 16x16 subimage starting at x, y
// * @param x
// * @param y
// * @return
// */
// public BufferedImage getSubimage (int x, int y) {
// return getSubimage(x, y, 16, 16);
// }
//
// public int getWidth() {
// return b.getWidth();
// }
//
// public int getHeight() {
// return b.getHeight();
// }
// }
//
// Path: core/src/main/java/net/panuska/tlappy/Constants.java
// public class Constants {
//
// static final int SCREEN_WIDTH = 320;
// static final int SCREEN_HEIGHT = 200;
// static final int NUM_SCENES = 200;
// static final int LIVES = 5;
// public static final int SPRITE_SIZE = 16;
// public static final int SPRITE_HALF = 8;
// public static final int FONT_WIDTH = SPRITE_HALF;
//
// static final int UP = 1;
// static final int DOWN = 2;
// static final int LEFT = 3;
// static final int RIGHT = 4;
// static final int FIRE = 5;
// static final int ESC = 255;
//
// static final int INTRO = -1;
// static final int GAME = -2;
// static final int SETUP = -3;
//
// static final byte SPACE = 0;
// static final byte MUSHROOM = 0x10;
// static final byte CHICKEN = 0x20;
// static final byte BLUE_ENEMY = 0x30;
// static final byte RED_ENEMY = 0x40;
// static final byte RED_BALL = 0x50;
// static final byte BLUE_BALL = 0x60;
// static final byte WALL = 0x70;
// static final byte BLUE_WALL = 0x71; // ORIGINAL: (byte) 0x80;
//
// }
//
// Path: core/src/main/java/net/panuska/tlappy/Device.java
// public class Device {
// private static final String TAG = Device.class.getSimpleName();
// public static Keyboard keyboard;
// public static VRAM vram;
// public static Music music;
//
// public static int displayWidth;
// public static int displayHeight;
//
// public static boolean initialized = false;
// public static void init (SurfaceView view) {
// if (initialized) {
// Log.d(TAG, "Device already initialized");
// return;
// }
// Log.d(TAG, "Init");
// Images.load(view.getResources());
// keyboard = Keyboard.getInstance();
// vram = VRAM.getInstance();
// vram.createWindow(view);
// music = Music.getInstance(view.getContext());
// WindowManager wm = (WindowManager) view.getContext().getSystemService(Context.WINDOW_SERVICE);
// Display display = wm.getDefaultDisplay();
// displayWidth = display.getWidth();
// displayHeight = display.getHeight();
// if (displayHeight > displayWidth) {
// Log.d(TAG, "Swapping display width and height "+displayWidth+", "+displayHeight);
// displayWidth = displayWidth + displayHeight;
// displayHeight = displayWidth - displayHeight;
// displayWidth = displayWidth - displayHeight;
// }
// initialized = true;
// }
//
// public static void destroy() {
// music.destroy();
// initialized = false;
// }
// }
// Path: core/src/main/java/net/panuska/tlappy/BlueEnemy.java
import net.panuska.tlappy.awt.BufferedImage;
import static net.panuska.tlappy.Constants.*;
import static net.panuska.tlappy.Device.*;
break;
case 0xFE:
drawMe(Images.blueEnemySleep3);
break;
case 0xFF:
default:
drawMe(Images.blueEnemySleep4);
break;
}
direction++;
return;
}
n2 = (n2 >> 4) & 0x0F;
if (n2 < 1) {
drawMe(Images.blueEnemyLeft2);
direction++;
} else if (n2 > 10) {
n = n & 0xFF;
if (n < 0xAE) {
drawMe(Images.blueEnemySleep5);
direction++;
} else if (n < 0xC8) {
drawMe(Images.blueEnemyLeft2);
direction++;
} else {
drawMe(Images.blueEnemyLeft2);
direction = 0;
}
} else {
n2 = n2 >> 1; | BufferedImage img = (n2 & 1) == 0 ? Images.blueEnemySleep5 : Images.blueEnemySleep6; |
pe-pan/flappy | core/src/main/java/net/panuska/tlappy/RedEnemy.java | // Path: core/src/main/java/net/panuska/tlappy/awt/BufferedImage.java
// public class BufferedImage {
// private Bitmap b;
// private Graphics g;
// public static final int TYPE_INT_RGB = Bitmap.Config.ARGB_8888.ordinal();
//
// public BufferedImage(BitmapDrawable d) {
// Bitmap immb = d.getBitmap();
// b = immb.copy(Bitmap.Config.ARGB_8888, false);
// }
//
// public BufferedImage(int width,
// int height,
// int imageType) {
// b = Bitmap.createBitmap(width, height, Bitmap.Config.ARGB_8888);
// g = new Graphics(b);
// }
//
// private BufferedImage(Bitmap b) {
// this.b = b;
// }
//
// public Graphics getGraphics() {
// return g;
// }
//
// public Bitmap getBitmap() {
// return b;
// }
//
// public BufferedImage getSubimage (int x, int y, int w, int h) {
// Bitmap b = Bitmap.createBitmap(this.b, x, y, w, h);
// return new BufferedImage(b);
// }
//
// /**
// * Returns a copy of this image rotated by 90 degrees.
// * @return
// */
// public BufferedImage getRotatedImage() {
// Matrix matrix = new Matrix();
// matrix.postRotate(90);
// Bitmap b = Bitmap.createBitmap(this.getBitmap(), 0, 0, this.getWidth(), this.getHeight(), matrix, false);
// return new BufferedImage(b);
// }
//
// /**
// * Returns a copy of this image mirrored by vertical axis
// * @return
// */
// public BufferedImage getMirroredImage() {
// Matrix matrix = new Matrix();
// matrix.preScale(-1, 1);
// Bitmap b = Bitmap.createBitmap(this.getBitmap(), 0, 0, this.getWidth(), this.getHeight(), matrix, false);
// return new BufferedImage(b);
// }
//
// /**
// * Returns 16x16 subimage starting at x, y
// * @param x
// * @param y
// * @return
// */
// public BufferedImage getSubimage (int x, int y) {
// return getSubimage(x, y, 16, 16);
// }
//
// public int getWidth() {
// return b.getWidth();
// }
//
// public int getHeight() {
// return b.getHeight();
// }
// }
//
// Path: core/src/main/java/net/panuska/tlappy/Constants.java
// public class Constants {
//
// static final int SCREEN_WIDTH = 320;
// static final int SCREEN_HEIGHT = 200;
// static final int NUM_SCENES = 200;
// static final int LIVES = 5;
// public static final int SPRITE_SIZE = 16;
// public static final int SPRITE_HALF = 8;
// public static final int FONT_WIDTH = SPRITE_HALF;
//
// static final int UP = 1;
// static final int DOWN = 2;
// static final int LEFT = 3;
// static final int RIGHT = 4;
// static final int FIRE = 5;
// static final int ESC = 255;
//
// static final int INTRO = -1;
// static final int GAME = -2;
// static final int SETUP = -3;
//
// static final byte SPACE = 0;
// static final byte MUSHROOM = 0x10;
// static final byte CHICKEN = 0x20;
// static final byte BLUE_ENEMY = 0x30;
// static final byte RED_ENEMY = 0x40;
// static final byte RED_BALL = 0x50;
// static final byte BLUE_BALL = 0x60;
// static final byte WALL = 0x70;
// static final byte BLUE_WALL = 0x71; // ORIGINAL: (byte) 0x80;
//
// }
//
// Path: core/src/main/java/net/panuska/tlappy/Device.java
// public class Device {
// private static final String TAG = Device.class.getSimpleName();
// public static Keyboard keyboard;
// public static VRAM vram;
// public static Music music;
//
// public static int displayWidth;
// public static int displayHeight;
//
// public static boolean initialized = false;
// public static void init (SurfaceView view) {
// if (initialized) {
// Log.d(TAG, "Device already initialized");
// return;
// }
// Log.d(TAG, "Init");
// Images.load(view.getResources());
// keyboard = Keyboard.getInstance();
// vram = VRAM.getInstance();
// vram.createWindow(view);
// music = Music.getInstance(view.getContext());
// WindowManager wm = (WindowManager) view.getContext().getSystemService(Context.WINDOW_SERVICE);
// Display display = wm.getDefaultDisplay();
// displayWidth = display.getWidth();
// displayHeight = display.getHeight();
// if (displayHeight > displayWidth) {
// Log.d(TAG, "Swapping display width and height "+displayWidth+", "+displayHeight);
// displayWidth = displayWidth + displayHeight;
// displayHeight = displayWidth - displayHeight;
// displayWidth = displayWidth - displayHeight;
// }
// initialized = true;
// }
//
// public static void destroy() {
// music.destroy();
// initialized = false;
// }
// }
| import net.panuska.tlappy.awt.BufferedImage;
import static net.panuska.tlappy.Constants.*;
import static net.panuska.tlappy.Device.*; | drawMe3x2(x, y, Images.redEnemyRightS2);
didMove = true;
}
}
}
// TODO: refactor this
private boolean testMove(int m1, int m2) {
boolean chick = false;
boolean wall = false;
if ((m1 & 0xF0) == CHICKEN || ((m2 & 0xF0) == CHICKEN)) chick = true;
if ((m1 & 0xF0) > CHICKEN || ((m2 & 0xF0) > CHICKEN)) wall = true;
if (wall) {
return false;
}
if (!chick) {
return true;
}
if (chicken.chickenEaten == 0) {
chicken.setChickenEaten();
return false;
}
return false;
}
private void setRandomMove() {
int rnd = (int) (Math.random() * 1000);
selectedMove = (rnd & 3) + 1;
}
| // Path: core/src/main/java/net/panuska/tlappy/awt/BufferedImage.java
// public class BufferedImage {
// private Bitmap b;
// private Graphics g;
// public static final int TYPE_INT_RGB = Bitmap.Config.ARGB_8888.ordinal();
//
// public BufferedImage(BitmapDrawable d) {
// Bitmap immb = d.getBitmap();
// b = immb.copy(Bitmap.Config.ARGB_8888, false);
// }
//
// public BufferedImage(int width,
// int height,
// int imageType) {
// b = Bitmap.createBitmap(width, height, Bitmap.Config.ARGB_8888);
// g = new Graphics(b);
// }
//
// private BufferedImage(Bitmap b) {
// this.b = b;
// }
//
// public Graphics getGraphics() {
// return g;
// }
//
// public Bitmap getBitmap() {
// return b;
// }
//
// public BufferedImage getSubimage (int x, int y, int w, int h) {
// Bitmap b = Bitmap.createBitmap(this.b, x, y, w, h);
// return new BufferedImage(b);
// }
//
// /**
// * Returns a copy of this image rotated by 90 degrees.
// * @return
// */
// public BufferedImage getRotatedImage() {
// Matrix matrix = new Matrix();
// matrix.postRotate(90);
// Bitmap b = Bitmap.createBitmap(this.getBitmap(), 0, 0, this.getWidth(), this.getHeight(), matrix, false);
// return new BufferedImage(b);
// }
//
// /**
// * Returns a copy of this image mirrored by vertical axis
// * @return
// */
// public BufferedImage getMirroredImage() {
// Matrix matrix = new Matrix();
// matrix.preScale(-1, 1);
// Bitmap b = Bitmap.createBitmap(this.getBitmap(), 0, 0, this.getWidth(), this.getHeight(), matrix, false);
// return new BufferedImage(b);
// }
//
// /**
// * Returns 16x16 subimage starting at x, y
// * @param x
// * @param y
// * @return
// */
// public BufferedImage getSubimage (int x, int y) {
// return getSubimage(x, y, 16, 16);
// }
//
// public int getWidth() {
// return b.getWidth();
// }
//
// public int getHeight() {
// return b.getHeight();
// }
// }
//
// Path: core/src/main/java/net/panuska/tlappy/Constants.java
// public class Constants {
//
// static final int SCREEN_WIDTH = 320;
// static final int SCREEN_HEIGHT = 200;
// static final int NUM_SCENES = 200;
// static final int LIVES = 5;
// public static final int SPRITE_SIZE = 16;
// public static final int SPRITE_HALF = 8;
// public static final int FONT_WIDTH = SPRITE_HALF;
//
// static final int UP = 1;
// static final int DOWN = 2;
// static final int LEFT = 3;
// static final int RIGHT = 4;
// static final int FIRE = 5;
// static final int ESC = 255;
//
// static final int INTRO = -1;
// static final int GAME = -2;
// static final int SETUP = -3;
//
// static final byte SPACE = 0;
// static final byte MUSHROOM = 0x10;
// static final byte CHICKEN = 0x20;
// static final byte BLUE_ENEMY = 0x30;
// static final byte RED_ENEMY = 0x40;
// static final byte RED_BALL = 0x50;
// static final byte BLUE_BALL = 0x60;
// static final byte WALL = 0x70;
// static final byte BLUE_WALL = 0x71; // ORIGINAL: (byte) 0x80;
//
// }
//
// Path: core/src/main/java/net/panuska/tlappy/Device.java
// public class Device {
// private static final String TAG = Device.class.getSimpleName();
// public static Keyboard keyboard;
// public static VRAM vram;
// public static Music music;
//
// public static int displayWidth;
// public static int displayHeight;
//
// public static boolean initialized = false;
// public static void init (SurfaceView view) {
// if (initialized) {
// Log.d(TAG, "Device already initialized");
// return;
// }
// Log.d(TAG, "Init");
// Images.load(view.getResources());
// keyboard = Keyboard.getInstance();
// vram = VRAM.getInstance();
// vram.createWindow(view);
// music = Music.getInstance(view.getContext());
// WindowManager wm = (WindowManager) view.getContext().getSystemService(Context.WINDOW_SERVICE);
// Display display = wm.getDefaultDisplay();
// displayWidth = display.getWidth();
// displayHeight = display.getHeight();
// if (displayHeight > displayWidth) {
// Log.d(TAG, "Swapping display width and height "+displayWidth+", "+displayHeight);
// displayWidth = displayWidth + displayHeight;
// displayHeight = displayWidth - displayHeight;
// displayWidth = displayWidth - displayHeight;
// }
// initialized = true;
// }
//
// public static void destroy() {
// music.destroy();
// initialized = false;
// }
// }
// Path: core/src/main/java/net/panuska/tlappy/RedEnemy.java
import net.panuska.tlappy.awt.BufferedImage;
import static net.panuska.tlappy.Constants.*;
import static net.panuska.tlappy.Device.*;
drawMe3x2(x, y, Images.redEnemyRightS2);
didMove = true;
}
}
}
// TODO: refactor this
private boolean testMove(int m1, int m2) {
boolean chick = false;
boolean wall = false;
if ((m1 & 0xF0) == CHICKEN || ((m2 & 0xF0) == CHICKEN)) chick = true;
if ((m1 & 0xF0) > CHICKEN || ((m2 & 0xF0) > CHICKEN)) wall = true;
if (wall) {
return false;
}
if (!chick) {
return true;
}
if (chicken.chickenEaten == 0) {
chicken.setChickenEaten();
return false;
}
return false;
}
private void setRandomMove() {
int rnd = (int) (Math.random() * 1000);
selectedMove = (rnd & 3) + 1;
}
| private void drawMe2x3(int x, int y, BufferedImage img) { |
pe-pan/flappy | core/src/main/java/net/panuska/tlappy/Main.java | // Path: core/src/main/java/net/panuska/tlappy/awt/Color.java
// public enum Color {
// BLACK(0xff000000),
// RED(0xffff0000),
// BLUE(0xff0000ff),
// YELLOW(0xffffff00),
// WHITE(0xffffffff),
// DARK_GRAY(0xff404040),
// LIGHT_GRAY(0xffc0c0c0),
// TRANSPARENT(0x00000000),
//
// black(0xff000000),
// red(0xffff0000),
// blue(0xff0000ff),
// yellow(0xffffff00),
// white(0xffffffff),
// dark_gray(0xff404040);
//
// private final int color;
// Color(int color) { this.color = color; }
// public int getValue() { return color; }
// }
//
// Path: core/src/main/java/net/panuska/tlappy/Constants.java
// public class Constants {
//
// static final int SCREEN_WIDTH = 320;
// static final int SCREEN_HEIGHT = 200;
// static final int NUM_SCENES = 200;
// static final int LIVES = 5;
// public static final int SPRITE_SIZE = 16;
// public static final int SPRITE_HALF = 8;
// public static final int FONT_WIDTH = SPRITE_HALF;
//
// static final int UP = 1;
// static final int DOWN = 2;
// static final int LEFT = 3;
// static final int RIGHT = 4;
// static final int FIRE = 5;
// static final int ESC = 255;
//
// static final int INTRO = -1;
// static final int GAME = -2;
// static final int SETUP = -3;
//
// static final byte SPACE = 0;
// static final byte MUSHROOM = 0x10;
// static final byte CHICKEN = 0x20;
// static final byte BLUE_ENEMY = 0x30;
// static final byte RED_ENEMY = 0x40;
// static final byte RED_BALL = 0x50;
// static final byte BLUE_BALL = 0x60;
// static final byte WALL = 0x70;
// static final byte BLUE_WALL = 0x71; // ORIGINAL: (byte) 0x80;
//
// }
//
// Path: core/src/main/java/net/panuska/tlappy/Device.java
// public class Device {
// private static final String TAG = Device.class.getSimpleName();
// public static Keyboard keyboard;
// public static VRAM vram;
// public static Music music;
//
// public static int displayWidth;
// public static int displayHeight;
//
// public static boolean initialized = false;
// public static void init (SurfaceView view) {
// if (initialized) {
// Log.d(TAG, "Device already initialized");
// return;
// }
// Log.d(TAG, "Init");
// Images.load(view.getResources());
// keyboard = Keyboard.getInstance();
// vram = VRAM.getInstance();
// vram.createWindow(view);
// music = Music.getInstance(view.getContext());
// WindowManager wm = (WindowManager) view.getContext().getSystemService(Context.WINDOW_SERVICE);
// Display display = wm.getDefaultDisplay();
// displayWidth = display.getWidth();
// displayHeight = display.getHeight();
// if (displayHeight > displayWidth) {
// Log.d(TAG, "Swapping display width and height "+displayWidth+", "+displayHeight);
// displayWidth = displayWidth + displayHeight;
// displayHeight = displayWidth - displayHeight;
// displayWidth = displayWidth - displayHeight;
// }
// initialized = true;
// }
//
// public static void destroy() {
// music.destroy();
// initialized = false;
// }
// }
| import android.util.Log;
import android.view.SurfaceView;
import net.panuska.tlappy.awt.Color;
import static net.panuska.tlappy.Constants.*;
import static net.panuska.tlappy.Device.*; | // todo shift the scenes also upon unsuccessful run
Main.setState(NORMAL_WAIT);
lives--;
if (lives == 0) {
s.gameOver();
return;
}
} else {
listener.gameFinished(scNo, score, lives, 0); //todo time should be also saved here
previousScore += score; // re-initialize score
score = 0;
if (scNo % 5 == 0) {
scNoRestart = scNo + 1;
password = s.printPassword(scNo / 5);
}
scNo++;
if (scNo > 200) {
finalScr.finalCertificate();
scNoRestart = 1;
sel = INTRO;
}
}
}
}
private int setup() {
keyboard.clear();
music.stop();
vram.clear();
Scene.drawSimpleBorder(); | // Path: core/src/main/java/net/panuska/tlappy/awt/Color.java
// public enum Color {
// BLACK(0xff000000),
// RED(0xffff0000),
// BLUE(0xff0000ff),
// YELLOW(0xffffff00),
// WHITE(0xffffffff),
// DARK_GRAY(0xff404040),
// LIGHT_GRAY(0xffc0c0c0),
// TRANSPARENT(0x00000000),
//
// black(0xff000000),
// red(0xffff0000),
// blue(0xff0000ff),
// yellow(0xffffff00),
// white(0xffffffff),
// dark_gray(0xff404040);
//
// private final int color;
// Color(int color) { this.color = color; }
// public int getValue() { return color; }
// }
//
// Path: core/src/main/java/net/panuska/tlappy/Constants.java
// public class Constants {
//
// static final int SCREEN_WIDTH = 320;
// static final int SCREEN_HEIGHT = 200;
// static final int NUM_SCENES = 200;
// static final int LIVES = 5;
// public static final int SPRITE_SIZE = 16;
// public static final int SPRITE_HALF = 8;
// public static final int FONT_WIDTH = SPRITE_HALF;
//
// static final int UP = 1;
// static final int DOWN = 2;
// static final int LEFT = 3;
// static final int RIGHT = 4;
// static final int FIRE = 5;
// static final int ESC = 255;
//
// static final int INTRO = -1;
// static final int GAME = -2;
// static final int SETUP = -3;
//
// static final byte SPACE = 0;
// static final byte MUSHROOM = 0x10;
// static final byte CHICKEN = 0x20;
// static final byte BLUE_ENEMY = 0x30;
// static final byte RED_ENEMY = 0x40;
// static final byte RED_BALL = 0x50;
// static final byte BLUE_BALL = 0x60;
// static final byte WALL = 0x70;
// static final byte BLUE_WALL = 0x71; // ORIGINAL: (byte) 0x80;
//
// }
//
// Path: core/src/main/java/net/panuska/tlappy/Device.java
// public class Device {
// private static final String TAG = Device.class.getSimpleName();
// public static Keyboard keyboard;
// public static VRAM vram;
// public static Music music;
//
// public static int displayWidth;
// public static int displayHeight;
//
// public static boolean initialized = false;
// public static void init (SurfaceView view) {
// if (initialized) {
// Log.d(TAG, "Device already initialized");
// return;
// }
// Log.d(TAG, "Init");
// Images.load(view.getResources());
// keyboard = Keyboard.getInstance();
// vram = VRAM.getInstance();
// vram.createWindow(view);
// music = Music.getInstance(view.getContext());
// WindowManager wm = (WindowManager) view.getContext().getSystemService(Context.WINDOW_SERVICE);
// Display display = wm.getDefaultDisplay();
// displayWidth = display.getWidth();
// displayHeight = display.getHeight();
// if (displayHeight > displayWidth) {
// Log.d(TAG, "Swapping display width and height "+displayWidth+", "+displayHeight);
// displayWidth = displayWidth + displayHeight;
// displayHeight = displayWidth - displayHeight;
// displayWidth = displayWidth - displayHeight;
// }
// initialized = true;
// }
//
// public static void destroy() {
// music.destroy();
// initialized = false;
// }
// }
// Path: core/src/main/java/net/panuska/tlappy/Main.java
import android.util.Log;
import android.view.SurfaceView;
import net.panuska.tlappy.awt.Color;
import static net.panuska.tlappy.Constants.*;
import static net.panuska.tlappy.Device.*;
// todo shift the scenes also upon unsuccessful run
Main.setState(NORMAL_WAIT);
lives--;
if (lives == 0) {
s.gameOver();
return;
}
} else {
listener.gameFinished(scNo, score, lives, 0); //todo time should be also saved here
previousScore += score; // re-initialize score
score = 0;
if (scNo % 5 == 0) {
scNoRestart = scNo + 1;
password = s.printPassword(scNo / 5);
}
scNo++;
if (scNo > 200) {
finalScr.finalCertificate();
scNoRestart = 1;
sel = INTRO;
}
}
}
}
private int setup() {
keyboard.clear();
music.stop();
vram.clear();
Scene.drawSimpleBorder(); | vram.printText(16, 5, "M E N U", Color.BLUE); |
pe-pan/flappy | core/src/main/java/net/panuska/tlappy/VRAM.java | // Path: core/src/main/java/net/panuska/tlappy/awt/BufferedImage.java
// public class BufferedImage {
// private Bitmap b;
// private Graphics g;
// public static final int TYPE_INT_RGB = Bitmap.Config.ARGB_8888.ordinal();
//
// public BufferedImage(BitmapDrawable d) {
// Bitmap immb = d.getBitmap();
// b = immb.copy(Bitmap.Config.ARGB_8888, false);
// }
//
// public BufferedImage(int width,
// int height,
// int imageType) {
// b = Bitmap.createBitmap(width, height, Bitmap.Config.ARGB_8888);
// g = new Graphics(b);
// }
//
// private BufferedImage(Bitmap b) {
// this.b = b;
// }
//
// public Graphics getGraphics() {
// return g;
// }
//
// public Bitmap getBitmap() {
// return b;
// }
//
// public BufferedImage getSubimage (int x, int y, int w, int h) {
// Bitmap b = Bitmap.createBitmap(this.b, x, y, w, h);
// return new BufferedImage(b);
// }
//
// /**
// * Returns a copy of this image rotated by 90 degrees.
// * @return
// */
// public BufferedImage getRotatedImage() {
// Matrix matrix = new Matrix();
// matrix.postRotate(90);
// Bitmap b = Bitmap.createBitmap(this.getBitmap(), 0, 0, this.getWidth(), this.getHeight(), matrix, false);
// return new BufferedImage(b);
// }
//
// /**
// * Returns a copy of this image mirrored by vertical axis
// * @return
// */
// public BufferedImage getMirroredImage() {
// Matrix matrix = new Matrix();
// matrix.preScale(-1, 1);
// Bitmap b = Bitmap.createBitmap(this.getBitmap(), 0, 0, this.getWidth(), this.getHeight(), matrix, false);
// return new BufferedImage(b);
// }
//
// /**
// * Returns 16x16 subimage starting at x, y
// * @param x
// * @param y
// * @return
// */
// public BufferedImage getSubimage (int x, int y) {
// return getSubimage(x, y, 16, 16);
// }
//
// public int getWidth() {
// return b.getWidth();
// }
//
// public int getHeight() {
// return b.getHeight();
// }
// }
//
// Path: core/src/main/java/net/panuska/tlappy/awt/Color.java
// public enum Color {
// BLACK(0xff000000),
// RED(0xffff0000),
// BLUE(0xff0000ff),
// YELLOW(0xffffff00),
// WHITE(0xffffffff),
// DARK_GRAY(0xff404040),
// LIGHT_GRAY(0xffc0c0c0),
// TRANSPARENT(0x00000000),
//
// black(0xff000000),
// red(0xffff0000),
// blue(0xff0000ff),
// yellow(0xffffff00),
// white(0xffffffff),
// dark_gray(0xff404040);
//
// private final int color;
// Color(int color) { this.color = color; }
// public int getValue() { return color; }
// }
//
// Path: core/src/main/java/net/panuska/tlappy/awt/Graphics.java
// public class Graphics {
// private Canvas c;
// static final private Paint p = new Paint();
//
// public Graphics(Bitmap b) {
// c = new Canvas(b);
// }
//
// public void setColor(Color c) {
// p.setColor(c.getValue());
// }
//
// public void fillRect(int x, int y, int width, int height) {
// p.setStyle(Paint.Style.FILL);
// c.drawRect(x, y, x+width, y+height, p);
// }
//
// public void drawRect(int x, int y, int width, int height) {
// p.setStyle(Paint.Style.STROKE);
// c.drawRect(x, y, x+width, y+height, p);
// }
//
// public boolean drawImage(BufferedImage img, int x, int y, Paint paint) {
// c.drawBitmap(img.getBitmap(), x, y, paint);
// return true;
// }
//
// public void drawString(String str, int x, int y, Color color) {
// Paint p = new Paint();
// p.setTypeface(Typeface.DEFAULT_BOLD);
// p.setTextSize(Constants.SPRITE_SIZE);
// p.setColor(color.getValue());
// c.drawText(str, x, y + Constants.SPRITE_SIZE, p);
// }
//
// /**
// * Draws string using monospaced (Flappy built-in) font.
// * @param text
// * @param x
// * @param y
// * @param color
// */
// public void drawText(String text, int x, int y, Color color) {
// //todo copied from VRAM.printText()
// for (int i = 0, maxi = text.length(); i < maxi; i++) {
// int z = text.charAt(i);
// if (z < 0x20 || z > 0x7a) {
// z = '!';
// }
// z -= 0x20;
// BufferedImage imgChar = ImageUtils.createLetterImage(z, color, Color.BLACK);
// drawImage(imgChar, x, y, null);
// x += Constants.FONT_WIDTH;
// }
// }
// }
| import android.graphics.Canvas;
import android.graphics.Paint;
import android.util.Log;
import android.view.SurfaceHolder;
import android.view.SurfaceView;
import net.panuska.tlappy.awt.BufferedImage;
import net.panuska.tlappy.awt.Color;
import net.panuska.tlappy.awt.Graphics; | package net.panuska.tlappy;
/**
* VideoRAM "routines".
*
* @author Petr Slechta
*/
public class VRAM {
private static final int ZOOM = 1;
private static final int Y_OFS = 3;
private static VRAM me;
static VRAM getInstance() {
if (me == null) me = new VRAM();
return me;
} | // Path: core/src/main/java/net/panuska/tlappy/awt/BufferedImage.java
// public class BufferedImage {
// private Bitmap b;
// private Graphics g;
// public static final int TYPE_INT_RGB = Bitmap.Config.ARGB_8888.ordinal();
//
// public BufferedImage(BitmapDrawable d) {
// Bitmap immb = d.getBitmap();
// b = immb.copy(Bitmap.Config.ARGB_8888, false);
// }
//
// public BufferedImage(int width,
// int height,
// int imageType) {
// b = Bitmap.createBitmap(width, height, Bitmap.Config.ARGB_8888);
// g = new Graphics(b);
// }
//
// private BufferedImage(Bitmap b) {
// this.b = b;
// }
//
// public Graphics getGraphics() {
// return g;
// }
//
// public Bitmap getBitmap() {
// return b;
// }
//
// public BufferedImage getSubimage (int x, int y, int w, int h) {
// Bitmap b = Bitmap.createBitmap(this.b, x, y, w, h);
// return new BufferedImage(b);
// }
//
// /**
// * Returns a copy of this image rotated by 90 degrees.
// * @return
// */
// public BufferedImage getRotatedImage() {
// Matrix matrix = new Matrix();
// matrix.postRotate(90);
// Bitmap b = Bitmap.createBitmap(this.getBitmap(), 0, 0, this.getWidth(), this.getHeight(), matrix, false);
// return new BufferedImage(b);
// }
//
// /**
// * Returns a copy of this image mirrored by vertical axis
// * @return
// */
// public BufferedImage getMirroredImage() {
// Matrix matrix = new Matrix();
// matrix.preScale(-1, 1);
// Bitmap b = Bitmap.createBitmap(this.getBitmap(), 0, 0, this.getWidth(), this.getHeight(), matrix, false);
// return new BufferedImage(b);
// }
//
// /**
// * Returns 16x16 subimage starting at x, y
// * @param x
// * @param y
// * @return
// */
// public BufferedImage getSubimage (int x, int y) {
// return getSubimage(x, y, 16, 16);
// }
//
// public int getWidth() {
// return b.getWidth();
// }
//
// public int getHeight() {
// return b.getHeight();
// }
// }
//
// Path: core/src/main/java/net/panuska/tlappy/awt/Color.java
// public enum Color {
// BLACK(0xff000000),
// RED(0xffff0000),
// BLUE(0xff0000ff),
// YELLOW(0xffffff00),
// WHITE(0xffffffff),
// DARK_GRAY(0xff404040),
// LIGHT_GRAY(0xffc0c0c0),
// TRANSPARENT(0x00000000),
//
// black(0xff000000),
// red(0xffff0000),
// blue(0xff0000ff),
// yellow(0xffffff00),
// white(0xffffffff),
// dark_gray(0xff404040);
//
// private final int color;
// Color(int color) { this.color = color; }
// public int getValue() { return color; }
// }
//
// Path: core/src/main/java/net/panuska/tlappy/awt/Graphics.java
// public class Graphics {
// private Canvas c;
// static final private Paint p = new Paint();
//
// public Graphics(Bitmap b) {
// c = new Canvas(b);
// }
//
// public void setColor(Color c) {
// p.setColor(c.getValue());
// }
//
// public void fillRect(int x, int y, int width, int height) {
// p.setStyle(Paint.Style.FILL);
// c.drawRect(x, y, x+width, y+height, p);
// }
//
// public void drawRect(int x, int y, int width, int height) {
// p.setStyle(Paint.Style.STROKE);
// c.drawRect(x, y, x+width, y+height, p);
// }
//
// public boolean drawImage(BufferedImage img, int x, int y, Paint paint) {
// c.drawBitmap(img.getBitmap(), x, y, paint);
// return true;
// }
//
// public void drawString(String str, int x, int y, Color color) {
// Paint p = new Paint();
// p.setTypeface(Typeface.DEFAULT_BOLD);
// p.setTextSize(Constants.SPRITE_SIZE);
// p.setColor(color.getValue());
// c.drawText(str, x, y + Constants.SPRITE_SIZE, p);
// }
//
// /**
// * Draws string using monospaced (Flappy built-in) font.
// * @param text
// * @param x
// * @param y
// * @param color
// */
// public void drawText(String text, int x, int y, Color color) {
// //todo copied from VRAM.printText()
// for (int i = 0, maxi = text.length(); i < maxi; i++) {
// int z = text.charAt(i);
// if (z < 0x20 || z > 0x7a) {
// z = '!';
// }
// z -= 0x20;
// BufferedImage imgChar = ImageUtils.createLetterImage(z, color, Color.BLACK);
// drawImage(imgChar, x, y, null);
// x += Constants.FONT_WIDTH;
// }
// }
// }
// Path: core/src/main/java/net/panuska/tlappy/VRAM.java
import android.graphics.Canvas;
import android.graphics.Paint;
import android.util.Log;
import android.view.SurfaceHolder;
import android.view.SurfaceView;
import net.panuska.tlappy.awt.BufferedImage;
import net.panuska.tlappy.awt.Color;
import net.panuska.tlappy.awt.Graphics;
package net.panuska.tlappy;
/**
* VideoRAM "routines".
*
* @author Petr Slechta
*/
public class VRAM {
private static final int ZOOM = 1;
private static final int Y_OFS = 3;
private static VRAM me;
static VRAM getInstance() {
if (me == null) me = new VRAM();
return me;
} | private BufferedImage img; |
pe-pan/flappy | core/src/main/java/net/panuska/tlappy/Moveable.java | // Path: core/src/main/java/net/panuska/tlappy/awt/BufferedImage.java
// public class BufferedImage {
// private Bitmap b;
// private Graphics g;
// public static final int TYPE_INT_RGB = Bitmap.Config.ARGB_8888.ordinal();
//
// public BufferedImage(BitmapDrawable d) {
// Bitmap immb = d.getBitmap();
// b = immb.copy(Bitmap.Config.ARGB_8888, false);
// }
//
// public BufferedImage(int width,
// int height,
// int imageType) {
// b = Bitmap.createBitmap(width, height, Bitmap.Config.ARGB_8888);
// g = new Graphics(b);
// }
//
// private BufferedImage(Bitmap b) {
// this.b = b;
// }
//
// public Graphics getGraphics() {
// return g;
// }
//
// public Bitmap getBitmap() {
// return b;
// }
//
// public BufferedImage getSubimage (int x, int y, int w, int h) {
// Bitmap b = Bitmap.createBitmap(this.b, x, y, w, h);
// return new BufferedImage(b);
// }
//
// /**
// * Returns a copy of this image rotated by 90 degrees.
// * @return
// */
// public BufferedImage getRotatedImage() {
// Matrix matrix = new Matrix();
// matrix.postRotate(90);
// Bitmap b = Bitmap.createBitmap(this.getBitmap(), 0, 0, this.getWidth(), this.getHeight(), matrix, false);
// return new BufferedImage(b);
// }
//
// /**
// * Returns a copy of this image mirrored by vertical axis
// * @return
// */
// public BufferedImage getMirroredImage() {
// Matrix matrix = new Matrix();
// matrix.preScale(-1, 1);
// Bitmap b = Bitmap.createBitmap(this.getBitmap(), 0, 0, this.getWidth(), this.getHeight(), matrix, false);
// return new BufferedImage(b);
// }
//
// /**
// * Returns 16x16 subimage starting at x, y
// * @param x
// * @param y
// * @return
// */
// public BufferedImage getSubimage (int x, int y) {
// return getSubimage(x, y, 16, 16);
// }
//
// public int getWidth() {
// return b.getWidth();
// }
//
// public int getHeight() {
// return b.getHeight();
// }
// }
//
// Path: core/src/main/java/net/panuska/tlappy/Device.java
// public class Device {
// private static final String TAG = Device.class.getSimpleName();
// public static Keyboard keyboard;
// public static VRAM vram;
// public static Music music;
//
// public static int displayWidth;
// public static int displayHeight;
//
// public static boolean initialized = false;
// public static void init (SurfaceView view) {
// if (initialized) {
// Log.d(TAG, "Device already initialized");
// return;
// }
// Log.d(TAG, "Init");
// Images.load(view.getResources());
// keyboard = Keyboard.getInstance();
// vram = VRAM.getInstance();
// vram.createWindow(view);
// music = Music.getInstance(view.getContext());
// WindowManager wm = (WindowManager) view.getContext().getSystemService(Context.WINDOW_SERVICE);
// Display display = wm.getDefaultDisplay();
// displayWidth = display.getWidth();
// displayHeight = display.getHeight();
// if (displayHeight > displayWidth) {
// Log.d(TAG, "Swapping display width and height "+displayWidth+", "+displayHeight);
// displayWidth = displayWidth + displayHeight;
// displayHeight = displayWidth - displayHeight;
// displayWidth = displayWidth - displayHeight;
// }
// initialized = true;
// }
//
// public static void destroy() {
// music.destroy();
// initialized = false;
// }
// }
| import net.panuska.tlappy.awt.BufferedImage;
import static net.panuska.tlappy.Device.*; | package net.panuska.tlappy;
/**
* Flappy:
* Original game created by dB-SOFT in 1984 for SHARP MZ-800 computer.
* Java version by Petr Slechta, 2014.
*/
class Moveable {
protected int x, y;
protected byte objType;
protected byte number;
protected byte sig;
protected boolean finished = false;
protected byte[][] model;
protected Scene scene;
protected Moveable(int x, int y, byte objType, int num, Scene scene) {
this.x = x;
this.y = y;
this.objType = objType;
this.number = (byte) num;
this.sig = (byte) (objType | num);
this.model = scene.getModel();
this.scene = scene;
}
boolean isFinished() {
return finished;
}
| // Path: core/src/main/java/net/panuska/tlappy/awt/BufferedImage.java
// public class BufferedImage {
// private Bitmap b;
// private Graphics g;
// public static final int TYPE_INT_RGB = Bitmap.Config.ARGB_8888.ordinal();
//
// public BufferedImage(BitmapDrawable d) {
// Bitmap immb = d.getBitmap();
// b = immb.copy(Bitmap.Config.ARGB_8888, false);
// }
//
// public BufferedImage(int width,
// int height,
// int imageType) {
// b = Bitmap.createBitmap(width, height, Bitmap.Config.ARGB_8888);
// g = new Graphics(b);
// }
//
// private BufferedImage(Bitmap b) {
// this.b = b;
// }
//
// public Graphics getGraphics() {
// return g;
// }
//
// public Bitmap getBitmap() {
// return b;
// }
//
// public BufferedImage getSubimage (int x, int y, int w, int h) {
// Bitmap b = Bitmap.createBitmap(this.b, x, y, w, h);
// return new BufferedImage(b);
// }
//
// /**
// * Returns a copy of this image rotated by 90 degrees.
// * @return
// */
// public BufferedImage getRotatedImage() {
// Matrix matrix = new Matrix();
// matrix.postRotate(90);
// Bitmap b = Bitmap.createBitmap(this.getBitmap(), 0, 0, this.getWidth(), this.getHeight(), matrix, false);
// return new BufferedImage(b);
// }
//
// /**
// * Returns a copy of this image mirrored by vertical axis
// * @return
// */
// public BufferedImage getMirroredImage() {
// Matrix matrix = new Matrix();
// matrix.preScale(-1, 1);
// Bitmap b = Bitmap.createBitmap(this.getBitmap(), 0, 0, this.getWidth(), this.getHeight(), matrix, false);
// return new BufferedImage(b);
// }
//
// /**
// * Returns 16x16 subimage starting at x, y
// * @param x
// * @param y
// * @return
// */
// public BufferedImage getSubimage (int x, int y) {
// return getSubimage(x, y, 16, 16);
// }
//
// public int getWidth() {
// return b.getWidth();
// }
//
// public int getHeight() {
// return b.getHeight();
// }
// }
//
// Path: core/src/main/java/net/panuska/tlappy/Device.java
// public class Device {
// private static final String TAG = Device.class.getSimpleName();
// public static Keyboard keyboard;
// public static VRAM vram;
// public static Music music;
//
// public static int displayWidth;
// public static int displayHeight;
//
// public static boolean initialized = false;
// public static void init (SurfaceView view) {
// if (initialized) {
// Log.d(TAG, "Device already initialized");
// return;
// }
// Log.d(TAG, "Init");
// Images.load(view.getResources());
// keyboard = Keyboard.getInstance();
// vram = VRAM.getInstance();
// vram.createWindow(view);
// music = Music.getInstance(view.getContext());
// WindowManager wm = (WindowManager) view.getContext().getSystemService(Context.WINDOW_SERVICE);
// Display display = wm.getDefaultDisplay();
// displayWidth = display.getWidth();
// displayHeight = display.getHeight();
// if (displayHeight > displayWidth) {
// Log.d(TAG, "Swapping display width and height "+displayWidth+", "+displayHeight);
// displayWidth = displayWidth + displayHeight;
// displayHeight = displayWidth - displayHeight;
// displayWidth = displayWidth - displayHeight;
// }
// initialized = true;
// }
//
// public static void destroy() {
// music.destroy();
// initialized = false;
// }
// }
// Path: core/src/main/java/net/panuska/tlappy/Moveable.java
import net.panuska.tlappy.awt.BufferedImage;
import static net.panuska.tlappy.Device.*;
package net.panuska.tlappy;
/**
* Flappy:
* Original game created by dB-SOFT in 1984 for SHARP MZ-800 computer.
* Java version by Petr Slechta, 2014.
*/
class Moveable {
protected int x, y;
protected byte objType;
protected byte number;
protected byte sig;
protected boolean finished = false;
protected byte[][] model;
protected Scene scene;
protected Moveable(int x, int y, byte objType, int num, Scene scene) {
this.x = x;
this.y = y;
this.objType = objType;
this.number = (byte) num;
this.sig = (byte) (objType | num);
this.model = scene.getModel();
this.scene = scene;
}
boolean isFinished() {
return finished;
}
| protected void drawMe(BufferedImage img) { |
pe-pan/flappy | core/src/main/java/net/panuska/tlappy/ImageUtils.java | // Path: core/src/main/java/net/panuska/tlappy/awt/Color.java
// public enum Color {
// BLACK(0xff000000),
// RED(0xffff0000),
// BLUE(0xff0000ff),
// YELLOW(0xffffff00),
// WHITE(0xffffffff),
// DARK_GRAY(0xff404040),
// LIGHT_GRAY(0xffc0c0c0),
// TRANSPARENT(0x00000000),
//
// black(0xff000000),
// red(0xffff0000),
// blue(0xff0000ff),
// yellow(0xffffff00),
// white(0xffffffff),
// dark_gray(0xff404040);
//
// private final int color;
// Color(int color) { this.color = color; }
// public int getValue() { return color; }
// }
//
// Path: core/src/main/java/net/panuska/tlappy/awt/Graphics.java
// public class Graphics {
// private Canvas c;
// static final private Paint p = new Paint();
//
// public Graphics(Bitmap b) {
// c = new Canvas(b);
// }
//
// public void setColor(Color c) {
// p.setColor(c.getValue());
// }
//
// public void fillRect(int x, int y, int width, int height) {
// p.setStyle(Paint.Style.FILL);
// c.drawRect(x, y, x+width, y+height, p);
// }
//
// public void drawRect(int x, int y, int width, int height) {
// p.setStyle(Paint.Style.STROKE);
// c.drawRect(x, y, x+width, y+height, p);
// }
//
// public boolean drawImage(BufferedImage img, int x, int y, Paint paint) {
// c.drawBitmap(img.getBitmap(), x, y, paint);
// return true;
// }
//
// public void drawString(String str, int x, int y, Color color) {
// Paint p = new Paint();
// p.setTypeface(Typeface.DEFAULT_BOLD);
// p.setTextSize(Constants.SPRITE_SIZE);
// p.setColor(color.getValue());
// c.drawText(str, x, y + Constants.SPRITE_SIZE, p);
// }
//
// /**
// * Draws string using monospaced (Flappy built-in) font.
// * @param text
// * @param x
// * @param y
// * @param color
// */
// public void drawText(String text, int x, int y, Color color) {
// //todo copied from VRAM.printText()
// for (int i = 0, maxi = text.length(); i < maxi; i++) {
// int z = text.charAt(i);
// if (z < 0x20 || z > 0x7a) {
// z = '!';
// }
// z -= 0x20;
// BufferedImage imgChar = ImageUtils.createLetterImage(z, color, Color.BLACK);
// drawImage(imgChar, x, y, null);
// x += Constants.FONT_WIDTH;
// }
// }
// }
//
// Path: core/src/main/java/net/panuska/tlappy/awt/BufferedImage.java
// public class BufferedImage {
// private Bitmap b;
// private Graphics g;
// public static final int TYPE_INT_RGB = Bitmap.Config.ARGB_8888.ordinal();
//
// public BufferedImage(BitmapDrawable d) {
// Bitmap immb = d.getBitmap();
// b = immb.copy(Bitmap.Config.ARGB_8888, false);
// }
//
// public BufferedImage(int width,
// int height,
// int imageType) {
// b = Bitmap.createBitmap(width, height, Bitmap.Config.ARGB_8888);
// g = new Graphics(b);
// }
//
// private BufferedImage(Bitmap b) {
// this.b = b;
// }
//
// public Graphics getGraphics() {
// return g;
// }
//
// public Bitmap getBitmap() {
// return b;
// }
//
// public BufferedImage getSubimage (int x, int y, int w, int h) {
// Bitmap b = Bitmap.createBitmap(this.b, x, y, w, h);
// return new BufferedImage(b);
// }
//
// /**
// * Returns a copy of this image rotated by 90 degrees.
// * @return
// */
// public BufferedImage getRotatedImage() {
// Matrix matrix = new Matrix();
// matrix.postRotate(90);
// Bitmap b = Bitmap.createBitmap(this.getBitmap(), 0, 0, this.getWidth(), this.getHeight(), matrix, false);
// return new BufferedImage(b);
// }
//
// /**
// * Returns a copy of this image mirrored by vertical axis
// * @return
// */
// public BufferedImage getMirroredImage() {
// Matrix matrix = new Matrix();
// matrix.preScale(-1, 1);
// Bitmap b = Bitmap.createBitmap(this.getBitmap(), 0, 0, this.getWidth(), this.getHeight(), matrix, false);
// return new BufferedImage(b);
// }
//
// /**
// * Returns 16x16 subimage starting at x, y
// * @param x
// * @param y
// * @return
// */
// public BufferedImage getSubimage (int x, int y) {
// return getSubimage(x, y, 16, 16);
// }
//
// public int getWidth() {
// return b.getWidth();
// }
//
// public int getHeight() {
// return b.getHeight();
// }
// }
| import android.content.res.Resources;
import android.graphics.drawable.BitmapDrawable;
import net.panuska.tlappy.awt.Color;
import net.panuska.tlappy.awt.Graphics;
import net.panuska.tlappy.awt.BufferedImage; | package net.panuska.tlappy;
/**
* Image utilities.
*
* @author Petr Slechta 2014; Petr Panuska 2016
*/
public class ImageUtils {
private static final int ZOOM = 1;
private ImageUtils() {
} | // Path: core/src/main/java/net/panuska/tlappy/awt/Color.java
// public enum Color {
// BLACK(0xff000000),
// RED(0xffff0000),
// BLUE(0xff0000ff),
// YELLOW(0xffffff00),
// WHITE(0xffffffff),
// DARK_GRAY(0xff404040),
// LIGHT_GRAY(0xffc0c0c0),
// TRANSPARENT(0x00000000),
//
// black(0xff000000),
// red(0xffff0000),
// blue(0xff0000ff),
// yellow(0xffffff00),
// white(0xffffffff),
// dark_gray(0xff404040);
//
// private final int color;
// Color(int color) { this.color = color; }
// public int getValue() { return color; }
// }
//
// Path: core/src/main/java/net/panuska/tlappy/awt/Graphics.java
// public class Graphics {
// private Canvas c;
// static final private Paint p = new Paint();
//
// public Graphics(Bitmap b) {
// c = new Canvas(b);
// }
//
// public void setColor(Color c) {
// p.setColor(c.getValue());
// }
//
// public void fillRect(int x, int y, int width, int height) {
// p.setStyle(Paint.Style.FILL);
// c.drawRect(x, y, x+width, y+height, p);
// }
//
// public void drawRect(int x, int y, int width, int height) {
// p.setStyle(Paint.Style.STROKE);
// c.drawRect(x, y, x+width, y+height, p);
// }
//
// public boolean drawImage(BufferedImage img, int x, int y, Paint paint) {
// c.drawBitmap(img.getBitmap(), x, y, paint);
// return true;
// }
//
// public void drawString(String str, int x, int y, Color color) {
// Paint p = new Paint();
// p.setTypeface(Typeface.DEFAULT_BOLD);
// p.setTextSize(Constants.SPRITE_SIZE);
// p.setColor(color.getValue());
// c.drawText(str, x, y + Constants.SPRITE_SIZE, p);
// }
//
// /**
// * Draws string using monospaced (Flappy built-in) font.
// * @param text
// * @param x
// * @param y
// * @param color
// */
// public void drawText(String text, int x, int y, Color color) {
// //todo copied from VRAM.printText()
// for (int i = 0, maxi = text.length(); i < maxi; i++) {
// int z = text.charAt(i);
// if (z < 0x20 || z > 0x7a) {
// z = '!';
// }
// z -= 0x20;
// BufferedImage imgChar = ImageUtils.createLetterImage(z, color, Color.BLACK);
// drawImage(imgChar, x, y, null);
// x += Constants.FONT_WIDTH;
// }
// }
// }
//
// Path: core/src/main/java/net/panuska/tlappy/awt/BufferedImage.java
// public class BufferedImage {
// private Bitmap b;
// private Graphics g;
// public static final int TYPE_INT_RGB = Bitmap.Config.ARGB_8888.ordinal();
//
// public BufferedImage(BitmapDrawable d) {
// Bitmap immb = d.getBitmap();
// b = immb.copy(Bitmap.Config.ARGB_8888, false);
// }
//
// public BufferedImage(int width,
// int height,
// int imageType) {
// b = Bitmap.createBitmap(width, height, Bitmap.Config.ARGB_8888);
// g = new Graphics(b);
// }
//
// private BufferedImage(Bitmap b) {
// this.b = b;
// }
//
// public Graphics getGraphics() {
// return g;
// }
//
// public Bitmap getBitmap() {
// return b;
// }
//
// public BufferedImage getSubimage (int x, int y, int w, int h) {
// Bitmap b = Bitmap.createBitmap(this.b, x, y, w, h);
// return new BufferedImage(b);
// }
//
// /**
// * Returns a copy of this image rotated by 90 degrees.
// * @return
// */
// public BufferedImage getRotatedImage() {
// Matrix matrix = new Matrix();
// matrix.postRotate(90);
// Bitmap b = Bitmap.createBitmap(this.getBitmap(), 0, 0, this.getWidth(), this.getHeight(), matrix, false);
// return new BufferedImage(b);
// }
//
// /**
// * Returns a copy of this image mirrored by vertical axis
// * @return
// */
// public BufferedImage getMirroredImage() {
// Matrix matrix = new Matrix();
// matrix.preScale(-1, 1);
// Bitmap b = Bitmap.createBitmap(this.getBitmap(), 0, 0, this.getWidth(), this.getHeight(), matrix, false);
// return new BufferedImage(b);
// }
//
// /**
// * Returns 16x16 subimage starting at x, y
// * @param x
// * @param y
// * @return
// */
// public BufferedImage getSubimage (int x, int y) {
// return getSubimage(x, y, 16, 16);
// }
//
// public int getWidth() {
// return b.getWidth();
// }
//
// public int getHeight() {
// return b.getHeight();
// }
// }
// Path: core/src/main/java/net/panuska/tlappy/ImageUtils.java
import android.content.res.Resources;
import android.graphics.drawable.BitmapDrawable;
import net.panuska.tlappy.awt.Color;
import net.panuska.tlappy.awt.Graphics;
import net.panuska.tlappy.awt.BufferedImage;
package net.panuska.tlappy;
/**
* Image utilities.
*
* @author Petr Slechta 2014; Petr Panuska 2016
*/
public class ImageUtils {
private static final int ZOOM = 1;
private ImageUtils() {
} | static BufferedImage loadDrawable(Resources r, int drawableId) { |
pe-pan/flappy | core/src/main/java/net/panuska/tlappy/ImageUtils.java | // Path: core/src/main/java/net/panuska/tlappy/awt/Color.java
// public enum Color {
// BLACK(0xff000000),
// RED(0xffff0000),
// BLUE(0xff0000ff),
// YELLOW(0xffffff00),
// WHITE(0xffffffff),
// DARK_GRAY(0xff404040),
// LIGHT_GRAY(0xffc0c0c0),
// TRANSPARENT(0x00000000),
//
// black(0xff000000),
// red(0xffff0000),
// blue(0xff0000ff),
// yellow(0xffffff00),
// white(0xffffffff),
// dark_gray(0xff404040);
//
// private final int color;
// Color(int color) { this.color = color; }
// public int getValue() { return color; }
// }
//
// Path: core/src/main/java/net/panuska/tlappy/awt/Graphics.java
// public class Graphics {
// private Canvas c;
// static final private Paint p = new Paint();
//
// public Graphics(Bitmap b) {
// c = new Canvas(b);
// }
//
// public void setColor(Color c) {
// p.setColor(c.getValue());
// }
//
// public void fillRect(int x, int y, int width, int height) {
// p.setStyle(Paint.Style.FILL);
// c.drawRect(x, y, x+width, y+height, p);
// }
//
// public void drawRect(int x, int y, int width, int height) {
// p.setStyle(Paint.Style.STROKE);
// c.drawRect(x, y, x+width, y+height, p);
// }
//
// public boolean drawImage(BufferedImage img, int x, int y, Paint paint) {
// c.drawBitmap(img.getBitmap(), x, y, paint);
// return true;
// }
//
// public void drawString(String str, int x, int y, Color color) {
// Paint p = new Paint();
// p.setTypeface(Typeface.DEFAULT_BOLD);
// p.setTextSize(Constants.SPRITE_SIZE);
// p.setColor(color.getValue());
// c.drawText(str, x, y + Constants.SPRITE_SIZE, p);
// }
//
// /**
// * Draws string using monospaced (Flappy built-in) font.
// * @param text
// * @param x
// * @param y
// * @param color
// */
// public void drawText(String text, int x, int y, Color color) {
// //todo copied from VRAM.printText()
// for (int i = 0, maxi = text.length(); i < maxi; i++) {
// int z = text.charAt(i);
// if (z < 0x20 || z > 0x7a) {
// z = '!';
// }
// z -= 0x20;
// BufferedImage imgChar = ImageUtils.createLetterImage(z, color, Color.BLACK);
// drawImage(imgChar, x, y, null);
// x += Constants.FONT_WIDTH;
// }
// }
// }
//
// Path: core/src/main/java/net/panuska/tlappy/awt/BufferedImage.java
// public class BufferedImage {
// private Bitmap b;
// private Graphics g;
// public static final int TYPE_INT_RGB = Bitmap.Config.ARGB_8888.ordinal();
//
// public BufferedImage(BitmapDrawable d) {
// Bitmap immb = d.getBitmap();
// b = immb.copy(Bitmap.Config.ARGB_8888, false);
// }
//
// public BufferedImage(int width,
// int height,
// int imageType) {
// b = Bitmap.createBitmap(width, height, Bitmap.Config.ARGB_8888);
// g = new Graphics(b);
// }
//
// private BufferedImage(Bitmap b) {
// this.b = b;
// }
//
// public Graphics getGraphics() {
// return g;
// }
//
// public Bitmap getBitmap() {
// return b;
// }
//
// public BufferedImage getSubimage (int x, int y, int w, int h) {
// Bitmap b = Bitmap.createBitmap(this.b, x, y, w, h);
// return new BufferedImage(b);
// }
//
// /**
// * Returns a copy of this image rotated by 90 degrees.
// * @return
// */
// public BufferedImage getRotatedImage() {
// Matrix matrix = new Matrix();
// matrix.postRotate(90);
// Bitmap b = Bitmap.createBitmap(this.getBitmap(), 0, 0, this.getWidth(), this.getHeight(), matrix, false);
// return new BufferedImage(b);
// }
//
// /**
// * Returns a copy of this image mirrored by vertical axis
// * @return
// */
// public BufferedImage getMirroredImage() {
// Matrix matrix = new Matrix();
// matrix.preScale(-1, 1);
// Bitmap b = Bitmap.createBitmap(this.getBitmap(), 0, 0, this.getWidth(), this.getHeight(), matrix, false);
// return new BufferedImage(b);
// }
//
// /**
// * Returns 16x16 subimage starting at x, y
// * @param x
// * @param y
// * @return
// */
// public BufferedImage getSubimage (int x, int y) {
// return getSubimage(x, y, 16, 16);
// }
//
// public int getWidth() {
// return b.getWidth();
// }
//
// public int getHeight() {
// return b.getHeight();
// }
// }
| import android.content.res.Resources;
import android.graphics.drawable.BitmapDrawable;
import net.panuska.tlappy.awt.Color;
import net.panuska.tlappy.awt.Graphics;
import net.panuska.tlappy.awt.BufferedImage; | package net.panuska.tlappy;
/**
* Image utilities.
*
* @author Petr Slechta 2014; Petr Panuska 2016
*/
public class ImageUtils {
private static final int ZOOM = 1;
private ImageUtils() {
}
static BufferedImage loadDrawable(Resources r, int drawableId) {
BitmapDrawable d = (BitmapDrawable)r.getDrawable(drawableId);
return new BufferedImage(d);
}
public static final int FONT_SIZE = 8; | // Path: core/src/main/java/net/panuska/tlappy/awt/Color.java
// public enum Color {
// BLACK(0xff000000),
// RED(0xffff0000),
// BLUE(0xff0000ff),
// YELLOW(0xffffff00),
// WHITE(0xffffffff),
// DARK_GRAY(0xff404040),
// LIGHT_GRAY(0xffc0c0c0),
// TRANSPARENT(0x00000000),
//
// black(0xff000000),
// red(0xffff0000),
// blue(0xff0000ff),
// yellow(0xffffff00),
// white(0xffffffff),
// dark_gray(0xff404040);
//
// private final int color;
// Color(int color) { this.color = color; }
// public int getValue() { return color; }
// }
//
// Path: core/src/main/java/net/panuska/tlappy/awt/Graphics.java
// public class Graphics {
// private Canvas c;
// static final private Paint p = new Paint();
//
// public Graphics(Bitmap b) {
// c = new Canvas(b);
// }
//
// public void setColor(Color c) {
// p.setColor(c.getValue());
// }
//
// public void fillRect(int x, int y, int width, int height) {
// p.setStyle(Paint.Style.FILL);
// c.drawRect(x, y, x+width, y+height, p);
// }
//
// public void drawRect(int x, int y, int width, int height) {
// p.setStyle(Paint.Style.STROKE);
// c.drawRect(x, y, x+width, y+height, p);
// }
//
// public boolean drawImage(BufferedImage img, int x, int y, Paint paint) {
// c.drawBitmap(img.getBitmap(), x, y, paint);
// return true;
// }
//
// public void drawString(String str, int x, int y, Color color) {
// Paint p = new Paint();
// p.setTypeface(Typeface.DEFAULT_BOLD);
// p.setTextSize(Constants.SPRITE_SIZE);
// p.setColor(color.getValue());
// c.drawText(str, x, y + Constants.SPRITE_SIZE, p);
// }
//
// /**
// * Draws string using monospaced (Flappy built-in) font.
// * @param text
// * @param x
// * @param y
// * @param color
// */
// public void drawText(String text, int x, int y, Color color) {
// //todo copied from VRAM.printText()
// for (int i = 0, maxi = text.length(); i < maxi; i++) {
// int z = text.charAt(i);
// if (z < 0x20 || z > 0x7a) {
// z = '!';
// }
// z -= 0x20;
// BufferedImage imgChar = ImageUtils.createLetterImage(z, color, Color.BLACK);
// drawImage(imgChar, x, y, null);
// x += Constants.FONT_WIDTH;
// }
// }
// }
//
// Path: core/src/main/java/net/panuska/tlappy/awt/BufferedImage.java
// public class BufferedImage {
// private Bitmap b;
// private Graphics g;
// public static final int TYPE_INT_RGB = Bitmap.Config.ARGB_8888.ordinal();
//
// public BufferedImage(BitmapDrawable d) {
// Bitmap immb = d.getBitmap();
// b = immb.copy(Bitmap.Config.ARGB_8888, false);
// }
//
// public BufferedImage(int width,
// int height,
// int imageType) {
// b = Bitmap.createBitmap(width, height, Bitmap.Config.ARGB_8888);
// g = new Graphics(b);
// }
//
// private BufferedImage(Bitmap b) {
// this.b = b;
// }
//
// public Graphics getGraphics() {
// return g;
// }
//
// public Bitmap getBitmap() {
// return b;
// }
//
// public BufferedImage getSubimage (int x, int y, int w, int h) {
// Bitmap b = Bitmap.createBitmap(this.b, x, y, w, h);
// return new BufferedImage(b);
// }
//
// /**
// * Returns a copy of this image rotated by 90 degrees.
// * @return
// */
// public BufferedImage getRotatedImage() {
// Matrix matrix = new Matrix();
// matrix.postRotate(90);
// Bitmap b = Bitmap.createBitmap(this.getBitmap(), 0, 0, this.getWidth(), this.getHeight(), matrix, false);
// return new BufferedImage(b);
// }
//
// /**
// * Returns a copy of this image mirrored by vertical axis
// * @return
// */
// public BufferedImage getMirroredImage() {
// Matrix matrix = new Matrix();
// matrix.preScale(-1, 1);
// Bitmap b = Bitmap.createBitmap(this.getBitmap(), 0, 0, this.getWidth(), this.getHeight(), matrix, false);
// return new BufferedImage(b);
// }
//
// /**
// * Returns 16x16 subimage starting at x, y
// * @param x
// * @param y
// * @return
// */
// public BufferedImage getSubimage (int x, int y) {
// return getSubimage(x, y, 16, 16);
// }
//
// public int getWidth() {
// return b.getWidth();
// }
//
// public int getHeight() {
// return b.getHeight();
// }
// }
// Path: core/src/main/java/net/panuska/tlappy/ImageUtils.java
import android.content.res.Resources;
import android.graphics.drawable.BitmapDrawable;
import net.panuska.tlappy.awt.Color;
import net.panuska.tlappy.awt.Graphics;
import net.panuska.tlappy.awt.BufferedImage;
package net.panuska.tlappy;
/**
* Image utilities.
*
* @author Petr Slechta 2014; Petr Panuska 2016
*/
public class ImageUtils {
private static final int ZOOM = 1;
private ImageUtils() {
}
static BufferedImage loadDrawable(Resources r, int drawableId) {
BitmapDrawable d = (BitmapDrawable)r.getDrawable(drawableId);
return new BufferedImage(d);
}
public static final int FONT_SIZE = 8; | public static BufferedImage createLetterImage(int z, Color color, Color background) { |
pe-pan/flappy | mobile/src/main/java/net/panuska/tlappy/CustomControlsActivity.java | // Path: core/src/main/java/net/panuska/tlappy/awt/BufferedImage.java
// public class BufferedImage {
// private Bitmap b;
// private Graphics g;
// public static final int TYPE_INT_RGB = Bitmap.Config.ARGB_8888.ordinal();
//
// public BufferedImage(BitmapDrawable d) {
// Bitmap immb = d.getBitmap();
// b = immb.copy(Bitmap.Config.ARGB_8888, false);
// }
//
// public BufferedImage(int width,
// int height,
// int imageType) {
// b = Bitmap.createBitmap(width, height, Bitmap.Config.ARGB_8888);
// g = new Graphics(b);
// }
//
// private BufferedImage(Bitmap b) {
// this.b = b;
// }
//
// public Graphics getGraphics() {
// return g;
// }
//
// public Bitmap getBitmap() {
// return b;
// }
//
// public BufferedImage getSubimage (int x, int y, int w, int h) {
// Bitmap b = Bitmap.createBitmap(this.b, x, y, w, h);
// return new BufferedImage(b);
// }
//
// /**
// * Returns a copy of this image rotated by 90 degrees.
// * @return
// */
// public BufferedImage getRotatedImage() {
// Matrix matrix = new Matrix();
// matrix.postRotate(90);
// Bitmap b = Bitmap.createBitmap(this.getBitmap(), 0, 0, this.getWidth(), this.getHeight(), matrix, false);
// return new BufferedImage(b);
// }
//
// /**
// * Returns a copy of this image mirrored by vertical axis
// * @return
// */
// public BufferedImage getMirroredImage() {
// Matrix matrix = new Matrix();
// matrix.preScale(-1, 1);
// Bitmap b = Bitmap.createBitmap(this.getBitmap(), 0, 0, this.getWidth(), this.getHeight(), matrix, false);
// return new BufferedImage(b);
// }
//
// /**
// * Returns 16x16 subimage starting at x, y
// * @param x
// * @param y
// * @return
// */
// public BufferedImage getSubimage (int x, int y) {
// return getSubimage(x, y, 16, 16);
// }
//
// public int getWidth() {
// return b.getWidth();
// }
//
// public int getHeight() {
// return b.getHeight();
// }
// }
//
// Path: core/src/main/java/net/panuska/tlappy/awt/Color.java
// public enum Color {
// BLACK(0xff000000),
// RED(0xffff0000),
// BLUE(0xff0000ff),
// YELLOW(0xffffff00),
// WHITE(0xffffffff),
// DARK_GRAY(0xff404040),
// LIGHT_GRAY(0xffc0c0c0),
// TRANSPARENT(0x00000000),
//
// black(0xff000000),
// red(0xffff0000),
// blue(0xff0000ff),
// yellow(0xffffff00),
// white(0xffffffff),
// dark_gray(0xff404040);
//
// private final int color;
// Color(int color) { this.color = color; }
// public int getValue() { return color; }
// }
//
// Path: core/src/main/java/net/panuska/tlappy/Device.java
// public static VRAM vram;
//
// Path: mobile/src/main/java/net/panuska/tlappy/FullscreenActivity.java
// static final int DOWN = 40;
//
// Path: mobile/src/main/java/net/panuska/tlappy/FullscreenActivity.java
// static final int LEFT = 37;
//
// Path: mobile/src/main/java/net/panuska/tlappy/FullscreenActivity.java
// static final int RIGHT = 39;
//
// Path: mobile/src/main/java/net/panuska/tlappy/FullscreenActivity.java
// static final int SPACE_BAR = 32;
//
// Path: mobile/src/main/java/net/panuska/tlappy/FullscreenActivity.java
// static final int UP = 38;
| import android.os.AsyncTask;
import android.os.Bundle;
import android.util.Log;
import android.util.SparseIntArray;
import android.view.KeyEvent;
import android.view.SurfaceView;
import net.panuska.tlappy.awt.BufferedImage;
import net.panuska.tlappy.awt.Color;
import net.panuska.tlappy.mobile.R;
import static net.panuska.tlappy.Device.vram;
import static net.panuska.tlappy.FullscreenActivity.DOWN;
import static net.panuska.tlappy.FullscreenActivity.LEFT;
import static net.panuska.tlappy.FullscreenActivity.RIGHT;
import static net.panuska.tlappy.FullscreenActivity.SPACE_BAR;
import static net.panuska.tlappy.FullscreenActivity.UP; | package net.panuska.tlappy;
/**
* Flappy:
* Original game created by dB-SOFT in 1984 for SHARP MZ-800 computer.
* Java version by Petr Slechta, 2014.
* Android version by Petr Panuska, 2017.
*/
public class CustomControlsActivity extends TlappyActivity {
private static final String TAG = CustomControlsActivity.class.getSimpleName();
private SparseIntArray tempKeyboardMap; // used for custom key recording
static final SparseIntArray keyboardMap = new SparseIntArray();
private AsyncTask<Void, Void, Void> game;
volatile int state;
volatile int index;
volatile int maxIndex;
volatile String message, systemMessage;
| // Path: core/src/main/java/net/panuska/tlappy/awt/BufferedImage.java
// public class BufferedImage {
// private Bitmap b;
// private Graphics g;
// public static final int TYPE_INT_RGB = Bitmap.Config.ARGB_8888.ordinal();
//
// public BufferedImage(BitmapDrawable d) {
// Bitmap immb = d.getBitmap();
// b = immb.copy(Bitmap.Config.ARGB_8888, false);
// }
//
// public BufferedImage(int width,
// int height,
// int imageType) {
// b = Bitmap.createBitmap(width, height, Bitmap.Config.ARGB_8888);
// g = new Graphics(b);
// }
//
// private BufferedImage(Bitmap b) {
// this.b = b;
// }
//
// public Graphics getGraphics() {
// return g;
// }
//
// public Bitmap getBitmap() {
// return b;
// }
//
// public BufferedImage getSubimage (int x, int y, int w, int h) {
// Bitmap b = Bitmap.createBitmap(this.b, x, y, w, h);
// return new BufferedImage(b);
// }
//
// /**
// * Returns a copy of this image rotated by 90 degrees.
// * @return
// */
// public BufferedImage getRotatedImage() {
// Matrix matrix = new Matrix();
// matrix.postRotate(90);
// Bitmap b = Bitmap.createBitmap(this.getBitmap(), 0, 0, this.getWidth(), this.getHeight(), matrix, false);
// return new BufferedImage(b);
// }
//
// /**
// * Returns a copy of this image mirrored by vertical axis
// * @return
// */
// public BufferedImage getMirroredImage() {
// Matrix matrix = new Matrix();
// matrix.preScale(-1, 1);
// Bitmap b = Bitmap.createBitmap(this.getBitmap(), 0, 0, this.getWidth(), this.getHeight(), matrix, false);
// return new BufferedImage(b);
// }
//
// /**
// * Returns 16x16 subimage starting at x, y
// * @param x
// * @param y
// * @return
// */
// public BufferedImage getSubimage (int x, int y) {
// return getSubimage(x, y, 16, 16);
// }
//
// public int getWidth() {
// return b.getWidth();
// }
//
// public int getHeight() {
// return b.getHeight();
// }
// }
//
// Path: core/src/main/java/net/panuska/tlappy/awt/Color.java
// public enum Color {
// BLACK(0xff000000),
// RED(0xffff0000),
// BLUE(0xff0000ff),
// YELLOW(0xffffff00),
// WHITE(0xffffffff),
// DARK_GRAY(0xff404040),
// LIGHT_GRAY(0xffc0c0c0),
// TRANSPARENT(0x00000000),
//
// black(0xff000000),
// red(0xffff0000),
// blue(0xff0000ff),
// yellow(0xffffff00),
// white(0xffffffff),
// dark_gray(0xff404040);
//
// private final int color;
// Color(int color) { this.color = color; }
// public int getValue() { return color; }
// }
//
// Path: core/src/main/java/net/panuska/tlappy/Device.java
// public static VRAM vram;
//
// Path: mobile/src/main/java/net/panuska/tlappy/FullscreenActivity.java
// static final int DOWN = 40;
//
// Path: mobile/src/main/java/net/panuska/tlappy/FullscreenActivity.java
// static final int LEFT = 37;
//
// Path: mobile/src/main/java/net/panuska/tlappy/FullscreenActivity.java
// static final int RIGHT = 39;
//
// Path: mobile/src/main/java/net/panuska/tlappy/FullscreenActivity.java
// static final int SPACE_BAR = 32;
//
// Path: mobile/src/main/java/net/panuska/tlappy/FullscreenActivity.java
// static final int UP = 38;
// Path: mobile/src/main/java/net/panuska/tlappy/CustomControlsActivity.java
import android.os.AsyncTask;
import android.os.Bundle;
import android.util.Log;
import android.util.SparseIntArray;
import android.view.KeyEvent;
import android.view.SurfaceView;
import net.panuska.tlappy.awt.BufferedImage;
import net.panuska.tlappy.awt.Color;
import net.panuska.tlappy.mobile.R;
import static net.panuska.tlappy.Device.vram;
import static net.panuska.tlappy.FullscreenActivity.DOWN;
import static net.panuska.tlappy.FullscreenActivity.LEFT;
import static net.panuska.tlappy.FullscreenActivity.RIGHT;
import static net.panuska.tlappy.FullscreenActivity.SPACE_BAR;
import static net.panuska.tlappy.FullscreenActivity.UP;
package net.panuska.tlappy;
/**
* Flappy:
* Original game created by dB-SOFT in 1984 for SHARP MZ-800 computer.
* Java version by Petr Slechta, 2014.
* Android version by Petr Panuska, 2017.
*/
public class CustomControlsActivity extends TlappyActivity {
private static final String TAG = CustomControlsActivity.class.getSimpleName();
private SparseIntArray tempKeyboardMap; // used for custom key recording
static final SparseIntArray keyboardMap = new SparseIntArray();
private AsyncTask<Void, Void, Void> game;
volatile int state;
volatile int index;
volatile int maxIndex;
volatile String message, systemMessage;
| private static final int[] STATES = {LEFT, RIGHT, UP, DOWN, SPACE_BAR, -1}; |
pe-pan/flappy | mobile/src/main/java/net/panuska/tlappy/CustomControlsActivity.java | // Path: core/src/main/java/net/panuska/tlappy/awt/BufferedImage.java
// public class BufferedImage {
// private Bitmap b;
// private Graphics g;
// public static final int TYPE_INT_RGB = Bitmap.Config.ARGB_8888.ordinal();
//
// public BufferedImage(BitmapDrawable d) {
// Bitmap immb = d.getBitmap();
// b = immb.copy(Bitmap.Config.ARGB_8888, false);
// }
//
// public BufferedImage(int width,
// int height,
// int imageType) {
// b = Bitmap.createBitmap(width, height, Bitmap.Config.ARGB_8888);
// g = new Graphics(b);
// }
//
// private BufferedImage(Bitmap b) {
// this.b = b;
// }
//
// public Graphics getGraphics() {
// return g;
// }
//
// public Bitmap getBitmap() {
// return b;
// }
//
// public BufferedImage getSubimage (int x, int y, int w, int h) {
// Bitmap b = Bitmap.createBitmap(this.b, x, y, w, h);
// return new BufferedImage(b);
// }
//
// /**
// * Returns a copy of this image rotated by 90 degrees.
// * @return
// */
// public BufferedImage getRotatedImage() {
// Matrix matrix = new Matrix();
// matrix.postRotate(90);
// Bitmap b = Bitmap.createBitmap(this.getBitmap(), 0, 0, this.getWidth(), this.getHeight(), matrix, false);
// return new BufferedImage(b);
// }
//
// /**
// * Returns a copy of this image mirrored by vertical axis
// * @return
// */
// public BufferedImage getMirroredImage() {
// Matrix matrix = new Matrix();
// matrix.preScale(-1, 1);
// Bitmap b = Bitmap.createBitmap(this.getBitmap(), 0, 0, this.getWidth(), this.getHeight(), matrix, false);
// return new BufferedImage(b);
// }
//
// /**
// * Returns 16x16 subimage starting at x, y
// * @param x
// * @param y
// * @return
// */
// public BufferedImage getSubimage (int x, int y) {
// return getSubimage(x, y, 16, 16);
// }
//
// public int getWidth() {
// return b.getWidth();
// }
//
// public int getHeight() {
// return b.getHeight();
// }
// }
//
// Path: core/src/main/java/net/panuska/tlappy/awt/Color.java
// public enum Color {
// BLACK(0xff000000),
// RED(0xffff0000),
// BLUE(0xff0000ff),
// YELLOW(0xffffff00),
// WHITE(0xffffffff),
// DARK_GRAY(0xff404040),
// LIGHT_GRAY(0xffc0c0c0),
// TRANSPARENT(0x00000000),
//
// black(0xff000000),
// red(0xffff0000),
// blue(0xff0000ff),
// yellow(0xffffff00),
// white(0xffffffff),
// dark_gray(0xff404040);
//
// private final int color;
// Color(int color) { this.color = color; }
// public int getValue() { return color; }
// }
//
// Path: core/src/main/java/net/panuska/tlappy/Device.java
// public static VRAM vram;
//
// Path: mobile/src/main/java/net/panuska/tlappy/FullscreenActivity.java
// static final int DOWN = 40;
//
// Path: mobile/src/main/java/net/panuska/tlappy/FullscreenActivity.java
// static final int LEFT = 37;
//
// Path: mobile/src/main/java/net/panuska/tlappy/FullscreenActivity.java
// static final int RIGHT = 39;
//
// Path: mobile/src/main/java/net/panuska/tlappy/FullscreenActivity.java
// static final int SPACE_BAR = 32;
//
// Path: mobile/src/main/java/net/panuska/tlappy/FullscreenActivity.java
// static final int UP = 38;
| import android.os.AsyncTask;
import android.os.Bundle;
import android.util.Log;
import android.util.SparseIntArray;
import android.view.KeyEvent;
import android.view.SurfaceView;
import net.panuska.tlappy.awt.BufferedImage;
import net.panuska.tlappy.awt.Color;
import net.panuska.tlappy.mobile.R;
import static net.panuska.tlappy.Device.vram;
import static net.panuska.tlappy.FullscreenActivity.DOWN;
import static net.panuska.tlappy.FullscreenActivity.LEFT;
import static net.panuska.tlappy.FullscreenActivity.RIGHT;
import static net.panuska.tlappy.FullscreenActivity.SPACE_BAR;
import static net.panuska.tlappy.FullscreenActivity.UP; | package net.panuska.tlappy;
/**
* Flappy:
* Original game created by dB-SOFT in 1984 for SHARP MZ-800 computer.
* Java version by Petr Slechta, 2014.
* Android version by Petr Panuska, 2017.
*/
public class CustomControlsActivity extends TlappyActivity {
private static final String TAG = CustomControlsActivity.class.getSimpleName();
private SparseIntArray tempKeyboardMap; // used for custom key recording
static final SparseIntArray keyboardMap = new SparseIntArray();
private AsyncTask<Void, Void, Void> game;
volatile int state;
volatile int index;
volatile int maxIndex;
volatile String message, systemMessage;
| // Path: core/src/main/java/net/panuska/tlappy/awt/BufferedImage.java
// public class BufferedImage {
// private Bitmap b;
// private Graphics g;
// public static final int TYPE_INT_RGB = Bitmap.Config.ARGB_8888.ordinal();
//
// public BufferedImage(BitmapDrawable d) {
// Bitmap immb = d.getBitmap();
// b = immb.copy(Bitmap.Config.ARGB_8888, false);
// }
//
// public BufferedImage(int width,
// int height,
// int imageType) {
// b = Bitmap.createBitmap(width, height, Bitmap.Config.ARGB_8888);
// g = new Graphics(b);
// }
//
// private BufferedImage(Bitmap b) {
// this.b = b;
// }
//
// public Graphics getGraphics() {
// return g;
// }
//
// public Bitmap getBitmap() {
// return b;
// }
//
// public BufferedImage getSubimage (int x, int y, int w, int h) {
// Bitmap b = Bitmap.createBitmap(this.b, x, y, w, h);
// return new BufferedImage(b);
// }
//
// /**
// * Returns a copy of this image rotated by 90 degrees.
// * @return
// */
// public BufferedImage getRotatedImage() {
// Matrix matrix = new Matrix();
// matrix.postRotate(90);
// Bitmap b = Bitmap.createBitmap(this.getBitmap(), 0, 0, this.getWidth(), this.getHeight(), matrix, false);
// return new BufferedImage(b);
// }
//
// /**
// * Returns a copy of this image mirrored by vertical axis
// * @return
// */
// public BufferedImage getMirroredImage() {
// Matrix matrix = new Matrix();
// matrix.preScale(-1, 1);
// Bitmap b = Bitmap.createBitmap(this.getBitmap(), 0, 0, this.getWidth(), this.getHeight(), matrix, false);
// return new BufferedImage(b);
// }
//
// /**
// * Returns 16x16 subimage starting at x, y
// * @param x
// * @param y
// * @return
// */
// public BufferedImage getSubimage (int x, int y) {
// return getSubimage(x, y, 16, 16);
// }
//
// public int getWidth() {
// return b.getWidth();
// }
//
// public int getHeight() {
// return b.getHeight();
// }
// }
//
// Path: core/src/main/java/net/panuska/tlappy/awt/Color.java
// public enum Color {
// BLACK(0xff000000),
// RED(0xffff0000),
// BLUE(0xff0000ff),
// YELLOW(0xffffff00),
// WHITE(0xffffffff),
// DARK_GRAY(0xff404040),
// LIGHT_GRAY(0xffc0c0c0),
// TRANSPARENT(0x00000000),
//
// black(0xff000000),
// red(0xffff0000),
// blue(0xff0000ff),
// yellow(0xffffff00),
// white(0xffffffff),
// dark_gray(0xff404040);
//
// private final int color;
// Color(int color) { this.color = color; }
// public int getValue() { return color; }
// }
//
// Path: core/src/main/java/net/panuska/tlappy/Device.java
// public static VRAM vram;
//
// Path: mobile/src/main/java/net/panuska/tlappy/FullscreenActivity.java
// static final int DOWN = 40;
//
// Path: mobile/src/main/java/net/panuska/tlappy/FullscreenActivity.java
// static final int LEFT = 37;
//
// Path: mobile/src/main/java/net/panuska/tlappy/FullscreenActivity.java
// static final int RIGHT = 39;
//
// Path: mobile/src/main/java/net/panuska/tlappy/FullscreenActivity.java
// static final int SPACE_BAR = 32;
//
// Path: mobile/src/main/java/net/panuska/tlappy/FullscreenActivity.java
// static final int UP = 38;
// Path: mobile/src/main/java/net/panuska/tlappy/CustomControlsActivity.java
import android.os.AsyncTask;
import android.os.Bundle;
import android.util.Log;
import android.util.SparseIntArray;
import android.view.KeyEvent;
import android.view.SurfaceView;
import net.panuska.tlappy.awt.BufferedImage;
import net.panuska.tlappy.awt.Color;
import net.panuska.tlappy.mobile.R;
import static net.panuska.tlappy.Device.vram;
import static net.panuska.tlappy.FullscreenActivity.DOWN;
import static net.panuska.tlappy.FullscreenActivity.LEFT;
import static net.panuska.tlappy.FullscreenActivity.RIGHT;
import static net.panuska.tlappy.FullscreenActivity.SPACE_BAR;
import static net.panuska.tlappy.FullscreenActivity.UP;
package net.panuska.tlappy;
/**
* Flappy:
* Original game created by dB-SOFT in 1984 for SHARP MZ-800 computer.
* Java version by Petr Slechta, 2014.
* Android version by Petr Panuska, 2017.
*/
public class CustomControlsActivity extends TlappyActivity {
private static final String TAG = CustomControlsActivity.class.getSimpleName();
private SparseIntArray tempKeyboardMap; // used for custom key recording
static final SparseIntArray keyboardMap = new SparseIntArray();
private AsyncTask<Void, Void, Void> game;
volatile int state;
volatile int index;
volatile int maxIndex;
volatile String message, systemMessage;
| private static final int[] STATES = {LEFT, RIGHT, UP, DOWN, SPACE_BAR, -1}; |
pe-pan/flappy | mobile/src/main/java/net/panuska/tlappy/CustomControlsActivity.java | // Path: core/src/main/java/net/panuska/tlappy/awt/BufferedImage.java
// public class BufferedImage {
// private Bitmap b;
// private Graphics g;
// public static final int TYPE_INT_RGB = Bitmap.Config.ARGB_8888.ordinal();
//
// public BufferedImage(BitmapDrawable d) {
// Bitmap immb = d.getBitmap();
// b = immb.copy(Bitmap.Config.ARGB_8888, false);
// }
//
// public BufferedImage(int width,
// int height,
// int imageType) {
// b = Bitmap.createBitmap(width, height, Bitmap.Config.ARGB_8888);
// g = new Graphics(b);
// }
//
// private BufferedImage(Bitmap b) {
// this.b = b;
// }
//
// public Graphics getGraphics() {
// return g;
// }
//
// public Bitmap getBitmap() {
// return b;
// }
//
// public BufferedImage getSubimage (int x, int y, int w, int h) {
// Bitmap b = Bitmap.createBitmap(this.b, x, y, w, h);
// return new BufferedImage(b);
// }
//
// /**
// * Returns a copy of this image rotated by 90 degrees.
// * @return
// */
// public BufferedImage getRotatedImage() {
// Matrix matrix = new Matrix();
// matrix.postRotate(90);
// Bitmap b = Bitmap.createBitmap(this.getBitmap(), 0, 0, this.getWidth(), this.getHeight(), matrix, false);
// return new BufferedImage(b);
// }
//
// /**
// * Returns a copy of this image mirrored by vertical axis
// * @return
// */
// public BufferedImage getMirroredImage() {
// Matrix matrix = new Matrix();
// matrix.preScale(-1, 1);
// Bitmap b = Bitmap.createBitmap(this.getBitmap(), 0, 0, this.getWidth(), this.getHeight(), matrix, false);
// return new BufferedImage(b);
// }
//
// /**
// * Returns 16x16 subimage starting at x, y
// * @param x
// * @param y
// * @return
// */
// public BufferedImage getSubimage (int x, int y) {
// return getSubimage(x, y, 16, 16);
// }
//
// public int getWidth() {
// return b.getWidth();
// }
//
// public int getHeight() {
// return b.getHeight();
// }
// }
//
// Path: core/src/main/java/net/panuska/tlappy/awt/Color.java
// public enum Color {
// BLACK(0xff000000),
// RED(0xffff0000),
// BLUE(0xff0000ff),
// YELLOW(0xffffff00),
// WHITE(0xffffffff),
// DARK_GRAY(0xff404040),
// LIGHT_GRAY(0xffc0c0c0),
// TRANSPARENT(0x00000000),
//
// black(0xff000000),
// red(0xffff0000),
// blue(0xff0000ff),
// yellow(0xffffff00),
// white(0xffffffff),
// dark_gray(0xff404040);
//
// private final int color;
// Color(int color) { this.color = color; }
// public int getValue() { return color; }
// }
//
// Path: core/src/main/java/net/panuska/tlappy/Device.java
// public static VRAM vram;
//
// Path: mobile/src/main/java/net/panuska/tlappy/FullscreenActivity.java
// static final int DOWN = 40;
//
// Path: mobile/src/main/java/net/panuska/tlappy/FullscreenActivity.java
// static final int LEFT = 37;
//
// Path: mobile/src/main/java/net/panuska/tlappy/FullscreenActivity.java
// static final int RIGHT = 39;
//
// Path: mobile/src/main/java/net/panuska/tlappy/FullscreenActivity.java
// static final int SPACE_BAR = 32;
//
// Path: mobile/src/main/java/net/panuska/tlappy/FullscreenActivity.java
// static final int UP = 38;
| import android.os.AsyncTask;
import android.os.Bundle;
import android.util.Log;
import android.util.SparseIntArray;
import android.view.KeyEvent;
import android.view.SurfaceView;
import net.panuska.tlappy.awt.BufferedImage;
import net.panuska.tlappy.awt.Color;
import net.panuska.tlappy.mobile.R;
import static net.panuska.tlappy.Device.vram;
import static net.panuska.tlappy.FullscreenActivity.DOWN;
import static net.panuska.tlappy.FullscreenActivity.LEFT;
import static net.panuska.tlappy.FullscreenActivity.RIGHT;
import static net.panuska.tlappy.FullscreenActivity.SPACE_BAR;
import static net.panuska.tlappy.FullscreenActivity.UP; | package net.panuska.tlappy;
/**
* Flappy:
* Original game created by dB-SOFT in 1984 for SHARP MZ-800 computer.
* Java version by Petr Slechta, 2014.
* Android version by Petr Panuska, 2017.
*/
public class CustomControlsActivity extends TlappyActivity {
private static final String TAG = CustomControlsActivity.class.getSimpleName();
private SparseIntArray tempKeyboardMap; // used for custom key recording
static final SparseIntArray keyboardMap = new SparseIntArray();
private AsyncTask<Void, Void, Void> game;
volatile int state;
volatile int index;
volatile int maxIndex;
volatile String message, systemMessage;
| // Path: core/src/main/java/net/panuska/tlappy/awt/BufferedImage.java
// public class BufferedImage {
// private Bitmap b;
// private Graphics g;
// public static final int TYPE_INT_RGB = Bitmap.Config.ARGB_8888.ordinal();
//
// public BufferedImage(BitmapDrawable d) {
// Bitmap immb = d.getBitmap();
// b = immb.copy(Bitmap.Config.ARGB_8888, false);
// }
//
// public BufferedImage(int width,
// int height,
// int imageType) {
// b = Bitmap.createBitmap(width, height, Bitmap.Config.ARGB_8888);
// g = new Graphics(b);
// }
//
// private BufferedImage(Bitmap b) {
// this.b = b;
// }
//
// public Graphics getGraphics() {
// return g;
// }
//
// public Bitmap getBitmap() {
// return b;
// }
//
// public BufferedImage getSubimage (int x, int y, int w, int h) {
// Bitmap b = Bitmap.createBitmap(this.b, x, y, w, h);
// return new BufferedImage(b);
// }
//
// /**
// * Returns a copy of this image rotated by 90 degrees.
// * @return
// */
// public BufferedImage getRotatedImage() {
// Matrix matrix = new Matrix();
// matrix.postRotate(90);
// Bitmap b = Bitmap.createBitmap(this.getBitmap(), 0, 0, this.getWidth(), this.getHeight(), matrix, false);
// return new BufferedImage(b);
// }
//
// /**
// * Returns a copy of this image mirrored by vertical axis
// * @return
// */
// public BufferedImage getMirroredImage() {
// Matrix matrix = new Matrix();
// matrix.preScale(-1, 1);
// Bitmap b = Bitmap.createBitmap(this.getBitmap(), 0, 0, this.getWidth(), this.getHeight(), matrix, false);
// return new BufferedImage(b);
// }
//
// /**
// * Returns 16x16 subimage starting at x, y
// * @param x
// * @param y
// * @return
// */
// public BufferedImage getSubimage (int x, int y) {
// return getSubimage(x, y, 16, 16);
// }
//
// public int getWidth() {
// return b.getWidth();
// }
//
// public int getHeight() {
// return b.getHeight();
// }
// }
//
// Path: core/src/main/java/net/panuska/tlappy/awt/Color.java
// public enum Color {
// BLACK(0xff000000),
// RED(0xffff0000),
// BLUE(0xff0000ff),
// YELLOW(0xffffff00),
// WHITE(0xffffffff),
// DARK_GRAY(0xff404040),
// LIGHT_GRAY(0xffc0c0c0),
// TRANSPARENT(0x00000000),
//
// black(0xff000000),
// red(0xffff0000),
// blue(0xff0000ff),
// yellow(0xffffff00),
// white(0xffffffff),
// dark_gray(0xff404040);
//
// private final int color;
// Color(int color) { this.color = color; }
// public int getValue() { return color; }
// }
//
// Path: core/src/main/java/net/panuska/tlappy/Device.java
// public static VRAM vram;
//
// Path: mobile/src/main/java/net/panuska/tlappy/FullscreenActivity.java
// static final int DOWN = 40;
//
// Path: mobile/src/main/java/net/panuska/tlappy/FullscreenActivity.java
// static final int LEFT = 37;
//
// Path: mobile/src/main/java/net/panuska/tlappy/FullscreenActivity.java
// static final int RIGHT = 39;
//
// Path: mobile/src/main/java/net/panuska/tlappy/FullscreenActivity.java
// static final int SPACE_BAR = 32;
//
// Path: mobile/src/main/java/net/panuska/tlappy/FullscreenActivity.java
// static final int UP = 38;
// Path: mobile/src/main/java/net/panuska/tlappy/CustomControlsActivity.java
import android.os.AsyncTask;
import android.os.Bundle;
import android.util.Log;
import android.util.SparseIntArray;
import android.view.KeyEvent;
import android.view.SurfaceView;
import net.panuska.tlappy.awt.BufferedImage;
import net.panuska.tlappy.awt.Color;
import net.panuska.tlappy.mobile.R;
import static net.panuska.tlappy.Device.vram;
import static net.panuska.tlappy.FullscreenActivity.DOWN;
import static net.panuska.tlappy.FullscreenActivity.LEFT;
import static net.panuska.tlappy.FullscreenActivity.RIGHT;
import static net.panuska.tlappy.FullscreenActivity.SPACE_BAR;
import static net.panuska.tlappy.FullscreenActivity.UP;
package net.panuska.tlappy;
/**
* Flappy:
* Original game created by dB-SOFT in 1984 for SHARP MZ-800 computer.
* Java version by Petr Slechta, 2014.
* Android version by Petr Panuska, 2017.
*/
public class CustomControlsActivity extends TlappyActivity {
private static final String TAG = CustomControlsActivity.class.getSimpleName();
private SparseIntArray tempKeyboardMap; // used for custom key recording
static final SparseIntArray keyboardMap = new SparseIntArray();
private AsyncTask<Void, Void, Void> game;
volatile int state;
volatile int index;
volatile int maxIndex;
volatile String message, systemMessage;
| private static final int[] STATES = {LEFT, RIGHT, UP, DOWN, SPACE_BAR, -1}; |
pe-pan/flappy | mobile/src/main/java/net/panuska/tlappy/CustomControlsActivity.java | // Path: core/src/main/java/net/panuska/tlappy/awt/BufferedImage.java
// public class BufferedImage {
// private Bitmap b;
// private Graphics g;
// public static final int TYPE_INT_RGB = Bitmap.Config.ARGB_8888.ordinal();
//
// public BufferedImage(BitmapDrawable d) {
// Bitmap immb = d.getBitmap();
// b = immb.copy(Bitmap.Config.ARGB_8888, false);
// }
//
// public BufferedImage(int width,
// int height,
// int imageType) {
// b = Bitmap.createBitmap(width, height, Bitmap.Config.ARGB_8888);
// g = new Graphics(b);
// }
//
// private BufferedImage(Bitmap b) {
// this.b = b;
// }
//
// public Graphics getGraphics() {
// return g;
// }
//
// public Bitmap getBitmap() {
// return b;
// }
//
// public BufferedImage getSubimage (int x, int y, int w, int h) {
// Bitmap b = Bitmap.createBitmap(this.b, x, y, w, h);
// return new BufferedImage(b);
// }
//
// /**
// * Returns a copy of this image rotated by 90 degrees.
// * @return
// */
// public BufferedImage getRotatedImage() {
// Matrix matrix = new Matrix();
// matrix.postRotate(90);
// Bitmap b = Bitmap.createBitmap(this.getBitmap(), 0, 0, this.getWidth(), this.getHeight(), matrix, false);
// return new BufferedImage(b);
// }
//
// /**
// * Returns a copy of this image mirrored by vertical axis
// * @return
// */
// public BufferedImage getMirroredImage() {
// Matrix matrix = new Matrix();
// matrix.preScale(-1, 1);
// Bitmap b = Bitmap.createBitmap(this.getBitmap(), 0, 0, this.getWidth(), this.getHeight(), matrix, false);
// return new BufferedImage(b);
// }
//
// /**
// * Returns 16x16 subimage starting at x, y
// * @param x
// * @param y
// * @return
// */
// public BufferedImage getSubimage (int x, int y) {
// return getSubimage(x, y, 16, 16);
// }
//
// public int getWidth() {
// return b.getWidth();
// }
//
// public int getHeight() {
// return b.getHeight();
// }
// }
//
// Path: core/src/main/java/net/panuska/tlappy/awt/Color.java
// public enum Color {
// BLACK(0xff000000),
// RED(0xffff0000),
// BLUE(0xff0000ff),
// YELLOW(0xffffff00),
// WHITE(0xffffffff),
// DARK_GRAY(0xff404040),
// LIGHT_GRAY(0xffc0c0c0),
// TRANSPARENT(0x00000000),
//
// black(0xff000000),
// red(0xffff0000),
// blue(0xff0000ff),
// yellow(0xffffff00),
// white(0xffffffff),
// dark_gray(0xff404040);
//
// private final int color;
// Color(int color) { this.color = color; }
// public int getValue() { return color; }
// }
//
// Path: core/src/main/java/net/panuska/tlappy/Device.java
// public static VRAM vram;
//
// Path: mobile/src/main/java/net/panuska/tlappy/FullscreenActivity.java
// static final int DOWN = 40;
//
// Path: mobile/src/main/java/net/panuska/tlappy/FullscreenActivity.java
// static final int LEFT = 37;
//
// Path: mobile/src/main/java/net/panuska/tlappy/FullscreenActivity.java
// static final int RIGHT = 39;
//
// Path: mobile/src/main/java/net/panuska/tlappy/FullscreenActivity.java
// static final int SPACE_BAR = 32;
//
// Path: mobile/src/main/java/net/panuska/tlappy/FullscreenActivity.java
// static final int UP = 38;
| import android.os.AsyncTask;
import android.os.Bundle;
import android.util.Log;
import android.util.SparseIntArray;
import android.view.KeyEvent;
import android.view.SurfaceView;
import net.panuska.tlappy.awt.BufferedImage;
import net.panuska.tlappy.awt.Color;
import net.panuska.tlappy.mobile.R;
import static net.panuska.tlappy.Device.vram;
import static net.panuska.tlappy.FullscreenActivity.DOWN;
import static net.panuska.tlappy.FullscreenActivity.LEFT;
import static net.panuska.tlappy.FullscreenActivity.RIGHT;
import static net.panuska.tlappy.FullscreenActivity.SPACE_BAR;
import static net.panuska.tlappy.FullscreenActivity.UP; | package net.panuska.tlappy;
/**
* Flappy:
* Original game created by dB-SOFT in 1984 for SHARP MZ-800 computer.
* Java version by Petr Slechta, 2014.
* Android version by Petr Panuska, 2017.
*/
public class CustomControlsActivity extends TlappyActivity {
private static final String TAG = CustomControlsActivity.class.getSimpleName();
private SparseIntArray tempKeyboardMap; // used for custom key recording
static final SparseIntArray keyboardMap = new SparseIntArray();
private AsyncTask<Void, Void, Void> game;
volatile int state;
volatile int index;
volatile int maxIndex;
volatile String message, systemMessage;
| // Path: core/src/main/java/net/panuska/tlappy/awt/BufferedImage.java
// public class BufferedImage {
// private Bitmap b;
// private Graphics g;
// public static final int TYPE_INT_RGB = Bitmap.Config.ARGB_8888.ordinal();
//
// public BufferedImage(BitmapDrawable d) {
// Bitmap immb = d.getBitmap();
// b = immb.copy(Bitmap.Config.ARGB_8888, false);
// }
//
// public BufferedImage(int width,
// int height,
// int imageType) {
// b = Bitmap.createBitmap(width, height, Bitmap.Config.ARGB_8888);
// g = new Graphics(b);
// }
//
// private BufferedImage(Bitmap b) {
// this.b = b;
// }
//
// public Graphics getGraphics() {
// return g;
// }
//
// public Bitmap getBitmap() {
// return b;
// }
//
// public BufferedImage getSubimage (int x, int y, int w, int h) {
// Bitmap b = Bitmap.createBitmap(this.b, x, y, w, h);
// return new BufferedImage(b);
// }
//
// /**
// * Returns a copy of this image rotated by 90 degrees.
// * @return
// */
// public BufferedImage getRotatedImage() {
// Matrix matrix = new Matrix();
// matrix.postRotate(90);
// Bitmap b = Bitmap.createBitmap(this.getBitmap(), 0, 0, this.getWidth(), this.getHeight(), matrix, false);
// return new BufferedImage(b);
// }
//
// /**
// * Returns a copy of this image mirrored by vertical axis
// * @return
// */
// public BufferedImage getMirroredImage() {
// Matrix matrix = new Matrix();
// matrix.preScale(-1, 1);
// Bitmap b = Bitmap.createBitmap(this.getBitmap(), 0, 0, this.getWidth(), this.getHeight(), matrix, false);
// return new BufferedImage(b);
// }
//
// /**
// * Returns 16x16 subimage starting at x, y
// * @param x
// * @param y
// * @return
// */
// public BufferedImage getSubimage (int x, int y) {
// return getSubimage(x, y, 16, 16);
// }
//
// public int getWidth() {
// return b.getWidth();
// }
//
// public int getHeight() {
// return b.getHeight();
// }
// }
//
// Path: core/src/main/java/net/panuska/tlappy/awt/Color.java
// public enum Color {
// BLACK(0xff000000),
// RED(0xffff0000),
// BLUE(0xff0000ff),
// YELLOW(0xffffff00),
// WHITE(0xffffffff),
// DARK_GRAY(0xff404040),
// LIGHT_GRAY(0xffc0c0c0),
// TRANSPARENT(0x00000000),
//
// black(0xff000000),
// red(0xffff0000),
// blue(0xff0000ff),
// yellow(0xffffff00),
// white(0xffffffff),
// dark_gray(0xff404040);
//
// private final int color;
// Color(int color) { this.color = color; }
// public int getValue() { return color; }
// }
//
// Path: core/src/main/java/net/panuska/tlappy/Device.java
// public static VRAM vram;
//
// Path: mobile/src/main/java/net/panuska/tlappy/FullscreenActivity.java
// static final int DOWN = 40;
//
// Path: mobile/src/main/java/net/panuska/tlappy/FullscreenActivity.java
// static final int LEFT = 37;
//
// Path: mobile/src/main/java/net/panuska/tlappy/FullscreenActivity.java
// static final int RIGHT = 39;
//
// Path: mobile/src/main/java/net/panuska/tlappy/FullscreenActivity.java
// static final int SPACE_BAR = 32;
//
// Path: mobile/src/main/java/net/panuska/tlappy/FullscreenActivity.java
// static final int UP = 38;
// Path: mobile/src/main/java/net/panuska/tlappy/CustomControlsActivity.java
import android.os.AsyncTask;
import android.os.Bundle;
import android.util.Log;
import android.util.SparseIntArray;
import android.view.KeyEvent;
import android.view.SurfaceView;
import net.panuska.tlappy.awt.BufferedImage;
import net.panuska.tlappy.awt.Color;
import net.panuska.tlappy.mobile.R;
import static net.panuska.tlappy.Device.vram;
import static net.panuska.tlappy.FullscreenActivity.DOWN;
import static net.panuska.tlappy.FullscreenActivity.LEFT;
import static net.panuska.tlappy.FullscreenActivity.RIGHT;
import static net.panuska.tlappy.FullscreenActivity.SPACE_BAR;
import static net.panuska.tlappy.FullscreenActivity.UP;
package net.panuska.tlappy;
/**
* Flappy:
* Original game created by dB-SOFT in 1984 for SHARP MZ-800 computer.
* Java version by Petr Slechta, 2014.
* Android version by Petr Panuska, 2017.
*/
public class CustomControlsActivity extends TlappyActivity {
private static final String TAG = CustomControlsActivity.class.getSimpleName();
private SparseIntArray tempKeyboardMap; // used for custom key recording
static final SparseIntArray keyboardMap = new SparseIntArray();
private AsyncTask<Void, Void, Void> game;
volatile int state;
volatile int index;
volatile int maxIndex;
volatile String message, systemMessage;
| private static final int[] STATES = {LEFT, RIGHT, UP, DOWN, SPACE_BAR, -1}; |
pe-pan/flappy | mobile/src/main/java/net/panuska/tlappy/CustomControlsActivity.java | // Path: core/src/main/java/net/panuska/tlappy/awt/BufferedImage.java
// public class BufferedImage {
// private Bitmap b;
// private Graphics g;
// public static final int TYPE_INT_RGB = Bitmap.Config.ARGB_8888.ordinal();
//
// public BufferedImage(BitmapDrawable d) {
// Bitmap immb = d.getBitmap();
// b = immb.copy(Bitmap.Config.ARGB_8888, false);
// }
//
// public BufferedImage(int width,
// int height,
// int imageType) {
// b = Bitmap.createBitmap(width, height, Bitmap.Config.ARGB_8888);
// g = new Graphics(b);
// }
//
// private BufferedImage(Bitmap b) {
// this.b = b;
// }
//
// public Graphics getGraphics() {
// return g;
// }
//
// public Bitmap getBitmap() {
// return b;
// }
//
// public BufferedImage getSubimage (int x, int y, int w, int h) {
// Bitmap b = Bitmap.createBitmap(this.b, x, y, w, h);
// return new BufferedImage(b);
// }
//
// /**
// * Returns a copy of this image rotated by 90 degrees.
// * @return
// */
// public BufferedImage getRotatedImage() {
// Matrix matrix = new Matrix();
// matrix.postRotate(90);
// Bitmap b = Bitmap.createBitmap(this.getBitmap(), 0, 0, this.getWidth(), this.getHeight(), matrix, false);
// return new BufferedImage(b);
// }
//
// /**
// * Returns a copy of this image mirrored by vertical axis
// * @return
// */
// public BufferedImage getMirroredImage() {
// Matrix matrix = new Matrix();
// matrix.preScale(-1, 1);
// Bitmap b = Bitmap.createBitmap(this.getBitmap(), 0, 0, this.getWidth(), this.getHeight(), matrix, false);
// return new BufferedImage(b);
// }
//
// /**
// * Returns 16x16 subimage starting at x, y
// * @param x
// * @param y
// * @return
// */
// public BufferedImage getSubimage (int x, int y) {
// return getSubimage(x, y, 16, 16);
// }
//
// public int getWidth() {
// return b.getWidth();
// }
//
// public int getHeight() {
// return b.getHeight();
// }
// }
//
// Path: core/src/main/java/net/panuska/tlappy/awt/Color.java
// public enum Color {
// BLACK(0xff000000),
// RED(0xffff0000),
// BLUE(0xff0000ff),
// YELLOW(0xffffff00),
// WHITE(0xffffffff),
// DARK_GRAY(0xff404040),
// LIGHT_GRAY(0xffc0c0c0),
// TRANSPARENT(0x00000000),
//
// black(0xff000000),
// red(0xffff0000),
// blue(0xff0000ff),
// yellow(0xffffff00),
// white(0xffffffff),
// dark_gray(0xff404040);
//
// private final int color;
// Color(int color) { this.color = color; }
// public int getValue() { return color; }
// }
//
// Path: core/src/main/java/net/panuska/tlappy/Device.java
// public static VRAM vram;
//
// Path: mobile/src/main/java/net/panuska/tlappy/FullscreenActivity.java
// static final int DOWN = 40;
//
// Path: mobile/src/main/java/net/panuska/tlappy/FullscreenActivity.java
// static final int LEFT = 37;
//
// Path: mobile/src/main/java/net/panuska/tlappy/FullscreenActivity.java
// static final int RIGHT = 39;
//
// Path: mobile/src/main/java/net/panuska/tlappy/FullscreenActivity.java
// static final int SPACE_BAR = 32;
//
// Path: mobile/src/main/java/net/panuska/tlappy/FullscreenActivity.java
// static final int UP = 38;
| import android.os.AsyncTask;
import android.os.Bundle;
import android.util.Log;
import android.util.SparseIntArray;
import android.view.KeyEvent;
import android.view.SurfaceView;
import net.panuska.tlappy.awt.BufferedImage;
import net.panuska.tlappy.awt.Color;
import net.panuska.tlappy.mobile.R;
import static net.panuska.tlappy.Device.vram;
import static net.panuska.tlappy.FullscreenActivity.DOWN;
import static net.panuska.tlappy.FullscreenActivity.LEFT;
import static net.panuska.tlappy.FullscreenActivity.RIGHT;
import static net.panuska.tlappy.FullscreenActivity.SPACE_BAR;
import static net.panuska.tlappy.FullscreenActivity.UP; | package net.panuska.tlappy;
/**
* Flappy:
* Original game created by dB-SOFT in 1984 for SHARP MZ-800 computer.
* Java version by Petr Slechta, 2014.
* Android version by Petr Panuska, 2017.
*/
public class CustomControlsActivity extends TlappyActivity {
private static final String TAG = CustomControlsActivity.class.getSimpleName();
private SparseIntArray tempKeyboardMap; // used for custom key recording
static final SparseIntArray keyboardMap = new SparseIntArray();
private AsyncTask<Void, Void, Void> game;
volatile int state;
volatile int index;
volatile int maxIndex;
volatile String message, systemMessage;
| // Path: core/src/main/java/net/panuska/tlappy/awt/BufferedImage.java
// public class BufferedImage {
// private Bitmap b;
// private Graphics g;
// public static final int TYPE_INT_RGB = Bitmap.Config.ARGB_8888.ordinal();
//
// public BufferedImage(BitmapDrawable d) {
// Bitmap immb = d.getBitmap();
// b = immb.copy(Bitmap.Config.ARGB_8888, false);
// }
//
// public BufferedImage(int width,
// int height,
// int imageType) {
// b = Bitmap.createBitmap(width, height, Bitmap.Config.ARGB_8888);
// g = new Graphics(b);
// }
//
// private BufferedImage(Bitmap b) {
// this.b = b;
// }
//
// public Graphics getGraphics() {
// return g;
// }
//
// public Bitmap getBitmap() {
// return b;
// }
//
// public BufferedImage getSubimage (int x, int y, int w, int h) {
// Bitmap b = Bitmap.createBitmap(this.b, x, y, w, h);
// return new BufferedImage(b);
// }
//
// /**
// * Returns a copy of this image rotated by 90 degrees.
// * @return
// */
// public BufferedImage getRotatedImage() {
// Matrix matrix = new Matrix();
// matrix.postRotate(90);
// Bitmap b = Bitmap.createBitmap(this.getBitmap(), 0, 0, this.getWidth(), this.getHeight(), matrix, false);
// return new BufferedImage(b);
// }
//
// /**
// * Returns a copy of this image mirrored by vertical axis
// * @return
// */
// public BufferedImage getMirroredImage() {
// Matrix matrix = new Matrix();
// matrix.preScale(-1, 1);
// Bitmap b = Bitmap.createBitmap(this.getBitmap(), 0, 0, this.getWidth(), this.getHeight(), matrix, false);
// return new BufferedImage(b);
// }
//
// /**
// * Returns 16x16 subimage starting at x, y
// * @param x
// * @param y
// * @return
// */
// public BufferedImage getSubimage (int x, int y) {
// return getSubimage(x, y, 16, 16);
// }
//
// public int getWidth() {
// return b.getWidth();
// }
//
// public int getHeight() {
// return b.getHeight();
// }
// }
//
// Path: core/src/main/java/net/panuska/tlappy/awt/Color.java
// public enum Color {
// BLACK(0xff000000),
// RED(0xffff0000),
// BLUE(0xff0000ff),
// YELLOW(0xffffff00),
// WHITE(0xffffffff),
// DARK_GRAY(0xff404040),
// LIGHT_GRAY(0xffc0c0c0),
// TRANSPARENT(0x00000000),
//
// black(0xff000000),
// red(0xffff0000),
// blue(0xff0000ff),
// yellow(0xffffff00),
// white(0xffffffff),
// dark_gray(0xff404040);
//
// private final int color;
// Color(int color) { this.color = color; }
// public int getValue() { return color; }
// }
//
// Path: core/src/main/java/net/panuska/tlappy/Device.java
// public static VRAM vram;
//
// Path: mobile/src/main/java/net/panuska/tlappy/FullscreenActivity.java
// static final int DOWN = 40;
//
// Path: mobile/src/main/java/net/panuska/tlappy/FullscreenActivity.java
// static final int LEFT = 37;
//
// Path: mobile/src/main/java/net/panuska/tlappy/FullscreenActivity.java
// static final int RIGHT = 39;
//
// Path: mobile/src/main/java/net/panuska/tlappy/FullscreenActivity.java
// static final int SPACE_BAR = 32;
//
// Path: mobile/src/main/java/net/panuska/tlappy/FullscreenActivity.java
// static final int UP = 38;
// Path: mobile/src/main/java/net/panuska/tlappy/CustomControlsActivity.java
import android.os.AsyncTask;
import android.os.Bundle;
import android.util.Log;
import android.util.SparseIntArray;
import android.view.KeyEvent;
import android.view.SurfaceView;
import net.panuska.tlappy.awt.BufferedImage;
import net.panuska.tlappy.awt.Color;
import net.panuska.tlappy.mobile.R;
import static net.panuska.tlappy.Device.vram;
import static net.panuska.tlappy.FullscreenActivity.DOWN;
import static net.panuska.tlappy.FullscreenActivity.LEFT;
import static net.panuska.tlappy.FullscreenActivity.RIGHT;
import static net.panuska.tlappy.FullscreenActivity.SPACE_BAR;
import static net.panuska.tlappy.FullscreenActivity.UP;
package net.panuska.tlappy;
/**
* Flappy:
* Original game created by dB-SOFT in 1984 for SHARP MZ-800 computer.
* Java version by Petr Slechta, 2014.
* Android version by Petr Panuska, 2017.
*/
public class CustomControlsActivity extends TlappyActivity {
private static final String TAG = CustomControlsActivity.class.getSimpleName();
private SparseIntArray tempKeyboardMap; // used for custom key recording
static final SparseIntArray keyboardMap = new SparseIntArray();
private AsyncTask<Void, Void, Void> game;
volatile int state;
volatile int index;
volatile int maxIndex;
volatile String message, systemMessage;
| private static final int[] STATES = {LEFT, RIGHT, UP, DOWN, SPACE_BAR, -1}; |
pe-pan/flappy | mobile/src/main/java/net/panuska/tlappy/CustomControlsActivity.java | // Path: core/src/main/java/net/panuska/tlappy/awt/BufferedImage.java
// public class BufferedImage {
// private Bitmap b;
// private Graphics g;
// public static final int TYPE_INT_RGB = Bitmap.Config.ARGB_8888.ordinal();
//
// public BufferedImage(BitmapDrawable d) {
// Bitmap immb = d.getBitmap();
// b = immb.copy(Bitmap.Config.ARGB_8888, false);
// }
//
// public BufferedImage(int width,
// int height,
// int imageType) {
// b = Bitmap.createBitmap(width, height, Bitmap.Config.ARGB_8888);
// g = new Graphics(b);
// }
//
// private BufferedImage(Bitmap b) {
// this.b = b;
// }
//
// public Graphics getGraphics() {
// return g;
// }
//
// public Bitmap getBitmap() {
// return b;
// }
//
// public BufferedImage getSubimage (int x, int y, int w, int h) {
// Bitmap b = Bitmap.createBitmap(this.b, x, y, w, h);
// return new BufferedImage(b);
// }
//
// /**
// * Returns a copy of this image rotated by 90 degrees.
// * @return
// */
// public BufferedImage getRotatedImage() {
// Matrix matrix = new Matrix();
// matrix.postRotate(90);
// Bitmap b = Bitmap.createBitmap(this.getBitmap(), 0, 0, this.getWidth(), this.getHeight(), matrix, false);
// return new BufferedImage(b);
// }
//
// /**
// * Returns a copy of this image mirrored by vertical axis
// * @return
// */
// public BufferedImage getMirroredImage() {
// Matrix matrix = new Matrix();
// matrix.preScale(-1, 1);
// Bitmap b = Bitmap.createBitmap(this.getBitmap(), 0, 0, this.getWidth(), this.getHeight(), matrix, false);
// return new BufferedImage(b);
// }
//
// /**
// * Returns 16x16 subimage starting at x, y
// * @param x
// * @param y
// * @return
// */
// public BufferedImage getSubimage (int x, int y) {
// return getSubimage(x, y, 16, 16);
// }
//
// public int getWidth() {
// return b.getWidth();
// }
//
// public int getHeight() {
// return b.getHeight();
// }
// }
//
// Path: core/src/main/java/net/panuska/tlappy/awt/Color.java
// public enum Color {
// BLACK(0xff000000),
// RED(0xffff0000),
// BLUE(0xff0000ff),
// YELLOW(0xffffff00),
// WHITE(0xffffffff),
// DARK_GRAY(0xff404040),
// LIGHT_GRAY(0xffc0c0c0),
// TRANSPARENT(0x00000000),
//
// black(0xff000000),
// red(0xffff0000),
// blue(0xff0000ff),
// yellow(0xffffff00),
// white(0xffffffff),
// dark_gray(0xff404040);
//
// private final int color;
// Color(int color) { this.color = color; }
// public int getValue() { return color; }
// }
//
// Path: core/src/main/java/net/panuska/tlappy/Device.java
// public static VRAM vram;
//
// Path: mobile/src/main/java/net/panuska/tlappy/FullscreenActivity.java
// static final int DOWN = 40;
//
// Path: mobile/src/main/java/net/panuska/tlappy/FullscreenActivity.java
// static final int LEFT = 37;
//
// Path: mobile/src/main/java/net/panuska/tlappy/FullscreenActivity.java
// static final int RIGHT = 39;
//
// Path: mobile/src/main/java/net/panuska/tlappy/FullscreenActivity.java
// static final int SPACE_BAR = 32;
//
// Path: mobile/src/main/java/net/panuska/tlappy/FullscreenActivity.java
// static final int UP = 38;
| import android.os.AsyncTask;
import android.os.Bundle;
import android.util.Log;
import android.util.SparseIntArray;
import android.view.KeyEvent;
import android.view.SurfaceView;
import net.panuska.tlappy.awt.BufferedImage;
import net.panuska.tlappy.awt.Color;
import net.panuska.tlappy.mobile.R;
import static net.panuska.tlappy.Device.vram;
import static net.panuska.tlappy.FullscreenActivity.DOWN;
import static net.panuska.tlappy.FullscreenActivity.LEFT;
import static net.panuska.tlappy.FullscreenActivity.RIGHT;
import static net.panuska.tlappy.FullscreenActivity.SPACE_BAR;
import static net.panuska.tlappy.FullscreenActivity.UP; | package net.panuska.tlappy;
/**
* Flappy:
* Original game created by dB-SOFT in 1984 for SHARP MZ-800 computer.
* Java version by Petr Slechta, 2014.
* Android version by Petr Panuska, 2017.
*/
public class CustomControlsActivity extends TlappyActivity {
private static final String TAG = CustomControlsActivity.class.getSimpleName();
private SparseIntArray tempKeyboardMap; // used for custom key recording
static final SparseIntArray keyboardMap = new SparseIntArray();
private AsyncTask<Void, Void, Void> game;
volatile int state;
volatile int index;
volatile int maxIndex;
volatile String message, systemMessage;
private static final int[] STATES = {LEFT, RIGHT, UP, DOWN, SPACE_BAR, -1}; | // Path: core/src/main/java/net/panuska/tlappy/awt/BufferedImage.java
// public class BufferedImage {
// private Bitmap b;
// private Graphics g;
// public static final int TYPE_INT_RGB = Bitmap.Config.ARGB_8888.ordinal();
//
// public BufferedImage(BitmapDrawable d) {
// Bitmap immb = d.getBitmap();
// b = immb.copy(Bitmap.Config.ARGB_8888, false);
// }
//
// public BufferedImage(int width,
// int height,
// int imageType) {
// b = Bitmap.createBitmap(width, height, Bitmap.Config.ARGB_8888);
// g = new Graphics(b);
// }
//
// private BufferedImage(Bitmap b) {
// this.b = b;
// }
//
// public Graphics getGraphics() {
// return g;
// }
//
// public Bitmap getBitmap() {
// return b;
// }
//
// public BufferedImage getSubimage (int x, int y, int w, int h) {
// Bitmap b = Bitmap.createBitmap(this.b, x, y, w, h);
// return new BufferedImage(b);
// }
//
// /**
// * Returns a copy of this image rotated by 90 degrees.
// * @return
// */
// public BufferedImage getRotatedImage() {
// Matrix matrix = new Matrix();
// matrix.postRotate(90);
// Bitmap b = Bitmap.createBitmap(this.getBitmap(), 0, 0, this.getWidth(), this.getHeight(), matrix, false);
// return new BufferedImage(b);
// }
//
// /**
// * Returns a copy of this image mirrored by vertical axis
// * @return
// */
// public BufferedImage getMirroredImage() {
// Matrix matrix = new Matrix();
// matrix.preScale(-1, 1);
// Bitmap b = Bitmap.createBitmap(this.getBitmap(), 0, 0, this.getWidth(), this.getHeight(), matrix, false);
// return new BufferedImage(b);
// }
//
// /**
// * Returns 16x16 subimage starting at x, y
// * @param x
// * @param y
// * @return
// */
// public BufferedImage getSubimage (int x, int y) {
// return getSubimage(x, y, 16, 16);
// }
//
// public int getWidth() {
// return b.getWidth();
// }
//
// public int getHeight() {
// return b.getHeight();
// }
// }
//
// Path: core/src/main/java/net/panuska/tlappy/awt/Color.java
// public enum Color {
// BLACK(0xff000000),
// RED(0xffff0000),
// BLUE(0xff0000ff),
// YELLOW(0xffffff00),
// WHITE(0xffffffff),
// DARK_GRAY(0xff404040),
// LIGHT_GRAY(0xffc0c0c0),
// TRANSPARENT(0x00000000),
//
// black(0xff000000),
// red(0xffff0000),
// blue(0xff0000ff),
// yellow(0xffffff00),
// white(0xffffffff),
// dark_gray(0xff404040);
//
// private final int color;
// Color(int color) { this.color = color; }
// public int getValue() { return color; }
// }
//
// Path: core/src/main/java/net/panuska/tlappy/Device.java
// public static VRAM vram;
//
// Path: mobile/src/main/java/net/panuska/tlappy/FullscreenActivity.java
// static final int DOWN = 40;
//
// Path: mobile/src/main/java/net/panuska/tlappy/FullscreenActivity.java
// static final int LEFT = 37;
//
// Path: mobile/src/main/java/net/panuska/tlappy/FullscreenActivity.java
// static final int RIGHT = 39;
//
// Path: mobile/src/main/java/net/panuska/tlappy/FullscreenActivity.java
// static final int SPACE_BAR = 32;
//
// Path: mobile/src/main/java/net/panuska/tlappy/FullscreenActivity.java
// static final int UP = 38;
// Path: mobile/src/main/java/net/panuska/tlappy/CustomControlsActivity.java
import android.os.AsyncTask;
import android.os.Bundle;
import android.util.Log;
import android.util.SparseIntArray;
import android.view.KeyEvent;
import android.view.SurfaceView;
import net.panuska.tlappy.awt.BufferedImage;
import net.panuska.tlappy.awt.Color;
import net.panuska.tlappy.mobile.R;
import static net.panuska.tlappy.Device.vram;
import static net.panuska.tlappy.FullscreenActivity.DOWN;
import static net.panuska.tlappy.FullscreenActivity.LEFT;
import static net.panuska.tlappy.FullscreenActivity.RIGHT;
import static net.panuska.tlappy.FullscreenActivity.SPACE_BAR;
import static net.panuska.tlappy.FullscreenActivity.UP;
package net.panuska.tlappy;
/**
* Flappy:
* Original game created by dB-SOFT in 1984 for SHARP MZ-800 computer.
* Java version by Petr Slechta, 2014.
* Android version by Petr Panuska, 2017.
*/
public class CustomControlsActivity extends TlappyActivity {
private static final String TAG = CustomControlsActivity.class.getSimpleName();
private SparseIntArray tempKeyboardMap; // used for custom key recording
static final SparseIntArray keyboardMap = new SparseIntArray();
private AsyncTask<Void, Void, Void> game;
volatile int state;
volatile int index;
volatile int maxIndex;
volatile String message, systemMessage;
private static final int[] STATES = {LEFT, RIGHT, UP, DOWN, SPACE_BAR, -1}; | private static final BufferedImage[][] animation = { |
pe-pan/flappy | mobile/src/main/java/net/panuska/tlappy/CustomControlsActivity.java | // Path: core/src/main/java/net/panuska/tlappy/awt/BufferedImage.java
// public class BufferedImage {
// private Bitmap b;
// private Graphics g;
// public static final int TYPE_INT_RGB = Bitmap.Config.ARGB_8888.ordinal();
//
// public BufferedImage(BitmapDrawable d) {
// Bitmap immb = d.getBitmap();
// b = immb.copy(Bitmap.Config.ARGB_8888, false);
// }
//
// public BufferedImage(int width,
// int height,
// int imageType) {
// b = Bitmap.createBitmap(width, height, Bitmap.Config.ARGB_8888);
// g = new Graphics(b);
// }
//
// private BufferedImage(Bitmap b) {
// this.b = b;
// }
//
// public Graphics getGraphics() {
// return g;
// }
//
// public Bitmap getBitmap() {
// return b;
// }
//
// public BufferedImage getSubimage (int x, int y, int w, int h) {
// Bitmap b = Bitmap.createBitmap(this.b, x, y, w, h);
// return new BufferedImage(b);
// }
//
// /**
// * Returns a copy of this image rotated by 90 degrees.
// * @return
// */
// public BufferedImage getRotatedImage() {
// Matrix matrix = new Matrix();
// matrix.postRotate(90);
// Bitmap b = Bitmap.createBitmap(this.getBitmap(), 0, 0, this.getWidth(), this.getHeight(), matrix, false);
// return new BufferedImage(b);
// }
//
// /**
// * Returns a copy of this image mirrored by vertical axis
// * @return
// */
// public BufferedImage getMirroredImage() {
// Matrix matrix = new Matrix();
// matrix.preScale(-1, 1);
// Bitmap b = Bitmap.createBitmap(this.getBitmap(), 0, 0, this.getWidth(), this.getHeight(), matrix, false);
// return new BufferedImage(b);
// }
//
// /**
// * Returns 16x16 subimage starting at x, y
// * @param x
// * @param y
// * @return
// */
// public BufferedImage getSubimage (int x, int y) {
// return getSubimage(x, y, 16, 16);
// }
//
// public int getWidth() {
// return b.getWidth();
// }
//
// public int getHeight() {
// return b.getHeight();
// }
// }
//
// Path: core/src/main/java/net/panuska/tlappy/awt/Color.java
// public enum Color {
// BLACK(0xff000000),
// RED(0xffff0000),
// BLUE(0xff0000ff),
// YELLOW(0xffffff00),
// WHITE(0xffffffff),
// DARK_GRAY(0xff404040),
// LIGHT_GRAY(0xffc0c0c0),
// TRANSPARENT(0x00000000),
//
// black(0xff000000),
// red(0xffff0000),
// blue(0xff0000ff),
// yellow(0xffffff00),
// white(0xffffffff),
// dark_gray(0xff404040);
//
// private final int color;
// Color(int color) { this.color = color; }
// public int getValue() { return color; }
// }
//
// Path: core/src/main/java/net/panuska/tlappy/Device.java
// public static VRAM vram;
//
// Path: mobile/src/main/java/net/panuska/tlappy/FullscreenActivity.java
// static final int DOWN = 40;
//
// Path: mobile/src/main/java/net/panuska/tlappy/FullscreenActivity.java
// static final int LEFT = 37;
//
// Path: mobile/src/main/java/net/panuska/tlappy/FullscreenActivity.java
// static final int RIGHT = 39;
//
// Path: mobile/src/main/java/net/panuska/tlappy/FullscreenActivity.java
// static final int SPACE_BAR = 32;
//
// Path: mobile/src/main/java/net/panuska/tlappy/FullscreenActivity.java
// static final int UP = 38;
| import android.os.AsyncTask;
import android.os.Bundle;
import android.util.Log;
import android.util.SparseIntArray;
import android.view.KeyEvent;
import android.view.SurfaceView;
import net.panuska.tlappy.awt.BufferedImage;
import net.panuska.tlappy.awt.Color;
import net.panuska.tlappy.mobile.R;
import static net.panuska.tlappy.Device.vram;
import static net.panuska.tlappy.FullscreenActivity.DOWN;
import static net.panuska.tlappy.FullscreenActivity.LEFT;
import static net.panuska.tlappy.FullscreenActivity.RIGHT;
import static net.panuska.tlappy.FullscreenActivity.SPACE_BAR;
import static net.panuska.tlappy.FullscreenActivity.UP; | {Images.chickenLeft, Images.chickenLeft1},
{Images.chickenRight, Images.chickenRight1},
{Images.chickenUp, Images.chickenUp1, Images.chickenUp, Images.chickenUp2},
{Images.chickenDown, Images.chickenDown1, Images.chickenDown, Images.chickenDown2},
{Images.chickenDownFire1, Images.chickenDownFire2, Images.chickenDownFire1, Images.chickenDownFire2, Images.chickenDown, Images.chickenDown},
{Images.chickenJump1, Images.chickenJump2, Images.chickenDown, Images.chickenDown, Images.chickenDown, Images.chickenDown}
};
private static final int[] MESSAGES = {
R.string.move_left,
R.string.move_right,
R.string.move_up,
R.string.move_down,
R.string.throw_mushroom,
R.string.controls_saved};
volatile BufferedImage[] selectedAnimation;
@Override
protected void onCreate(Bundle savedInstanceState) {
Log.d(TAG, "onCreate");
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_customcontrols);
view = (SurfaceView) findViewById(R.id.customControlsContent);
}
@Override
protected void onResume() {
super.onResume();
Main.getInstance(view); //todo hack | // Path: core/src/main/java/net/panuska/tlappy/awt/BufferedImage.java
// public class BufferedImage {
// private Bitmap b;
// private Graphics g;
// public static final int TYPE_INT_RGB = Bitmap.Config.ARGB_8888.ordinal();
//
// public BufferedImage(BitmapDrawable d) {
// Bitmap immb = d.getBitmap();
// b = immb.copy(Bitmap.Config.ARGB_8888, false);
// }
//
// public BufferedImage(int width,
// int height,
// int imageType) {
// b = Bitmap.createBitmap(width, height, Bitmap.Config.ARGB_8888);
// g = new Graphics(b);
// }
//
// private BufferedImage(Bitmap b) {
// this.b = b;
// }
//
// public Graphics getGraphics() {
// return g;
// }
//
// public Bitmap getBitmap() {
// return b;
// }
//
// public BufferedImage getSubimage (int x, int y, int w, int h) {
// Bitmap b = Bitmap.createBitmap(this.b, x, y, w, h);
// return new BufferedImage(b);
// }
//
// /**
// * Returns a copy of this image rotated by 90 degrees.
// * @return
// */
// public BufferedImage getRotatedImage() {
// Matrix matrix = new Matrix();
// matrix.postRotate(90);
// Bitmap b = Bitmap.createBitmap(this.getBitmap(), 0, 0, this.getWidth(), this.getHeight(), matrix, false);
// return new BufferedImage(b);
// }
//
// /**
// * Returns a copy of this image mirrored by vertical axis
// * @return
// */
// public BufferedImage getMirroredImage() {
// Matrix matrix = new Matrix();
// matrix.preScale(-1, 1);
// Bitmap b = Bitmap.createBitmap(this.getBitmap(), 0, 0, this.getWidth(), this.getHeight(), matrix, false);
// return new BufferedImage(b);
// }
//
// /**
// * Returns 16x16 subimage starting at x, y
// * @param x
// * @param y
// * @return
// */
// public BufferedImage getSubimage (int x, int y) {
// return getSubimage(x, y, 16, 16);
// }
//
// public int getWidth() {
// return b.getWidth();
// }
//
// public int getHeight() {
// return b.getHeight();
// }
// }
//
// Path: core/src/main/java/net/panuska/tlappy/awt/Color.java
// public enum Color {
// BLACK(0xff000000),
// RED(0xffff0000),
// BLUE(0xff0000ff),
// YELLOW(0xffffff00),
// WHITE(0xffffffff),
// DARK_GRAY(0xff404040),
// LIGHT_GRAY(0xffc0c0c0),
// TRANSPARENT(0x00000000),
//
// black(0xff000000),
// red(0xffff0000),
// blue(0xff0000ff),
// yellow(0xffffff00),
// white(0xffffffff),
// dark_gray(0xff404040);
//
// private final int color;
// Color(int color) { this.color = color; }
// public int getValue() { return color; }
// }
//
// Path: core/src/main/java/net/panuska/tlappy/Device.java
// public static VRAM vram;
//
// Path: mobile/src/main/java/net/panuska/tlappy/FullscreenActivity.java
// static final int DOWN = 40;
//
// Path: mobile/src/main/java/net/panuska/tlappy/FullscreenActivity.java
// static final int LEFT = 37;
//
// Path: mobile/src/main/java/net/panuska/tlappy/FullscreenActivity.java
// static final int RIGHT = 39;
//
// Path: mobile/src/main/java/net/panuska/tlappy/FullscreenActivity.java
// static final int SPACE_BAR = 32;
//
// Path: mobile/src/main/java/net/panuska/tlappy/FullscreenActivity.java
// static final int UP = 38;
// Path: mobile/src/main/java/net/panuska/tlappy/CustomControlsActivity.java
import android.os.AsyncTask;
import android.os.Bundle;
import android.util.Log;
import android.util.SparseIntArray;
import android.view.KeyEvent;
import android.view.SurfaceView;
import net.panuska.tlappy.awt.BufferedImage;
import net.panuska.tlappy.awt.Color;
import net.panuska.tlappy.mobile.R;
import static net.panuska.tlappy.Device.vram;
import static net.panuska.tlappy.FullscreenActivity.DOWN;
import static net.panuska.tlappy.FullscreenActivity.LEFT;
import static net.panuska.tlappy.FullscreenActivity.RIGHT;
import static net.panuska.tlappy.FullscreenActivity.SPACE_BAR;
import static net.panuska.tlappy.FullscreenActivity.UP;
{Images.chickenLeft, Images.chickenLeft1},
{Images.chickenRight, Images.chickenRight1},
{Images.chickenUp, Images.chickenUp1, Images.chickenUp, Images.chickenUp2},
{Images.chickenDown, Images.chickenDown1, Images.chickenDown, Images.chickenDown2},
{Images.chickenDownFire1, Images.chickenDownFire2, Images.chickenDownFire1, Images.chickenDownFire2, Images.chickenDown, Images.chickenDown},
{Images.chickenJump1, Images.chickenJump2, Images.chickenDown, Images.chickenDown, Images.chickenDown, Images.chickenDown}
};
private static final int[] MESSAGES = {
R.string.move_left,
R.string.move_right,
R.string.move_up,
R.string.move_down,
R.string.throw_mushroom,
R.string.controls_saved};
volatile BufferedImage[] selectedAnimation;
@Override
protected void onCreate(Bundle savedInstanceState) {
Log.d(TAG, "onCreate");
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_customcontrols);
view = (SurfaceView) findViewById(R.id.customControlsContent);
}
@Override
protected void onResume() {
super.onResume();
Main.getInstance(view); //todo hack | vram.clear(); |
pe-pan/flappy | mobile/src/main/java/net/panuska/tlappy/CustomControlsActivity.java | // Path: core/src/main/java/net/panuska/tlappy/awt/BufferedImage.java
// public class BufferedImage {
// private Bitmap b;
// private Graphics g;
// public static final int TYPE_INT_RGB = Bitmap.Config.ARGB_8888.ordinal();
//
// public BufferedImage(BitmapDrawable d) {
// Bitmap immb = d.getBitmap();
// b = immb.copy(Bitmap.Config.ARGB_8888, false);
// }
//
// public BufferedImage(int width,
// int height,
// int imageType) {
// b = Bitmap.createBitmap(width, height, Bitmap.Config.ARGB_8888);
// g = new Graphics(b);
// }
//
// private BufferedImage(Bitmap b) {
// this.b = b;
// }
//
// public Graphics getGraphics() {
// return g;
// }
//
// public Bitmap getBitmap() {
// return b;
// }
//
// public BufferedImage getSubimage (int x, int y, int w, int h) {
// Bitmap b = Bitmap.createBitmap(this.b, x, y, w, h);
// return new BufferedImage(b);
// }
//
// /**
// * Returns a copy of this image rotated by 90 degrees.
// * @return
// */
// public BufferedImage getRotatedImage() {
// Matrix matrix = new Matrix();
// matrix.postRotate(90);
// Bitmap b = Bitmap.createBitmap(this.getBitmap(), 0, 0, this.getWidth(), this.getHeight(), matrix, false);
// return new BufferedImage(b);
// }
//
// /**
// * Returns a copy of this image mirrored by vertical axis
// * @return
// */
// public BufferedImage getMirroredImage() {
// Matrix matrix = new Matrix();
// matrix.preScale(-1, 1);
// Bitmap b = Bitmap.createBitmap(this.getBitmap(), 0, 0, this.getWidth(), this.getHeight(), matrix, false);
// return new BufferedImage(b);
// }
//
// /**
// * Returns 16x16 subimage starting at x, y
// * @param x
// * @param y
// * @return
// */
// public BufferedImage getSubimage (int x, int y) {
// return getSubimage(x, y, 16, 16);
// }
//
// public int getWidth() {
// return b.getWidth();
// }
//
// public int getHeight() {
// return b.getHeight();
// }
// }
//
// Path: core/src/main/java/net/panuska/tlappy/awt/Color.java
// public enum Color {
// BLACK(0xff000000),
// RED(0xffff0000),
// BLUE(0xff0000ff),
// YELLOW(0xffffff00),
// WHITE(0xffffffff),
// DARK_GRAY(0xff404040),
// LIGHT_GRAY(0xffc0c0c0),
// TRANSPARENT(0x00000000),
//
// black(0xff000000),
// red(0xffff0000),
// blue(0xff0000ff),
// yellow(0xffffff00),
// white(0xffffffff),
// dark_gray(0xff404040);
//
// private final int color;
// Color(int color) { this.color = color; }
// public int getValue() { return color; }
// }
//
// Path: core/src/main/java/net/panuska/tlappy/Device.java
// public static VRAM vram;
//
// Path: mobile/src/main/java/net/panuska/tlappy/FullscreenActivity.java
// static final int DOWN = 40;
//
// Path: mobile/src/main/java/net/panuska/tlappy/FullscreenActivity.java
// static final int LEFT = 37;
//
// Path: mobile/src/main/java/net/panuska/tlappy/FullscreenActivity.java
// static final int RIGHT = 39;
//
// Path: mobile/src/main/java/net/panuska/tlappy/FullscreenActivity.java
// static final int SPACE_BAR = 32;
//
// Path: mobile/src/main/java/net/panuska/tlappy/FullscreenActivity.java
// static final int UP = 38;
| import android.os.AsyncTask;
import android.os.Bundle;
import android.util.Log;
import android.util.SparseIntArray;
import android.view.KeyEvent;
import android.view.SurfaceView;
import net.panuska.tlappy.awt.BufferedImage;
import net.panuska.tlappy.awt.Color;
import net.panuska.tlappy.mobile.R;
import static net.panuska.tlappy.Device.vram;
import static net.panuska.tlappy.FullscreenActivity.DOWN;
import static net.panuska.tlappy.FullscreenActivity.LEFT;
import static net.panuska.tlappy.FullscreenActivity.RIGHT;
import static net.panuska.tlappy.FullscreenActivity.SPACE_BAR;
import static net.panuska.tlappy.FullscreenActivity.UP; |
@Override
protected void onCreate(Bundle savedInstanceState) {
Log.d(TAG, "onCreate");
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_customcontrols);
view = (SurfaceView) findViewById(R.id.customControlsContent);
}
@Override
protected void onResume() {
super.onResume();
Main.getInstance(view); //todo hack
vram.clear();
index = 0;
maxIndex = Integer.MAX_VALUE; // hopefully big enough
step = 0;
switchState(); // to init
systemMessage = null;
tempKeyboardMap = new SparseIntArray();
game = new AsyncTask<Void, Void, Void>() {
@Override
protected Void doInBackground(Void... params) {
for (index = 0; index < maxIndex; index++) {
vram.clear();
vram.imageNoOfs(20, 10, selectedAnimation[index % selectedAnimation.length]); | // Path: core/src/main/java/net/panuska/tlappy/awt/BufferedImage.java
// public class BufferedImage {
// private Bitmap b;
// private Graphics g;
// public static final int TYPE_INT_RGB = Bitmap.Config.ARGB_8888.ordinal();
//
// public BufferedImage(BitmapDrawable d) {
// Bitmap immb = d.getBitmap();
// b = immb.copy(Bitmap.Config.ARGB_8888, false);
// }
//
// public BufferedImage(int width,
// int height,
// int imageType) {
// b = Bitmap.createBitmap(width, height, Bitmap.Config.ARGB_8888);
// g = new Graphics(b);
// }
//
// private BufferedImage(Bitmap b) {
// this.b = b;
// }
//
// public Graphics getGraphics() {
// return g;
// }
//
// public Bitmap getBitmap() {
// return b;
// }
//
// public BufferedImage getSubimage (int x, int y, int w, int h) {
// Bitmap b = Bitmap.createBitmap(this.b, x, y, w, h);
// return new BufferedImage(b);
// }
//
// /**
// * Returns a copy of this image rotated by 90 degrees.
// * @return
// */
// public BufferedImage getRotatedImage() {
// Matrix matrix = new Matrix();
// matrix.postRotate(90);
// Bitmap b = Bitmap.createBitmap(this.getBitmap(), 0, 0, this.getWidth(), this.getHeight(), matrix, false);
// return new BufferedImage(b);
// }
//
// /**
// * Returns a copy of this image mirrored by vertical axis
// * @return
// */
// public BufferedImage getMirroredImage() {
// Matrix matrix = new Matrix();
// matrix.preScale(-1, 1);
// Bitmap b = Bitmap.createBitmap(this.getBitmap(), 0, 0, this.getWidth(), this.getHeight(), matrix, false);
// return new BufferedImage(b);
// }
//
// /**
// * Returns 16x16 subimage starting at x, y
// * @param x
// * @param y
// * @return
// */
// public BufferedImage getSubimage (int x, int y) {
// return getSubimage(x, y, 16, 16);
// }
//
// public int getWidth() {
// return b.getWidth();
// }
//
// public int getHeight() {
// return b.getHeight();
// }
// }
//
// Path: core/src/main/java/net/panuska/tlappy/awt/Color.java
// public enum Color {
// BLACK(0xff000000),
// RED(0xffff0000),
// BLUE(0xff0000ff),
// YELLOW(0xffffff00),
// WHITE(0xffffffff),
// DARK_GRAY(0xff404040),
// LIGHT_GRAY(0xffc0c0c0),
// TRANSPARENT(0x00000000),
//
// black(0xff000000),
// red(0xffff0000),
// blue(0xff0000ff),
// yellow(0xffffff00),
// white(0xffffffff),
// dark_gray(0xff404040);
//
// private final int color;
// Color(int color) { this.color = color; }
// public int getValue() { return color; }
// }
//
// Path: core/src/main/java/net/panuska/tlappy/Device.java
// public static VRAM vram;
//
// Path: mobile/src/main/java/net/panuska/tlappy/FullscreenActivity.java
// static final int DOWN = 40;
//
// Path: mobile/src/main/java/net/panuska/tlappy/FullscreenActivity.java
// static final int LEFT = 37;
//
// Path: mobile/src/main/java/net/panuska/tlappy/FullscreenActivity.java
// static final int RIGHT = 39;
//
// Path: mobile/src/main/java/net/panuska/tlappy/FullscreenActivity.java
// static final int SPACE_BAR = 32;
//
// Path: mobile/src/main/java/net/panuska/tlappy/FullscreenActivity.java
// static final int UP = 38;
// Path: mobile/src/main/java/net/panuska/tlappy/CustomControlsActivity.java
import android.os.AsyncTask;
import android.os.Bundle;
import android.util.Log;
import android.util.SparseIntArray;
import android.view.KeyEvent;
import android.view.SurfaceView;
import net.panuska.tlappy.awt.BufferedImage;
import net.panuska.tlappy.awt.Color;
import net.panuska.tlappy.mobile.R;
import static net.panuska.tlappy.Device.vram;
import static net.panuska.tlappy.FullscreenActivity.DOWN;
import static net.panuska.tlappy.FullscreenActivity.LEFT;
import static net.panuska.tlappy.FullscreenActivity.RIGHT;
import static net.panuska.tlappy.FullscreenActivity.SPACE_BAR;
import static net.panuska.tlappy.FullscreenActivity.UP;
@Override
protected void onCreate(Bundle savedInstanceState) {
Log.d(TAG, "onCreate");
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_customcontrols);
view = (SurfaceView) findViewById(R.id.customControlsContent);
}
@Override
protected void onResume() {
super.onResume();
Main.getInstance(view); //todo hack
vram.clear();
index = 0;
maxIndex = Integer.MAX_VALUE; // hopefully big enough
step = 0;
switchState(); // to init
systemMessage = null;
tempKeyboardMap = new SparseIntArray();
game = new AsyncTask<Void, Void, Void>() {
@Override
protected Void doInBackground(Void... params) {
for (index = 0; index < maxIndex; index++) {
vram.clear();
vram.imageNoOfs(20, 10, selectedAnimation[index % selectedAnimation.length]); | printMessageInCenter(20, message, Color.YELLOW); |
pe-pan/flappy | mobile/src/main/java/net/panuska/tlappy/FullscreenActivity.java | // Path: core/src/main/java/net/panuska/tlappy/Device.java
// public static Keyboard keyboard;
| import android.content.Intent;
import android.os.AsyncTask;
import android.os.Bundle;
import android.util.Log;
import android.view.KeyEvent;
import android.view.MotionEvent;
import android.view.SurfaceView;
import android.view.View;
import net.panuska.tlappy.mobile.R;
import static net.panuska.tlappy.Device.keyboard; |
@Override
public void onWindowFocusChanged(boolean hasFocus) {
super.onWindowFocusChanged(hasFocus);
if (hasFocus) { // when getting back from pause
Device.vram.refresh();
}
}
private static final int MOVE_LIMIT = 5;
private float initialX;
private float initialY;
private float lastX;
private float lastY;
boolean isMove;
static final int SPACE_BAR = 32;
static final int LEFT = 37;
static final int UP = 38;
static final int RIGHT = 39;
static final int DOWN = 40;
private int key;
@Override
public boolean dispatchKeyEvent(KeyEvent event) {
int translatedKey = CustomControlsActivity.keyboardMap.get(event.getKeyCode(), -1);
if (translatedKey != -1) { // value found
if (event.getAction() == KeyEvent.ACTION_DOWN) { | // Path: core/src/main/java/net/panuska/tlappy/Device.java
// public static Keyboard keyboard;
// Path: mobile/src/main/java/net/panuska/tlappy/FullscreenActivity.java
import android.content.Intent;
import android.os.AsyncTask;
import android.os.Bundle;
import android.util.Log;
import android.view.KeyEvent;
import android.view.MotionEvent;
import android.view.SurfaceView;
import android.view.View;
import net.panuska.tlappy.mobile.R;
import static net.panuska.tlappy.Device.keyboard;
@Override
public void onWindowFocusChanged(boolean hasFocus) {
super.onWindowFocusChanged(hasFocus);
if (hasFocus) { // when getting back from pause
Device.vram.refresh();
}
}
private static final int MOVE_LIMIT = 5;
private float initialX;
private float initialY;
private float lastX;
private float lastY;
boolean isMove;
static final int SPACE_BAR = 32;
static final int LEFT = 37;
static final int UP = 38;
static final int RIGHT = 39;
static final int DOWN = 40;
private int key;
@Override
public boolean dispatchKeyEvent(KeyEvent event) {
int translatedKey = CustomControlsActivity.keyboardMap.get(event.getKeyCode(), -1);
if (translatedKey != -1) { // value found
if (event.getAction() == KeyEvent.ACTION_DOWN) { | keyboard.keyDown(translatedKey); |
decorators-squad/eva | src/test/java/com/amihaiemil/eva/EvolutionaryAlgorithmTest.java | // Path: src/main/java/com/amihaiemil/eva/concurrency/AsynchronousEvaThread.java
// public final class AsynchronousEvaThread implements Runnable {
// private SolutionCallback callback;
// private Eva algorithm;
// private String threadName;
// private int runs;
// private Thread tr;
// /**
// * Constructor.
// * @param algorithm The evolutionary algorithm to be run.
// * @param callback The callback logic (what to do with the found solution?).
// * @param name The name of this runnable (it will be suffixed with _nrOfRuns).
// */
// public AsynchronousEvaThread(Eva algorithm, SolutionCallback callback, String name) {
// this.algorithm = algorithm;
// this.callback = callback;
// this.threadName = name;
// }
//
// public void run() {
// callback.execute(algorithm.calculate());
// }
//
// /**
// * Start the execution of a new thread.
// */
// public void start() {
// runs++;
// tr = new Thread(this, threadName + "_" + runs);
// tr.start();
//
// }
//
// public void stop() {
// tr.interrupt();
// }
// }
//
// Path: src/main/java/com/amihaiemil/eva/concurrency/SolutionCallback.java
// public interface SolutionCallback {
// /**
// * Logic to be performed on the found solution.
// * @param result The algorithm's final solution.
// */
// void execute(Solution result);
// }
//
// Path: src/main/java/com/amihaiemil/eva/util/BinaryArraySolutionsGenerator.java
// public class BinaryArraySolutionsGenerator implements SolutionsGenerator {
// /**
// * Size of the representation array.
// */
// private int size;
// private Random r = new Random();
// public BinaryArraySolutionsGenerator(int size) {
// this.size = size;
// }
// public Solution generateRandomSolution() {
// NumericalRepresentation representation = new NumericalRepresentation();
// for(int i=0;i<size;i++) {
// representation = representation.addNumber(r.nextInt(2));
// }
// Solution generated = new BinaryArraySolution(new Random());
// generated.setRepresentation(representation);
// return generated;
// }
// }
| import java.util.concurrent.ExecutionException;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Future;
import com.amihaiemil.eva.concurrency.AsynchronousEvaThread;
import com.amihaiemil.eva.concurrency.SolutionCallback;
import org.junit.Test;
import com.amihaiemil.eva.backpack.FitnessForBackpackEvaluator;
import com.amihaiemil.eva.util.BinaryArraySolutionsGenerator;
import static org.junit.Assert.assertTrue;
import java.util.Random; | /*
Copyright (c) 2016, Mihai-Emil Andronache
All rights reserved.
Redistribution and use in source and binary forms, with or without modification,
are permitted provided that the following conditions are met:
1. Redistributions of source code must retain the above copyright notice,
this list of conditions and the following disclaimer.
2. Redistributions in binary form must reproduce the above copyright notice,
this list of conditions and the following disclaimer in the documentation
and/or other materials provided with the distribution.
3. Neither the name of the copyright holder nor the names of its contributors
may be used to endorse or promote products derived from this software
without specific prior written permission.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO,
THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
ARE DISCLAIMED.
IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT,
INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
package com.amihaiemil.eva;
/**
* Test cases for {@link Eva} implementations.
* @author Mihai Andronache (amihaiemil@gmail.com)
*/
public class EvolutionaryAlgorithmTest {
private Random r = new Random();
/**
* {@link SimpleEvolutionaryAlgorithm} can find an acceptable solution.
* @throws Exception If something goes wrong.
*/
@Test
public void simpleEvaFindsASolution() throws Exception {
// The algorithm should stop only when the found solution is acceptable.
Condition solutionIsAcceptable = new Condition() {
public boolean passed(Solution solution) {
return solution.isAcceptable();
}
};
Solution solution = this.initAlgorithm(solutionIsAcceptable).calculate();
assertTrue(
"Expected solution with weight <= 100",
solutionIsAcceptable.passed(solution)
);
}
/**
* {@link SimpleEvolutionaryAlgorithm} can find an acceptable solution when run on a separate thread..
* @throws Exception If something goes wrong.
*/
@Test
public void asyncSimpleEvaFindsASolution() throws InterruptedException, ExecutionException {
// The algorithm should stop when the found solution is acceptable.
final Condition solutionIsAcceptable = new Condition() {
public boolean passed(Solution solution) {
return solution.isAcceptable();
}
}; | // Path: src/main/java/com/amihaiemil/eva/concurrency/AsynchronousEvaThread.java
// public final class AsynchronousEvaThread implements Runnable {
// private SolutionCallback callback;
// private Eva algorithm;
// private String threadName;
// private int runs;
// private Thread tr;
// /**
// * Constructor.
// * @param algorithm The evolutionary algorithm to be run.
// * @param callback The callback logic (what to do with the found solution?).
// * @param name The name of this runnable (it will be suffixed with _nrOfRuns).
// */
// public AsynchronousEvaThread(Eva algorithm, SolutionCallback callback, String name) {
// this.algorithm = algorithm;
// this.callback = callback;
// this.threadName = name;
// }
//
// public void run() {
// callback.execute(algorithm.calculate());
// }
//
// /**
// * Start the execution of a new thread.
// */
// public void start() {
// runs++;
// tr = new Thread(this, threadName + "_" + runs);
// tr.start();
//
// }
//
// public void stop() {
// tr.interrupt();
// }
// }
//
// Path: src/main/java/com/amihaiemil/eva/concurrency/SolutionCallback.java
// public interface SolutionCallback {
// /**
// * Logic to be performed on the found solution.
// * @param result The algorithm's final solution.
// */
// void execute(Solution result);
// }
//
// Path: src/main/java/com/amihaiemil/eva/util/BinaryArraySolutionsGenerator.java
// public class BinaryArraySolutionsGenerator implements SolutionsGenerator {
// /**
// * Size of the representation array.
// */
// private int size;
// private Random r = new Random();
// public BinaryArraySolutionsGenerator(int size) {
// this.size = size;
// }
// public Solution generateRandomSolution() {
// NumericalRepresentation representation = new NumericalRepresentation();
// for(int i=0;i<size;i++) {
// representation = representation.addNumber(r.nextInt(2));
// }
// Solution generated = new BinaryArraySolution(new Random());
// generated.setRepresentation(representation);
// return generated;
// }
// }
// Path: src/test/java/com/amihaiemil/eva/EvolutionaryAlgorithmTest.java
import java.util.concurrent.ExecutionException;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Future;
import com.amihaiemil.eva.concurrency.AsynchronousEvaThread;
import com.amihaiemil.eva.concurrency.SolutionCallback;
import org.junit.Test;
import com.amihaiemil.eva.backpack.FitnessForBackpackEvaluator;
import com.amihaiemil.eva.util.BinaryArraySolutionsGenerator;
import static org.junit.Assert.assertTrue;
import java.util.Random;
/*
Copyright (c) 2016, Mihai-Emil Andronache
All rights reserved.
Redistribution and use in source and binary forms, with or without modification,
are permitted provided that the following conditions are met:
1. Redistributions of source code must retain the above copyright notice,
this list of conditions and the following disclaimer.
2. Redistributions in binary form must reproduce the above copyright notice,
this list of conditions and the following disclaimer in the documentation
and/or other materials provided with the distribution.
3. Neither the name of the copyright holder nor the names of its contributors
may be used to endorse or promote products derived from this software
without specific prior written permission.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO,
THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
ARE DISCLAIMED.
IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT,
INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
package com.amihaiemil.eva;
/**
* Test cases for {@link Eva} implementations.
* @author Mihai Andronache (amihaiemil@gmail.com)
*/
public class EvolutionaryAlgorithmTest {
private Random r = new Random();
/**
* {@link SimpleEvolutionaryAlgorithm} can find an acceptable solution.
* @throws Exception If something goes wrong.
*/
@Test
public void simpleEvaFindsASolution() throws Exception {
// The algorithm should stop only when the found solution is acceptable.
Condition solutionIsAcceptable = new Condition() {
public boolean passed(Solution solution) {
return solution.isAcceptable();
}
};
Solution solution = this.initAlgorithm(solutionIsAcceptable).calculate();
assertTrue(
"Expected solution with weight <= 100",
solutionIsAcceptable.passed(solution)
);
}
/**
* {@link SimpleEvolutionaryAlgorithm} can find an acceptable solution when run on a separate thread..
* @throws Exception If something goes wrong.
*/
@Test
public void asyncSimpleEvaFindsASolution() throws InterruptedException, ExecutionException {
// The algorithm should stop when the found solution is acceptable.
final Condition solutionIsAcceptable = new Condition() {
public boolean passed(Solution solution) {
return solution.isAcceptable();
}
}; | SolutionCallback assertsCallback = new SolutionCallback() { |
decorators-squad/eva | src/test/java/com/amihaiemil/eva/EvolutionaryAlgorithmTest.java | // Path: src/main/java/com/amihaiemil/eva/concurrency/AsynchronousEvaThread.java
// public final class AsynchronousEvaThread implements Runnable {
// private SolutionCallback callback;
// private Eva algorithm;
// private String threadName;
// private int runs;
// private Thread tr;
// /**
// * Constructor.
// * @param algorithm The evolutionary algorithm to be run.
// * @param callback The callback logic (what to do with the found solution?).
// * @param name The name of this runnable (it will be suffixed with _nrOfRuns).
// */
// public AsynchronousEvaThread(Eva algorithm, SolutionCallback callback, String name) {
// this.algorithm = algorithm;
// this.callback = callback;
// this.threadName = name;
// }
//
// public void run() {
// callback.execute(algorithm.calculate());
// }
//
// /**
// * Start the execution of a new thread.
// */
// public void start() {
// runs++;
// tr = new Thread(this, threadName + "_" + runs);
// tr.start();
//
// }
//
// public void stop() {
// tr.interrupt();
// }
// }
//
// Path: src/main/java/com/amihaiemil/eva/concurrency/SolutionCallback.java
// public interface SolutionCallback {
// /**
// * Logic to be performed on the found solution.
// * @param result The algorithm's final solution.
// */
// void execute(Solution result);
// }
//
// Path: src/main/java/com/amihaiemil/eva/util/BinaryArraySolutionsGenerator.java
// public class BinaryArraySolutionsGenerator implements SolutionsGenerator {
// /**
// * Size of the representation array.
// */
// private int size;
// private Random r = new Random();
// public BinaryArraySolutionsGenerator(int size) {
// this.size = size;
// }
// public Solution generateRandomSolution() {
// NumericalRepresentation representation = new NumericalRepresentation();
// for(int i=0;i<size;i++) {
// representation = representation.addNumber(r.nextInt(2));
// }
// Solution generated = new BinaryArraySolution(new Random());
// generated.setRepresentation(representation);
// return generated;
// }
// }
| import java.util.concurrent.ExecutionException;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Future;
import com.amihaiemil.eva.concurrency.AsynchronousEvaThread;
import com.amihaiemil.eva.concurrency.SolutionCallback;
import org.junit.Test;
import com.amihaiemil.eva.backpack.FitnessForBackpackEvaluator;
import com.amihaiemil.eva.util.BinaryArraySolutionsGenerator;
import static org.junit.Assert.assertTrue;
import java.util.Random; | /*
Copyright (c) 2016, Mihai-Emil Andronache
All rights reserved.
Redistribution and use in source and binary forms, with or without modification,
are permitted provided that the following conditions are met:
1. Redistributions of source code must retain the above copyright notice,
this list of conditions and the following disclaimer.
2. Redistributions in binary form must reproduce the above copyright notice,
this list of conditions and the following disclaimer in the documentation
and/or other materials provided with the distribution.
3. Neither the name of the copyright holder nor the names of its contributors
may be used to endorse or promote products derived from this software
without specific prior written permission.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO,
THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
ARE DISCLAIMED.
IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT,
INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
package com.amihaiemil.eva;
/**
* Test cases for {@link Eva} implementations.
* @author Mihai Andronache (amihaiemil@gmail.com)
*/
public class EvolutionaryAlgorithmTest {
private Random r = new Random();
/**
* {@link SimpleEvolutionaryAlgorithm} can find an acceptable solution.
* @throws Exception If something goes wrong.
*/
@Test
public void simpleEvaFindsASolution() throws Exception {
// The algorithm should stop only when the found solution is acceptable.
Condition solutionIsAcceptable = new Condition() {
public boolean passed(Solution solution) {
return solution.isAcceptable();
}
};
Solution solution = this.initAlgorithm(solutionIsAcceptable).calculate();
assertTrue(
"Expected solution with weight <= 100",
solutionIsAcceptable.passed(solution)
);
}
/**
* {@link SimpleEvolutionaryAlgorithm} can find an acceptable solution when run on a separate thread..
* @throws Exception If something goes wrong.
*/
@Test
public void asyncSimpleEvaFindsASolution() throws InterruptedException, ExecutionException {
// The algorithm should stop when the found solution is acceptable.
final Condition solutionIsAcceptable = new Condition() {
public boolean passed(Solution solution) {
return solution.isAcceptable();
}
};
SolutionCallback assertsCallback = new SolutionCallback() {
public void execute(Solution result) {
assertTrue(result != null);
assertTrue(solutionIsAcceptable.passed(result));
}
};
Eva eva = initAlgorithm(solutionIsAcceptable); | // Path: src/main/java/com/amihaiemil/eva/concurrency/AsynchronousEvaThread.java
// public final class AsynchronousEvaThread implements Runnable {
// private SolutionCallback callback;
// private Eva algorithm;
// private String threadName;
// private int runs;
// private Thread tr;
// /**
// * Constructor.
// * @param algorithm The evolutionary algorithm to be run.
// * @param callback The callback logic (what to do with the found solution?).
// * @param name The name of this runnable (it will be suffixed with _nrOfRuns).
// */
// public AsynchronousEvaThread(Eva algorithm, SolutionCallback callback, String name) {
// this.algorithm = algorithm;
// this.callback = callback;
// this.threadName = name;
// }
//
// public void run() {
// callback.execute(algorithm.calculate());
// }
//
// /**
// * Start the execution of a new thread.
// */
// public void start() {
// runs++;
// tr = new Thread(this, threadName + "_" + runs);
// tr.start();
//
// }
//
// public void stop() {
// tr.interrupt();
// }
// }
//
// Path: src/main/java/com/amihaiemil/eva/concurrency/SolutionCallback.java
// public interface SolutionCallback {
// /**
// * Logic to be performed on the found solution.
// * @param result The algorithm's final solution.
// */
// void execute(Solution result);
// }
//
// Path: src/main/java/com/amihaiemil/eva/util/BinaryArraySolutionsGenerator.java
// public class BinaryArraySolutionsGenerator implements SolutionsGenerator {
// /**
// * Size of the representation array.
// */
// private int size;
// private Random r = new Random();
// public BinaryArraySolutionsGenerator(int size) {
// this.size = size;
// }
// public Solution generateRandomSolution() {
// NumericalRepresentation representation = new NumericalRepresentation();
// for(int i=0;i<size;i++) {
// representation = representation.addNumber(r.nextInt(2));
// }
// Solution generated = new BinaryArraySolution(new Random());
// generated.setRepresentation(representation);
// return generated;
// }
// }
// Path: src/test/java/com/amihaiemil/eva/EvolutionaryAlgorithmTest.java
import java.util.concurrent.ExecutionException;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Future;
import com.amihaiemil.eva.concurrency.AsynchronousEvaThread;
import com.amihaiemil.eva.concurrency.SolutionCallback;
import org.junit.Test;
import com.amihaiemil.eva.backpack.FitnessForBackpackEvaluator;
import com.amihaiemil.eva.util.BinaryArraySolutionsGenerator;
import static org.junit.Assert.assertTrue;
import java.util.Random;
/*
Copyright (c) 2016, Mihai-Emil Andronache
All rights reserved.
Redistribution and use in source and binary forms, with or without modification,
are permitted provided that the following conditions are met:
1. Redistributions of source code must retain the above copyright notice,
this list of conditions and the following disclaimer.
2. Redistributions in binary form must reproduce the above copyright notice,
this list of conditions and the following disclaimer in the documentation
and/or other materials provided with the distribution.
3. Neither the name of the copyright holder nor the names of its contributors
may be used to endorse or promote products derived from this software
without specific prior written permission.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO,
THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
ARE DISCLAIMED.
IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT,
INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
package com.amihaiemil.eva;
/**
* Test cases for {@link Eva} implementations.
* @author Mihai Andronache (amihaiemil@gmail.com)
*/
public class EvolutionaryAlgorithmTest {
private Random r = new Random();
/**
* {@link SimpleEvolutionaryAlgorithm} can find an acceptable solution.
* @throws Exception If something goes wrong.
*/
@Test
public void simpleEvaFindsASolution() throws Exception {
// The algorithm should stop only when the found solution is acceptable.
Condition solutionIsAcceptable = new Condition() {
public boolean passed(Solution solution) {
return solution.isAcceptable();
}
};
Solution solution = this.initAlgorithm(solutionIsAcceptable).calculate();
assertTrue(
"Expected solution with weight <= 100",
solutionIsAcceptable.passed(solution)
);
}
/**
* {@link SimpleEvolutionaryAlgorithm} can find an acceptable solution when run on a separate thread..
* @throws Exception If something goes wrong.
*/
@Test
public void asyncSimpleEvaFindsASolution() throws InterruptedException, ExecutionException {
// The algorithm should stop when the found solution is acceptable.
final Condition solutionIsAcceptable = new Condition() {
public boolean passed(Solution solution) {
return solution.isAcceptable();
}
};
SolutionCallback assertsCallback = new SolutionCallback() {
public void execute(Solution result) {
assertTrue(result != null);
assertTrue(solutionIsAcceptable.passed(result));
}
};
Eva eva = initAlgorithm(solutionIsAcceptable); | AsynchronousEvaThread asyncEva = new AsynchronousEvaThread(eva, assertsCallback, "testAsyncEva"); |
decorators-squad/eva | src/test/java/com/amihaiemil/eva/EvolutionaryAlgorithmTest.java | // Path: src/main/java/com/amihaiemil/eva/concurrency/AsynchronousEvaThread.java
// public final class AsynchronousEvaThread implements Runnable {
// private SolutionCallback callback;
// private Eva algorithm;
// private String threadName;
// private int runs;
// private Thread tr;
// /**
// * Constructor.
// * @param algorithm The evolutionary algorithm to be run.
// * @param callback The callback logic (what to do with the found solution?).
// * @param name The name of this runnable (it will be suffixed with _nrOfRuns).
// */
// public AsynchronousEvaThread(Eva algorithm, SolutionCallback callback, String name) {
// this.algorithm = algorithm;
// this.callback = callback;
// this.threadName = name;
// }
//
// public void run() {
// callback.execute(algorithm.calculate());
// }
//
// /**
// * Start the execution of a new thread.
// */
// public void start() {
// runs++;
// tr = new Thread(this, threadName + "_" + runs);
// tr.start();
//
// }
//
// public void stop() {
// tr.interrupt();
// }
// }
//
// Path: src/main/java/com/amihaiemil/eva/concurrency/SolutionCallback.java
// public interface SolutionCallback {
// /**
// * Logic to be performed on the found solution.
// * @param result The algorithm's final solution.
// */
// void execute(Solution result);
// }
//
// Path: src/main/java/com/amihaiemil/eva/util/BinaryArraySolutionsGenerator.java
// public class BinaryArraySolutionsGenerator implements SolutionsGenerator {
// /**
// * Size of the representation array.
// */
// private int size;
// private Random r = new Random();
// public BinaryArraySolutionsGenerator(int size) {
// this.size = size;
// }
// public Solution generateRandomSolution() {
// NumericalRepresentation representation = new NumericalRepresentation();
// for(int i=0;i<size;i++) {
// representation = representation.addNumber(r.nextInt(2));
// }
// Solution generated = new BinaryArraySolution(new Random());
// generated.setRepresentation(representation);
// return generated;
// }
// }
| import java.util.concurrent.ExecutionException;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Future;
import com.amihaiemil.eva.concurrency.AsynchronousEvaThread;
import com.amihaiemil.eva.concurrency.SolutionCallback;
import org.junit.Test;
import com.amihaiemil.eva.backpack.FitnessForBackpackEvaluator;
import com.amihaiemil.eva.util.BinaryArraySolutionsGenerator;
import static org.junit.Assert.assertTrue;
import java.util.Random; | * @throws Exception If something goes wrong.
*/
@Test
public void asyncSimpleEvaFindsASolution() throws InterruptedException, ExecutionException {
// The algorithm should stop when the found solution is acceptable.
final Condition solutionIsAcceptable = new Condition() {
public boolean passed(Solution solution) {
return solution.isAcceptable();
}
};
SolutionCallback assertsCallback = new SolutionCallback() {
public void execute(Solution result) {
assertTrue(result != null);
assertTrue(solutionIsAcceptable.passed(result));
}
};
Eva eva = initAlgorithm(solutionIsAcceptable);
AsynchronousEvaThread asyncEva = new AsynchronousEvaThread(eva, assertsCallback, "testAsyncEva");
final ExecutorService executorService = Executors.newSingleThreadExecutor();
Future future = executorService.submit(asyncEva);
assertTrue(future.get()==null);
}
private Eva initAlgorithm(Condition solutionIsAcceptable) {
long[] weights = new long[10];
for(int i=0;i<10;i++) {
weights[i] = r.nextInt(100);
}
FitnessForBackpackEvaluator evaluator = new FitnessForBackpackEvaluator(weights); | // Path: src/main/java/com/amihaiemil/eva/concurrency/AsynchronousEvaThread.java
// public final class AsynchronousEvaThread implements Runnable {
// private SolutionCallback callback;
// private Eva algorithm;
// private String threadName;
// private int runs;
// private Thread tr;
// /**
// * Constructor.
// * @param algorithm The evolutionary algorithm to be run.
// * @param callback The callback logic (what to do with the found solution?).
// * @param name The name of this runnable (it will be suffixed with _nrOfRuns).
// */
// public AsynchronousEvaThread(Eva algorithm, SolutionCallback callback, String name) {
// this.algorithm = algorithm;
// this.callback = callback;
// this.threadName = name;
// }
//
// public void run() {
// callback.execute(algorithm.calculate());
// }
//
// /**
// * Start the execution of a new thread.
// */
// public void start() {
// runs++;
// tr = new Thread(this, threadName + "_" + runs);
// tr.start();
//
// }
//
// public void stop() {
// tr.interrupt();
// }
// }
//
// Path: src/main/java/com/amihaiemil/eva/concurrency/SolutionCallback.java
// public interface SolutionCallback {
// /**
// * Logic to be performed on the found solution.
// * @param result The algorithm's final solution.
// */
// void execute(Solution result);
// }
//
// Path: src/main/java/com/amihaiemil/eva/util/BinaryArraySolutionsGenerator.java
// public class BinaryArraySolutionsGenerator implements SolutionsGenerator {
// /**
// * Size of the representation array.
// */
// private int size;
// private Random r = new Random();
// public BinaryArraySolutionsGenerator(int size) {
// this.size = size;
// }
// public Solution generateRandomSolution() {
// NumericalRepresentation representation = new NumericalRepresentation();
// for(int i=0;i<size;i++) {
// representation = representation.addNumber(r.nextInt(2));
// }
// Solution generated = new BinaryArraySolution(new Random());
// generated.setRepresentation(representation);
// return generated;
// }
// }
// Path: src/test/java/com/amihaiemil/eva/EvolutionaryAlgorithmTest.java
import java.util.concurrent.ExecutionException;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Future;
import com.amihaiemil.eva.concurrency.AsynchronousEvaThread;
import com.amihaiemil.eva.concurrency.SolutionCallback;
import org.junit.Test;
import com.amihaiemil.eva.backpack.FitnessForBackpackEvaluator;
import com.amihaiemil.eva.util.BinaryArraySolutionsGenerator;
import static org.junit.Assert.assertTrue;
import java.util.Random;
* @throws Exception If something goes wrong.
*/
@Test
public void asyncSimpleEvaFindsASolution() throws InterruptedException, ExecutionException {
// The algorithm should stop when the found solution is acceptable.
final Condition solutionIsAcceptable = new Condition() {
public boolean passed(Solution solution) {
return solution.isAcceptable();
}
};
SolutionCallback assertsCallback = new SolutionCallback() {
public void execute(Solution result) {
assertTrue(result != null);
assertTrue(solutionIsAcceptable.passed(result));
}
};
Eva eva = initAlgorithm(solutionIsAcceptable);
AsynchronousEvaThread asyncEva = new AsynchronousEvaThread(eva, assertsCallback, "testAsyncEva");
final ExecutorService executorService = Executors.newSingleThreadExecutor();
Future future = executorService.submit(asyncEva);
assertTrue(future.get()==null);
}
private Eva initAlgorithm(Condition solutionIsAcceptable) {
long[] weights = new long[10];
for(int i=0;i<10;i++) {
weights[i] = r.nextInt(100);
}
FitnessForBackpackEvaluator evaluator = new FitnessForBackpackEvaluator(weights); | BinaryArraySolutionsGenerator generator = new BinaryArraySolutionsGenerator(weights.length); |
decorators-squad/eva | src/test/java/com/amihaiemil/eva/util/BinaryArraySolutionsGeneratorTestCase.java | // Path: src/main/java/com/amihaiemil/eva/Solution.java
// public abstract class Solution {
//
// /**
// * Fitness of this solution. How good it is (how fit) in comparison to other solutions.
// */
// private Fitness fitness;
//
// /**
// * Representation of this solution.
// */
// private Representation representation;
//
// /**
// * Each solution should have a comparable fitness that makes it better or worse than other solutions.
// * @return The Fitness of this solution.
// */
// public Fitness getFitness() {
// return this.fitness;
// }
//
// /**
// * Set the fitness of this solution.
// * @param fitness The set fitness of this solution.
// */
// public void setFitness(Fitness fitness) {
// this.fitness = fitness;
// }
//
// /**
// * Each solution should have a representation.
// * @return The representation of this solution.
// */
// public Representation getRepresentation() {
// return this.representation;
// }
//
// public void setRepresentation(Representation rep) {
// this.representation = rep;
// }
//
// /**
// * Mutate (change) this solution's representation with regards to pm - possibility of mutation.
// * @param pm A random chosen double (0 < pm < 1) that should give the random element in this solution's mutation.
// */
// public abstract void mutate(double pm);
//
// /**
// * Crossover this solution with the given partner.
// * In other words, create a new solution with data taken from both this solution and the partner.
// * @param partner Another solution.
// * @param cp Crossover probability.
// * @return The newly created solution.
// */
// public abstract Solution crossover(Solution partner, double cp);
//
// /**
// * A solution is acceptable if its fitness is ok.
// * @return true if acceptable, false otherwise.
// */
// public boolean isAcceptable() {
// return this.fitness.isOk();
// }
// }
//
// Path: src/main/java/com/amihaiemil/eva/SolutionsGenerator.java
// public interface SolutionsGenerator {
//
// /**
// * Generate a possible solution. Make sure this method does return a random solution every time.
// * @return A possible solution to the problem.
// */
// Solution generateRandomSolution();
// }
| import static org.junit.Assert.assertTrue;
import com.amihaiemil.eva.Solution;
import com.amihaiemil.eva.SolutionsGenerator;
import org.junit.Test; | /*
Copyright (c) 2016, Mihai-Emil Andronache
All rights reserved.
Redistribution and use in source and binary forms, with or without modification,
are permitted provided that the following conditions are met:
1. Redistributions of source code must retain the above copyright notice,
this list of conditions and the following disclaimer.
2. Redistributions in binary form must reproduce the above copyright notice,
this list of conditions and the following disclaimer in the documentation
and/or other materials provided with the distribution.
3. Neither the name of the copyright holder nor the names of its contributors
may be used to endorse or promote products derived from this software
without specific prior written permission.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO,
THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
ARE DISCLAIMED.
IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT,
INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
package com.amihaiemil.eva.util;
/**
* @author Mihai Andronache (amihaiemil@gmail.com)
*/
public class BinaryArraySolutionsGeneratorTestCase {
/**
* A solution cen be created using a {@link BinaryArraySolutionsGenerator}.
*/
@Test
public void generatesSolution() { | // Path: src/main/java/com/amihaiemil/eva/Solution.java
// public abstract class Solution {
//
// /**
// * Fitness of this solution. How good it is (how fit) in comparison to other solutions.
// */
// private Fitness fitness;
//
// /**
// * Representation of this solution.
// */
// private Representation representation;
//
// /**
// * Each solution should have a comparable fitness that makes it better or worse than other solutions.
// * @return The Fitness of this solution.
// */
// public Fitness getFitness() {
// return this.fitness;
// }
//
// /**
// * Set the fitness of this solution.
// * @param fitness The set fitness of this solution.
// */
// public void setFitness(Fitness fitness) {
// this.fitness = fitness;
// }
//
// /**
// * Each solution should have a representation.
// * @return The representation of this solution.
// */
// public Representation getRepresentation() {
// return this.representation;
// }
//
// public void setRepresentation(Representation rep) {
// this.representation = rep;
// }
//
// /**
// * Mutate (change) this solution's representation with regards to pm - possibility of mutation.
// * @param pm A random chosen double (0 < pm < 1) that should give the random element in this solution's mutation.
// */
// public abstract void mutate(double pm);
//
// /**
// * Crossover this solution with the given partner.
// * In other words, create a new solution with data taken from both this solution and the partner.
// * @param partner Another solution.
// * @param cp Crossover probability.
// * @return The newly created solution.
// */
// public abstract Solution crossover(Solution partner, double cp);
//
// /**
// * A solution is acceptable if its fitness is ok.
// * @return true if acceptable, false otherwise.
// */
// public boolean isAcceptable() {
// return this.fitness.isOk();
// }
// }
//
// Path: src/main/java/com/amihaiemil/eva/SolutionsGenerator.java
// public interface SolutionsGenerator {
//
// /**
// * Generate a possible solution. Make sure this method does return a random solution every time.
// * @return A possible solution to the problem.
// */
// Solution generateRandomSolution();
// }
// Path: src/test/java/com/amihaiemil/eva/util/BinaryArraySolutionsGeneratorTestCase.java
import static org.junit.Assert.assertTrue;
import com.amihaiemil.eva.Solution;
import com.amihaiemil.eva.SolutionsGenerator;
import org.junit.Test;
/*
Copyright (c) 2016, Mihai-Emil Andronache
All rights reserved.
Redistribution and use in source and binary forms, with or without modification,
are permitted provided that the following conditions are met:
1. Redistributions of source code must retain the above copyright notice,
this list of conditions and the following disclaimer.
2. Redistributions in binary form must reproduce the above copyright notice,
this list of conditions and the following disclaimer in the documentation
and/or other materials provided with the distribution.
3. Neither the name of the copyright holder nor the names of its contributors
may be used to endorse or promote products derived from this software
without specific prior written permission.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO,
THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
ARE DISCLAIMED.
IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT,
INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
package com.amihaiemil.eva.util;
/**
* @author Mihai Andronache (amihaiemil@gmail.com)
*/
public class BinaryArraySolutionsGeneratorTestCase {
/**
* A solution cen be created using a {@link BinaryArraySolutionsGenerator}.
*/
@Test
public void generatesSolution() { | SolutionsGenerator generator = new BinaryArraySolutionsGenerator(5); |
decorators-squad/eva | src/test/java/com/amihaiemil/eva/util/BinaryArraySolutionsGeneratorTestCase.java | // Path: src/main/java/com/amihaiemil/eva/Solution.java
// public abstract class Solution {
//
// /**
// * Fitness of this solution. How good it is (how fit) in comparison to other solutions.
// */
// private Fitness fitness;
//
// /**
// * Representation of this solution.
// */
// private Representation representation;
//
// /**
// * Each solution should have a comparable fitness that makes it better or worse than other solutions.
// * @return The Fitness of this solution.
// */
// public Fitness getFitness() {
// return this.fitness;
// }
//
// /**
// * Set the fitness of this solution.
// * @param fitness The set fitness of this solution.
// */
// public void setFitness(Fitness fitness) {
// this.fitness = fitness;
// }
//
// /**
// * Each solution should have a representation.
// * @return The representation of this solution.
// */
// public Representation getRepresentation() {
// return this.representation;
// }
//
// public void setRepresentation(Representation rep) {
// this.representation = rep;
// }
//
// /**
// * Mutate (change) this solution's representation with regards to pm - possibility of mutation.
// * @param pm A random chosen double (0 < pm < 1) that should give the random element in this solution's mutation.
// */
// public abstract void mutate(double pm);
//
// /**
// * Crossover this solution with the given partner.
// * In other words, create a new solution with data taken from both this solution and the partner.
// * @param partner Another solution.
// * @param cp Crossover probability.
// * @return The newly created solution.
// */
// public abstract Solution crossover(Solution partner, double cp);
//
// /**
// * A solution is acceptable if its fitness is ok.
// * @return true if acceptable, false otherwise.
// */
// public boolean isAcceptable() {
// return this.fitness.isOk();
// }
// }
//
// Path: src/main/java/com/amihaiemil/eva/SolutionsGenerator.java
// public interface SolutionsGenerator {
//
// /**
// * Generate a possible solution. Make sure this method does return a random solution every time.
// * @return A possible solution to the problem.
// */
// Solution generateRandomSolution();
// }
| import static org.junit.Assert.assertTrue;
import com.amihaiemil.eva.Solution;
import com.amihaiemil.eva.SolutionsGenerator;
import org.junit.Test; | /*
Copyright (c) 2016, Mihai-Emil Andronache
All rights reserved.
Redistribution and use in source and binary forms, with or without modification,
are permitted provided that the following conditions are met:
1. Redistributions of source code must retain the above copyright notice,
this list of conditions and the following disclaimer.
2. Redistributions in binary form must reproduce the above copyright notice,
this list of conditions and the following disclaimer in the documentation
and/or other materials provided with the distribution.
3. Neither the name of the copyright holder nor the names of its contributors
may be used to endorse or promote products derived from this software
without specific prior written permission.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO,
THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
ARE DISCLAIMED.
IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT,
INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
package com.amihaiemil.eva.util;
/**
* @author Mihai Andronache (amihaiemil@gmail.com)
*/
public class BinaryArraySolutionsGeneratorTestCase {
/**
* A solution cen be created using a {@link BinaryArraySolutionsGenerator}.
*/
@Test
public void generatesSolution() {
SolutionsGenerator generator = new BinaryArraySolutionsGenerator(5); | // Path: src/main/java/com/amihaiemil/eva/Solution.java
// public abstract class Solution {
//
// /**
// * Fitness of this solution. How good it is (how fit) in comparison to other solutions.
// */
// private Fitness fitness;
//
// /**
// * Representation of this solution.
// */
// private Representation representation;
//
// /**
// * Each solution should have a comparable fitness that makes it better or worse than other solutions.
// * @return The Fitness of this solution.
// */
// public Fitness getFitness() {
// return this.fitness;
// }
//
// /**
// * Set the fitness of this solution.
// * @param fitness The set fitness of this solution.
// */
// public void setFitness(Fitness fitness) {
// this.fitness = fitness;
// }
//
// /**
// * Each solution should have a representation.
// * @return The representation of this solution.
// */
// public Representation getRepresentation() {
// return this.representation;
// }
//
// public void setRepresentation(Representation rep) {
// this.representation = rep;
// }
//
// /**
// * Mutate (change) this solution's representation with regards to pm - possibility of mutation.
// * @param pm A random chosen double (0 < pm < 1) that should give the random element in this solution's mutation.
// */
// public abstract void mutate(double pm);
//
// /**
// * Crossover this solution with the given partner.
// * In other words, create a new solution with data taken from both this solution and the partner.
// * @param partner Another solution.
// * @param cp Crossover probability.
// * @return The newly created solution.
// */
// public abstract Solution crossover(Solution partner, double cp);
//
// /**
// * A solution is acceptable if its fitness is ok.
// * @return true if acceptable, false otherwise.
// */
// public boolean isAcceptable() {
// return this.fitness.isOk();
// }
// }
//
// Path: src/main/java/com/amihaiemil/eva/SolutionsGenerator.java
// public interface SolutionsGenerator {
//
// /**
// * Generate a possible solution. Make sure this method does return a random solution every time.
// * @return A possible solution to the problem.
// */
// Solution generateRandomSolution();
// }
// Path: src/test/java/com/amihaiemil/eva/util/BinaryArraySolutionsGeneratorTestCase.java
import static org.junit.Assert.assertTrue;
import com.amihaiemil.eva.Solution;
import com.amihaiemil.eva.SolutionsGenerator;
import org.junit.Test;
/*
Copyright (c) 2016, Mihai-Emil Andronache
All rights reserved.
Redistribution and use in source and binary forms, with or without modification,
are permitted provided that the following conditions are met:
1. Redistributions of source code must retain the above copyright notice,
this list of conditions and the following disclaimer.
2. Redistributions in binary form must reproduce the above copyright notice,
this list of conditions and the following disclaimer in the documentation
and/or other materials provided with the distribution.
3. Neither the name of the copyright holder nor the names of its contributors
may be used to endorse or promote products derived from this software
without specific prior written permission.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO,
THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
ARE DISCLAIMED.
IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT,
INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
package com.amihaiemil.eva.util;
/**
* @author Mihai Andronache (amihaiemil@gmail.com)
*/
public class BinaryArraySolutionsGeneratorTestCase {
/**
* A solution cen be created using a {@link BinaryArraySolutionsGenerator}.
*/
@Test
public void generatesSolution() {
SolutionsGenerator generator = new BinaryArraySolutionsGenerator(5); | Solution generatedSolution = generator.generateRandomSolution(); |
decorators-squad/eva | src/test/java/com/amihaiemil/eva/backpack/FitnessForBackpackTestCase.java | // Path: src/main/java/com/amihaiemil/eva/Fitness.java
// public interface Fitness extends Comparable<Fitness>{
// /**
// * Indicates whether this fitness is OK.
// * E.g. If it is not OK, then it's not even worth comparing it to others, since
// * we know that a solution with this fitness is not good.
// * @return true if this fitness is considered OK, or false otherwise.
// */
// boolean isOk();
// }
//
// Path: src/main/java/com/amihaiemil/eva/backpack/FitnessForBackpack.java
// public final class FitnessForBackpack implements Fitness{
// private long backpackCapacity;
// private long solutionWeight;
// FitnessForBackpack(long weight, long backpackCapacity) {
// this.backpackCapacity = backpackCapacity;
// this.solutionWeight = weight;
// }
//
// public long getWeight() {
// return this.solutionWeight;
// }
// public long getSolutionWeight() {
// return this.solutionWeight;
// }
//
// public boolean isOk() {
// return solutionWeight > 0 && solutionWeight <= backpackCapacity;
// }
//
// public int compareTo(Fitness o) {
// FitnessForBackpack other = (FitnessForBackpack) o;
// if(this.solutionWeight > other.getSolutionWeight()) {
// return -1;
// }
// if(this.solutionWeight == other.getSolutionWeight()) {
// return 0;
// }
// return 1;
// }
// }
| import org.junit.Test;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertTrue;
import com.amihaiemil.eva.Fitness;
import com.amihaiemil.eva.backpack.FitnessForBackpack; | /*
Copyright (c) 2016, Mihai-Emil Andronache
All rights reserved.
Redistribution and use in source and binary forms, with or without modification,
are permitted provided that the following conditions are met:
1. Redistributions of source code must retain the above copyright notice,
this list of conditions and the following disclaimer.
2. Redistributions in binary form must reproduce the above copyright notice,
this list of conditions and the following disclaimer in the documentation
and/or other materials provided with the distribution.
3. Neither the name of the copyright holder nor the names of its contributors
may be used to endorse or promote products derived from this software
without specific prior written permission.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO,
THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
ARE DISCLAIMED.
IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT,
INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
package com.amihaiemil.eva.backpack;
/**
* Tests for {@link FitnessForBackpack}
* @author Mihai Andronache (amihaiemil@gmail.com)
*/
public class FitnessForBackpackTestCase {
/**
* The Fitness can tell if it's ok or not.
*/
@Test
public void isFitnessOkOrNot() { | // Path: src/main/java/com/amihaiemil/eva/Fitness.java
// public interface Fitness extends Comparable<Fitness>{
// /**
// * Indicates whether this fitness is OK.
// * E.g. If it is not OK, then it's not even worth comparing it to others, since
// * we know that a solution with this fitness is not good.
// * @return true if this fitness is considered OK, or false otherwise.
// */
// boolean isOk();
// }
//
// Path: src/main/java/com/amihaiemil/eva/backpack/FitnessForBackpack.java
// public final class FitnessForBackpack implements Fitness{
// private long backpackCapacity;
// private long solutionWeight;
// FitnessForBackpack(long weight, long backpackCapacity) {
// this.backpackCapacity = backpackCapacity;
// this.solutionWeight = weight;
// }
//
// public long getWeight() {
// return this.solutionWeight;
// }
// public long getSolutionWeight() {
// return this.solutionWeight;
// }
//
// public boolean isOk() {
// return solutionWeight > 0 && solutionWeight <= backpackCapacity;
// }
//
// public int compareTo(Fitness o) {
// FitnessForBackpack other = (FitnessForBackpack) o;
// if(this.solutionWeight > other.getSolutionWeight()) {
// return -1;
// }
// if(this.solutionWeight == other.getSolutionWeight()) {
// return 0;
// }
// return 1;
// }
// }
// Path: src/test/java/com/amihaiemil/eva/backpack/FitnessForBackpackTestCase.java
import org.junit.Test;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertTrue;
import com.amihaiemil.eva.Fitness;
import com.amihaiemil.eva.backpack.FitnessForBackpack;
/*
Copyright (c) 2016, Mihai-Emil Andronache
All rights reserved.
Redistribution and use in source and binary forms, with or without modification,
are permitted provided that the following conditions are met:
1. Redistributions of source code must retain the above copyright notice,
this list of conditions and the following disclaimer.
2. Redistributions in binary form must reproduce the above copyright notice,
this list of conditions and the following disclaimer in the documentation
and/or other materials provided with the distribution.
3. Neither the name of the copyright holder nor the names of its contributors
may be used to endorse or promote products derived from this software
without specific prior written permission.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO,
THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
ARE DISCLAIMED.
IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT,
INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
package com.amihaiemil.eva.backpack;
/**
* Tests for {@link FitnessForBackpack}
* @author Mihai Andronache (amihaiemil@gmail.com)
*/
public class FitnessForBackpackTestCase {
/**
* The Fitness can tell if it's ok or not.
*/
@Test
public void isFitnessOkOrNot() { | Fitness fitness = new FitnessForBackpack(56, 100); |
decorators-squad/eva | src/test/java/com/amihaiemil/eva/backpack/FitnessForBackpackTestCase.java | // Path: src/main/java/com/amihaiemil/eva/Fitness.java
// public interface Fitness extends Comparable<Fitness>{
// /**
// * Indicates whether this fitness is OK.
// * E.g. If it is not OK, then it's not even worth comparing it to others, since
// * we know that a solution with this fitness is not good.
// * @return true if this fitness is considered OK, or false otherwise.
// */
// boolean isOk();
// }
//
// Path: src/main/java/com/amihaiemil/eva/backpack/FitnessForBackpack.java
// public final class FitnessForBackpack implements Fitness{
// private long backpackCapacity;
// private long solutionWeight;
// FitnessForBackpack(long weight, long backpackCapacity) {
// this.backpackCapacity = backpackCapacity;
// this.solutionWeight = weight;
// }
//
// public long getWeight() {
// return this.solutionWeight;
// }
// public long getSolutionWeight() {
// return this.solutionWeight;
// }
//
// public boolean isOk() {
// return solutionWeight > 0 && solutionWeight <= backpackCapacity;
// }
//
// public int compareTo(Fitness o) {
// FitnessForBackpack other = (FitnessForBackpack) o;
// if(this.solutionWeight > other.getSolutionWeight()) {
// return -1;
// }
// if(this.solutionWeight == other.getSolutionWeight()) {
// return 0;
// }
// return 1;
// }
// }
| import org.junit.Test;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertTrue;
import com.amihaiemil.eva.Fitness;
import com.amihaiemil.eva.backpack.FitnessForBackpack; | /*
Copyright (c) 2016, Mihai-Emil Andronache
All rights reserved.
Redistribution and use in source and binary forms, with or without modification,
are permitted provided that the following conditions are met:
1. Redistributions of source code must retain the above copyright notice,
this list of conditions and the following disclaimer.
2. Redistributions in binary form must reproduce the above copyright notice,
this list of conditions and the following disclaimer in the documentation
and/or other materials provided with the distribution.
3. Neither the name of the copyright holder nor the names of its contributors
may be used to endorse or promote products derived from this software
without specific prior written permission.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO,
THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
ARE DISCLAIMED.
IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT,
INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
package com.amihaiemil.eva.backpack;
/**
* Tests for {@link FitnessForBackpack}
* @author Mihai Andronache (amihaiemil@gmail.com)
*/
public class FitnessForBackpackTestCase {
/**
* The Fitness can tell if it's ok or not.
*/
@Test
public void isFitnessOkOrNot() { | // Path: src/main/java/com/amihaiemil/eva/Fitness.java
// public interface Fitness extends Comparable<Fitness>{
// /**
// * Indicates whether this fitness is OK.
// * E.g. If it is not OK, then it's not even worth comparing it to others, since
// * we know that a solution with this fitness is not good.
// * @return true if this fitness is considered OK, or false otherwise.
// */
// boolean isOk();
// }
//
// Path: src/main/java/com/amihaiemil/eva/backpack/FitnessForBackpack.java
// public final class FitnessForBackpack implements Fitness{
// private long backpackCapacity;
// private long solutionWeight;
// FitnessForBackpack(long weight, long backpackCapacity) {
// this.backpackCapacity = backpackCapacity;
// this.solutionWeight = weight;
// }
//
// public long getWeight() {
// return this.solutionWeight;
// }
// public long getSolutionWeight() {
// return this.solutionWeight;
// }
//
// public boolean isOk() {
// return solutionWeight > 0 && solutionWeight <= backpackCapacity;
// }
//
// public int compareTo(Fitness o) {
// FitnessForBackpack other = (FitnessForBackpack) o;
// if(this.solutionWeight > other.getSolutionWeight()) {
// return -1;
// }
// if(this.solutionWeight == other.getSolutionWeight()) {
// return 0;
// }
// return 1;
// }
// }
// Path: src/test/java/com/amihaiemil/eva/backpack/FitnessForBackpackTestCase.java
import org.junit.Test;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertTrue;
import com.amihaiemil.eva.Fitness;
import com.amihaiemil.eva.backpack.FitnessForBackpack;
/*
Copyright (c) 2016, Mihai-Emil Andronache
All rights reserved.
Redistribution and use in source and binary forms, with or without modification,
are permitted provided that the following conditions are met:
1. Redistributions of source code must retain the above copyright notice,
this list of conditions and the following disclaimer.
2. Redistributions in binary form must reproduce the above copyright notice,
this list of conditions and the following disclaimer in the documentation
and/or other materials provided with the distribution.
3. Neither the name of the copyright holder nor the names of its contributors
may be used to endorse or promote products derived from this software
without specific prior written permission.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO,
THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
ARE DISCLAIMED.
IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT,
INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
package com.amihaiemil.eva.backpack;
/**
* Tests for {@link FitnessForBackpack}
* @author Mihai Andronache (amihaiemil@gmail.com)
*/
public class FitnessForBackpackTestCase {
/**
* The Fitness can tell if it's ok or not.
*/
@Test
public void isFitnessOkOrNot() { | Fitness fitness = new FitnessForBackpack(56, 100); |
decorators-squad/eva | src/test/java/com/amihaiemil/eva/util/BinaryArraySolutionTestCase.java | // Path: src/main/java/com/amihaiemil/eva/Solution.java
// public abstract class Solution {
//
// /**
// * Fitness of this solution. How good it is (how fit) in comparison to other solutions.
// */
// private Fitness fitness;
//
// /**
// * Representation of this solution.
// */
// private Representation representation;
//
// /**
// * Each solution should have a comparable fitness that makes it better or worse than other solutions.
// * @return The Fitness of this solution.
// */
// public Fitness getFitness() {
// return this.fitness;
// }
//
// /**
// * Set the fitness of this solution.
// * @param fitness The set fitness of this solution.
// */
// public void setFitness(Fitness fitness) {
// this.fitness = fitness;
// }
//
// /**
// * Each solution should have a representation.
// * @return The representation of this solution.
// */
// public Representation getRepresentation() {
// return this.representation;
// }
//
// public void setRepresentation(Representation rep) {
// this.representation = rep;
// }
//
// /**
// * Mutate (change) this solution's representation with regards to pm - possibility of mutation.
// * @param pm A random chosen double (0 < pm < 1) that should give the random element in this solution's mutation.
// */
// public abstract void mutate(double pm);
//
// /**
// * Crossover this solution with the given partner.
// * In other words, create a new solution with data taken from both this solution and the partner.
// * @param partner Another solution.
// * @param cp Crossover probability.
// * @return The newly created solution.
// */
// public abstract Solution crossover(Solution partner, double cp);
//
// /**
// * A solution is acceptable if its fitness is ok.
// * @return true if acceptable, false otherwise.
// */
// public boolean isAcceptable() {
// return this.fitness.isOk();
// }
// }
| import java.util.Arrays;
import java.util.Random;
import static org.junit.Assert.assertTrue;
import com.amihaiemil.eva.Solution;
import org.junit.Test;
import org.mockito.Mockito; | /*
Copyright (c) 2016, Mihai-Emil Andronache
All rights reserved.
Redistribution and use in source and binary forms, with or without modification,
are permitted provided that the following conditions are met:
1. Redistributions of source code must retain the above copyright notice,
this list of conditions and the following disclaimer.
2. Redistributions in binary form must reproduce the above copyright notice,
this list of conditions and the following disclaimer in the documentation
and/or other materials provided with the distribution.
3. Neither the name of the copyright holder nor the names of its contributors
may be used to endorse or promote products derived from this software
without specific prior written permission.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO,
THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
ARE DISCLAIMED.
IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT,
INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
package com.amihaiemil.eva.util;
/**
* Tests for {@link BinaryArraySolution}.
* @author Mihai Andronache (amihaiemil@gmail.com)
*/
public class BinaryArraySolutionTestCase {
/**
* BinaryArraySolution can mutate.
*/
@Test
public void solutionMutates() {
Random mockChance = Mockito.mock(Random.class);
Mockito.when(mockChance.nextDouble()).thenReturn(0.3);
| // Path: src/main/java/com/amihaiemil/eva/Solution.java
// public abstract class Solution {
//
// /**
// * Fitness of this solution. How good it is (how fit) in comparison to other solutions.
// */
// private Fitness fitness;
//
// /**
// * Representation of this solution.
// */
// private Representation representation;
//
// /**
// * Each solution should have a comparable fitness that makes it better or worse than other solutions.
// * @return The Fitness of this solution.
// */
// public Fitness getFitness() {
// return this.fitness;
// }
//
// /**
// * Set the fitness of this solution.
// * @param fitness The set fitness of this solution.
// */
// public void setFitness(Fitness fitness) {
// this.fitness = fitness;
// }
//
// /**
// * Each solution should have a representation.
// * @return The representation of this solution.
// */
// public Representation getRepresentation() {
// return this.representation;
// }
//
// public void setRepresentation(Representation rep) {
// this.representation = rep;
// }
//
// /**
// * Mutate (change) this solution's representation with regards to pm - possibility of mutation.
// * @param pm A random chosen double (0 < pm < 1) that should give the random element in this solution's mutation.
// */
// public abstract void mutate(double pm);
//
// /**
// * Crossover this solution with the given partner.
// * In other words, create a new solution with data taken from both this solution and the partner.
// * @param partner Another solution.
// * @param cp Crossover probability.
// * @return The newly created solution.
// */
// public abstract Solution crossover(Solution partner, double cp);
//
// /**
// * A solution is acceptable if its fitness is ok.
// * @return true if acceptable, false otherwise.
// */
// public boolean isAcceptable() {
// return this.fitness.isOk();
// }
// }
// Path: src/test/java/com/amihaiemil/eva/util/BinaryArraySolutionTestCase.java
import java.util.Arrays;
import java.util.Random;
import static org.junit.Assert.assertTrue;
import com.amihaiemil.eva.Solution;
import org.junit.Test;
import org.mockito.Mockito;
/*
Copyright (c) 2016, Mihai-Emil Andronache
All rights reserved.
Redistribution and use in source and binary forms, with or without modification,
are permitted provided that the following conditions are met:
1. Redistributions of source code must retain the above copyright notice,
this list of conditions and the following disclaimer.
2. Redistributions in binary form must reproduce the above copyright notice,
this list of conditions and the following disclaimer in the documentation
and/or other materials provided with the distribution.
3. Neither the name of the copyright holder nor the names of its contributors
may be used to endorse or promote products derived from this software
without specific prior written permission.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO,
THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
ARE DISCLAIMED.
IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT,
INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
package com.amihaiemil.eva.util;
/**
* Tests for {@link BinaryArraySolution}.
* @author Mihai Andronache (amihaiemil@gmail.com)
*/
public class BinaryArraySolutionTestCase {
/**
* BinaryArraySolution can mutate.
*/
@Test
public void solutionMutates() {
Random mockChance = Mockito.mock(Random.class);
Mockito.when(mockChance.nextDouble()).thenReturn(0.3);
| Solution testSolution = new BinaryArraySolution(mockChance); |
decorators-squad/eva | src/main/java/com/amihaiemil/eva/util/BinaryArraySolutionsGenerator.java | // Path: src/main/java/com/amihaiemil/eva/Solution.java
// public abstract class Solution {
//
// /**
// * Fitness of this solution. How good it is (how fit) in comparison to other solutions.
// */
// private Fitness fitness;
//
// /**
// * Representation of this solution.
// */
// private Representation representation;
//
// /**
// * Each solution should have a comparable fitness that makes it better or worse than other solutions.
// * @return The Fitness of this solution.
// */
// public Fitness getFitness() {
// return this.fitness;
// }
//
// /**
// * Set the fitness of this solution.
// * @param fitness The set fitness of this solution.
// */
// public void setFitness(Fitness fitness) {
// this.fitness = fitness;
// }
//
// /**
// * Each solution should have a representation.
// * @return The representation of this solution.
// */
// public Representation getRepresentation() {
// return this.representation;
// }
//
// public void setRepresentation(Representation rep) {
// this.representation = rep;
// }
//
// /**
// * Mutate (change) this solution's representation with regards to pm - possibility of mutation.
// * @param pm A random chosen double (0 < pm < 1) that should give the random element in this solution's mutation.
// */
// public abstract void mutate(double pm);
//
// /**
// * Crossover this solution with the given partner.
// * In other words, create a new solution with data taken from both this solution and the partner.
// * @param partner Another solution.
// * @param cp Crossover probability.
// * @return The newly created solution.
// */
// public abstract Solution crossover(Solution partner, double cp);
//
// /**
// * A solution is acceptable if its fitness is ok.
// * @return true if acceptable, false otherwise.
// */
// public boolean isAcceptable() {
// return this.fitness.isOk();
// }
// }
//
// Path: src/main/java/com/amihaiemil/eva/SolutionsGenerator.java
// public interface SolutionsGenerator {
//
// /**
// * Generate a possible solution. Make sure this method does return a random solution every time.
// * @return A possible solution to the problem.
// */
// Solution generateRandomSolution();
// }
| import java.util.Random;
import com.amihaiemil.eva.Solution;
import com.amihaiemil.eva.SolutionsGenerator; | /*
Copyright (c) 2016, Mihai-Emil Andronache
All rights reserved.
Redistribution and use in source and binary forms, with or without modification,
are permitted provided that the following conditions are met:
1. Redistributions of source code must retain the above copyright notice,
this list of conditions and the following disclaimer.
2. Redistributions in binary form must reproduce the above copyright notice,
this list of conditions and the following disclaimer in the documentation
and/or other materials provided with the distribution.
3. Neither the name of the copyright holder nor the names of its contributors
may be used to endorse or promote products derived from this software
without specific prior written permission.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO,
THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
ARE DISCLAIMED.
IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT,
INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
package com.amihaiemil.eva.util;
/**
* The algorithm starts off by generating a number of possible
* solutions for the problem.
* @author Mihai Andronache (amihaiemil@gmail.com)
*/
public class BinaryArraySolutionsGenerator implements SolutionsGenerator {
/**
* Size of the representation array.
*/
private int size;
private Random r = new Random();
public BinaryArraySolutionsGenerator(int size) {
this.size = size;
} | // Path: src/main/java/com/amihaiemil/eva/Solution.java
// public abstract class Solution {
//
// /**
// * Fitness of this solution. How good it is (how fit) in comparison to other solutions.
// */
// private Fitness fitness;
//
// /**
// * Representation of this solution.
// */
// private Representation representation;
//
// /**
// * Each solution should have a comparable fitness that makes it better or worse than other solutions.
// * @return The Fitness of this solution.
// */
// public Fitness getFitness() {
// return this.fitness;
// }
//
// /**
// * Set the fitness of this solution.
// * @param fitness The set fitness of this solution.
// */
// public void setFitness(Fitness fitness) {
// this.fitness = fitness;
// }
//
// /**
// * Each solution should have a representation.
// * @return The representation of this solution.
// */
// public Representation getRepresentation() {
// return this.representation;
// }
//
// public void setRepresentation(Representation rep) {
// this.representation = rep;
// }
//
// /**
// * Mutate (change) this solution's representation with regards to pm - possibility of mutation.
// * @param pm A random chosen double (0 < pm < 1) that should give the random element in this solution's mutation.
// */
// public abstract void mutate(double pm);
//
// /**
// * Crossover this solution with the given partner.
// * In other words, create a new solution with data taken from both this solution and the partner.
// * @param partner Another solution.
// * @param cp Crossover probability.
// * @return The newly created solution.
// */
// public abstract Solution crossover(Solution partner, double cp);
//
// /**
// * A solution is acceptable if its fitness is ok.
// * @return true if acceptable, false otherwise.
// */
// public boolean isAcceptable() {
// return this.fitness.isOk();
// }
// }
//
// Path: src/main/java/com/amihaiemil/eva/SolutionsGenerator.java
// public interface SolutionsGenerator {
//
// /**
// * Generate a possible solution. Make sure this method does return a random solution every time.
// * @return A possible solution to the problem.
// */
// Solution generateRandomSolution();
// }
// Path: src/main/java/com/amihaiemil/eva/util/BinaryArraySolutionsGenerator.java
import java.util.Random;
import com.amihaiemil.eva.Solution;
import com.amihaiemil.eva.SolutionsGenerator;
/*
Copyright (c) 2016, Mihai-Emil Andronache
All rights reserved.
Redistribution and use in source and binary forms, with or without modification,
are permitted provided that the following conditions are met:
1. Redistributions of source code must retain the above copyright notice,
this list of conditions and the following disclaimer.
2. Redistributions in binary form must reproduce the above copyright notice,
this list of conditions and the following disclaimer in the documentation
and/or other materials provided with the distribution.
3. Neither the name of the copyright holder nor the names of its contributors
may be used to endorse or promote products derived from this software
without specific prior written permission.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO,
THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
ARE DISCLAIMED.
IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT,
INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
package com.amihaiemil.eva.util;
/**
* The algorithm starts off by generating a number of possible
* solutions for the problem.
* @author Mihai Andronache (amihaiemil@gmail.com)
*/
public class BinaryArraySolutionsGenerator implements SolutionsGenerator {
/**
* Size of the representation array.
*/
private int size;
private Random r = new Random();
public BinaryArraySolutionsGenerator(int size) {
this.size = size;
} | public Solution generateRandomSolution() { |
decorators-squad/eva | src/test/java/com/amihaiemil/eva/SolutionsTestCase.java | // Path: src/main/java/com/amihaiemil/eva/util/BinaryArraySolution.java
// public class BinaryArraySolution extends Solution {
// private Random chance;
//
// public BinaryArraySolution() {
// this.chance = new Random();
// }
//
// public BinaryArraySolution(NumericalRepresentation representation) {
// this.chance = new Random();
// for(int i=0;i<representation.getSize();i++) {
// if(representation.get(i) != 0 && representation.get(i) != 1) {
// throw new IllegalArgumentException(
// "Expected a numerical representation with 0s and 1s only!"
// );
// }
// }
// this.setRepresentation(representation);
// }
//
// public BinaryArraySolution(Random chance) {
// this.chance = chance;
// }
//
// @Override
// public void mutate(double pm) {
// NumericalRepresentation representation = (NumericalRepresentation) this.getRepresentation();
// for(int i=0;i<representation.getSize();i++) {
// if(chance.nextDouble() < pm) {
// representation = representation.replaceAt(i, 1-representation.get(i));
// }
// }
// this.setRepresentation(representation);
// }
//
// @Override
// public Solution crossover(Solution partner, double cp) {
// if(chance.nextDouble() < cp) { //parents have an offspring
// NumericalRepresentation representation = (NumericalRepresentation) this.getRepresentation();
// NumericalRepresentation partnerRepresentation = (NumericalRepresentation) partner.getRepresentation();
//
// Solution offspring = new BinaryArraySolution(new Random());
// NumericalRepresentation offSpringRepresentation = new NumericalRepresentation();
// int point = chance.nextInt(representation.getSize());
// for(int i=0;i<point;i++) {
// offSpringRepresentation = offSpringRepresentation.addNumber(representation.get(i));
// }
// for(int i=point;i<representation.getSize();i++) {
// offSpringRepresentation = offSpringRepresentation.addNumber(partnerRepresentation.get(i));
// }
// offspring.setRepresentation(offSpringRepresentation);
// return offspring;
// } else { //no offspring, return best parent.
// if(this.getFitness().compareTo(partner.getFitness()) == 1) {
// return this;
// }
// return partner;
// }
//
// }
//
// }
| import java.util.Collection;
import org.junit.Before;
import org.junit.Test;
import org.mockito.Mockito;
import com.amihaiemil.eva.util.BinaryArraySolution;
import static org.junit.Assert.assertTrue; | /*
Copyright (c) 2016, Mihai-Emil Andronache
All rights reserved.
Redistribution and use in source and binary forms, with or without modification,
are permitted provided that the following conditions are met:
1. Redistributions of source code must retain the above copyright notice,
this list of conditions and the following disclaimer.
2. Redistributions in binary form must reproduce the above copyright notice,
this list of conditions and the following disclaimer in the documentation
and/or other materials provided with the distribution.
3. Neither the name of the copyright holder nor the names of its contributors
may be used to endorse or promote products derived from this software
without specific prior written permission.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO,
THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
ARE DISCLAIMED.
IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT,
INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
package com.amihaiemil.eva;
/**
* Test cases for {@link Solutions}
* @author Mihai Andronache (amihaiemil@gmail.com)
*/
public class SolutionsTestCase {
/**
* Population under test.
*/
private Solutions popUt;
@Before
public void setup() {
SolutionsGenerator generator = Mockito.mock(SolutionsGenerator.class);
FitnessEvaluator evaluator = Mockito.mock(FitnessEvaluator.class);
| // Path: src/main/java/com/amihaiemil/eva/util/BinaryArraySolution.java
// public class BinaryArraySolution extends Solution {
// private Random chance;
//
// public BinaryArraySolution() {
// this.chance = new Random();
// }
//
// public BinaryArraySolution(NumericalRepresentation representation) {
// this.chance = new Random();
// for(int i=0;i<representation.getSize();i++) {
// if(representation.get(i) != 0 && representation.get(i) != 1) {
// throw new IllegalArgumentException(
// "Expected a numerical representation with 0s and 1s only!"
// );
// }
// }
// this.setRepresentation(representation);
// }
//
// public BinaryArraySolution(Random chance) {
// this.chance = chance;
// }
//
// @Override
// public void mutate(double pm) {
// NumericalRepresentation representation = (NumericalRepresentation) this.getRepresentation();
// for(int i=0;i<representation.getSize();i++) {
// if(chance.nextDouble() < pm) {
// representation = representation.replaceAt(i, 1-representation.get(i));
// }
// }
// this.setRepresentation(representation);
// }
//
// @Override
// public Solution crossover(Solution partner, double cp) {
// if(chance.nextDouble() < cp) { //parents have an offspring
// NumericalRepresentation representation = (NumericalRepresentation) this.getRepresentation();
// NumericalRepresentation partnerRepresentation = (NumericalRepresentation) partner.getRepresentation();
//
// Solution offspring = new BinaryArraySolution(new Random());
// NumericalRepresentation offSpringRepresentation = new NumericalRepresentation();
// int point = chance.nextInt(representation.getSize());
// for(int i=0;i<point;i++) {
// offSpringRepresentation = offSpringRepresentation.addNumber(representation.get(i));
// }
// for(int i=point;i<representation.getSize();i++) {
// offSpringRepresentation = offSpringRepresentation.addNumber(partnerRepresentation.get(i));
// }
// offspring.setRepresentation(offSpringRepresentation);
// return offspring;
// } else { //no offspring, return best parent.
// if(this.getFitness().compareTo(partner.getFitness()) == 1) {
// return this;
// }
// return partner;
// }
//
// }
//
// }
// Path: src/test/java/com/amihaiemil/eva/SolutionsTestCase.java
import java.util.Collection;
import org.junit.Before;
import org.junit.Test;
import org.mockito.Mockito;
import com.amihaiemil.eva.util.BinaryArraySolution;
import static org.junit.Assert.assertTrue;
/*
Copyright (c) 2016, Mihai-Emil Andronache
All rights reserved.
Redistribution and use in source and binary forms, with or without modification,
are permitted provided that the following conditions are met:
1. Redistributions of source code must retain the above copyright notice,
this list of conditions and the following disclaimer.
2. Redistributions in binary form must reproduce the above copyright notice,
this list of conditions and the following disclaimer in the documentation
and/or other materials provided with the distribution.
3. Neither the name of the copyright holder nor the names of its contributors
may be used to endorse or promote products derived from this software
without specific prior written permission.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO,
THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
ARE DISCLAIMED.
IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT,
INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
package com.amihaiemil.eva;
/**
* Test cases for {@link Solutions}
* @author Mihai Andronache (amihaiemil@gmail.com)
*/
public class SolutionsTestCase {
/**
* Population under test.
*/
private Solutions popUt;
@Before
public void setup() {
SolutionsGenerator generator = Mockito.mock(SolutionsGenerator.class);
FitnessEvaluator evaluator = Mockito.mock(FitnessEvaluator.class);
| Solution solution = Mockito.spy(new BinaryArraySolution()); |
Pokechu22/WorldDownloader-Serverside-Companion | src/main/java/wdl/request/PermissionRequest.java | // Path: src/main/java/wdl/range/ProtectionRange.java
// public final class ProtectionRange {
// public ProtectionRange(String tag, int x1, int z1, int x2, int z2) {
// if (tag == null) {
// tag = "";
// }
// this.tag = tag;
// this.x1 = x1;
// this.z1 = z1;
// this.x2 = x2;
// this.z2 = z2;
// }
//
// /**
// * "Tag" for this chunk. Multiple {@link ProtectionRange}s can share the
// * same tag; this is used to identify sub groups. May be empty. If null
// * is passed to the constructor for tag, an empty string is used instead.
// */
// public final String tag;
// /**
// * Range of coordinates. If x1 is greater than x2, they will be swapped
// * (and the same for y). These are chunk coordinates.
// */
// public final int x1, z1, x2, z2;
//
// @Override
// public String toString() {
// return "Chunks from (" + x1 + ", " + z1 + ") to (" + x2 + ", " + z2
// + ") (tagged " + tag + ")";
// }
// }
| import java.util.List;
import java.util.Map;
import java.util.UUID;
import org.bukkit.ChatColor;
import org.bukkit.entity.Player;
import org.bukkit.scheduler.BukkitTask;
import com.google.common.collect.ImmutableList;
import com.google.common.collect.ImmutableMap;
import wdl.range.ProtectionRange;
| package wdl.request;
/**
* Represents a single request.
*/
public class PermissionRequest {
/**
* Different states a request can be in.
*/
public static enum State {
/**
* The request is waiting on moderator action.
*/
WAITING(ChatColor.YELLOW),
/**
* The request has been accepted and the player granted the right permissions.
*/
ACCEPTED(ChatColor.GREEN),
/**
* The request has been rejected by a moderator.
*/
REJECTED(ChatColor.RED),
/**
* The request has been withdrawn by the submitting player (either
* directly or by creating a new request).
*/
WITHDRAWN(ChatColor.GRAY, ChatColor.ITALIC, ChatColor.STRIKETHROUGH),
/**
* The request has been revoked by a moderator after previously being
* accepted.
*/
REVOKED(ChatColor.GRAY, ChatColor.STRIKETHROUGH),
/**
* The request was accepted and has expired after being used.
*/
EXPIRED(ChatColor.GRAY, ChatColor.ITALIC);
public final String prefix;
private State(ChatColor... colors) {
StringBuilder builder = new StringBuilder();
for (ChatColor color : colors) {
builder.append(color);
}
prefix = builder.toString();
}
}
/**
* Current state of this permission request.
*/
public State state;
/**
* Unique ID of the requesting player.
*/
public final UUID playerId;
/**
* Name of the requesting player.
*/
public final String playerName;
/**
* The reason for the request from the given player.
*/
public final String requestReason;
/**
* The permissions that were requested.
*/
public final Map<String, String> requestedPerms;
/**
* The ranges that were requested.
*/
| // Path: src/main/java/wdl/range/ProtectionRange.java
// public final class ProtectionRange {
// public ProtectionRange(String tag, int x1, int z1, int x2, int z2) {
// if (tag == null) {
// tag = "";
// }
// this.tag = tag;
// this.x1 = x1;
// this.z1 = z1;
// this.x2 = x2;
// this.z2 = z2;
// }
//
// /**
// * "Tag" for this chunk. Multiple {@link ProtectionRange}s can share the
// * same tag; this is used to identify sub groups. May be empty. If null
// * is passed to the constructor for tag, an empty string is used instead.
// */
// public final String tag;
// /**
// * Range of coordinates. If x1 is greater than x2, they will be swapped
// * (and the same for y). These are chunk coordinates.
// */
// public final int x1, z1, x2, z2;
//
// @Override
// public String toString() {
// return "Chunks from (" + x1 + ", " + z1 + ") to (" + x2 + ", " + z2
// + ") (tagged " + tag + ")";
// }
// }
// Path: src/main/java/wdl/request/PermissionRequest.java
import java.util.List;
import java.util.Map;
import java.util.UUID;
import org.bukkit.ChatColor;
import org.bukkit.entity.Player;
import org.bukkit.scheduler.BukkitTask;
import com.google.common.collect.ImmutableList;
import com.google.common.collect.ImmutableMap;
import wdl.range.ProtectionRange;
package wdl.request;
/**
* Represents a single request.
*/
public class PermissionRequest {
/**
* Different states a request can be in.
*/
public static enum State {
/**
* The request is waiting on moderator action.
*/
WAITING(ChatColor.YELLOW),
/**
* The request has been accepted and the player granted the right permissions.
*/
ACCEPTED(ChatColor.GREEN),
/**
* The request has been rejected by a moderator.
*/
REJECTED(ChatColor.RED),
/**
* The request has been withdrawn by the submitting player (either
* directly or by creating a new request).
*/
WITHDRAWN(ChatColor.GRAY, ChatColor.ITALIC, ChatColor.STRIKETHROUGH),
/**
* The request has been revoked by a moderator after previously being
* accepted.
*/
REVOKED(ChatColor.GRAY, ChatColor.STRIKETHROUGH),
/**
* The request was accepted and has expired after being used.
*/
EXPIRED(ChatColor.GRAY, ChatColor.ITALIC);
public final String prefix;
private State(ChatColor... colors) {
StringBuilder builder = new StringBuilder();
for (ChatColor color : colors) {
builder.append(color);
}
prefix = builder.toString();
}
}
/**
* Current state of this permission request.
*/
public State state;
/**
* Unique ID of the requesting player.
*/
public final UUID playerId;
/**
* Name of the requesting player.
*/
public final String playerName;
/**
* The reason for the request from the given player.
*/
public final String requestReason;
/**
* The permissions that were requested.
*/
public final Map<String, String> requestedPerms;
/**
* The ranges that were requested.
*/
| public final List<ProtectionRange> rangeRequests;
|
Pokechu22/WorldDownloader-Serverside-Companion | src/main/java/wdl/WDLPackets.java | // Path: src/main/java/wdl/range/ProtectionRange.java
// public final class ProtectionRange {
// public ProtectionRange(String tag, int x1, int z1, int x2, int z2) {
// if (tag == null) {
// tag = "";
// }
// this.tag = tag;
// this.x1 = x1;
// this.z1 = z1;
// this.x2 = x2;
// this.z2 = z2;
// }
//
// /**
// * "Tag" for this chunk. Multiple {@link ProtectionRange}s can share the
// * same tag; this is used to identify sub groups. May be empty. If null
// * is passed to the constructor for tag, an empty string is used instead.
// */
// public final String tag;
// /**
// * Range of coordinates. If x1 is greater than x2, they will be swapped
// * (and the same for y). These are chunk coordinates.
// */
// public final int x1, z1, x2, z2;
//
// @Override
// public String toString() {
// return "Chunks from (" + x1 + ", " + z1 + ") to (" + x2 + ", " + z2
// + ") (tagged " + tag + ")";
// }
// }
//
// Path: src/main/java/wdl/request/PermissionRequest.java
// public class PermissionRequest {
// /**
// * Different states a request can be in.
// */
// public static enum State {
// /**
// * The request is waiting on moderator action.
// */
// WAITING(ChatColor.YELLOW),
// /**
// * The request has been accepted and the player granted the right permissions.
// */
// ACCEPTED(ChatColor.GREEN),
// /**
// * The request has been rejected by a moderator.
// */
// REJECTED(ChatColor.RED),
// /**
// * The request has been withdrawn by the submitting player (either
// * directly or by creating a new request).
// */
// WITHDRAWN(ChatColor.GRAY, ChatColor.ITALIC, ChatColor.STRIKETHROUGH),
// /**
// * The request has been revoked by a moderator after previously being
// * accepted.
// */
// REVOKED(ChatColor.GRAY, ChatColor.STRIKETHROUGH),
// /**
// * The request was accepted and has expired after being used.
// */
// EXPIRED(ChatColor.GRAY, ChatColor.ITALIC);
//
// public final String prefix;
//
// private State(ChatColor... colors) {
// StringBuilder builder = new StringBuilder();
// for (ChatColor color : colors) {
// builder.append(color);
// }
// prefix = builder.toString();
// }
// }
//
// /**
// * Current state of this permission request.
// */
// public State state;
// /**
// * Unique ID of the requesting player.
// */
// public final UUID playerId;
// /**
// * Name of the requesting player.
// */
// public final String playerName;
// /**
// * The reason for the request from the given player.
// */
// public final String requestReason;
// /**
// * The permissions that were requested.
// */
// public final Map<String, String> requestedPerms;
// /**
// * The ranges that were requested.
// */
// public final List<ProtectionRange> rangeRequests;
// /**
// * The time at which this request expires (in the format returned by
// * {@link System#currentTimeMillis()}).
// */
// public long expirationTime;
// /**
// * {@link BukkitTask} used to mark this request as expired.
// */
// public BukkitTask expireTask;
//
// public PermissionRequest(Player player, String requestReason,
// Map<String, String> requestedPerms,
// List<ProtectionRange> rangeRequests) {
// this.state = State.WAITING;
//
// this.playerId = player.getUniqueId();
// this.playerName = player.getName();
// this.requestReason = requestReason;
// this.requestedPerms = ImmutableMap.copyOf(requestedPerms);
// this.rangeRequests = ImmutableList.copyOf(rangeRequests);
// }
//
// @Override
// public String toString() {
// return playerName + ": " + requestedPerms.size() + " perm(s), " + rangeRequests.size() + " range(s)";
// }
// }
| import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import org.bukkit.entity.Player;
import wdl.range.ProtectionRange;
import wdl.request.PermissionRequest;
import com.google.common.io.ByteArrayDataInput;
import com.google.common.io.ByteArrayDataOutput;
import com.google.common.io.ByteStreams;
| *
* This packet replaces all of the ranges with the given tag with a new set
* of ranges.
*
* This packet starts with a String stating the group, then a second string
* that specifies the tag to replace. After that, there is an int stating
* the number of ranges, and then each range as formated by
* {@link #writeProtectionRange(ProtectionRange, ByteArrayDataOutput)}.
*/
public static byte[] createWDLPacket7(String group,
String tag, List<ProtectionRange> newRanges) {
ByteArrayDataOutput output = ByteStreams.newDataOutput();
output.writeInt(7);
output.writeUTF(group);
output.writeUTF(tag);
output.writeInt(newRanges.size());
for (ProtectionRange range : newRanges) {
writeProtectionRange(range, output);
}
return output.toByteArray();
}
/**
* Reads a permission request.
*/
| // Path: src/main/java/wdl/range/ProtectionRange.java
// public final class ProtectionRange {
// public ProtectionRange(String tag, int x1, int z1, int x2, int z2) {
// if (tag == null) {
// tag = "";
// }
// this.tag = tag;
// this.x1 = x1;
// this.z1 = z1;
// this.x2 = x2;
// this.z2 = z2;
// }
//
// /**
// * "Tag" for this chunk. Multiple {@link ProtectionRange}s can share the
// * same tag; this is used to identify sub groups. May be empty. If null
// * is passed to the constructor for tag, an empty string is used instead.
// */
// public final String tag;
// /**
// * Range of coordinates. If x1 is greater than x2, they will be swapped
// * (and the same for y). These are chunk coordinates.
// */
// public final int x1, z1, x2, z2;
//
// @Override
// public String toString() {
// return "Chunks from (" + x1 + ", " + z1 + ") to (" + x2 + ", " + z2
// + ") (tagged " + tag + ")";
// }
// }
//
// Path: src/main/java/wdl/request/PermissionRequest.java
// public class PermissionRequest {
// /**
// * Different states a request can be in.
// */
// public static enum State {
// /**
// * The request is waiting on moderator action.
// */
// WAITING(ChatColor.YELLOW),
// /**
// * The request has been accepted and the player granted the right permissions.
// */
// ACCEPTED(ChatColor.GREEN),
// /**
// * The request has been rejected by a moderator.
// */
// REJECTED(ChatColor.RED),
// /**
// * The request has been withdrawn by the submitting player (either
// * directly or by creating a new request).
// */
// WITHDRAWN(ChatColor.GRAY, ChatColor.ITALIC, ChatColor.STRIKETHROUGH),
// /**
// * The request has been revoked by a moderator after previously being
// * accepted.
// */
// REVOKED(ChatColor.GRAY, ChatColor.STRIKETHROUGH),
// /**
// * The request was accepted and has expired after being used.
// */
// EXPIRED(ChatColor.GRAY, ChatColor.ITALIC);
//
// public final String prefix;
//
// private State(ChatColor... colors) {
// StringBuilder builder = new StringBuilder();
// for (ChatColor color : colors) {
// builder.append(color);
// }
// prefix = builder.toString();
// }
// }
//
// /**
// * Current state of this permission request.
// */
// public State state;
// /**
// * Unique ID of the requesting player.
// */
// public final UUID playerId;
// /**
// * Name of the requesting player.
// */
// public final String playerName;
// /**
// * The reason for the request from the given player.
// */
// public final String requestReason;
// /**
// * The permissions that were requested.
// */
// public final Map<String, String> requestedPerms;
// /**
// * The ranges that were requested.
// */
// public final List<ProtectionRange> rangeRequests;
// /**
// * The time at which this request expires (in the format returned by
// * {@link System#currentTimeMillis()}).
// */
// public long expirationTime;
// /**
// * {@link BukkitTask} used to mark this request as expired.
// */
// public BukkitTask expireTask;
//
// public PermissionRequest(Player player, String requestReason,
// Map<String, String> requestedPerms,
// List<ProtectionRange> rangeRequests) {
// this.state = State.WAITING;
//
// this.playerId = player.getUniqueId();
// this.playerName = player.getName();
// this.requestReason = requestReason;
// this.requestedPerms = ImmutableMap.copyOf(requestedPerms);
// this.rangeRequests = ImmutableList.copyOf(rangeRequests);
// }
//
// @Override
// public String toString() {
// return playerName + ": " + requestedPerms.size() + " perm(s), " + rangeRequests.size() + " range(s)";
// }
// }
// Path: src/main/java/wdl/WDLPackets.java
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import org.bukkit.entity.Player;
import wdl.range.ProtectionRange;
import wdl.request.PermissionRequest;
import com.google.common.io.ByteArrayDataInput;
import com.google.common.io.ByteArrayDataOutput;
import com.google.common.io.ByteStreams;
*
* This packet replaces all of the ranges with the given tag with a new set
* of ranges.
*
* This packet starts with a String stating the group, then a second string
* that specifies the tag to replace. After that, there is an int stating
* the number of ranges, and then each range as formated by
* {@link #writeProtectionRange(ProtectionRange, ByteArrayDataOutput)}.
*/
public static byte[] createWDLPacket7(String group,
String tag, List<ProtectionRange> newRanges) {
ByteArrayDataOutput output = ByteStreams.newDataOutput();
output.writeInt(7);
output.writeUTF(group);
output.writeUTF(tag);
output.writeInt(newRanges.size());
for (ProtectionRange range : newRanges) {
writeProtectionRange(range, output);
}
return output.toByteArray();
}
/**
* Reads a permission request.
*/
| public static PermissionRequest readPermissionRequest(
|
Pokechu22/WorldDownloader-Serverside-Companion | src/main/java/wdl/PermissionHandler.java | // Path: src/main/java/wdl/request/PermissionRequest.java
// public class PermissionRequest {
// /**
// * Different states a request can be in.
// */
// public static enum State {
// /**
// * The request is waiting on moderator action.
// */
// WAITING(ChatColor.YELLOW),
// /**
// * The request has been accepted and the player granted the right permissions.
// */
// ACCEPTED(ChatColor.GREEN),
// /**
// * The request has been rejected by a moderator.
// */
// REJECTED(ChatColor.RED),
// /**
// * The request has been withdrawn by the submitting player (either
// * directly or by creating a new request).
// */
// WITHDRAWN(ChatColor.GRAY, ChatColor.ITALIC, ChatColor.STRIKETHROUGH),
// /**
// * The request has been revoked by a moderator after previously being
// * accepted.
// */
// REVOKED(ChatColor.GRAY, ChatColor.STRIKETHROUGH),
// /**
// * The request was accepted and has expired after being used.
// */
// EXPIRED(ChatColor.GRAY, ChatColor.ITALIC);
//
// public final String prefix;
//
// private State(ChatColor... colors) {
// StringBuilder builder = new StringBuilder();
// for (ChatColor color : colors) {
// builder.append(color);
// }
// prefix = builder.toString();
// }
// }
//
// /**
// * Current state of this permission request.
// */
// public State state;
// /**
// * Unique ID of the requesting player.
// */
// public final UUID playerId;
// /**
// * Name of the requesting player.
// */
// public final String playerName;
// /**
// * The reason for the request from the given player.
// */
// public final String requestReason;
// /**
// * The permissions that were requested.
// */
// public final Map<String, String> requestedPerms;
// /**
// * The ranges that were requested.
// */
// public final List<ProtectionRange> rangeRequests;
// /**
// * The time at which this request expires (in the format returned by
// * {@link System#currentTimeMillis()}).
// */
// public long expirationTime;
// /**
// * {@link BukkitTask} used to mark this request as expired.
// */
// public BukkitTask expireTask;
//
// public PermissionRequest(Player player, String requestReason,
// Map<String, String> requestedPerms,
// List<ProtectionRange> rangeRequests) {
// this.state = State.WAITING;
//
// this.playerId = player.getUniqueId();
// this.playerName = player.getName();
// this.requestReason = requestReason;
// this.requestedPerms = ImmutableMap.copyOf(requestedPerms);
// this.rangeRequests = ImmutableList.copyOf(rangeRequests);
// }
//
// @Override
// public String toString() {
// return playerName + ": " + requestedPerms.size() + " perm(s), " + rangeRequests.size() + " range(s)";
// }
// }
| import java.util.logging.Level;
import org.bukkit.entity.Player;
import wdl.request.PermissionRequest;
| }
// No request value for this.
return getPerworldBoolean(player, "canDoNewThings");
}
/**
* Should the given player receive entity range data?
*/
public boolean getSendEntityRanges(Player player) {
if (player.hasPermission("wdl.override.sendEntityRanges")) {
return true;
}
if (getRequestedBoolean(player, "getEntityRanges")) {
return true;
}
return getPerworldBoolean(player, "sendEntityRanges");
}
/**
* Gets the distance (in chunks) that the given player can download from
* themselves.
*
*/
public int getSaveRadius(Player player) {
if (player.hasPermission("wdl.override.maxSaveRadius")) {
return -1;
}
| // Path: src/main/java/wdl/request/PermissionRequest.java
// public class PermissionRequest {
// /**
// * Different states a request can be in.
// */
// public static enum State {
// /**
// * The request is waiting on moderator action.
// */
// WAITING(ChatColor.YELLOW),
// /**
// * The request has been accepted and the player granted the right permissions.
// */
// ACCEPTED(ChatColor.GREEN),
// /**
// * The request has been rejected by a moderator.
// */
// REJECTED(ChatColor.RED),
// /**
// * The request has been withdrawn by the submitting player (either
// * directly or by creating a new request).
// */
// WITHDRAWN(ChatColor.GRAY, ChatColor.ITALIC, ChatColor.STRIKETHROUGH),
// /**
// * The request has been revoked by a moderator after previously being
// * accepted.
// */
// REVOKED(ChatColor.GRAY, ChatColor.STRIKETHROUGH),
// /**
// * The request was accepted and has expired after being used.
// */
// EXPIRED(ChatColor.GRAY, ChatColor.ITALIC);
//
// public final String prefix;
//
// private State(ChatColor... colors) {
// StringBuilder builder = new StringBuilder();
// for (ChatColor color : colors) {
// builder.append(color);
// }
// prefix = builder.toString();
// }
// }
//
// /**
// * Current state of this permission request.
// */
// public State state;
// /**
// * Unique ID of the requesting player.
// */
// public final UUID playerId;
// /**
// * Name of the requesting player.
// */
// public final String playerName;
// /**
// * The reason for the request from the given player.
// */
// public final String requestReason;
// /**
// * The permissions that were requested.
// */
// public final Map<String, String> requestedPerms;
// /**
// * The ranges that were requested.
// */
// public final List<ProtectionRange> rangeRequests;
// /**
// * The time at which this request expires (in the format returned by
// * {@link System#currentTimeMillis()}).
// */
// public long expirationTime;
// /**
// * {@link BukkitTask} used to mark this request as expired.
// */
// public BukkitTask expireTask;
//
// public PermissionRequest(Player player, String requestReason,
// Map<String, String> requestedPerms,
// List<ProtectionRange> rangeRequests) {
// this.state = State.WAITING;
//
// this.playerId = player.getUniqueId();
// this.playerName = player.getName();
// this.requestReason = requestReason;
// this.requestedPerms = ImmutableMap.copyOf(requestedPerms);
// this.rangeRequests = ImmutableList.copyOf(rangeRequests);
// }
//
// @Override
// public String toString() {
// return playerName + ": " + requestedPerms.size() + " perm(s), " + rangeRequests.size() + " range(s)";
// }
// }
// Path: src/main/java/wdl/PermissionHandler.java
import java.util.logging.Level;
import org.bukkit.entity.Player;
import wdl.request.PermissionRequest;
}
// No request value for this.
return getPerworldBoolean(player, "canDoNewThings");
}
/**
* Should the given player receive entity range data?
*/
public boolean getSendEntityRanges(Player player) {
if (player.hasPermission("wdl.override.sendEntityRanges")) {
return true;
}
if (getRequestedBoolean(player, "getEntityRanges")) {
return true;
}
return getPerworldBoolean(player, "sendEntityRanges");
}
/**
* Gets the distance (in chunks) that the given player can download from
* themselves.
*
*/
public int getSaveRadius(Player player) {
if (player.hasPermission("wdl.override.maxSaveRadius")) {
return -1;
}
| PermissionRequest request = plugin.requestManager.getPlayerRequest(player);
|
Pokechu22/WorldDownloader-Serverside-Companion | src/main/java/wdl/RangeGroupTypeRegistrationEvent.java | // Path: src/main/java/wdl/range/IRangeGroupType.java
// public interface IRangeGroupType<T extends IRangeProducer> {
// /**
// * Validates that the given {@link ConfigurationSection} is acceptable.
// *
// * @param config
// * The config to check.
// * @param warnings
// * A list to put warnings into if if any occur.
// * @param errors
// * A list to put errors into if if any occur.
// * @return <code>false</code> if the configuration is fatally unacceptable
// * to the point where this {@link IRangeProducer} should not
// * use it. Note that other {@link ConfigurationSection}s may still
// * be used with this {@link IRangeProducer}.
// */
// public abstract boolean isValidConfig(ConfigurationSection config,
// List<String> warnings, List<String> errors);
//
// /**
// * Creates a new {@link IRangeProducer} from the given configuration
// * section. Will only be called if
// * {@link #isValidConfig(ConfigurationSection, List, List)} returned true.
// *
// * @param config
// * The config to check.
// */
// public abstract T createRangeProducer(
// IRangeGroup group, ConfigurationSection config);
//
// /**
// * Disposes of this {@link IRangeGroupType}. Events should be unregistered,
// * etc. Note that this should NOT dispose any created {@link IRangeProducer}s;
// * they will be handled manually.
// *
// * After this method has been called, this {@link IRangeGroupType} instance
// * will no longer be used. In most cases, a new instance will be created
// * (potentially with a different configuration).
// *
// * Note: To unregister all events in a {@link Listener}, you can call
// * {@link HandlerList#unregisterAll(Listener)}.
// */
// public abstract void dispose();
// }
| import org.bukkit.event.Event;
import org.bukkit.event.HandlerList;
import org.bukkit.plugin.AuthorNagException;
import wdl.range.IRangeGroupType;
| package wdl;
/**
* Event that is raised when {@link WDLCompanion} is ready to receive new
* {@link IRangeGroupType} registrations.
*/
public final class RangeGroupTypeRegistrationEvent extends Event {
private static final HandlerList handlers = new HandlerList();
private final WDLCompanion plugin;
/**
* Has the registration finished (and thus no more registrations should be
* allowed via this event?)
*/
private boolean finished = false;
RangeGroupTypeRegistrationEvent(WDLCompanion plugin) {
super(false);
this.plugin = plugin;
}
@Override
public HandlerList getHandlers() {
return handlers;
}
public static HandlerList getHandlerList() {
return handlers;
}
/**
* Registers a new {@link IRangeGroupType}, with the given name.
*
* @param id
* The ID to register under.
* @param rangeGroupType
* The {@link IRangeGroupType} to register.
* @throws IllegalArgumentException
* If there already is a registration for the given ID
* @throws IllegalArgumentException
* If either id or rangeProducer are null.
*/
| // Path: src/main/java/wdl/range/IRangeGroupType.java
// public interface IRangeGroupType<T extends IRangeProducer> {
// /**
// * Validates that the given {@link ConfigurationSection} is acceptable.
// *
// * @param config
// * The config to check.
// * @param warnings
// * A list to put warnings into if if any occur.
// * @param errors
// * A list to put errors into if if any occur.
// * @return <code>false</code> if the configuration is fatally unacceptable
// * to the point where this {@link IRangeProducer} should not
// * use it. Note that other {@link ConfigurationSection}s may still
// * be used with this {@link IRangeProducer}.
// */
// public abstract boolean isValidConfig(ConfigurationSection config,
// List<String> warnings, List<String> errors);
//
// /**
// * Creates a new {@link IRangeProducer} from the given configuration
// * section. Will only be called if
// * {@link #isValidConfig(ConfigurationSection, List, List)} returned true.
// *
// * @param config
// * The config to check.
// */
// public abstract T createRangeProducer(
// IRangeGroup group, ConfigurationSection config);
//
// /**
// * Disposes of this {@link IRangeGroupType}. Events should be unregistered,
// * etc. Note that this should NOT dispose any created {@link IRangeProducer}s;
// * they will be handled manually.
// *
// * After this method has been called, this {@link IRangeGroupType} instance
// * will no longer be used. In most cases, a new instance will be created
// * (potentially with a different configuration).
// *
// * Note: To unregister all events in a {@link Listener}, you can call
// * {@link HandlerList#unregisterAll(Listener)}.
// */
// public abstract void dispose();
// }
// Path: src/main/java/wdl/RangeGroupTypeRegistrationEvent.java
import org.bukkit.event.Event;
import org.bukkit.event.HandlerList;
import org.bukkit.plugin.AuthorNagException;
import wdl.range.IRangeGroupType;
package wdl;
/**
* Event that is raised when {@link WDLCompanion} is ready to receive new
* {@link IRangeGroupType} registrations.
*/
public final class RangeGroupTypeRegistrationEvent extends Event {
private static final HandlerList handlers = new HandlerList();
private final WDLCompanion plugin;
/**
* Has the registration finished (and thus no more registrations should be
* allowed via this event?)
*/
private boolean finished = false;
RangeGroupTypeRegistrationEvent(WDLCompanion plugin) {
super(false);
this.plugin = plugin;
}
@Override
public HandlerList getHandlers() {
return handlers;
}
public static HandlerList getHandlerList() {
return handlers;
}
/**
* Registers a new {@link IRangeGroupType}, with the given name.
*
* @param id
* The ID to register under.
* @param rangeGroupType
* The {@link IRangeGroupType} to register.
* @throws IllegalArgumentException
* If there already is a registration for the given ID
* @throws IllegalArgumentException
* If either id or rangeProducer are null.
*/
| public void addRegistration(String id, IRangeGroupType<?> rangeGroupType)
|
Pokechu22/WorldDownloader-Serverside-Companion | src/main/java/wdl/ConfigValidation.java | // Path: src/main/java/wdl/range/IRangeGroupType.java
// public interface IRangeGroupType<T extends IRangeProducer> {
// /**
// * Validates that the given {@link ConfigurationSection} is acceptable.
// *
// * @param config
// * The config to check.
// * @param warnings
// * A list to put warnings into if if any occur.
// * @param errors
// * A list to put errors into if if any occur.
// * @return <code>false</code> if the configuration is fatally unacceptable
// * to the point where this {@link IRangeProducer} should not
// * use it. Note that other {@link ConfigurationSection}s may still
// * be used with this {@link IRangeProducer}.
// */
// public abstract boolean isValidConfig(ConfigurationSection config,
// List<String> warnings, List<String> errors);
//
// /**
// * Creates a new {@link IRangeProducer} from the given configuration
// * section. Will only be called if
// * {@link #isValidConfig(ConfigurationSection, List, List)} returned true.
// *
// * @param config
// * The config to check.
// */
// public abstract T createRangeProducer(
// IRangeGroup group, ConfigurationSection config);
//
// /**
// * Disposes of this {@link IRangeGroupType}. Events should be unregistered,
// * etc. Note that this should NOT dispose any created {@link IRangeProducer}s;
// * they will be handled manually.
// *
// * After this method has been called, this {@link IRangeGroupType} instance
// * will no longer be used. In most cases, a new instance will be created
// * (potentially with a different configuration).
// *
// * Note: To unregister all events in a {@link Listener}, you can call
// * {@link HandlerList#unregisterAll(Listener)}.
// */
// public abstract void dispose();
// }
| import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.Set;
import org.bukkit.Bukkit;
import org.bukkit.command.CommandSender;
import org.bukkit.configuration.Configuration;
import org.bukkit.configuration.ConfigurationSection;
import wdl.range.IRangeGroupType;
| }
}
/**
* Validates the given chunk override.
*
* @param override The {@link ConfigurationSection} for the chunk override.
* @param key ID of the override
* @param warnTo The player to complain to if something is wrong.
* @param plugin The instance of the plugin.
* @return True if the override is valid, false otherwise.
*/
private static boolean validateChunkOverride(ConfigurationSection override,
String key, CommandSender warnTo, WDLCompanion plugin) {
if (!override.isString("type")) {
warnTo.sendMessage("§c[WDL] ERROR: 'type' for chunk "
+ "override '" + key + "' is not set or not a "
+ "string! It will be ignored.");
return false;
}
String typeName = override.getString("type");
if (!plugin.registeredRangeGroupTypes.containsKey(typeName)) {
warnTo.sendMessage("§c[WDL] ERROR: 'type' for chunk "
+ "override '" + key + "' is not a valid option! "
+ "Currently '" + typeName + "', expected one of "
+ plugin.registeredRangeGroupTypes.keySet() + ". "
+ "It will be ignored.");
return false;
}
| // Path: src/main/java/wdl/range/IRangeGroupType.java
// public interface IRangeGroupType<T extends IRangeProducer> {
// /**
// * Validates that the given {@link ConfigurationSection} is acceptable.
// *
// * @param config
// * The config to check.
// * @param warnings
// * A list to put warnings into if if any occur.
// * @param errors
// * A list to put errors into if if any occur.
// * @return <code>false</code> if the configuration is fatally unacceptable
// * to the point where this {@link IRangeProducer} should not
// * use it. Note that other {@link ConfigurationSection}s may still
// * be used with this {@link IRangeProducer}.
// */
// public abstract boolean isValidConfig(ConfigurationSection config,
// List<String> warnings, List<String> errors);
//
// /**
// * Creates a new {@link IRangeProducer} from the given configuration
// * section. Will only be called if
// * {@link #isValidConfig(ConfigurationSection, List, List)} returned true.
// *
// * @param config
// * The config to check.
// */
// public abstract T createRangeProducer(
// IRangeGroup group, ConfigurationSection config);
//
// /**
// * Disposes of this {@link IRangeGroupType}. Events should be unregistered,
// * etc. Note that this should NOT dispose any created {@link IRangeProducer}s;
// * they will be handled manually.
// *
// * After this method has been called, this {@link IRangeGroupType} instance
// * will no longer be used. In most cases, a new instance will be created
// * (potentially with a different configuration).
// *
// * Note: To unregister all events in a {@link Listener}, you can call
// * {@link HandlerList#unregisterAll(Listener)}.
// */
// public abstract void dispose();
// }
// Path: src/main/java/wdl/ConfigValidation.java
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.Set;
import org.bukkit.Bukkit;
import org.bukkit.command.CommandSender;
import org.bukkit.configuration.Configuration;
import org.bukkit.configuration.ConfigurationSection;
import wdl.range.IRangeGroupType;
}
}
/**
* Validates the given chunk override.
*
* @param override The {@link ConfigurationSection} for the chunk override.
* @param key ID of the override
* @param warnTo The player to complain to if something is wrong.
* @param plugin The instance of the plugin.
* @return True if the override is valid, false otherwise.
*/
private static boolean validateChunkOverride(ConfigurationSection override,
String key, CommandSender warnTo, WDLCompanion plugin) {
if (!override.isString("type")) {
warnTo.sendMessage("§c[WDL] ERROR: 'type' for chunk "
+ "override '" + key + "' is not set or not a "
+ "string! It will be ignored.");
return false;
}
String typeName = override.getString("type");
if (!plugin.registeredRangeGroupTypes.containsKey(typeName)) {
warnTo.sendMessage("§c[WDL] ERROR: 'type' for chunk "
+ "override '" + key + "' is not a valid option! "
+ "Currently '" + typeName + "', expected one of "
+ plugin.registeredRangeGroupTypes.keySet() + ". "
+ "It will be ignored.");
return false;
}
| IRangeGroupType<?> type = plugin.registeredRangeGroupTypes.get(typeName);
|
KodeMunkie/imagetozxspec | src/main/java/uk/co/silentsoftware/core/converters/image/orderedditherstrategy/BayerFourByFourDitherStrategy.java | // Path: src/main/java/uk/co/silentsoftware/config/LanguageSupport.java
// public static String getCaption(String key) {
// String translation = null;
// if (captions != null) {
// try {
// translation = captions.getString(key);
// } catch(MissingResourceException ignore){}
// }
// // We're missing a key's value, use the key as the value :(
// if (translation == null || translation.trim().length()==0) {
// translation=key;
// }
// return translation;
// }
| import static uk.co.silentsoftware.config.LanguageSupport.getCaption; | /* Image to ZX Spec
* Copyright (C) 2020 Silent Software (Benjamin Brown)
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU Affero General Public License
* as published by the Free Software Foundation, either version 3
* of the License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package uk.co.silentsoftware.core.converters.image.orderedditherstrategy;
/**
* Implementation of the classical Bayer 4x4 ordered dither algorithm
*/
public class BayerFourByFourDitherStrategy extends AbstractOrderedDitherStrategy implements OrderedDitherStrategy {
private static final int[] COEFFS = new int[]{
0,12,3,15,
8,4,11,7,
2,14,1,13,
10,6,9,5
};
/*
* {@inheritDoc}
*/
public int[] getCoefficients() {
return COEFFS;
}
/*
* {@inheritDoc}
*/
public int getMatrixWidth() {
return 4;
}
/*
* {@inheritDoc}
*/
public int getMatrixHeight() {
return 4;
}
/*
* {@inheritDoc}
*/
public String toString() { | // Path: src/main/java/uk/co/silentsoftware/config/LanguageSupport.java
// public static String getCaption(String key) {
// String translation = null;
// if (captions != null) {
// try {
// translation = captions.getString(key);
// } catch(MissingResourceException ignore){}
// }
// // We're missing a key's value, use the key as the value :(
// if (translation == null || translation.trim().length()==0) {
// translation=key;
// }
// return translation;
// }
// Path: src/main/java/uk/co/silentsoftware/core/converters/image/orderedditherstrategy/BayerFourByFourDitherStrategy.java
import static uk.co.silentsoftware.config.LanguageSupport.getCaption;
/* Image to ZX Spec
* Copyright (C) 2020 Silent Software (Benjamin Brown)
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU Affero General Public License
* as published by the Free Software Foundation, either version 3
* of the License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package uk.co.silentsoftware.core.converters.image.orderedditherstrategy;
/**
* Implementation of the classical Bayer 4x4 ordered dither algorithm
*/
public class BayerFourByFourDitherStrategy extends AbstractOrderedDitherStrategy implements OrderedDitherStrategy {
private static final int[] COEFFS = new int[]{
0,12,3,15,
8,4,11,7,
2,14,1,13,
10,6,9,5
};
/*
* {@inheritDoc}
*/
public int[] getCoefficients() {
return COEFFS;
}
/*
* {@inheritDoc}
*/
public int getMatrixWidth() {
return 4;
}
/*
* {@inheritDoc}
*/
public int getMatrixHeight() {
return 4;
}
/*
* {@inheritDoc}
*/
public String toString() { | return "Bayer 4x4 ("+getCaption("ordered_dither")+")"; |
KodeMunkie/imagetozxspec | src/main/java/uk/co/silentsoftware/core/converters/image/errordiffusionstrategy/SierraFilterLightStrategy.java | // Path: src/main/java/uk/co/silentsoftware/config/LanguageSupport.java
// public static String getCaption(String key) {
// String translation = null;
// if (captions != null) {
// try {
// translation = captions.getString(key);
// } catch(MissingResourceException ignore){}
// }
// // We're missing a key's value, use the key as the value :(
// if (translation == null || translation.trim().length()==0) {
// translation=key;
// }
// return translation;
// }
| import java.awt.image.BufferedImage;
import static uk.co.silentsoftware.config.LanguageSupport.getCaption; | /* Image to ZX Spec
* Copyright (C) 2020 Silent Software (Benjamin Brown)
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU Affero General Public License
* as published by the Free Software Foundation, either version 3
* of the License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package uk.co.silentsoftware.core.converters.image.errordiffusionstrategy;
/**
* Implementation of the Sierra Filter Light error diffusion algorithm
*/
public class SierraFilterLightStrategy extends AbstractErrorDiffusionDitherStrategy implements ErrorDiffusionDitherStrategy {
public final static float QUARTER = 1f/4f;
public final static float HALF = 1f/2f;
/*
* {@inheritDoc}
*/
public void distributeError(BufferedImage output, int oldPixel, int newPixel, int x, int y, Integer boundX, Integer boundY) {
if (isInBounds(output, x+1, y, boundX, boundY)) {output.setRGB(x+1, y, calculateAdjustedRGB(oldPixel, newPixel, output.getRGB(x+1, y), HALF));}
if (isInBounds(output, x, y+1, boundX, boundY)) {output.setRGB(x, y+1, calculateAdjustedRGB(oldPixel, newPixel, output.getRGB(x, y+1), QUARTER));}
if (isInBounds(output, x-1, y+1, boundX, boundY)) {output.setRGB(x-1, y+1, calculateAdjustedRGB(oldPixel, newPixel, output.getRGB(x-1, y+1), QUARTER));}
}
@Override
public String toString() { | // Path: src/main/java/uk/co/silentsoftware/config/LanguageSupport.java
// public static String getCaption(String key) {
// String translation = null;
// if (captions != null) {
// try {
// translation = captions.getString(key);
// } catch(MissingResourceException ignore){}
// }
// // We're missing a key's value, use the key as the value :(
// if (translation == null || translation.trim().length()==0) {
// translation=key;
// }
// return translation;
// }
// Path: src/main/java/uk/co/silentsoftware/core/converters/image/errordiffusionstrategy/SierraFilterLightStrategy.java
import java.awt.image.BufferedImage;
import static uk.co.silentsoftware.config.LanguageSupport.getCaption;
/* Image to ZX Spec
* Copyright (C) 2020 Silent Software (Benjamin Brown)
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU Affero General Public License
* as published by the Free Software Foundation, either version 3
* of the License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package uk.co.silentsoftware.core.converters.image.errordiffusionstrategy;
/**
* Implementation of the Sierra Filter Light error diffusion algorithm
*/
public class SierraFilterLightStrategy extends AbstractErrorDiffusionDitherStrategy implements ErrorDiffusionDitherStrategy {
public final static float QUARTER = 1f/4f;
public final static float HALF = 1f/2f;
/*
* {@inheritDoc}
*/
public void distributeError(BufferedImage output, int oldPixel, int newPixel, int x, int y, Integer boundX, Integer boundY) {
if (isInBounds(output, x+1, y, boundX, boundY)) {output.setRGB(x+1, y, calculateAdjustedRGB(oldPixel, newPixel, output.getRGB(x+1, y), HALF));}
if (isInBounds(output, x, y+1, boundX, boundY)) {output.setRGB(x, y+1, calculateAdjustedRGB(oldPixel, newPixel, output.getRGB(x, y+1), QUARTER));}
if (isInBounds(output, x-1, y+1, boundX, boundY)) {output.setRGB(x-1, y+1, calculateAdjustedRGB(oldPixel, newPixel, output.getRGB(x-1, y+1), QUARTER));}
}
@Override
public String toString() { | return "Sierra Filter Light ("+getCaption("error_diffusion")+")"; |
KodeMunkie/imagetozxspec | src/main/java/uk/co/silentsoftware/core/converters/image/orderedditherstrategy/MagicSquareDitherStrategy.java | // Path: src/main/java/uk/co/silentsoftware/config/LanguageSupport.java
// public static String getCaption(String key) {
// String translation = null;
// if (captions != null) {
// try {
// translation = captions.getString(key);
// } catch(MissingResourceException ignore){}
// }
// // We're missing a key's value, use the key as the value :(
// if (translation == null || translation.trim().length()==0) {
// translation=key;
// }
// return translation;
// }
| import static uk.co.silentsoftware.config.LanguageSupport.getCaption; | /* Image to ZX Spec
* Copyright (C) 2020 Silent Software (Benjamin Brown)
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU Affero General Public License
* as published by the Free Software Foundation, either version 3
* of the License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package uk.co.silentsoftware.core.converters.image.orderedditherstrategy;
/**
* Traditional "magic square" 4x4 dither algorithm whose sum of rows and columns are equal
*/
public class MagicSquareDitherStrategy extends AbstractOrderedDitherStrategy implements OrderedDitherStrategy {
private static final int[] COEFFS = new int[]{
0,15,10,5,
5,0,15,10,
10,5,0,15,
15,10,5,0
};
/*
* {@inheritDoc}
*/
public int[] getCoefficients() {
return COEFFS;
}
/*
* {@inheritDoc}
*/
public int getMatrixWidth() {
return 4;
}
/*
* {@inheritDoc}
*/
public int getMatrixHeight() {
return 4;
}
/*
* {@inheritDoc}
*/
public String toString() { | // Path: src/main/java/uk/co/silentsoftware/config/LanguageSupport.java
// public static String getCaption(String key) {
// String translation = null;
// if (captions != null) {
// try {
// translation = captions.getString(key);
// } catch(MissingResourceException ignore){}
// }
// // We're missing a key's value, use the key as the value :(
// if (translation == null || translation.trim().length()==0) {
// translation=key;
// }
// return translation;
// }
// Path: src/main/java/uk/co/silentsoftware/core/converters/image/orderedditherstrategy/MagicSquareDitherStrategy.java
import static uk.co.silentsoftware.config.LanguageSupport.getCaption;
/* Image to ZX Spec
* Copyright (C) 2020 Silent Software (Benjamin Brown)
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU Affero General Public License
* as published by the Free Software Foundation, either version 3
* of the License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package uk.co.silentsoftware.core.converters.image.orderedditherstrategy;
/**
* Traditional "magic square" 4x4 dither algorithm whose sum of rows and columns are equal
*/
public class MagicSquareDitherStrategy extends AbstractOrderedDitherStrategy implements OrderedDitherStrategy {
private static final int[] COEFFS = new int[]{
0,15,10,5,
5,0,15,10,
10,5,0,15,
15,10,5,0
};
/*
* {@inheritDoc}
*/
public int[] getCoefficients() {
return COEFFS;
}
/*
* {@inheritDoc}
*/
public int getMatrixWidth() {
return 4;
}
/*
* {@inheritDoc}
*/
public int getMatrixHeight() {
return 4;
}
/*
* {@inheritDoc}
*/
public String toString() { | return "Magic Square 4x4 ("+getCaption("ordered_dither")+")"; |
KodeMunkie/imagetozxspec | src/main/java/uk/co/silentsoftware/core/converters/image/DitherStrategy.java | // Path: src/main/java/uk/co/silentsoftware/core/colourstrategy/ColourChoiceStrategy.java
// public interface ColourChoiceStrategy {
//
// /**
// * Method to return the RGB int colour (Spectrum colour) that should be
// * used for a given pixel based on the Spectrum colours
// * passed in as mostPopularColour and secondMostPopularColour.
// * originalRgb is either the original pixel colour or
// * part converted colour (e.g. a pixel that has already undergone
// * colour processing).
// *
// * @param originalRgb the source rgb value
// * @param mostPopularRgbColours the rgb values from which to choose the closest match
// * @return the closest colour from the most popular array
// */
// int chooseBestPaletteMatch(int originalRgb, int[] mostPopularRgbColours);
//
// int chooseBestPaletteMatch(int rgb);
//
// int[] getPalette();
//
// BufferedImage colourAttributes(BufferedImage image);
//
// }
//
// Path: src/main/java/uk/co/silentsoftware/core/converters/image/processors/ImageConverter.java
// public interface ImageConverter {
//
// /**
// * Convert the original image to the output image
// * @param original the original image
// * @return the result images (preview, final)
// */
// ResultImage[] convert(final BufferedImage original);
//
// String getDitherStrategyLabel();
//
// boolean getDrawStrategyLabel();
// }
| import uk.co.silentsoftware.core.colourstrategy.ColourChoiceStrategy;
import uk.co.silentsoftware.core.converters.image.processors.ImageConverter; | /* Image to ZX Spec
* Copyright (C) 2020 Silent Software (Benjamin Brown)
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU Affero General Public License
* as published by the Free Software Foundation, either version 3
* of the License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package uk.co.silentsoftware.core.converters.image;
/**
* Marker interface for a dither strategy (typically error diffusion or ordered dither)
*/
public interface DitherStrategy {
ImageConverter createImageConverter();
| // Path: src/main/java/uk/co/silentsoftware/core/colourstrategy/ColourChoiceStrategy.java
// public interface ColourChoiceStrategy {
//
// /**
// * Method to return the RGB int colour (Spectrum colour) that should be
// * used for a given pixel based on the Spectrum colours
// * passed in as mostPopularColour and secondMostPopularColour.
// * originalRgb is either the original pixel colour or
// * part converted colour (e.g. a pixel that has already undergone
// * colour processing).
// *
// * @param originalRgb the source rgb value
// * @param mostPopularRgbColours the rgb values from which to choose the closest match
// * @return the closest colour from the most popular array
// */
// int chooseBestPaletteMatch(int originalRgb, int[] mostPopularRgbColours);
//
// int chooseBestPaletteMatch(int rgb);
//
// int[] getPalette();
//
// BufferedImage colourAttributes(BufferedImage image);
//
// }
//
// Path: src/main/java/uk/co/silentsoftware/core/converters/image/processors/ImageConverter.java
// public interface ImageConverter {
//
// /**
// * Convert the original image to the output image
// * @param original the original image
// * @return the result images (preview, final)
// */
// ResultImage[] convert(final BufferedImage original);
//
// String getDitherStrategyLabel();
//
// boolean getDrawStrategyLabel();
// }
// Path: src/main/java/uk/co/silentsoftware/core/converters/image/DitherStrategy.java
import uk.co.silentsoftware.core.colourstrategy.ColourChoiceStrategy;
import uk.co.silentsoftware.core.converters.image.processors.ImageConverter;
/* Image to ZX Spec
* Copyright (C) 2020 Silent Software (Benjamin Brown)
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU Affero General Public License
* as published by the Free Software Foundation, either version 3
* of the License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package uk.co.silentsoftware.core.converters.image;
/**
* Marker interface for a dither strategy (typically error diffusion or ordered dither)
*/
public interface DitherStrategy {
ImageConverter createImageConverter();
| ImageConverter createPreviewImageConverter(ColourChoiceStrategy colourChoiceStrategy); |
KodeMunkie/imagetozxspec | src/main/java/uk/co/silentsoftware/core/helpers/colourdistance/EuclideanColourDistance.java | // Path: src/main/java/uk/co/silentsoftware/config/LanguageSupport.java
// public static String getCaption(String key) {
// String translation = null;
// if (captions != null) {
// try {
// translation = captions.getString(key);
// } catch(MissingResourceException ignore){}
// }
// // We're missing a key's value, use the key as the value :(
// if (translation == null || translation.trim().length()==0) {
// translation=key;
// }
// return translation;
// }
| import static uk.co.silentsoftware.config.LanguageSupport.getCaption; | /* Image to ZX Spec
* Copyright (C) 2020 Silent Software (Benjamin Brown)
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU Affero General Public License
* as published by the Free Software Foundation, either version 3
* of the License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package uk.co.silentsoftware.core.helpers.colourdistance;
/**
* Fast Euclidean colour distance calculation that doesn't consider human colour perception
*/
public class EuclideanColourDistance implements ColourDistanceStrategy {
@Override
public double getColourDistance(int red, int green, int blue, int[] colourSetComps) {
return Math.pow(red - colourSetComps[0], 2d) + Math.pow(green - colourSetComps[1], 2d) + Math.pow(blue - colourSetComps[2], 2d);
}
@Override
public String toString() { | // Path: src/main/java/uk/co/silentsoftware/config/LanguageSupport.java
// public static String getCaption(String key) {
// String translation = null;
// if (captions != null) {
// try {
// translation = captions.getString(key);
// } catch(MissingResourceException ignore){}
// }
// // We're missing a key's value, use the key as the value :(
// if (translation == null || translation.trim().length()==0) {
// translation=key;
// }
// return translation;
// }
// Path: src/main/java/uk/co/silentsoftware/core/helpers/colourdistance/EuclideanColourDistance.java
import static uk.co.silentsoftware.config.LanguageSupport.getCaption;
/* Image to ZX Spec
* Copyright (C) 2020 Silent Software (Benjamin Brown)
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU Affero General Public License
* as published by the Free Software Foundation, either version 3
* of the License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package uk.co.silentsoftware.core.helpers.colourdistance;
/**
* Fast Euclidean colour distance calculation that doesn't consider human colour perception
*/
public class EuclideanColourDistance implements ColourDistanceStrategy {
@Override
public double getColourDistance(int red, int green, int blue, int[] colourSetComps) {
return Math.pow(red - colourSetComps[0], 2d) + Math.pow(green - colourSetComps[1], 2d) + Math.pow(blue - colourSetComps[2], 2d);
}
@Override
public String toString() { | return getCaption("adv_colour_dist_euclidean") ; |
KodeMunkie/imagetozxspec | src/main/java/uk/co/silentsoftware/core/converters/video/VLCVideoImportEngine.java | // Path: src/main/java/uk/co/silentsoftware/config/LanguageSupport.java
// public static String getCaption(String key) {
// String translation = null;
// if (captions != null) {
// try {
// translation = captions.getString(key);
// } catch(MissingResourceException ignore){}
// }
// // We're missing a key's value, use the key as the value :(
// if (translation == null || translation.trim().length()==0) {
// translation=key;
// }
// return translation;
// }
| import com.sun.jna.Native;
import com.sun.jna.NativeLibrary;
import uk.co.caprica.vlcj.binding.LibVlc;
import uk.co.caprica.vlcj.component.EmbeddedMediaPlayerComponent;
import uk.co.caprica.vlcj.player.MediaPlayer;
import uk.co.caprica.vlcj.runtime.RuntimeUtil;
import static uk.co.silentsoftware.config.LanguageSupport.getCaption;
import java.awt.Image;
import java.io.File;
import java.io.IOException;
import java.util.Optional;
import java.util.Random;
import java.util.concurrent.BlockingQueue;
import java.util.concurrent.TimeUnit;
import javax.swing.JWindow;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory; | if (cancel) {
break;
}
// Always add images if we don't want a single preview
// image or when the time exceeds the point we want a
// single image from
if (singleImageSelectionTime == -1 || player.getTime() >= singleImageSelectionTime) {
sharedQueue.add(player.getSnapshot());
// We only want one image if single image selection
// is turned on
if (singleImageSelectionTime != -1 && player.getTime() >= singleImageSelectionTime) {
break;
}
}
}
} finally {
player.stop();
player.release();
mediaPlayerComponent.release();
cancel = false;
}
}
/*
* {@inheritDoc}
*/
@Override
public String toString() { | // Path: src/main/java/uk/co/silentsoftware/config/LanguageSupport.java
// public static String getCaption(String key) {
// String translation = null;
// if (captions != null) {
// try {
// translation = captions.getString(key);
// } catch(MissingResourceException ignore){}
// }
// // We're missing a key's value, use the key as the value :(
// if (translation == null || translation.trim().length()==0) {
// translation=key;
// }
// return translation;
// }
// Path: src/main/java/uk/co/silentsoftware/core/converters/video/VLCVideoImportEngine.java
import com.sun.jna.Native;
import com.sun.jna.NativeLibrary;
import uk.co.caprica.vlcj.binding.LibVlc;
import uk.co.caprica.vlcj.component.EmbeddedMediaPlayerComponent;
import uk.co.caprica.vlcj.player.MediaPlayer;
import uk.co.caprica.vlcj.runtime.RuntimeUtil;
import static uk.co.silentsoftware.config.LanguageSupport.getCaption;
import java.awt.Image;
import java.io.File;
import java.io.IOException;
import java.util.Optional;
import java.util.Random;
import java.util.concurrent.BlockingQueue;
import java.util.concurrent.TimeUnit;
import javax.swing.JWindow;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
if (cancel) {
break;
}
// Always add images if we don't want a single preview
// image or when the time exceeds the point we want a
// single image from
if (singleImageSelectionTime == -1 || player.getTime() >= singleImageSelectionTime) {
sharedQueue.add(player.getSnapshot());
// We only want one image if single image selection
// is turned on
if (singleImageSelectionTime != -1 && player.getTime() >= singleImageSelectionTime) {
break;
}
}
}
} finally {
player.stop();
player.release();
mediaPlayerComponent.release();
cancel = false;
}
}
/*
* {@inheritDoc}
*/
@Override
public String toString() { | return getCaption("VLC"); |
KodeMunkie/imagetozxspec | src/main/java/uk/co/silentsoftware/core/helpers/colourdistance/ClassicColourDistanceStrategy.java | // Path: src/main/java/uk/co/silentsoftware/config/LanguageSupport.java
// public static String getCaption(String key) {
// String translation = null;
// if (captions != null) {
// try {
// translation = captions.getString(key);
// } catch(MissingResourceException ignore){}
// }
// // We're missing a key's value, use the key as the value :(
// if (translation == null || translation.trim().length()==0) {
// translation=key;
// }
// return translation;
// }
| import static uk.co.silentsoftware.config.LanguageSupport.getCaption; | /* Image to ZX Spec
* Copyright (C) 2020 Silent Software (Benjamin Brown)
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU Affero General Public License
* as published by the Free Software Foundation, either version 3
* of the License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package uk.co.silentsoftware.core.helpers.colourdistance;
/**
* Default colour distance algorithm used by Image to ZX Spec pre 2.1
*/
public class ClassicColourDistanceStrategy implements ColourDistanceStrategy {
@Override
public double getColourDistance(int red, int green, int blue, int[] colourSetComps) {
return Math.abs(red - colourSetComps[0]) + Math.abs(green - colourSetComps[1]) + Math.abs(blue - colourSetComps[2]);
}
@Override
public String toString() { | // Path: src/main/java/uk/co/silentsoftware/config/LanguageSupport.java
// public static String getCaption(String key) {
// String translation = null;
// if (captions != null) {
// try {
// translation = captions.getString(key);
// } catch(MissingResourceException ignore){}
// }
// // We're missing a key's value, use the key as the value :(
// if (translation == null || translation.trim().length()==0) {
// translation=key;
// }
// return translation;
// }
// Path: src/main/java/uk/co/silentsoftware/core/helpers/colourdistance/ClassicColourDistanceStrategy.java
import static uk.co.silentsoftware.config.LanguageSupport.getCaption;
/* Image to ZX Spec
* Copyright (C) 2020 Silent Software (Benjamin Brown)
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU Affero General Public License
* as published by the Free Software Foundation, either version 3
* of the License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package uk.co.silentsoftware.core.helpers.colourdistance;
/**
* Default colour distance algorithm used by Image to ZX Spec pre 2.1
*/
public class ClassicColourDistanceStrategy implements ColourDistanceStrategy {
@Override
public double getColourDistance(int red, int green, int blue, int[] colourSetComps) {
return Math.abs(red - colourSetComps[0]) + Math.abs(green - colourSetComps[1]) + Math.abs(blue - colourSetComps[2]);
}
@Override
public String toString() { | return getCaption("adv_colour_dist_classic") ; |
KodeMunkie/imagetozxspec | src/main/java/uk/co/silentsoftware/core/converters/image/orderedditherstrategy/OmegaOrderedDitherStrategy.java | // Path: src/main/java/uk/co/silentsoftware/config/LanguageSupport.java
// public static String getCaption(String key) {
// String translation = null;
// if (captions != null) {
// try {
// translation = captions.getString(key);
// } catch(MissingResourceException ignore){}
// }
// // We're missing a key's value, use the key as the value :(
// if (translation == null || translation.trim().length()==0) {
// translation=key;
// }
// return translation;
// }
| import static uk.co.silentsoftware.config.LanguageSupport.getCaption; | /* Image to ZX Spec
* Copyright (C) 2020 Silent Software (Benjamin Brown)
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU Affero General Public License
* as published by the Free Software Foundation, either version 3
* of the License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package uk.co.silentsoftware.core.converters.image.orderedditherstrategy;
/**
* Ordered dithering algorithm based on an even distribution devised by
* Omega from World of Spectrum forums, revised by Benjamin Brown
*/
public class OmegaOrderedDitherStrategy extends AbstractOrderedDitherStrategy implements OrderedDitherStrategy {
private static final int[] COEFFS = new int[]{
0,1,
1,0
};
/*
* {@inheritDoc}
*/
public int[] getCoefficients() {
return COEFFS;
}
/*
* {@inheritDoc}
*/
public int getMatrixWidth() {
return 2;
}
/*
* {@inheritDoc}
*/
public int getMatrixHeight() {
return 2;
}
/*
* {@inheritDoc}
*/
public String toString() { | // Path: src/main/java/uk/co/silentsoftware/config/LanguageSupport.java
// public static String getCaption(String key) {
// String translation = null;
// if (captions != null) {
// try {
// translation = captions.getString(key);
// } catch(MissingResourceException ignore){}
// }
// // We're missing a key's value, use the key as the value :(
// if (translation == null || translation.trim().length()==0) {
// translation=key;
// }
// return translation;
// }
// Path: src/main/java/uk/co/silentsoftware/core/converters/image/orderedditherstrategy/OmegaOrderedDitherStrategy.java
import static uk.co.silentsoftware.config.LanguageSupport.getCaption;
/* Image to ZX Spec
* Copyright (C) 2020 Silent Software (Benjamin Brown)
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU Affero General Public License
* as published by the Free Software Foundation, either version 3
* of the License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package uk.co.silentsoftware.core.converters.image.orderedditherstrategy;
/**
* Ordered dithering algorithm based on an even distribution devised by
* Omega from World of Spectrum forums, revised by Benjamin Brown
*/
public class OmegaOrderedDitherStrategy extends AbstractOrderedDitherStrategy implements OrderedDitherStrategy {
private static final int[] COEFFS = new int[]{
0,1,
1,0
};
/*
* {@inheritDoc}
*/
public int[] getCoefficients() {
return COEFFS;
}
/*
* {@inheritDoc}
*/
public int getMatrixWidth() {
return 2;
}
/*
* {@inheritDoc}
*/
public int getMatrixHeight() {
return 2;
}
/*
* {@inheritDoc}
*/
public String toString() { | return "Omega Ordered 2x2 ("+getCaption("ordered_dither")+")"; |
KodeMunkie/imagetozxspec | src/main/java/uk/co/silentsoftware/core/converters/image/errordiffusionstrategy/LowErrorAtkinsonDitherStrategy.java | // Path: src/main/java/uk/co/silentsoftware/config/LanguageSupport.java
// public static String getCaption(String key) {
// String translation = null;
// if (captions != null) {
// try {
// translation = captions.getString(key);
// } catch(MissingResourceException ignore){}
// }
// // We're missing a key's value, use the key as the value :(
// if (translation == null || translation.trim().length()==0) {
// translation=key;
// }
// return translation;
// }
| import java.awt.image.BufferedImage;
import static uk.co.silentsoftware.config.LanguageSupport.getCaption; | /* Image to ZX Spec
* Copyright (C) 2020 Silent Software (Benjamin Brown)
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU Affero General Public License
* as published by the Free Software Foundation, either version 3
* of the License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package uk.co.silentsoftware.core.converters.image.errordiffusionstrategy;
/**
* Special low error dither strategy especially for Spectrum image conversion
* and only (currently) in use in this program, based on the Atkinson distribution
* but using only 25% error distribution. This strategy tends to get the best
* results in most cases, however images with high detail but similar colours
* (e.g. blues underwater/red light on a face etc etc) may lose some detail depending
* on pre process contrast. The trade off is that the error distribution is far less
* likely to propagate to surrounding *ZX Spectrum attribute blocks* resulting in
* less colour clash than the classical diffusion algorithms.
*
* This strategy's distribution of error was by Bill Atkinson but improved by me,
* Benjamin Brown, if anybody feels like documenting/publishing it :)
*/
public class LowErrorAtkinsonDitherStrategy extends AbstractErrorDiffusionDitherStrategy {
public final static float TWENTY_FOURTH = 1f/24f;
/*
* {@inheritDoc}
*/
public void distributeError(BufferedImage output, int oldPixel, int newPixel, int x, int y, Integer boundX, Integer boundY) {
if (isInBounds(output, x+1, y, boundX, boundY)) {output.setRGB(x+1, y, calculateAdjustedRGB(oldPixel, newPixel, output.getRGB(x+1, y), TWENTY_FOURTH));}
if (isInBounds(output, x+2, y, boundX, boundY)) {output.setRGB(x+2, y, calculateAdjustedRGB(oldPixel, newPixel, output.getRGB(x+2, y), TWENTY_FOURTH));}
if (isInBounds(output, x-1, y+1, boundX, boundY)) {output.setRGB(x-1, y+1, calculateAdjustedRGB(oldPixel, newPixel, output.getRGB(x-1, y+1), TWENTY_FOURTH));}
if (isInBounds(output, x, y+1, boundX, boundY)) {output.setRGB(x, y+1, calculateAdjustedRGB(oldPixel, newPixel, output.getRGB(x, y+1), TWENTY_FOURTH));}
if (isInBounds(output, x+1, y+1, boundX, boundY)) {output.setRGB(x+1, y+1, calculateAdjustedRGB(oldPixel, newPixel, output.getRGB(x+1, y+1), TWENTY_FOURTH));}
if (isInBounds(output, x, y+2, boundX, boundY)) {output.setRGB(x, y+2, calculateAdjustedRGB(oldPixel, newPixel, output.getRGB(x, y+2), TWENTY_FOURTH));}
}
@Override
public String toString() { | // Path: src/main/java/uk/co/silentsoftware/config/LanguageSupport.java
// public static String getCaption(String key) {
// String translation = null;
// if (captions != null) {
// try {
// translation = captions.getString(key);
// } catch(MissingResourceException ignore){}
// }
// // We're missing a key's value, use the key as the value :(
// if (translation == null || translation.trim().length()==0) {
// translation=key;
// }
// return translation;
// }
// Path: src/main/java/uk/co/silentsoftware/core/converters/image/errordiffusionstrategy/LowErrorAtkinsonDitherStrategy.java
import java.awt.image.BufferedImage;
import static uk.co.silentsoftware.config.LanguageSupport.getCaption;
/* Image to ZX Spec
* Copyright (C) 2020 Silent Software (Benjamin Brown)
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU Affero General Public License
* as published by the Free Software Foundation, either version 3
* of the License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package uk.co.silentsoftware.core.converters.image.errordiffusionstrategy;
/**
* Special low error dither strategy especially for Spectrum image conversion
* and only (currently) in use in this program, based on the Atkinson distribution
* but using only 25% error distribution. This strategy tends to get the best
* results in most cases, however images with high detail but similar colours
* (e.g. blues underwater/red light on a face etc etc) may lose some detail depending
* on pre process contrast. The trade off is that the error distribution is far less
* likely to propagate to surrounding *ZX Spectrum attribute blocks* resulting in
* less colour clash than the classical diffusion algorithms.
*
* This strategy's distribution of error was by Bill Atkinson but improved by me,
* Benjamin Brown, if anybody feels like documenting/publishing it :)
*/
public class LowErrorAtkinsonDitherStrategy extends AbstractErrorDiffusionDitherStrategy {
public final static float TWENTY_FOURTH = 1f/24f;
/*
* {@inheritDoc}
*/
public void distributeError(BufferedImage output, int oldPixel, int newPixel, int x, int y, Integer boundX, Integer boundY) {
if (isInBounds(output, x+1, y, boundX, boundY)) {output.setRGB(x+1, y, calculateAdjustedRGB(oldPixel, newPixel, output.getRGB(x+1, y), TWENTY_FOURTH));}
if (isInBounds(output, x+2, y, boundX, boundY)) {output.setRGB(x+2, y, calculateAdjustedRGB(oldPixel, newPixel, output.getRGB(x+2, y), TWENTY_FOURTH));}
if (isInBounds(output, x-1, y+1, boundX, boundY)) {output.setRGB(x-1, y+1, calculateAdjustedRGB(oldPixel, newPixel, output.getRGB(x-1, y+1), TWENTY_FOURTH));}
if (isInBounds(output, x, y+1, boundX, boundY)) {output.setRGB(x, y+1, calculateAdjustedRGB(oldPixel, newPixel, output.getRGB(x, y+1), TWENTY_FOURTH));}
if (isInBounds(output, x+1, y+1, boundX, boundY)) {output.setRGB(x+1, y+1, calculateAdjustedRGB(oldPixel, newPixel, output.getRGB(x+1, y+1), TWENTY_FOURTH));}
if (isInBounds(output, x, y+2, boundX, boundY)) {output.setRGB(x, y+2, calculateAdjustedRGB(oldPixel, newPixel, output.getRGB(x, y+2), TWENTY_FOURTH));}
}
@Override
public String toString() { | return "Low Error Atkinson ("+getCaption("error_diffusion")+")"; |
KodeMunkie/imagetozxspec | src/main/java/uk/co/silentsoftware/core/converters/image/orderedditherstrategy/BayerEightByEightDitherStrategy.java | // Path: src/main/java/uk/co/silentsoftware/config/LanguageSupport.java
// public static String getCaption(String key) {
// String translation = null;
// if (captions != null) {
// try {
// translation = captions.getString(key);
// } catch(MissingResourceException ignore){}
// }
// // We're missing a key's value, use the key as the value :(
// if (translation == null || translation.trim().length()==0) {
// translation=key;
// }
// return translation;
// }
| import static uk.co.silentsoftware.config.LanguageSupport.getCaption; | /* Image to ZX Spec
* Copyright (C) 2020 Silent Software (Benjamin Brown)
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU Affero General Public License
* as published by the Free Software Foundation, either version 3
* of the License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package uk.co.silentsoftware.core.converters.image.orderedditherstrategy;
/**
* Implementation of the classical Bayer 8x8 ordered dither algorithm
*/
public class BayerEightByEightDitherStrategy extends AbstractOrderedDitherStrategy implements OrderedDitherStrategy {
private static final int[] COEFFS = new int[]{
0,48,12,60,3,51,15,63,
32,16,44,28,35,19,47,31,
8,56,4,52,11,59,7,55,
40,24,36,20,43,27,39,23,
2,50,14,62,1,49,13,61,
34,18,46,30,33,17,45,29,
10,58,6,54,9,57,5,53,
42,26,38,22,41,25,37,21
};
/*
* {@inheritDoc}
*/
public int[] getCoefficients() {
return COEFFS;
}
/*
* {@inheritDoc}
*/
public int getMatrixWidth() {
return 8;
}
/*
* {@inheritDoc}
*/
public int getMatrixHeight() {
return 8;
}
/*
* {@inheritDoc}
*/
public String toString() { | // Path: src/main/java/uk/co/silentsoftware/config/LanguageSupport.java
// public static String getCaption(String key) {
// String translation = null;
// if (captions != null) {
// try {
// translation = captions.getString(key);
// } catch(MissingResourceException ignore){}
// }
// // We're missing a key's value, use the key as the value :(
// if (translation == null || translation.trim().length()==0) {
// translation=key;
// }
// return translation;
// }
// Path: src/main/java/uk/co/silentsoftware/core/converters/image/orderedditherstrategy/BayerEightByEightDitherStrategy.java
import static uk.co.silentsoftware.config.LanguageSupport.getCaption;
/* Image to ZX Spec
* Copyright (C) 2020 Silent Software (Benjamin Brown)
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU Affero General Public License
* as published by the Free Software Foundation, either version 3
* of the License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package uk.co.silentsoftware.core.converters.image.orderedditherstrategy;
/**
* Implementation of the classical Bayer 8x8 ordered dither algorithm
*/
public class BayerEightByEightDitherStrategy extends AbstractOrderedDitherStrategy implements OrderedDitherStrategy {
private static final int[] COEFFS = new int[]{
0,48,12,60,3,51,15,63,
32,16,44,28,35,19,47,31,
8,56,4,52,11,59,7,55,
40,24,36,20,43,27,39,23,
2,50,14,62,1,49,13,61,
34,18,46,30,33,17,45,29,
10,58,6,54,9,57,5,53,
42,26,38,22,41,25,37,21
};
/*
* {@inheritDoc}
*/
public int[] getCoefficients() {
return COEFFS;
}
/*
* {@inheritDoc}
*/
public int getMatrixWidth() {
return 8;
}
/*
* {@inheritDoc}
*/
public int getMatrixHeight() {
return 8;
}
/*
* {@inheritDoc}
*/
public String toString() { | return "Bayer 8x8 ("+getCaption("ordered_dither")+")"; |
KodeMunkie/imagetozxspec | src/main/java/uk/co/silentsoftware/core/helpers/colourdistance/CompuphaseColourDistanceStrategy.java | // Path: src/main/java/uk/co/silentsoftware/config/LanguageSupport.java
// public static String getCaption(String key) {
// String translation = null;
// if (captions != null) {
// try {
// translation = captions.getString(key);
// } catch(MissingResourceException ignore){}
// }
// // We're missing a key's value, use the key as the value :(
// if (translation == null || translation.trim().length()==0) {
// translation=key;
// }
// return translation;
// }
| import static uk.co.silentsoftware.config.LanguageSupport.getCaption; | /* Image to ZX Spec
* Copyright (C) 2020 Silent Software (Benjamin Brown)
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU Affero General Public License
* as published by the Free Software Foundation, either version 3
* of the License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package uk.co.silentsoftware.core.helpers.colourdistance;
/**
* Algorithm based on a paper at https://www.compuphase.com/cmetric.htmhttps://www.compuphase.com/cmetric.htm
* (Thiadmer Riemersma, CompuPhase)
*/
public class CompuphaseColourDistanceStrategy implements ColourDistanceStrategy {
@Override
public double getColourDistance(int red, int green, int blue, int[] colourSetComps) {
long rmean = ((long) colourSetComps[0] + (long) red) / 2;
long r = (long) colourSetComps[0] - (long) red;
long g = (long) colourSetComps[1] - (long) green;
long b = (long) colourSetComps[2] - (long) blue;
return Math.sqrt((((512 + rmean) * r * r) >> 8) + 4 * g * g + (((767 - rmean) * b * b) >> 8));
}
@Override
public String toString() { | // Path: src/main/java/uk/co/silentsoftware/config/LanguageSupport.java
// public static String getCaption(String key) {
// String translation = null;
// if (captions != null) {
// try {
// translation = captions.getString(key);
// } catch(MissingResourceException ignore){}
// }
// // We're missing a key's value, use the key as the value :(
// if (translation == null || translation.trim().length()==0) {
// translation=key;
// }
// return translation;
// }
// Path: src/main/java/uk/co/silentsoftware/core/helpers/colourdistance/CompuphaseColourDistanceStrategy.java
import static uk.co.silentsoftware.config.LanguageSupport.getCaption;
/* Image to ZX Spec
* Copyright (C) 2020 Silent Software (Benjamin Brown)
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU Affero General Public License
* as published by the Free Software Foundation, either version 3
* of the License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package uk.co.silentsoftware.core.helpers.colourdistance;
/**
* Algorithm based on a paper at https://www.compuphase.com/cmetric.htmhttps://www.compuphase.com/cmetric.htm
* (Thiadmer Riemersma, CompuPhase)
*/
public class CompuphaseColourDistanceStrategy implements ColourDistanceStrategy {
@Override
public double getColourDistance(int red, int green, int blue, int[] colourSetComps) {
long rmean = ((long) colourSetComps[0] + (long) red) / 2;
long r = (long) colourSetComps[0] - (long) red;
long g = (long) colourSetComps[1] - (long) green;
long b = (long) colourSetComps[2] - (long) blue;
return Math.sqrt((((512 + rmean) * r * r) >> 8) + 4 * g * g + (((767 - rmean) * b * b) >> 8));
}
@Override
public String toString() { | return getCaption("adv_colour_dist_compuphase") ; |
KodeMunkie/imagetozxspec | src/main/java/uk/co/silentsoftware/core/converters/image/orderedditherstrategy/BayerTwoByOneOrderedDitherStrategy.java | // Path: src/main/java/uk/co/silentsoftware/config/LanguageSupport.java
// public static String getCaption(String key) {
// String translation = null;
// if (captions != null) {
// try {
// translation = captions.getString(key);
// } catch(MissingResourceException ignore){}
// }
// // We're missing a key's value, use the key as the value :(
// if (translation == null || translation.trim().length()==0) {
// translation=key;
// }
// return translation;
// }
| import static uk.co.silentsoftware.config.LanguageSupport.getCaption; | /* Image to ZX Spec
* Copyright (C) 2020 Silent Software (Benjamin Brown)
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU Affero General Public License
* as published by the Free Software Foundation, either version 3
* of the License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package uk.co.silentsoftware.core.converters.image.orderedditherstrategy;
/**
* Implementation of the classical Bayer 2x1 ordered dither algorithm
*/
public class BayerTwoByOneOrderedDitherStrategy extends AbstractOrderedDitherStrategy implements OrderedDitherStrategy {
private static final int[] COEFFS = new int[]{
0, 3
};
/*
* {@inheritDoc}
*/
public int[] getCoefficients() {
return COEFFS;
}
/*
* {@inheritDoc}
*/
public int getMatrixWidth() {
return 2;
}
public int getMatrixHeight() {
return 1;
}
/*
* {@inheritDoc}
*/
public String toString() { | // Path: src/main/java/uk/co/silentsoftware/config/LanguageSupport.java
// public static String getCaption(String key) {
// String translation = null;
// if (captions != null) {
// try {
// translation = captions.getString(key);
// } catch(MissingResourceException ignore){}
// }
// // We're missing a key's value, use the key as the value :(
// if (translation == null || translation.trim().length()==0) {
// translation=key;
// }
// return translation;
// }
// Path: src/main/java/uk/co/silentsoftware/core/converters/image/orderedditherstrategy/BayerTwoByOneOrderedDitherStrategy.java
import static uk.co.silentsoftware.config.LanguageSupport.getCaption;
/* Image to ZX Spec
* Copyright (C) 2020 Silent Software (Benjamin Brown)
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU Affero General Public License
* as published by the Free Software Foundation, either version 3
* of the License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package uk.co.silentsoftware.core.converters.image.orderedditherstrategy;
/**
* Implementation of the classical Bayer 2x1 ordered dither algorithm
*/
public class BayerTwoByOneOrderedDitherStrategy extends AbstractOrderedDitherStrategy implements OrderedDitherStrategy {
private static final int[] COEFFS = new int[]{
0, 3
};
/*
* {@inheritDoc}
*/
public int[] getCoefficients() {
return COEFFS;
}
/*
* {@inheritDoc}
*/
public int getMatrixWidth() {
return 2;
}
public int getMatrixHeight() {
return 1;
}
/*
* {@inheritDoc}
*/
public String toString() { | return "Bayer 2x1 ("+getCaption("ordered_dither")+")"; |
KodeMunkie/imagetozxspec | src/main/java/uk/co/silentsoftware/core/converters/image/orderedditherstrategy/BayerTwoByTwoOrderedDitherStrategy.java | // Path: src/main/java/uk/co/silentsoftware/config/LanguageSupport.java
// public static String getCaption(String key) {
// String translation = null;
// if (captions != null) {
// try {
// translation = captions.getString(key);
// } catch(MissingResourceException ignore){}
// }
// // We're missing a key's value, use the key as the value :(
// if (translation == null || translation.trim().length()==0) {
// translation=key;
// }
// return translation;
// }
| import static uk.co.silentsoftware.config.LanguageSupport.getCaption; | /* Image to ZX Spec
* Copyright (C) 2020 Silent Software (Benjamin Brown)
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU Affero General Public License
* as published by the Free Software Foundation, either version 3
* of the License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package uk.co.silentsoftware.core.converters.image.orderedditherstrategy;
/**
* Implementation of the classical Bayer 2x2 ordered dither algorithm
*/
public class BayerTwoByTwoOrderedDitherStrategy extends AbstractOrderedDitherStrategy implements OrderedDitherStrategy {
private static final int[] COEFFS = new int[]{
0, 3,
2, 1
};
/*
* {@inheritDoc}
*/
public int[] getCoefficients() {
return COEFFS;
}
/*
* {@inheritDoc}
*/
public int getMatrixWidth() {
return 2;
}
/*
* {@inheritDoc}
*/
public int getMatrixHeight() {
return 2;
}
/*
* {@inheritDoc}
*/
public String toString() { | // Path: src/main/java/uk/co/silentsoftware/config/LanguageSupport.java
// public static String getCaption(String key) {
// String translation = null;
// if (captions != null) {
// try {
// translation = captions.getString(key);
// } catch(MissingResourceException ignore){}
// }
// // We're missing a key's value, use the key as the value :(
// if (translation == null || translation.trim().length()==0) {
// translation=key;
// }
// return translation;
// }
// Path: src/main/java/uk/co/silentsoftware/core/converters/image/orderedditherstrategy/BayerTwoByTwoOrderedDitherStrategy.java
import static uk.co.silentsoftware.config.LanguageSupport.getCaption;
/* Image to ZX Spec
* Copyright (C) 2020 Silent Software (Benjamin Brown)
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU Affero General Public License
* as published by the Free Software Foundation, either version 3
* of the License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package uk.co.silentsoftware.core.converters.image.orderedditherstrategy;
/**
* Implementation of the classical Bayer 2x2 ordered dither algorithm
*/
public class BayerTwoByTwoOrderedDitherStrategy extends AbstractOrderedDitherStrategy implements OrderedDitherStrategy {
private static final int[] COEFFS = new int[]{
0, 3,
2, 1
};
/*
* {@inheritDoc}
*/
public int[] getCoefficients() {
return COEFFS;
}
/*
* {@inheritDoc}
*/
public int getMatrixWidth() {
return 2;
}
/*
* {@inheritDoc}
*/
public int getMatrixHeight() {
return 2;
}
/*
* {@inheritDoc}
*/
public String toString() { | return "Bayer 2x2 ("+getCaption("ordered_dither")+")"; |
KodeMunkie/imagetozxspec | src/main/java/uk/co/silentsoftware/dispatcher/WorkContainer.java | // Path: src/main/java/uk/co/silentsoftware/core/converters/image/ResultImage.java
// public class ResultImage {
//
// private volatile ResultImageType resultImageType;
// private volatile BufferedImage image;
//
// public ResultImage(ResultImageType resultImageType, BufferedImage image) {
// this.resultImageType = resultImageType;
// this.image = image;
// }
//
// public ResultImageType getResultImageType() {
// return resultImageType;
// }
//
// public BufferedImage getImage() {
// return image;
// }
//
// public void setImage(BufferedImage image) {
// this.image = image;
// }
//
// public enum ResultImageType {
// FINAL_IMAGE, SUPPORTING_IMAGE
// }
//
// /**
// * Utility method to retrieve the final image from an array of result images
// *
// * @param images the array of ResultImages
// * @return a single ResultImage, if it exists
// */
// public static Optional<ResultImage> getFinalImage(ResultImage[] images) {
// try {
// for (ResultImage ri : images) {
// if (ResultImageType.FINAL_IMAGE == ri.getResultImageType() && ri.image != null) {
// return Optional.of(ri);
// }
// }
// } catch (NullPointerException npe) {
// // Occurs if settings changed mid run
// }
// return Optional.empty();
// }
// }
| import java.awt.image.BufferedImage;
import uk.co.silentsoftware.core.converters.image.ResultImage; | /* Image to ZX Spec
* Copyright (C) 2020 Silent Software (Benjamin Brown)
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU Affero General Public License
* as published by the Free Software Foundation, either version 3
* of the License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package uk.co.silentsoftware.dispatcher;
/**
* Wrapper container for holding processed and completed work ready for output
* and display
*/
class WorkContainer {
private String imageId = "(not set)";
/**
* The final result images
*/ | // Path: src/main/java/uk/co/silentsoftware/core/converters/image/ResultImage.java
// public class ResultImage {
//
// private volatile ResultImageType resultImageType;
// private volatile BufferedImage image;
//
// public ResultImage(ResultImageType resultImageType, BufferedImage image) {
// this.resultImageType = resultImageType;
// this.image = image;
// }
//
// public ResultImageType getResultImageType() {
// return resultImageType;
// }
//
// public BufferedImage getImage() {
// return image;
// }
//
// public void setImage(BufferedImage image) {
// this.image = image;
// }
//
// public enum ResultImageType {
// FINAL_IMAGE, SUPPORTING_IMAGE
// }
//
// /**
// * Utility method to retrieve the final image from an array of result images
// *
// * @param images the array of ResultImages
// * @return a single ResultImage, if it exists
// */
// public static Optional<ResultImage> getFinalImage(ResultImage[] images) {
// try {
// for (ResultImage ri : images) {
// if (ResultImageType.FINAL_IMAGE == ri.getResultImageType() && ri.image != null) {
// return Optional.of(ri);
// }
// }
// } catch (NullPointerException npe) {
// // Occurs if settings changed mid run
// }
// return Optional.empty();
// }
// }
// Path: src/main/java/uk/co/silentsoftware/dispatcher/WorkContainer.java
import java.awt.image.BufferedImage;
import uk.co.silentsoftware.core.converters.image.ResultImage;
/* Image to ZX Spec
* Copyright (C) 2020 Silent Software (Benjamin Brown)
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU Affero General Public License
* as published by the Free Software Foundation, either version 3
* of the License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package uk.co.silentsoftware.dispatcher;
/**
* Wrapper container for holding processed and completed work ready for output
* and display
*/
class WorkContainer {
private String imageId = "(not set)";
/**
* The final result images
*/ | private ResultImage[] resultImage; |
KodeMunkie/imagetozxspec | src/main/java/uk/co/silentsoftware/core/converters/image/orderedditherstrategy/NasikMagicSquareDitherStrategy.java | // Path: src/main/java/uk/co/silentsoftware/config/LanguageSupport.java
// public static String getCaption(String key) {
// String translation = null;
// if (captions != null) {
// try {
// translation = captions.getString(key);
// } catch(MissingResourceException ignore){}
// }
// // We're missing a key's value, use the key as the value :(
// if (translation == null || translation.trim().length()==0) {
// translation=key;
// }
// return translation;
// }
| import static uk.co.silentsoftware.config.LanguageSupport.getCaption; | /* Image to ZX Spec
* Copyright (C) 2020 Silent Software (Benjamin Brown)
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU Affero General Public License
* as published by the Free Software Foundation, either version 3
* of the License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package uk.co.silentsoftware.core.converters.image.orderedditherstrategy;
/**
* Special case of a magic square which has horizontal, vertical
* and diagonal totals all equal.
*
* An example of this dither is at http://en.wikipedia.org/wiki/Magic_square
*/
public class NasikMagicSquareDitherStrategy extends AbstractOrderedDitherStrategy implements OrderedDitherStrategy {
private static final int[] COEFFS = new int[]{
0,14,3,13,
11,5,8,6,
12,2,15,1,
7,9,4,10
};
/*
* {@inheritDoc}
*/
public int[] getCoefficients() {
return COEFFS;
}
/*
* {@inheritDoc}
*/
public int getMatrixWidth() {
return 4;
}
/*
* {@inheritDoc}
*/
public int getMatrixHeight() {
return 4;
}
/*
* {@inheritDoc}
*/
public String toString() { | // Path: src/main/java/uk/co/silentsoftware/config/LanguageSupport.java
// public static String getCaption(String key) {
// String translation = null;
// if (captions != null) {
// try {
// translation = captions.getString(key);
// } catch(MissingResourceException ignore){}
// }
// // We're missing a key's value, use the key as the value :(
// if (translation == null || translation.trim().length()==0) {
// translation=key;
// }
// return translation;
// }
// Path: src/main/java/uk/co/silentsoftware/core/converters/image/orderedditherstrategy/NasikMagicSquareDitherStrategy.java
import static uk.co.silentsoftware.config.LanguageSupport.getCaption;
/* Image to ZX Spec
* Copyright (C) 2020 Silent Software (Benjamin Brown)
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU Affero General Public License
* as published by the Free Software Foundation, either version 3
* of the License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package uk.co.silentsoftware.core.converters.image.orderedditherstrategy;
/**
* Special case of a magic square which has horizontal, vertical
* and diagonal totals all equal.
*
* An example of this dither is at http://en.wikipedia.org/wiki/Magic_square
*/
public class NasikMagicSquareDitherStrategy extends AbstractOrderedDitherStrategy implements OrderedDitherStrategy {
private static final int[] COEFFS = new int[]{
0,14,3,13,
11,5,8,6,
12,2,15,1,
7,9,4,10
};
/*
* {@inheritDoc}
*/
public int[] getCoefficients() {
return COEFFS;
}
/*
* {@inheritDoc}
*/
public int getMatrixWidth() {
return 4;
}
/*
* {@inheritDoc}
*/
public int getMatrixHeight() {
return 4;
}
/*
* {@inheritDoc}
*/
public String toString() { | return "Nasik Magic Square 4x4 ("+getCaption("ordered_dither")+")"; |