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 |
|---|---|---|---|---|---|---|
struts-community-plugins/struts2-jquery | struts2-jquery-mobile-plugin/src/main/java/com/jgeppert/struts2/jquery/mobile/views/velocity/components/RadioDirective.java | // Path: struts2-jquery-mobile-plugin/src/main/java/com/jgeppert/struts2/jquery/mobile/components/Radio.java
// @StrutsTag(name = "radio", tldTagClass = "com.jgeppert.struts2.jquery.mobile.views.jsp.ui.RadioTag", description = "Renders a radio button group", allowDynamicAttributes = true)
// public class Radio extends org.apache.struts2.components.CheckboxList implements ThemeableBean {
//
// public static final String TEMPLATE = "radio";
// public static final String COMPONENT_NAME = Radio.class.getName();
//
// private static final String PARAM_DATA_THEME = "dataTheme";
// private static final String PARAM_HORIZONTAL = "horizontal";
//
// protected String dataTheme;
// protected String horizontal;
//
// public Radio(ValueStack stack, HttpServletRequest request, HttpServletResponse response) {
// super(stack, request, response);
// }
//
// protected String getDefaultTemplate() {
// return TEMPLATE;
// }
//
// public void evaluateExtraParams() {
// super.evaluateExtraParams();
//
// if (dataTheme != null) {
// addParameter(PARAM_DATA_THEME, findString(dataTheme));
// }
// if (this.horizontal != null) {
// addParameter(PARAM_HORIZONTAL, findValue(this.horizontal, Boolean.class));
// }
// }
//
// @Override
// @StrutsTagSkipInheritance
// public void setTheme(String theme) {
// super.setTheme(theme);
// }
//
// @Override
// public String getTheme() {
// return "mobile";
// }
//
// @StrutsTagAttribute(description = "make a horizontal button set", defaultValue = "false", type = "Boolean")
// public void setHorizontal(String horizontal) {
// this.horizontal = horizontal;
// }
//
// @StrutsTagAttribute(description = "Set the Radio Button theme. e.g. a,b,c,d or e")
// public void setDataTheme(String dataTheme) {
// this.dataTheme = dataTheme;
// }
//
// }
| import com.jgeppert.struts2.jquery.mobile.components.Radio;
import com.opensymphony.xwork2.util.ValueStack;
import org.apache.struts2.components.Component;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse; | /*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package com.jgeppert.struts2.jquery.mobile.views.velocity.components;
/**
* @author <a href="http://www.jgeppert.com">Johannes Geppert</a>
* @see Radio
*/
public class RadioDirective extends JqueryMobileAbstractDirective {
public String getBeanName() {
return "radio";
}
protected Component getBean(ValueStack stack, HttpServletRequest req,
HttpServletResponse res) { | // Path: struts2-jquery-mobile-plugin/src/main/java/com/jgeppert/struts2/jquery/mobile/components/Radio.java
// @StrutsTag(name = "radio", tldTagClass = "com.jgeppert.struts2.jquery.mobile.views.jsp.ui.RadioTag", description = "Renders a radio button group", allowDynamicAttributes = true)
// public class Radio extends org.apache.struts2.components.CheckboxList implements ThemeableBean {
//
// public static final String TEMPLATE = "radio";
// public static final String COMPONENT_NAME = Radio.class.getName();
//
// private static final String PARAM_DATA_THEME = "dataTheme";
// private static final String PARAM_HORIZONTAL = "horizontal";
//
// protected String dataTheme;
// protected String horizontal;
//
// public Radio(ValueStack stack, HttpServletRequest request, HttpServletResponse response) {
// super(stack, request, response);
// }
//
// protected String getDefaultTemplate() {
// return TEMPLATE;
// }
//
// public void evaluateExtraParams() {
// super.evaluateExtraParams();
//
// if (dataTheme != null) {
// addParameter(PARAM_DATA_THEME, findString(dataTheme));
// }
// if (this.horizontal != null) {
// addParameter(PARAM_HORIZONTAL, findValue(this.horizontal, Boolean.class));
// }
// }
//
// @Override
// @StrutsTagSkipInheritance
// public void setTheme(String theme) {
// super.setTheme(theme);
// }
//
// @Override
// public String getTheme() {
// return "mobile";
// }
//
// @StrutsTagAttribute(description = "make a horizontal button set", defaultValue = "false", type = "Boolean")
// public void setHorizontal(String horizontal) {
// this.horizontal = horizontal;
// }
//
// @StrutsTagAttribute(description = "Set the Radio Button theme. e.g. a,b,c,d or e")
// public void setDataTheme(String dataTheme) {
// this.dataTheme = dataTheme;
// }
//
// }
// Path: struts2-jquery-mobile-plugin/src/main/java/com/jgeppert/struts2/jquery/mobile/views/velocity/components/RadioDirective.java
import com.jgeppert.struts2.jquery.mobile.components.Radio;
import com.opensymphony.xwork2.util.ValueStack;
import org.apache.struts2.components.Component;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
/*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package com.jgeppert.struts2.jquery.mobile.views.velocity.components;
/**
* @author <a href="http://www.jgeppert.com">Johannes Geppert</a>
* @see Radio
*/
public class RadioDirective extends JqueryMobileAbstractDirective {
public String getBeanName() {
return "radio";
}
protected Component getBean(ValueStack stack, HttpServletRequest req,
HttpServletResponse res) { | return new Radio(stack, req, res); |
struts-community-plugins/struts2-jquery | struts2-jquery-showcase/src/main/java/com/jgeppert/struts2/jquery/showcase/JsonSample.java | // Path: struts2-jquery-showcase/src/main/java/com/jgeppert/struts2/jquery/showcase/model/ListValue.java
// public class ListValue {
// private String myKey;
// private String myTitle;
// private String myValue;
//
// public ListValue(String myKey, String myValue) {
// this(myKey, myValue, null);
// }
//
// public ListValue(String myKey, String myValue, String myTitle) {
// super();
// this.myKey = myKey;
// this.myValue = myValue;
// this.myTitle = myTitle;
// }
//
// public String getMyKey() {
// return myKey;
// }
//
// public void setMyKey(String myKey) {
// this.myKey = myKey;
// }
//
// public String getMyTitle() {
// return myTitle;
// }
//
// public void setMyTitle(String myTitle) {
// this.myTitle = myTitle;
// }
//
// public String getMyValue() {
// return myValue;
// }
//
// public void setMyValue(String myValue) {
// this.myValue = myValue;
// }
// }
| import java.util.Map;
import com.jgeppert.struts2.jquery.showcase.model.ListValue;
import com.opensymphony.xwork2.ActionSupport;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.apache.struts2.convention.annotation.Action;
import org.apache.struts2.convention.annotation.Actions;
import org.apache.struts2.convention.annotation.Result;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List; | /*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package com.jgeppert.struts2.jquery.showcase;
public class JsonSample extends ActionSupport {
private static final long serialVersionUID = -2223948287805083119L;
private static final Log log = LogFactory.getLog(JsonSample.class);
private List<String> languageList; | // Path: struts2-jquery-showcase/src/main/java/com/jgeppert/struts2/jquery/showcase/model/ListValue.java
// public class ListValue {
// private String myKey;
// private String myTitle;
// private String myValue;
//
// public ListValue(String myKey, String myValue) {
// this(myKey, myValue, null);
// }
//
// public ListValue(String myKey, String myValue, String myTitle) {
// super();
// this.myKey = myKey;
// this.myValue = myValue;
// this.myTitle = myTitle;
// }
//
// public String getMyKey() {
// return myKey;
// }
//
// public void setMyKey(String myKey) {
// this.myKey = myKey;
// }
//
// public String getMyTitle() {
// return myTitle;
// }
//
// public void setMyTitle(String myTitle) {
// this.myTitle = myTitle;
// }
//
// public String getMyValue() {
// return myValue;
// }
//
// public void setMyValue(String myValue) {
// this.myValue = myValue;
// }
// }
// Path: struts2-jquery-showcase/src/main/java/com/jgeppert/struts2/jquery/showcase/JsonSample.java
import java.util.Map;
import com.jgeppert.struts2.jquery.showcase.model.ListValue;
import com.opensymphony.xwork2.ActionSupport;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.apache.struts2.convention.annotation.Action;
import org.apache.struts2.convention.annotation.Actions;
import org.apache.struts2.convention.annotation.Result;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
/*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package com.jgeppert.struts2.jquery.showcase;
public class JsonSample extends ActionSupport {
private static final long serialVersionUID = -2223948287805083119L;
private static final Log log = LogFactory.getLog(JsonSample.class);
private List<String> languageList; | private List<ListValue> languageObjList; |
SMXCore/SMXCore_NG | src/modules/MeterKamstrup.java | // Path: src/util/PropUtil.java
// public class PropUtil {
//
// public static Properties LoadFromFile(Properties pProp, String sFile) {
// try {
// if (pProp == null) {
// pProp = new Properties();
// }
// if (sFile.endsWith(".xml")) {
// pProp.loadFromXML(new FileInputStream(sFile));
// } else {
// pProp.load(new FileInputStream(sFile));
// }
//
// } catch (Exception ex) {
// //ex.printStackTrace();
// }
// return pProp;
// }
//
// public static void SaveToFile(Properties pProp, String sFile, String sComment) {
// try {
// if (sFile.endsWith(".xml")) {
// pProp.storeToXML(new FileOutputStream(sFile), sComment);
// } else {
// pProp.store(new FileOutputStream(sFile), sComment);
// }
//
// } catch (Exception ex) {
// // ex.printStackTrace();
// }
// }
//
// public static int GetInt(Properties pProp, String sKey, int iDefault) {
// try {
// return Integer.parseInt(pProp.getProperty(sKey, "").trim());
// } catch (Exception ex) {
//
// }
// return iDefault;
// }
//
// public static long GetLong(Properties pProp, String sKey, long lDefault) {
// try {
// return Long.parseLong(pProp.getProperty(sKey, "").trim());
// } catch (Exception ex) {
//
// }
// return lDefault;
// }
//
// public static double GetDouble(Properties pProp, String sKey, double lDefault) {
// try {
// return Double.parseDouble(pProp.getProperty(sKey, "").trim());
// } catch (Exception ex) {
//
// }
// return lDefault;
// }
//
// public static String GetString(Properties pProp, String sKey, String sDefault) {
// try {
// return pProp.getProperty(sKey, sDefault);
// } catch (Exception ex) {
// }
// return sDefault;
// }
// public static SimpleDateFormat sdfDate = new SimpleDateFormat("MM/dd/yyyy HH:mm:ss");
//
// public static Date GetDate(Properties pProp, String sKey, Date dtDefault) {
// Date dtRet;
// try {
// dtRet = sdfDate.parse(pProp.getProperty(sKey, ""));
// } catch (Exception ex) {
// dtRet = dtDefault;
// }
// return dtRet;
// }
//
// public static void PrintProp(Properties pProp) {
//
// Enumeration sKeys = pProp.keys();
// while (sKeys.hasMoreElements()) {
// try {
// String sKey = (String) sKeys.nextElement();
// String sValue = (String) pProp.get(sKey);
// System.out.println(sKey + " : " + sValue);
//
// } catch (Exception ex) {
// // System.out.println(ex.getMessage());
// }
// }
// }
//
// public static void SwitchKeyValue(Properties pInProp, Properties pOutProp) {
// try {
// if (pOutProp == null) {
// pOutProp = new Properties();
// }
// Enumeration sKeys = pInProp.keys();
// while (sKeys.hasMoreElements()) {
// String sKey = (String) sKeys.nextElement();
// String sValue = (String) pInProp.get(sKey);
// pOutProp.put(sValue, sKey);
// // System.out.println(sKey + " : " + sValue);
// }
// } catch (Exception ex) {
// }
// }
// }
| import java.io.BufferedReader;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.TimeZone;
import java.util.Properties;
import util.PropUtil;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileWriter;
import java.io.InputStreamReader;
import java.util.Enumeration;
| /*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package modules;
/**
*
* @author cristi
*/
public class MeterKamstrup extends Module {
@Override
public void Initialize() {
| // Path: src/util/PropUtil.java
// public class PropUtil {
//
// public static Properties LoadFromFile(Properties pProp, String sFile) {
// try {
// if (pProp == null) {
// pProp = new Properties();
// }
// if (sFile.endsWith(".xml")) {
// pProp.loadFromXML(new FileInputStream(sFile));
// } else {
// pProp.load(new FileInputStream(sFile));
// }
//
// } catch (Exception ex) {
// //ex.printStackTrace();
// }
// return pProp;
// }
//
// public static void SaveToFile(Properties pProp, String sFile, String sComment) {
// try {
// if (sFile.endsWith(".xml")) {
// pProp.storeToXML(new FileOutputStream(sFile), sComment);
// } else {
// pProp.store(new FileOutputStream(sFile), sComment);
// }
//
// } catch (Exception ex) {
// // ex.printStackTrace();
// }
// }
//
// public static int GetInt(Properties pProp, String sKey, int iDefault) {
// try {
// return Integer.parseInt(pProp.getProperty(sKey, "").trim());
// } catch (Exception ex) {
//
// }
// return iDefault;
// }
//
// public static long GetLong(Properties pProp, String sKey, long lDefault) {
// try {
// return Long.parseLong(pProp.getProperty(sKey, "").trim());
// } catch (Exception ex) {
//
// }
// return lDefault;
// }
//
// public static double GetDouble(Properties pProp, String sKey, double lDefault) {
// try {
// return Double.parseDouble(pProp.getProperty(sKey, "").trim());
// } catch (Exception ex) {
//
// }
// return lDefault;
// }
//
// public static String GetString(Properties pProp, String sKey, String sDefault) {
// try {
// return pProp.getProperty(sKey, sDefault);
// } catch (Exception ex) {
// }
// return sDefault;
// }
// public static SimpleDateFormat sdfDate = new SimpleDateFormat("MM/dd/yyyy HH:mm:ss");
//
// public static Date GetDate(Properties pProp, String sKey, Date dtDefault) {
// Date dtRet;
// try {
// dtRet = sdfDate.parse(pProp.getProperty(sKey, ""));
// } catch (Exception ex) {
// dtRet = dtDefault;
// }
// return dtRet;
// }
//
// public static void PrintProp(Properties pProp) {
//
// Enumeration sKeys = pProp.keys();
// while (sKeys.hasMoreElements()) {
// try {
// String sKey = (String) sKeys.nextElement();
// String sValue = (String) pProp.get(sKey);
// System.out.println(sKey + " : " + sValue);
//
// } catch (Exception ex) {
// // System.out.println(ex.getMessage());
// }
// }
// }
//
// public static void SwitchKeyValue(Properties pInProp, Properties pOutProp) {
// try {
// if (pOutProp == null) {
// pOutProp = new Properties();
// }
// Enumeration sKeys = pInProp.keys();
// while (sKeys.hasMoreElements()) {
// String sKey = (String) sKeys.nextElement();
// String sValue = (String) pInProp.get(sKey);
// pOutProp.put(sValue, sKey);
// // System.out.println(sKey + " : " + sValue);
// }
// } catch (Exception ex) {
// }
// }
// }
// Path: src/modules/MeterKamstrup.java
import java.io.BufferedReader;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.TimeZone;
import java.util.Properties;
import util.PropUtil;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileWriter;
import java.io.InputStreamReader;
import java.util.Enumeration;
/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package modules;
/**
*
* @author cristi
*/
public class MeterKamstrup extends Module {
@Override
public void Initialize() {
| pDataSet = mmManager.getSharedData(PropUtil.GetString(pAttributes, "pDataSet", sName));
|
SMXCore/SMXCore_NG | src/modules/MongoDBClient.java | // Path: src/util/PropUtil.java
// public class PropUtil {
//
// public static Properties LoadFromFile(Properties pProp, String sFile) {
// try {
// if (pProp == null) {
// pProp = new Properties();
// }
// if (sFile.endsWith(".xml")) {
// pProp.loadFromXML(new FileInputStream(sFile));
// } else {
// pProp.load(new FileInputStream(sFile));
// }
//
// } catch (Exception ex) {
// //ex.printStackTrace();
// }
// return pProp;
// }
//
// public static void SaveToFile(Properties pProp, String sFile, String sComment) {
// try {
// if (sFile.endsWith(".xml")) {
// pProp.storeToXML(new FileOutputStream(sFile), sComment);
// } else {
// pProp.store(new FileOutputStream(sFile), sComment);
// }
//
// } catch (Exception ex) {
// // ex.printStackTrace();
// }
// }
//
// public static int GetInt(Properties pProp, String sKey, int iDefault) {
// try {
// return Integer.parseInt(pProp.getProperty(sKey, "").trim());
// } catch (Exception ex) {
//
// }
// return iDefault;
// }
//
// public static long GetLong(Properties pProp, String sKey, long lDefault) {
// try {
// return Long.parseLong(pProp.getProperty(sKey, "").trim());
// } catch (Exception ex) {
//
// }
// return lDefault;
// }
//
// public static double GetDouble(Properties pProp, String sKey, double lDefault) {
// try {
// return Double.parseDouble(pProp.getProperty(sKey, "").trim());
// } catch (Exception ex) {
//
// }
// return lDefault;
// }
//
// public static String GetString(Properties pProp, String sKey, String sDefault) {
// try {
// return pProp.getProperty(sKey, sDefault);
// } catch (Exception ex) {
// }
// return sDefault;
// }
// public static SimpleDateFormat sdfDate = new SimpleDateFormat("MM/dd/yyyy HH:mm:ss");
//
// public static Date GetDate(Properties pProp, String sKey, Date dtDefault) {
// Date dtRet;
// try {
// dtRet = sdfDate.parse(pProp.getProperty(sKey, ""));
// } catch (Exception ex) {
// dtRet = dtDefault;
// }
// return dtRet;
// }
//
// public static void PrintProp(Properties pProp) {
//
// Enumeration sKeys = pProp.keys();
// while (sKeys.hasMoreElements()) {
// try {
// String sKey = (String) sKeys.nextElement();
// String sValue = (String) pProp.get(sKey);
// System.out.println(sKey + " : " + sValue);
//
// } catch (Exception ex) {
// // System.out.println(ex.getMessage());
// }
// }
// }
//
// public static void SwitchKeyValue(Properties pInProp, Properties pOutProp) {
// try {
// if (pOutProp == null) {
// pOutProp = new Properties();
// }
// Enumeration sKeys = pInProp.keys();
// while (sKeys.hasMoreElements()) {
// String sKey = (String) sKeys.nextElement();
// String sValue = (String) pInProp.get(sKey);
// pOutProp.put(sValue, sKey);
// // System.out.println(sKey + " : " + sValue);
// }
// } catch (Exception ex) {
// }
// }
// }
| import java.util.ArrayList;
import java.util.List;
import org.bson.Document;
import com.mongodb.MongoClientURI;
import com.mongodb.MongoClient;
import com.mongodb.client.MongoCollection;
import com.mongodb.client.MongoDatabase;
import com.mongodb.client.model.UpdateOptions;
import java.util.logging.Logger;
import java.util.logging.Level;
import com.mongodb.Block;
import com.mongodb.client.FindIterable;
import static com.mongodb.client.model.Filters.*;
import java.util.Enumeration;
import java.util.Properties;
import util.PropUtil;
| /*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package modules;
/**
*
* @author cristi
*/
public class MongoDBClient extends Module {
@Override
public void Initialize() {
| // Path: src/util/PropUtil.java
// public class PropUtil {
//
// public static Properties LoadFromFile(Properties pProp, String sFile) {
// try {
// if (pProp == null) {
// pProp = new Properties();
// }
// if (sFile.endsWith(".xml")) {
// pProp.loadFromXML(new FileInputStream(sFile));
// } else {
// pProp.load(new FileInputStream(sFile));
// }
//
// } catch (Exception ex) {
// //ex.printStackTrace();
// }
// return pProp;
// }
//
// public static void SaveToFile(Properties pProp, String sFile, String sComment) {
// try {
// if (sFile.endsWith(".xml")) {
// pProp.storeToXML(new FileOutputStream(sFile), sComment);
// } else {
// pProp.store(new FileOutputStream(sFile), sComment);
// }
//
// } catch (Exception ex) {
// // ex.printStackTrace();
// }
// }
//
// public static int GetInt(Properties pProp, String sKey, int iDefault) {
// try {
// return Integer.parseInt(pProp.getProperty(sKey, "").trim());
// } catch (Exception ex) {
//
// }
// return iDefault;
// }
//
// public static long GetLong(Properties pProp, String sKey, long lDefault) {
// try {
// return Long.parseLong(pProp.getProperty(sKey, "").trim());
// } catch (Exception ex) {
//
// }
// return lDefault;
// }
//
// public static double GetDouble(Properties pProp, String sKey, double lDefault) {
// try {
// return Double.parseDouble(pProp.getProperty(sKey, "").trim());
// } catch (Exception ex) {
//
// }
// return lDefault;
// }
//
// public static String GetString(Properties pProp, String sKey, String sDefault) {
// try {
// return pProp.getProperty(sKey, sDefault);
// } catch (Exception ex) {
// }
// return sDefault;
// }
// public static SimpleDateFormat sdfDate = new SimpleDateFormat("MM/dd/yyyy HH:mm:ss");
//
// public static Date GetDate(Properties pProp, String sKey, Date dtDefault) {
// Date dtRet;
// try {
// dtRet = sdfDate.parse(pProp.getProperty(sKey, ""));
// } catch (Exception ex) {
// dtRet = dtDefault;
// }
// return dtRet;
// }
//
// public static void PrintProp(Properties pProp) {
//
// Enumeration sKeys = pProp.keys();
// while (sKeys.hasMoreElements()) {
// try {
// String sKey = (String) sKeys.nextElement();
// String sValue = (String) pProp.get(sKey);
// System.out.println(sKey + " : " + sValue);
//
// } catch (Exception ex) {
// // System.out.println(ex.getMessage());
// }
// }
// }
//
// public static void SwitchKeyValue(Properties pInProp, Properties pOutProp) {
// try {
// if (pOutProp == null) {
// pOutProp = new Properties();
// }
// Enumeration sKeys = pInProp.keys();
// while (sKeys.hasMoreElements()) {
// String sKey = (String) sKeys.nextElement();
// String sValue = (String) pInProp.get(sKey);
// pOutProp.put(sValue, sKey);
// // System.out.println(sKey + " : " + sValue);
// }
// } catch (Exception ex) {
// }
// }
// }
// Path: src/modules/MongoDBClient.java
import java.util.ArrayList;
import java.util.List;
import org.bson.Document;
import com.mongodb.MongoClientURI;
import com.mongodb.MongoClient;
import com.mongodb.client.MongoCollection;
import com.mongodb.client.MongoDatabase;
import com.mongodb.client.model.UpdateOptions;
import java.util.logging.Logger;
import java.util.logging.Level;
import com.mongodb.Block;
import com.mongodb.client.FindIterable;
import static com.mongodb.client.model.Filters.*;
import java.util.Enumeration;
import java.util.Properties;
import util.PropUtil;
/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package modules;
/**
*
* @author cristi
*/
public class MongoDBClient extends Module {
@Override
public void Initialize() {
| sURI = PropUtil.GetString(pAttributes, "sURI", "mongodb://localhost");
|
SMXCore/SMXCore_NG | src/modules/MeterPQ.java | // Path: src/util/PropUtil.java
// public class PropUtil {
//
// public static Properties LoadFromFile(Properties pProp, String sFile) {
// try {
// if (pProp == null) {
// pProp = new Properties();
// }
// if (sFile.endsWith(".xml")) {
// pProp.loadFromXML(new FileInputStream(sFile));
// } else {
// pProp.load(new FileInputStream(sFile));
// }
//
// } catch (Exception ex) {
// //ex.printStackTrace();
// }
// return pProp;
// }
//
// public static void SaveToFile(Properties pProp, String sFile, String sComment) {
// try {
// if (sFile.endsWith(".xml")) {
// pProp.storeToXML(new FileOutputStream(sFile), sComment);
// } else {
// pProp.store(new FileOutputStream(sFile), sComment);
// }
//
// } catch (Exception ex) {
// // ex.printStackTrace();
// }
// }
//
// public static int GetInt(Properties pProp, String sKey, int iDefault) {
// try {
// return Integer.parseInt(pProp.getProperty(sKey, "").trim());
// } catch (Exception ex) {
//
// }
// return iDefault;
// }
//
// public static long GetLong(Properties pProp, String sKey, long lDefault) {
// try {
// return Long.parseLong(pProp.getProperty(sKey, "").trim());
// } catch (Exception ex) {
//
// }
// return lDefault;
// }
//
// public static double GetDouble(Properties pProp, String sKey, double lDefault) {
// try {
// return Double.parseDouble(pProp.getProperty(sKey, "").trim());
// } catch (Exception ex) {
//
// }
// return lDefault;
// }
//
// public static String GetString(Properties pProp, String sKey, String sDefault) {
// try {
// return pProp.getProperty(sKey, sDefault);
// } catch (Exception ex) {
// }
// return sDefault;
// }
// public static SimpleDateFormat sdfDate = new SimpleDateFormat("MM/dd/yyyy HH:mm:ss");
//
// public static Date GetDate(Properties pProp, String sKey, Date dtDefault) {
// Date dtRet;
// try {
// dtRet = sdfDate.parse(pProp.getProperty(sKey, ""));
// } catch (Exception ex) {
// dtRet = dtDefault;
// }
// return dtRet;
// }
//
// public static void PrintProp(Properties pProp) {
//
// Enumeration sKeys = pProp.keys();
// while (sKeys.hasMoreElements()) {
// try {
// String sKey = (String) sKeys.nextElement();
// String sValue = (String) pProp.get(sKey);
// System.out.println(sKey + " : " + sValue);
//
// } catch (Exception ex) {
// // System.out.println(ex.getMessage());
// }
// }
// }
//
// public static void SwitchKeyValue(Properties pInProp, Properties pOutProp) {
// try {
// if (pOutProp == null) {
// pOutProp = new Properties();
// }
// Enumeration sKeys = pInProp.keys();
// while (sKeys.hasMoreElements()) {
// String sKey = (String) sKeys.nextElement();
// String sValue = (String) pInProp.get(sKey);
// pOutProp.put(sValue, sKey);
// // System.out.println(sKey + " : " + sValue);
// }
// } catch (Exception ex) {
// }
// }
// }
| import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Properties;
import util.PropUtil;
import java.io.BufferedWriter;
import java.io.FileWriter;
import java.util.Enumeration;
| /*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package modules;
/**
*
* @author cristi
*/
public class MeterPQ extends Module {
@Override
public void Initialize() {
| // Path: src/util/PropUtil.java
// public class PropUtil {
//
// public static Properties LoadFromFile(Properties pProp, String sFile) {
// try {
// if (pProp == null) {
// pProp = new Properties();
// }
// if (sFile.endsWith(".xml")) {
// pProp.loadFromXML(new FileInputStream(sFile));
// } else {
// pProp.load(new FileInputStream(sFile));
// }
//
// } catch (Exception ex) {
// //ex.printStackTrace();
// }
// return pProp;
// }
//
// public static void SaveToFile(Properties pProp, String sFile, String sComment) {
// try {
// if (sFile.endsWith(".xml")) {
// pProp.storeToXML(new FileOutputStream(sFile), sComment);
// } else {
// pProp.store(new FileOutputStream(sFile), sComment);
// }
//
// } catch (Exception ex) {
// // ex.printStackTrace();
// }
// }
//
// public static int GetInt(Properties pProp, String sKey, int iDefault) {
// try {
// return Integer.parseInt(pProp.getProperty(sKey, "").trim());
// } catch (Exception ex) {
//
// }
// return iDefault;
// }
//
// public static long GetLong(Properties pProp, String sKey, long lDefault) {
// try {
// return Long.parseLong(pProp.getProperty(sKey, "").trim());
// } catch (Exception ex) {
//
// }
// return lDefault;
// }
//
// public static double GetDouble(Properties pProp, String sKey, double lDefault) {
// try {
// return Double.parseDouble(pProp.getProperty(sKey, "").trim());
// } catch (Exception ex) {
//
// }
// return lDefault;
// }
//
// public static String GetString(Properties pProp, String sKey, String sDefault) {
// try {
// return pProp.getProperty(sKey, sDefault);
// } catch (Exception ex) {
// }
// return sDefault;
// }
// public static SimpleDateFormat sdfDate = new SimpleDateFormat("MM/dd/yyyy HH:mm:ss");
//
// public static Date GetDate(Properties pProp, String sKey, Date dtDefault) {
// Date dtRet;
// try {
// dtRet = sdfDate.parse(pProp.getProperty(sKey, ""));
// } catch (Exception ex) {
// dtRet = dtDefault;
// }
// return dtRet;
// }
//
// public static void PrintProp(Properties pProp) {
//
// Enumeration sKeys = pProp.keys();
// while (sKeys.hasMoreElements()) {
// try {
// String sKey = (String) sKeys.nextElement();
// String sValue = (String) pProp.get(sKey);
// System.out.println(sKey + " : " + sValue);
//
// } catch (Exception ex) {
// // System.out.println(ex.getMessage());
// }
// }
// }
//
// public static void SwitchKeyValue(Properties pInProp, Properties pOutProp) {
// try {
// if (pOutProp == null) {
// pOutProp = new Properties();
// }
// Enumeration sKeys = pInProp.keys();
// while (sKeys.hasMoreElements()) {
// String sKey = (String) sKeys.nextElement();
// String sValue = (String) pInProp.get(sKey);
// pOutProp.put(sValue, sKey);
// // System.out.println(sKey + " : " + sValue);
// }
// } catch (Exception ex) {
// }
// }
// }
// Path: src/modules/MeterPQ.java
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Properties;
import util.PropUtil;
import java.io.BufferedWriter;
import java.io.FileWriter;
import java.util.Enumeration;
/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package modules;
/**
*
* @author cristi
*/
public class MeterPQ extends Module {
@Override
public void Initialize() {
| pDataSet = mmManager.getSharedData(PropUtil.GetString(pAttributes, "pDataSet", sName));
|
SMXCore/SMXCore_NG | src/modules/contrib/ProConSt.java | // Path: src/modules/Module.java
// public class Module extends Thread{
//
// protected volatile Properties pAttributes = new Properties(); // The attributes of the current module, loaded from a file.
// protected String sAttributesFile=""; // The file it is loaded from
// protected String sName = ""; // The name of the instance of the module
// protected ModulesManager mmManager = null; // The module manager
// protected Logger logger = null; // The logger used
// protected volatile boolean bReinitialize = false;
//
// public void setAttributes(Properties pSetAttributes) {
// pAttributes = pSetAttributes;
// }
//
// public void Initialize() {
//
// }
//
// public void Start() {
//
// }
//
// public void QueueTime() {
//
// }
//
// public void LoadConfig() {
// LoadTxtConfig();
// }
//
// void LoadTxtConfig() {
// PropUtil.LoadFromFile(pAttributes, sAttributesFile);
// }
//
// }
//
// Path: src/util/PropUtil.java
// public class PropUtil {
//
// public static Properties LoadFromFile(Properties pProp, String sFile) {
// try {
// if (pProp == null) {
// pProp = new Properties();
// }
// if (sFile.endsWith(".xml")) {
// pProp.loadFromXML(new FileInputStream(sFile));
// } else {
// pProp.load(new FileInputStream(sFile));
// }
//
// } catch (Exception ex) {
// //ex.printStackTrace();
// }
// return pProp;
// }
//
// public static void SaveToFile(Properties pProp, String sFile, String sComment) {
// try {
// if (sFile.endsWith(".xml")) {
// pProp.storeToXML(new FileOutputStream(sFile), sComment);
// } else {
// pProp.store(new FileOutputStream(sFile), sComment);
// }
//
// } catch (Exception ex) {
// // ex.printStackTrace();
// }
// }
//
// public static int GetInt(Properties pProp, String sKey, int iDefault) {
// try {
// return Integer.parseInt(pProp.getProperty(sKey, "").trim());
// } catch (Exception ex) {
//
// }
// return iDefault;
// }
//
// public static long GetLong(Properties pProp, String sKey, long lDefault) {
// try {
// return Long.parseLong(pProp.getProperty(sKey, "").trim());
// } catch (Exception ex) {
//
// }
// return lDefault;
// }
//
// public static double GetDouble(Properties pProp, String sKey, double lDefault) {
// try {
// return Double.parseDouble(pProp.getProperty(sKey, "").trim());
// } catch (Exception ex) {
//
// }
// return lDefault;
// }
//
// public static String GetString(Properties pProp, String sKey, String sDefault) {
// try {
// return pProp.getProperty(sKey, sDefault);
// } catch (Exception ex) {
// }
// return sDefault;
// }
// public static SimpleDateFormat sdfDate = new SimpleDateFormat("MM/dd/yyyy HH:mm:ss");
//
// public static Date GetDate(Properties pProp, String sKey, Date dtDefault) {
// Date dtRet;
// try {
// dtRet = sdfDate.parse(pProp.getProperty(sKey, ""));
// } catch (Exception ex) {
// dtRet = dtDefault;
// }
// return dtRet;
// }
//
// public static void PrintProp(Properties pProp) {
//
// Enumeration sKeys = pProp.keys();
// while (sKeys.hasMoreElements()) {
// try {
// String sKey = (String) sKeys.nextElement();
// String sValue = (String) pProp.get(sKey);
// System.out.println(sKey + " : " + sValue);
//
// } catch (Exception ex) {
// // System.out.println(ex.getMessage());
// }
// }
// }
//
// public static void SwitchKeyValue(Properties pInProp, Properties pOutProp) {
// try {
// if (pOutProp == null) {
// pOutProp = new Properties();
// }
// Enumeration sKeys = pInProp.keys();
// while (sKeys.hasMoreElements()) {
// String sKey = (String) sKeys.nextElement();
// String sValue = (String) pInProp.get(sKey);
// pOutProp.put(sValue, sKey);
// // System.out.println(sKey + " : " + sValue);
// }
// } catch (Exception ex) {
// }
// }
// }
| import modules.Module;
import util.PropUtil;
import java.util.Properties;
| /*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package modules.contrib;
/**
*
* @author Stela
*/
public class ProConSt extends Module {
@Override
public void Initialize() {
| // Path: src/modules/Module.java
// public class Module extends Thread{
//
// protected volatile Properties pAttributes = new Properties(); // The attributes of the current module, loaded from a file.
// protected String sAttributesFile=""; // The file it is loaded from
// protected String sName = ""; // The name of the instance of the module
// protected ModulesManager mmManager = null; // The module manager
// protected Logger logger = null; // The logger used
// protected volatile boolean bReinitialize = false;
//
// public void setAttributes(Properties pSetAttributes) {
// pAttributes = pSetAttributes;
// }
//
// public void Initialize() {
//
// }
//
// public void Start() {
//
// }
//
// public void QueueTime() {
//
// }
//
// public void LoadConfig() {
// LoadTxtConfig();
// }
//
// void LoadTxtConfig() {
// PropUtil.LoadFromFile(pAttributes, sAttributesFile);
// }
//
// }
//
// Path: src/util/PropUtil.java
// public class PropUtil {
//
// public static Properties LoadFromFile(Properties pProp, String sFile) {
// try {
// if (pProp == null) {
// pProp = new Properties();
// }
// if (sFile.endsWith(".xml")) {
// pProp.loadFromXML(new FileInputStream(sFile));
// } else {
// pProp.load(new FileInputStream(sFile));
// }
//
// } catch (Exception ex) {
// //ex.printStackTrace();
// }
// return pProp;
// }
//
// public static void SaveToFile(Properties pProp, String sFile, String sComment) {
// try {
// if (sFile.endsWith(".xml")) {
// pProp.storeToXML(new FileOutputStream(sFile), sComment);
// } else {
// pProp.store(new FileOutputStream(sFile), sComment);
// }
//
// } catch (Exception ex) {
// // ex.printStackTrace();
// }
// }
//
// public static int GetInt(Properties pProp, String sKey, int iDefault) {
// try {
// return Integer.parseInt(pProp.getProperty(sKey, "").trim());
// } catch (Exception ex) {
//
// }
// return iDefault;
// }
//
// public static long GetLong(Properties pProp, String sKey, long lDefault) {
// try {
// return Long.parseLong(pProp.getProperty(sKey, "").trim());
// } catch (Exception ex) {
//
// }
// return lDefault;
// }
//
// public static double GetDouble(Properties pProp, String sKey, double lDefault) {
// try {
// return Double.parseDouble(pProp.getProperty(sKey, "").trim());
// } catch (Exception ex) {
//
// }
// return lDefault;
// }
//
// public static String GetString(Properties pProp, String sKey, String sDefault) {
// try {
// return pProp.getProperty(sKey, sDefault);
// } catch (Exception ex) {
// }
// return sDefault;
// }
// public static SimpleDateFormat sdfDate = new SimpleDateFormat("MM/dd/yyyy HH:mm:ss");
//
// public static Date GetDate(Properties pProp, String sKey, Date dtDefault) {
// Date dtRet;
// try {
// dtRet = sdfDate.parse(pProp.getProperty(sKey, ""));
// } catch (Exception ex) {
// dtRet = dtDefault;
// }
// return dtRet;
// }
//
// public static void PrintProp(Properties pProp) {
//
// Enumeration sKeys = pProp.keys();
// while (sKeys.hasMoreElements()) {
// try {
// String sKey = (String) sKeys.nextElement();
// String sValue = (String) pProp.get(sKey);
// System.out.println(sKey + " : " + sValue);
//
// } catch (Exception ex) {
// // System.out.println(ex.getMessage());
// }
// }
// }
//
// public static void SwitchKeyValue(Properties pInProp, Properties pOutProp) {
// try {
// if (pOutProp == null) {
// pOutProp = new Properties();
// }
// Enumeration sKeys = pInProp.keys();
// while (sKeys.hasMoreElements()) {
// String sKey = (String) sKeys.nextElement();
// String sValue = (String) pInProp.get(sKey);
// pOutProp.put(sValue, sKey);
// // System.out.println(sKey + " : " + sValue);
// }
// } catch (Exception ex) {
// }
// }
// }
// Path: src/modules/contrib/ProConSt.java
import modules.Module;
import util.PropUtil;
import java.util.Properties;
/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package modules.contrib;
/**
*
* @author Stela
*/
public class ProConSt extends Module {
@Override
public void Initialize() {
| pDataSet = mmManager.getSharedData(PropUtil.GetString(pAttributes, "pDataSet", sName));
|
SMXCore/SMXCore_NG | src/modules/MeterVirtual.java | // Path: src/util/PropUtil.java
// public class PropUtil {
//
// public static Properties LoadFromFile(Properties pProp, String sFile) {
// try {
// if (pProp == null) {
// pProp = new Properties();
// }
// if (sFile.endsWith(".xml")) {
// pProp.loadFromXML(new FileInputStream(sFile));
// } else {
// pProp.load(new FileInputStream(sFile));
// }
//
// } catch (Exception ex) {
// //ex.printStackTrace();
// }
// return pProp;
// }
//
// public static void SaveToFile(Properties pProp, String sFile, String sComment) {
// try {
// if (sFile.endsWith(".xml")) {
// pProp.storeToXML(new FileOutputStream(sFile), sComment);
// } else {
// pProp.store(new FileOutputStream(sFile), sComment);
// }
//
// } catch (Exception ex) {
// // ex.printStackTrace();
// }
// }
//
// public static int GetInt(Properties pProp, String sKey, int iDefault) {
// try {
// return Integer.parseInt(pProp.getProperty(sKey, "").trim());
// } catch (Exception ex) {
//
// }
// return iDefault;
// }
//
// public static long GetLong(Properties pProp, String sKey, long lDefault) {
// try {
// return Long.parseLong(pProp.getProperty(sKey, "").trim());
// } catch (Exception ex) {
//
// }
// return lDefault;
// }
//
// public static double GetDouble(Properties pProp, String sKey, double lDefault) {
// try {
// return Double.parseDouble(pProp.getProperty(sKey, "").trim());
// } catch (Exception ex) {
//
// }
// return lDefault;
// }
//
// public static String GetString(Properties pProp, String sKey, String sDefault) {
// try {
// return pProp.getProperty(sKey, sDefault);
// } catch (Exception ex) {
// }
// return sDefault;
// }
// public static SimpleDateFormat sdfDate = new SimpleDateFormat("MM/dd/yyyy HH:mm:ss");
//
// public static Date GetDate(Properties pProp, String sKey, Date dtDefault) {
// Date dtRet;
// try {
// dtRet = sdfDate.parse(pProp.getProperty(sKey, ""));
// } catch (Exception ex) {
// dtRet = dtDefault;
// }
// return dtRet;
// }
//
// public static void PrintProp(Properties pProp) {
//
// Enumeration sKeys = pProp.keys();
// while (sKeys.hasMoreElements()) {
// try {
// String sKey = (String) sKeys.nextElement();
// String sValue = (String) pProp.get(sKey);
// System.out.println(sKey + " : " + sValue);
//
// } catch (Exception ex) {
// // System.out.println(ex.getMessage());
// }
// }
// }
//
// public static void SwitchKeyValue(Properties pInProp, Properties pOutProp) {
// try {
// if (pOutProp == null) {
// pOutProp = new Properties();
// }
// Enumeration sKeys = pInProp.keys();
// while (sKeys.hasMoreElements()) {
// String sKey = (String) sKeys.nextElement();
// String sValue = (String) pInProp.get(sKey);
// pOutProp.put(sValue, sKey);
// // System.out.println(sKey + " : " + sValue);
// }
// } catch (Exception ex) {
// }
// }
// }
| import java.util.Date;
import java.util.Properties;
import util.PropUtil;
import java.text.SimpleDateFormat;
| /*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package modules;
/**
*
* @author cristi
*/
public class MeterVirtual extends Module {
@Override
public void Initialize() {
| // Path: src/util/PropUtil.java
// public class PropUtil {
//
// public static Properties LoadFromFile(Properties pProp, String sFile) {
// try {
// if (pProp == null) {
// pProp = new Properties();
// }
// if (sFile.endsWith(".xml")) {
// pProp.loadFromXML(new FileInputStream(sFile));
// } else {
// pProp.load(new FileInputStream(sFile));
// }
//
// } catch (Exception ex) {
// //ex.printStackTrace();
// }
// return pProp;
// }
//
// public static void SaveToFile(Properties pProp, String sFile, String sComment) {
// try {
// if (sFile.endsWith(".xml")) {
// pProp.storeToXML(new FileOutputStream(sFile), sComment);
// } else {
// pProp.store(new FileOutputStream(sFile), sComment);
// }
//
// } catch (Exception ex) {
// // ex.printStackTrace();
// }
// }
//
// public static int GetInt(Properties pProp, String sKey, int iDefault) {
// try {
// return Integer.parseInt(pProp.getProperty(sKey, "").trim());
// } catch (Exception ex) {
//
// }
// return iDefault;
// }
//
// public static long GetLong(Properties pProp, String sKey, long lDefault) {
// try {
// return Long.parseLong(pProp.getProperty(sKey, "").trim());
// } catch (Exception ex) {
//
// }
// return lDefault;
// }
//
// public static double GetDouble(Properties pProp, String sKey, double lDefault) {
// try {
// return Double.parseDouble(pProp.getProperty(sKey, "").trim());
// } catch (Exception ex) {
//
// }
// return lDefault;
// }
//
// public static String GetString(Properties pProp, String sKey, String sDefault) {
// try {
// return pProp.getProperty(sKey, sDefault);
// } catch (Exception ex) {
// }
// return sDefault;
// }
// public static SimpleDateFormat sdfDate = new SimpleDateFormat("MM/dd/yyyy HH:mm:ss");
//
// public static Date GetDate(Properties pProp, String sKey, Date dtDefault) {
// Date dtRet;
// try {
// dtRet = sdfDate.parse(pProp.getProperty(sKey, ""));
// } catch (Exception ex) {
// dtRet = dtDefault;
// }
// return dtRet;
// }
//
// public static void PrintProp(Properties pProp) {
//
// Enumeration sKeys = pProp.keys();
// while (sKeys.hasMoreElements()) {
// try {
// String sKey = (String) sKeys.nextElement();
// String sValue = (String) pProp.get(sKey);
// System.out.println(sKey + " : " + sValue);
//
// } catch (Exception ex) {
// // System.out.println(ex.getMessage());
// }
// }
// }
//
// public static void SwitchKeyValue(Properties pInProp, Properties pOutProp) {
// try {
// if (pOutProp == null) {
// pOutProp = new Properties();
// }
// Enumeration sKeys = pInProp.keys();
// while (sKeys.hasMoreElements()) {
// String sKey = (String) sKeys.nextElement();
// String sValue = (String) pInProp.get(sKey);
// pOutProp.put(sValue, sKey);
// // System.out.println(sKey + " : " + sValue);
// }
// } catch (Exception ex) {
// }
// }
// }
// Path: src/modules/MeterVirtual.java
import java.util.Date;
import java.util.Properties;
import util.PropUtil;
import java.text.SimpleDateFormat;
/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package modules;
/**
*
* @author cristi
*/
public class MeterVirtual extends Module {
@Override
public void Initialize() {
| pDataSet = mmManager.getSharedData(PropUtil.GetString(pAttributes, "pDataSet", sName));
|
SMXCore/SMXCore_NG | src/modules/FileStorage.java | // Path: src/util/PropUtil.java
// public class PropUtil {
//
// public static Properties LoadFromFile(Properties pProp, String sFile) {
// try {
// if (pProp == null) {
// pProp = new Properties();
// }
// if (sFile.endsWith(".xml")) {
// pProp.loadFromXML(new FileInputStream(sFile));
// } else {
// pProp.load(new FileInputStream(sFile));
// }
//
// } catch (Exception ex) {
// //ex.printStackTrace();
// }
// return pProp;
// }
//
// public static void SaveToFile(Properties pProp, String sFile, String sComment) {
// try {
// if (sFile.endsWith(".xml")) {
// pProp.storeToXML(new FileOutputStream(sFile), sComment);
// } else {
// pProp.store(new FileOutputStream(sFile), sComment);
// }
//
// } catch (Exception ex) {
// // ex.printStackTrace();
// }
// }
//
// public static int GetInt(Properties pProp, String sKey, int iDefault) {
// try {
// return Integer.parseInt(pProp.getProperty(sKey, "").trim());
// } catch (Exception ex) {
//
// }
// return iDefault;
// }
//
// public static long GetLong(Properties pProp, String sKey, long lDefault) {
// try {
// return Long.parseLong(pProp.getProperty(sKey, "").trim());
// } catch (Exception ex) {
//
// }
// return lDefault;
// }
//
// public static double GetDouble(Properties pProp, String sKey, double lDefault) {
// try {
// return Double.parseDouble(pProp.getProperty(sKey, "").trim());
// } catch (Exception ex) {
//
// }
// return lDefault;
// }
//
// public static String GetString(Properties pProp, String sKey, String sDefault) {
// try {
// return pProp.getProperty(sKey, sDefault);
// } catch (Exception ex) {
// }
// return sDefault;
// }
// public static SimpleDateFormat sdfDate = new SimpleDateFormat("MM/dd/yyyy HH:mm:ss");
//
// public static Date GetDate(Properties pProp, String sKey, Date dtDefault) {
// Date dtRet;
// try {
// dtRet = sdfDate.parse(pProp.getProperty(sKey, ""));
// } catch (Exception ex) {
// dtRet = dtDefault;
// }
// return dtRet;
// }
//
// public static void PrintProp(Properties pProp) {
//
// Enumeration sKeys = pProp.keys();
// while (sKeys.hasMoreElements()) {
// try {
// String sKey = (String) sKeys.nextElement();
// String sValue = (String) pProp.get(sKey);
// System.out.println(sKey + " : " + sValue);
//
// } catch (Exception ex) {
// // System.out.println(ex.getMessage());
// }
// }
// }
//
// public static void SwitchKeyValue(Properties pInProp, Properties pOutProp) {
// try {
// if (pOutProp == null) {
// pOutProp = new Properties();
// }
// Enumeration sKeys = pInProp.keys();
// while (sKeys.hasMoreElements()) {
// String sKey = (String) sKeys.nextElement();
// String sValue = (String) pInProp.get(sKey);
// pOutProp.put(sValue, sKey);
// // System.out.println(sKey + " : " + sValue);
// }
// } catch (Exception ex) {
// }
// }
// }
| import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Properties;
import util.PropUtil;
import java.io.BufferedWriter;
import java.io.FileInputStream;
import java.io.FileWriter;
import java.util.ArrayList;
import java.util.Enumeration;
import java.util.Hashtable;
import java.util.Iterator;
import java.util.Map;
import java.util.regex.Pattern;
import javax.json.Json;
import javax.json.JsonArray;
import javax.json.JsonNumber;
import javax.json.JsonObject;
import javax.json.JsonReader;
import javax.json.JsonString;
import javax.json.JsonValue;
| /*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package modules;
/**
*
* @author cristi, mihai
*/
public class FileStorage extends Module {
@Override
public void Initialize() {
| // Path: src/util/PropUtil.java
// public class PropUtil {
//
// public static Properties LoadFromFile(Properties pProp, String sFile) {
// try {
// if (pProp == null) {
// pProp = new Properties();
// }
// if (sFile.endsWith(".xml")) {
// pProp.loadFromXML(new FileInputStream(sFile));
// } else {
// pProp.load(new FileInputStream(sFile));
// }
//
// } catch (Exception ex) {
// //ex.printStackTrace();
// }
// return pProp;
// }
//
// public static void SaveToFile(Properties pProp, String sFile, String sComment) {
// try {
// if (sFile.endsWith(".xml")) {
// pProp.storeToXML(new FileOutputStream(sFile), sComment);
// } else {
// pProp.store(new FileOutputStream(sFile), sComment);
// }
//
// } catch (Exception ex) {
// // ex.printStackTrace();
// }
// }
//
// public static int GetInt(Properties pProp, String sKey, int iDefault) {
// try {
// return Integer.parseInt(pProp.getProperty(sKey, "").trim());
// } catch (Exception ex) {
//
// }
// return iDefault;
// }
//
// public static long GetLong(Properties pProp, String sKey, long lDefault) {
// try {
// return Long.parseLong(pProp.getProperty(sKey, "").trim());
// } catch (Exception ex) {
//
// }
// return lDefault;
// }
//
// public static double GetDouble(Properties pProp, String sKey, double lDefault) {
// try {
// return Double.parseDouble(pProp.getProperty(sKey, "").trim());
// } catch (Exception ex) {
//
// }
// return lDefault;
// }
//
// public static String GetString(Properties pProp, String sKey, String sDefault) {
// try {
// return pProp.getProperty(sKey, sDefault);
// } catch (Exception ex) {
// }
// return sDefault;
// }
// public static SimpleDateFormat sdfDate = new SimpleDateFormat("MM/dd/yyyy HH:mm:ss");
//
// public static Date GetDate(Properties pProp, String sKey, Date dtDefault) {
// Date dtRet;
// try {
// dtRet = sdfDate.parse(pProp.getProperty(sKey, ""));
// } catch (Exception ex) {
// dtRet = dtDefault;
// }
// return dtRet;
// }
//
// public static void PrintProp(Properties pProp) {
//
// Enumeration sKeys = pProp.keys();
// while (sKeys.hasMoreElements()) {
// try {
// String sKey = (String) sKeys.nextElement();
// String sValue = (String) pProp.get(sKey);
// System.out.println(sKey + " : " + sValue);
//
// } catch (Exception ex) {
// // System.out.println(ex.getMessage());
// }
// }
// }
//
// public static void SwitchKeyValue(Properties pInProp, Properties pOutProp) {
// try {
// if (pOutProp == null) {
// pOutProp = new Properties();
// }
// Enumeration sKeys = pInProp.keys();
// while (sKeys.hasMoreElements()) {
// String sKey = (String) sKeys.nextElement();
// String sValue = (String) pInProp.get(sKey);
// pOutProp.put(sValue, sKey);
// // System.out.println(sKey + " : " + sValue);
// }
// } catch (Exception ex) {
// }
// }
// }
// Path: src/modules/FileStorage.java
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Properties;
import util.PropUtil;
import java.io.BufferedWriter;
import java.io.FileInputStream;
import java.io.FileWriter;
import java.util.ArrayList;
import java.util.Enumeration;
import java.util.Hashtable;
import java.util.Iterator;
import java.util.Map;
import java.util.regex.Pattern;
import javax.json.Json;
import javax.json.JsonArray;
import javax.json.JsonNumber;
import javax.json.JsonObject;
import javax.json.JsonReader;
import javax.json.JsonString;
import javax.json.JsonValue;
/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package modules;
/**
*
* @author cristi, mihai
*/
public class FileStorage extends Module {
@Override
public void Initialize() {
| pDataSet = mmManager.getSharedData(PropUtil.GetString(pAttributes, "pDataSet", sName));
|
SMXCore/SMXCore_NG | src/modules/MeterModbus.java | // Path: src/util/PropUtil.java
// public class PropUtil {
//
// public static Properties LoadFromFile(Properties pProp, String sFile) {
// try {
// if (pProp == null) {
// pProp = new Properties();
// }
// if (sFile.endsWith(".xml")) {
// pProp.loadFromXML(new FileInputStream(sFile));
// } else {
// pProp.load(new FileInputStream(sFile));
// }
//
// } catch (Exception ex) {
// //ex.printStackTrace();
// }
// return pProp;
// }
//
// public static void SaveToFile(Properties pProp, String sFile, String sComment) {
// try {
// if (sFile.endsWith(".xml")) {
// pProp.storeToXML(new FileOutputStream(sFile), sComment);
// } else {
// pProp.store(new FileOutputStream(sFile), sComment);
// }
//
// } catch (Exception ex) {
// // ex.printStackTrace();
// }
// }
//
// public static int GetInt(Properties pProp, String sKey, int iDefault) {
// try {
// return Integer.parseInt(pProp.getProperty(sKey, "").trim());
// } catch (Exception ex) {
//
// }
// return iDefault;
// }
//
// public static long GetLong(Properties pProp, String sKey, long lDefault) {
// try {
// return Long.parseLong(pProp.getProperty(sKey, "").trim());
// } catch (Exception ex) {
//
// }
// return lDefault;
// }
//
// public static double GetDouble(Properties pProp, String sKey, double lDefault) {
// try {
// return Double.parseDouble(pProp.getProperty(sKey, "").trim());
// } catch (Exception ex) {
//
// }
// return lDefault;
// }
//
// public static String GetString(Properties pProp, String sKey, String sDefault) {
// try {
// return pProp.getProperty(sKey, sDefault);
// } catch (Exception ex) {
// }
// return sDefault;
// }
// public static SimpleDateFormat sdfDate = new SimpleDateFormat("MM/dd/yyyy HH:mm:ss");
//
// public static Date GetDate(Properties pProp, String sKey, Date dtDefault) {
// Date dtRet;
// try {
// dtRet = sdfDate.parse(pProp.getProperty(sKey, ""));
// } catch (Exception ex) {
// dtRet = dtDefault;
// }
// return dtRet;
// }
//
// public static void PrintProp(Properties pProp) {
//
// Enumeration sKeys = pProp.keys();
// while (sKeys.hasMoreElements()) {
// try {
// String sKey = (String) sKeys.nextElement();
// String sValue = (String) pProp.get(sKey);
// System.out.println(sKey + " : " + sValue);
//
// } catch (Exception ex) {
// // System.out.println(ex.getMessage());
// }
// }
// }
//
// public static void SwitchKeyValue(Properties pInProp, Properties pOutProp) {
// try {
// if (pOutProp == null) {
// pOutProp = new Properties();
// }
// Enumeration sKeys = pInProp.keys();
// while (sKeys.hasMoreElements()) {
// String sKey = (String) sKeys.nextElement();
// String sValue = (String) pInProp.get(sKey);
// pOutProp.put(sValue, sKey);
// // System.out.println(sKey + " : " + sValue);
// }
// } catch (Exception ex) {
// }
// }
// }
| import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Properties;
import util.PropUtil;
import java.io.BufferedWriter;
import java.io.FileWriter;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.InetSocketAddress;
import java.net.Socket;
import java.text.DateFormat;
import java.util.Enumeration;
import java.util.TimeZone;
| /*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package modules;
/**
*
* @author cristi, mihai
*/
public class MeterModbus extends Module {
@Override
public void Initialize() {
| // Path: src/util/PropUtil.java
// public class PropUtil {
//
// public static Properties LoadFromFile(Properties pProp, String sFile) {
// try {
// if (pProp == null) {
// pProp = new Properties();
// }
// if (sFile.endsWith(".xml")) {
// pProp.loadFromXML(new FileInputStream(sFile));
// } else {
// pProp.load(new FileInputStream(sFile));
// }
//
// } catch (Exception ex) {
// //ex.printStackTrace();
// }
// return pProp;
// }
//
// public static void SaveToFile(Properties pProp, String sFile, String sComment) {
// try {
// if (sFile.endsWith(".xml")) {
// pProp.storeToXML(new FileOutputStream(sFile), sComment);
// } else {
// pProp.store(new FileOutputStream(sFile), sComment);
// }
//
// } catch (Exception ex) {
// // ex.printStackTrace();
// }
// }
//
// public static int GetInt(Properties pProp, String sKey, int iDefault) {
// try {
// return Integer.parseInt(pProp.getProperty(sKey, "").trim());
// } catch (Exception ex) {
//
// }
// return iDefault;
// }
//
// public static long GetLong(Properties pProp, String sKey, long lDefault) {
// try {
// return Long.parseLong(pProp.getProperty(sKey, "").trim());
// } catch (Exception ex) {
//
// }
// return lDefault;
// }
//
// public static double GetDouble(Properties pProp, String sKey, double lDefault) {
// try {
// return Double.parseDouble(pProp.getProperty(sKey, "").trim());
// } catch (Exception ex) {
//
// }
// return lDefault;
// }
//
// public static String GetString(Properties pProp, String sKey, String sDefault) {
// try {
// return pProp.getProperty(sKey, sDefault);
// } catch (Exception ex) {
// }
// return sDefault;
// }
// public static SimpleDateFormat sdfDate = new SimpleDateFormat("MM/dd/yyyy HH:mm:ss");
//
// public static Date GetDate(Properties pProp, String sKey, Date dtDefault) {
// Date dtRet;
// try {
// dtRet = sdfDate.parse(pProp.getProperty(sKey, ""));
// } catch (Exception ex) {
// dtRet = dtDefault;
// }
// return dtRet;
// }
//
// public static void PrintProp(Properties pProp) {
//
// Enumeration sKeys = pProp.keys();
// while (sKeys.hasMoreElements()) {
// try {
// String sKey = (String) sKeys.nextElement();
// String sValue = (String) pProp.get(sKey);
// System.out.println(sKey + " : " + sValue);
//
// } catch (Exception ex) {
// // System.out.println(ex.getMessage());
// }
// }
// }
//
// public static void SwitchKeyValue(Properties pInProp, Properties pOutProp) {
// try {
// if (pOutProp == null) {
// pOutProp = new Properties();
// }
// Enumeration sKeys = pInProp.keys();
// while (sKeys.hasMoreElements()) {
// String sKey = (String) sKeys.nextElement();
// String sValue = (String) pInProp.get(sKey);
// pOutProp.put(sValue, sKey);
// // System.out.println(sKey + " : " + sValue);
// }
// } catch (Exception ex) {
// }
// }
// }
// Path: src/modules/MeterModbus.java
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Properties;
import util.PropUtil;
import java.io.BufferedWriter;
import java.io.FileWriter;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.InetSocketAddress;
import java.net.Socket;
import java.text.DateFormat;
import java.util.Enumeration;
import java.util.TimeZone;
/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package modules;
/**
*
* @author cristi, mihai
*/
public class MeterModbus extends Module {
@Override
public void Initialize() {
| pDataSet = mmManager.getSharedData(PropUtil.GetString(pAttributes, "pDataSet", sName));
|
SMXCore/SMXCore_NG | src/modules/MeterVirtualLP.java | // Path: src/util/PropUtil.java
// public class PropUtil {
//
// public static Properties LoadFromFile(Properties pProp, String sFile) {
// try {
// if (pProp == null) {
// pProp = new Properties();
// }
// if (sFile.endsWith(".xml")) {
// pProp.loadFromXML(new FileInputStream(sFile));
// } else {
// pProp.load(new FileInputStream(sFile));
// }
//
// } catch (Exception ex) {
// //ex.printStackTrace();
// }
// return pProp;
// }
//
// public static void SaveToFile(Properties pProp, String sFile, String sComment) {
// try {
// if (sFile.endsWith(".xml")) {
// pProp.storeToXML(new FileOutputStream(sFile), sComment);
// } else {
// pProp.store(new FileOutputStream(sFile), sComment);
// }
//
// } catch (Exception ex) {
// // ex.printStackTrace();
// }
// }
//
// public static int GetInt(Properties pProp, String sKey, int iDefault) {
// try {
// return Integer.parseInt(pProp.getProperty(sKey, "").trim());
// } catch (Exception ex) {
//
// }
// return iDefault;
// }
//
// public static long GetLong(Properties pProp, String sKey, long lDefault) {
// try {
// return Long.parseLong(pProp.getProperty(sKey, "").trim());
// } catch (Exception ex) {
//
// }
// return lDefault;
// }
//
// public static double GetDouble(Properties pProp, String sKey, double lDefault) {
// try {
// return Double.parseDouble(pProp.getProperty(sKey, "").trim());
// } catch (Exception ex) {
//
// }
// return lDefault;
// }
//
// public static String GetString(Properties pProp, String sKey, String sDefault) {
// try {
// return pProp.getProperty(sKey, sDefault);
// } catch (Exception ex) {
// }
// return sDefault;
// }
// public static SimpleDateFormat sdfDate = new SimpleDateFormat("MM/dd/yyyy HH:mm:ss");
//
// public static Date GetDate(Properties pProp, String sKey, Date dtDefault) {
// Date dtRet;
// try {
// dtRet = sdfDate.parse(pProp.getProperty(sKey, ""));
// } catch (Exception ex) {
// dtRet = dtDefault;
// }
// return dtRet;
// }
//
// public static void PrintProp(Properties pProp) {
//
// Enumeration sKeys = pProp.keys();
// while (sKeys.hasMoreElements()) {
// try {
// String sKey = (String) sKeys.nextElement();
// String sValue = (String) pProp.get(sKey);
// System.out.println(sKey + " : " + sValue);
//
// } catch (Exception ex) {
// // System.out.println(ex.getMessage());
// }
// }
// }
//
// public static void SwitchKeyValue(Properties pInProp, Properties pOutProp) {
// try {
// if (pOutProp == null) {
// pOutProp = new Properties();
// }
// Enumeration sKeys = pInProp.keys();
// while (sKeys.hasMoreElements()) {
// String sKey = (String) sKeys.nextElement();
// String sValue = (String) pInProp.get(sKey);
// pOutProp.put(sValue, sKey);
// // System.out.println(sKey + " : " + sValue);
// }
// } catch (Exception ex) {
// }
// }
// }
| import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Properties;
import util.PropUtil;
import java.io.BufferedWriter;
import java.io.FileWriter;
import java.util.Enumeration;
import java.util.Hashtable;
import java.util.Vector;
| /*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package modules;
/**
*
* @author cristi
*/
public class MeterVirtualLP extends Module {
@Override
public void Initialize() {
| // Path: src/util/PropUtil.java
// public class PropUtil {
//
// public static Properties LoadFromFile(Properties pProp, String sFile) {
// try {
// if (pProp == null) {
// pProp = new Properties();
// }
// if (sFile.endsWith(".xml")) {
// pProp.loadFromXML(new FileInputStream(sFile));
// } else {
// pProp.load(new FileInputStream(sFile));
// }
//
// } catch (Exception ex) {
// //ex.printStackTrace();
// }
// return pProp;
// }
//
// public static void SaveToFile(Properties pProp, String sFile, String sComment) {
// try {
// if (sFile.endsWith(".xml")) {
// pProp.storeToXML(new FileOutputStream(sFile), sComment);
// } else {
// pProp.store(new FileOutputStream(sFile), sComment);
// }
//
// } catch (Exception ex) {
// // ex.printStackTrace();
// }
// }
//
// public static int GetInt(Properties pProp, String sKey, int iDefault) {
// try {
// return Integer.parseInt(pProp.getProperty(sKey, "").trim());
// } catch (Exception ex) {
//
// }
// return iDefault;
// }
//
// public static long GetLong(Properties pProp, String sKey, long lDefault) {
// try {
// return Long.parseLong(pProp.getProperty(sKey, "").trim());
// } catch (Exception ex) {
//
// }
// return lDefault;
// }
//
// public static double GetDouble(Properties pProp, String sKey, double lDefault) {
// try {
// return Double.parseDouble(pProp.getProperty(sKey, "").trim());
// } catch (Exception ex) {
//
// }
// return lDefault;
// }
//
// public static String GetString(Properties pProp, String sKey, String sDefault) {
// try {
// return pProp.getProperty(sKey, sDefault);
// } catch (Exception ex) {
// }
// return sDefault;
// }
// public static SimpleDateFormat sdfDate = new SimpleDateFormat("MM/dd/yyyy HH:mm:ss");
//
// public static Date GetDate(Properties pProp, String sKey, Date dtDefault) {
// Date dtRet;
// try {
// dtRet = sdfDate.parse(pProp.getProperty(sKey, ""));
// } catch (Exception ex) {
// dtRet = dtDefault;
// }
// return dtRet;
// }
//
// public static void PrintProp(Properties pProp) {
//
// Enumeration sKeys = pProp.keys();
// while (sKeys.hasMoreElements()) {
// try {
// String sKey = (String) sKeys.nextElement();
// String sValue = (String) pProp.get(sKey);
// System.out.println(sKey + " : " + sValue);
//
// } catch (Exception ex) {
// // System.out.println(ex.getMessage());
// }
// }
// }
//
// public static void SwitchKeyValue(Properties pInProp, Properties pOutProp) {
// try {
// if (pOutProp == null) {
// pOutProp = new Properties();
// }
// Enumeration sKeys = pInProp.keys();
// while (sKeys.hasMoreElements()) {
// String sKey = (String) sKeys.nextElement();
// String sValue = (String) pInProp.get(sKey);
// pOutProp.put(sValue, sKey);
// // System.out.println(sKey + " : " + sValue);
// }
// } catch (Exception ex) {
// }
// }
// }
// Path: src/modules/MeterVirtualLP.java
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Properties;
import util.PropUtil;
import java.io.BufferedWriter;
import java.io.FileWriter;
import java.util.Enumeration;
import java.util.Hashtable;
import java.util.Vector;
/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package modules;
/**
*
* @author cristi
*/
public class MeterVirtualLP extends Module {
@Override
public void Initialize() {
| pDataSet = mmManager.getSharedData(PropUtil.GetString(pAttributes, "pDataSet", sName));
|
SMXCore/SMXCore_NG | src/modules/DataSetAnl.java | // Path: src/util/PropUtil.java
// public class PropUtil {
//
// public static Properties LoadFromFile(Properties pProp, String sFile) {
// try {
// if (pProp == null) {
// pProp = new Properties();
// }
// if (sFile.endsWith(".xml")) {
// pProp.loadFromXML(new FileInputStream(sFile));
// } else {
// pProp.load(new FileInputStream(sFile));
// }
//
// } catch (Exception ex) {
// //ex.printStackTrace();
// }
// return pProp;
// }
//
// public static void SaveToFile(Properties pProp, String sFile, String sComment) {
// try {
// if (sFile.endsWith(".xml")) {
// pProp.storeToXML(new FileOutputStream(sFile), sComment);
// } else {
// pProp.store(new FileOutputStream(sFile), sComment);
// }
//
// } catch (Exception ex) {
// // ex.printStackTrace();
// }
// }
//
// public static int GetInt(Properties pProp, String sKey, int iDefault) {
// try {
// return Integer.parseInt(pProp.getProperty(sKey, "").trim());
// } catch (Exception ex) {
//
// }
// return iDefault;
// }
//
// public static long GetLong(Properties pProp, String sKey, long lDefault) {
// try {
// return Long.parseLong(pProp.getProperty(sKey, "").trim());
// } catch (Exception ex) {
//
// }
// return lDefault;
// }
//
// public static double GetDouble(Properties pProp, String sKey, double lDefault) {
// try {
// return Double.parseDouble(pProp.getProperty(sKey, "").trim());
// } catch (Exception ex) {
//
// }
// return lDefault;
// }
//
// public static String GetString(Properties pProp, String sKey, String sDefault) {
// try {
// return pProp.getProperty(sKey, sDefault);
// } catch (Exception ex) {
// }
// return sDefault;
// }
// public static SimpleDateFormat sdfDate = new SimpleDateFormat("MM/dd/yyyy HH:mm:ss");
//
// public static Date GetDate(Properties pProp, String sKey, Date dtDefault) {
// Date dtRet;
// try {
// dtRet = sdfDate.parse(pProp.getProperty(sKey, ""));
// } catch (Exception ex) {
// dtRet = dtDefault;
// }
// return dtRet;
// }
//
// public static void PrintProp(Properties pProp) {
//
// Enumeration sKeys = pProp.keys();
// while (sKeys.hasMoreElements()) {
// try {
// String sKey = (String) sKeys.nextElement();
// String sValue = (String) pProp.get(sKey);
// System.out.println(sKey + " : " + sValue);
//
// } catch (Exception ex) {
// // System.out.println(ex.getMessage());
// }
// }
// }
//
// public static void SwitchKeyValue(Properties pInProp, Properties pOutProp) {
// try {
// if (pOutProp == null) {
// pOutProp = new Properties();
// }
// Enumeration sKeys = pInProp.keys();
// while (sKeys.hasMoreElements()) {
// String sKey = (String) sKeys.nextElement();
// String sValue = (String) pInProp.get(sKey);
// pOutProp.put(sValue, sKey);
// // System.out.println(sKey + " : " + sValue);
// }
// } catch (Exception ex) {
// }
// }
// }
| import java.io.BufferedWriter;
import java.io.FileWriter;
import java.io.PrintWriter;
import java.io.StringWriter;
import java.nio.charset.Charset;
import java.nio.file.Files;
import java.nio.file.LinkOption;
import java.nio.file.Paths;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.Enumeration;
import java.util.Hashtable;
import java.util.Iterator;
import java.util.List;
import java.util.Properties;
import java.util.stream.Collector;
import java.util.stream.Stream;
import util.PropUtil;
| Date date = refreshFile();
file.println("------------------------------------------------------");
file.println(df.format(date) + s);
file.flush();
} catch (Exception e) {
e.printStackTrace();
}
}
void readCommandFile(String filename) {
try {
List<String> lines = Files.readAllLines(Paths.get(filename), Charset.defaultCharset());
commandList.addAll(lines);
Files.delete(Paths.get(filename));
} catch(Exception e) {
}
}
void processCommand(String line) {
try {
String[] args = line.split(" ");
if(args[0].equals("listAll")) {
printToFile("DataSet1: ");
list(pDataSet, file);
file.flush();
} else if(args[0].equals("reload")) {
// System.out.println("Reloading " + args[1]);
Module m = (Module) mmManager.getModuleDebug(args[1]);
if(args.length > 2) {
// System.out.println("From " + args[2]);
| // Path: src/util/PropUtil.java
// public class PropUtil {
//
// public static Properties LoadFromFile(Properties pProp, String sFile) {
// try {
// if (pProp == null) {
// pProp = new Properties();
// }
// if (sFile.endsWith(".xml")) {
// pProp.loadFromXML(new FileInputStream(sFile));
// } else {
// pProp.load(new FileInputStream(sFile));
// }
//
// } catch (Exception ex) {
// //ex.printStackTrace();
// }
// return pProp;
// }
//
// public static void SaveToFile(Properties pProp, String sFile, String sComment) {
// try {
// if (sFile.endsWith(".xml")) {
// pProp.storeToXML(new FileOutputStream(sFile), sComment);
// } else {
// pProp.store(new FileOutputStream(sFile), sComment);
// }
//
// } catch (Exception ex) {
// // ex.printStackTrace();
// }
// }
//
// public static int GetInt(Properties pProp, String sKey, int iDefault) {
// try {
// return Integer.parseInt(pProp.getProperty(sKey, "").trim());
// } catch (Exception ex) {
//
// }
// return iDefault;
// }
//
// public static long GetLong(Properties pProp, String sKey, long lDefault) {
// try {
// return Long.parseLong(pProp.getProperty(sKey, "").trim());
// } catch (Exception ex) {
//
// }
// return lDefault;
// }
//
// public static double GetDouble(Properties pProp, String sKey, double lDefault) {
// try {
// return Double.parseDouble(pProp.getProperty(sKey, "").trim());
// } catch (Exception ex) {
//
// }
// return lDefault;
// }
//
// public static String GetString(Properties pProp, String sKey, String sDefault) {
// try {
// return pProp.getProperty(sKey, sDefault);
// } catch (Exception ex) {
// }
// return sDefault;
// }
// public static SimpleDateFormat sdfDate = new SimpleDateFormat("MM/dd/yyyy HH:mm:ss");
//
// public static Date GetDate(Properties pProp, String sKey, Date dtDefault) {
// Date dtRet;
// try {
// dtRet = sdfDate.parse(pProp.getProperty(sKey, ""));
// } catch (Exception ex) {
// dtRet = dtDefault;
// }
// return dtRet;
// }
//
// public static void PrintProp(Properties pProp) {
//
// Enumeration sKeys = pProp.keys();
// while (sKeys.hasMoreElements()) {
// try {
// String sKey = (String) sKeys.nextElement();
// String sValue = (String) pProp.get(sKey);
// System.out.println(sKey + " : " + sValue);
//
// } catch (Exception ex) {
// // System.out.println(ex.getMessage());
// }
// }
// }
//
// public static void SwitchKeyValue(Properties pInProp, Properties pOutProp) {
// try {
// if (pOutProp == null) {
// pOutProp = new Properties();
// }
// Enumeration sKeys = pInProp.keys();
// while (sKeys.hasMoreElements()) {
// String sKey = (String) sKeys.nextElement();
// String sValue = (String) pInProp.get(sKey);
// pOutProp.put(sValue, sKey);
// // System.out.println(sKey + " : " + sValue);
// }
// } catch (Exception ex) {
// }
// }
// }
// Path: src/modules/DataSetAnl.java
import java.io.BufferedWriter;
import java.io.FileWriter;
import java.io.PrintWriter;
import java.io.StringWriter;
import java.nio.charset.Charset;
import java.nio.file.Files;
import java.nio.file.LinkOption;
import java.nio.file.Paths;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.Enumeration;
import java.util.Hashtable;
import java.util.Iterator;
import java.util.List;
import java.util.Properties;
import java.util.stream.Collector;
import java.util.stream.Stream;
import util.PropUtil;
Date date = refreshFile();
file.println("------------------------------------------------------");
file.println(df.format(date) + s);
file.flush();
} catch (Exception e) {
e.printStackTrace();
}
}
void readCommandFile(String filename) {
try {
List<String> lines = Files.readAllLines(Paths.get(filename), Charset.defaultCharset());
commandList.addAll(lines);
Files.delete(Paths.get(filename));
} catch(Exception e) {
}
}
void processCommand(String line) {
try {
String[] args = line.split(" ");
if(args[0].equals("listAll")) {
printToFile("DataSet1: ");
list(pDataSet, file);
file.flush();
} else if(args[0].equals("reload")) {
// System.out.println("Reloading " + args[1]);
Module m = (Module) mmManager.getModuleDebug(args[1]);
if(args.length > 2) {
// System.out.println("From " + args[2]);
| PropUtil.LoadFromFile(m.pAttributes, args[2]);
|
SMXCore/SMXCore_NG | src/modules/Module.java | // Path: src/util/PropUtil.java
// public class PropUtil {
//
// public static Properties LoadFromFile(Properties pProp, String sFile) {
// try {
// if (pProp == null) {
// pProp = new Properties();
// }
// if (sFile.endsWith(".xml")) {
// pProp.loadFromXML(new FileInputStream(sFile));
// } else {
// pProp.load(new FileInputStream(sFile));
// }
//
// } catch (Exception ex) {
// //ex.printStackTrace();
// }
// return pProp;
// }
//
// public static void SaveToFile(Properties pProp, String sFile, String sComment) {
// try {
// if (sFile.endsWith(".xml")) {
// pProp.storeToXML(new FileOutputStream(sFile), sComment);
// } else {
// pProp.store(new FileOutputStream(sFile), sComment);
// }
//
// } catch (Exception ex) {
// // ex.printStackTrace();
// }
// }
//
// public static int GetInt(Properties pProp, String sKey, int iDefault) {
// try {
// return Integer.parseInt(pProp.getProperty(sKey, "").trim());
// } catch (Exception ex) {
//
// }
// return iDefault;
// }
//
// public static long GetLong(Properties pProp, String sKey, long lDefault) {
// try {
// return Long.parseLong(pProp.getProperty(sKey, "").trim());
// } catch (Exception ex) {
//
// }
// return lDefault;
// }
//
// public static double GetDouble(Properties pProp, String sKey, double lDefault) {
// try {
// return Double.parseDouble(pProp.getProperty(sKey, "").trim());
// } catch (Exception ex) {
//
// }
// return lDefault;
// }
//
// public static String GetString(Properties pProp, String sKey, String sDefault) {
// try {
// return pProp.getProperty(sKey, sDefault);
// } catch (Exception ex) {
// }
// return sDefault;
// }
// public static SimpleDateFormat sdfDate = new SimpleDateFormat("MM/dd/yyyy HH:mm:ss");
//
// public static Date GetDate(Properties pProp, String sKey, Date dtDefault) {
// Date dtRet;
// try {
// dtRet = sdfDate.parse(pProp.getProperty(sKey, ""));
// } catch (Exception ex) {
// dtRet = dtDefault;
// }
// return dtRet;
// }
//
// public static void PrintProp(Properties pProp) {
//
// Enumeration sKeys = pProp.keys();
// while (sKeys.hasMoreElements()) {
// try {
// String sKey = (String) sKeys.nextElement();
// String sValue = (String) pProp.get(sKey);
// System.out.println(sKey + " : " + sValue);
//
// } catch (Exception ex) {
// // System.out.println(ex.getMessage());
// }
// }
// }
//
// public static void SwitchKeyValue(Properties pInProp, Properties pOutProp) {
// try {
// if (pOutProp == null) {
// pOutProp = new Properties();
// }
// Enumeration sKeys = pInProp.keys();
// while (sKeys.hasMoreElements()) {
// String sKey = (String) sKeys.nextElement();
// String sValue = (String) pInProp.get(sKey);
// pOutProp.put(sValue, sKey);
// // System.out.println(sKey + " : " + sValue);
// }
// } catch (Exception ex) {
// }
// }
// }
| import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Properties;
import java.util.logging.Logger;
import util.PropUtil;
| /*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package modules;
/**
*
* @author cristi
*/
public class Module extends Thread{
protected volatile Properties pAttributes = new Properties(); // The attributes of the current module, loaded from a file.
protected String sAttributesFile=""; // The file it is loaded from
protected String sName = ""; // The name of the instance of the module
protected ModulesManager mmManager = null; // The module manager
protected Logger logger = null; // The logger used
protected volatile boolean bReinitialize = false;
public void setAttributes(Properties pSetAttributes) {
pAttributes = pSetAttributes;
}
public void Initialize() {
}
public void Start() {
}
public void QueueTime() {
}
public void LoadConfig() {
LoadTxtConfig();
}
void LoadTxtConfig() {
| // Path: src/util/PropUtil.java
// public class PropUtil {
//
// public static Properties LoadFromFile(Properties pProp, String sFile) {
// try {
// if (pProp == null) {
// pProp = new Properties();
// }
// if (sFile.endsWith(".xml")) {
// pProp.loadFromXML(new FileInputStream(sFile));
// } else {
// pProp.load(new FileInputStream(sFile));
// }
//
// } catch (Exception ex) {
// //ex.printStackTrace();
// }
// return pProp;
// }
//
// public static void SaveToFile(Properties pProp, String sFile, String sComment) {
// try {
// if (sFile.endsWith(".xml")) {
// pProp.storeToXML(new FileOutputStream(sFile), sComment);
// } else {
// pProp.store(new FileOutputStream(sFile), sComment);
// }
//
// } catch (Exception ex) {
// // ex.printStackTrace();
// }
// }
//
// public static int GetInt(Properties pProp, String sKey, int iDefault) {
// try {
// return Integer.parseInt(pProp.getProperty(sKey, "").trim());
// } catch (Exception ex) {
//
// }
// return iDefault;
// }
//
// public static long GetLong(Properties pProp, String sKey, long lDefault) {
// try {
// return Long.parseLong(pProp.getProperty(sKey, "").trim());
// } catch (Exception ex) {
//
// }
// return lDefault;
// }
//
// public static double GetDouble(Properties pProp, String sKey, double lDefault) {
// try {
// return Double.parseDouble(pProp.getProperty(sKey, "").trim());
// } catch (Exception ex) {
//
// }
// return lDefault;
// }
//
// public static String GetString(Properties pProp, String sKey, String sDefault) {
// try {
// return pProp.getProperty(sKey, sDefault);
// } catch (Exception ex) {
// }
// return sDefault;
// }
// public static SimpleDateFormat sdfDate = new SimpleDateFormat("MM/dd/yyyy HH:mm:ss");
//
// public static Date GetDate(Properties pProp, String sKey, Date dtDefault) {
// Date dtRet;
// try {
// dtRet = sdfDate.parse(pProp.getProperty(sKey, ""));
// } catch (Exception ex) {
// dtRet = dtDefault;
// }
// return dtRet;
// }
//
// public static void PrintProp(Properties pProp) {
//
// Enumeration sKeys = pProp.keys();
// while (sKeys.hasMoreElements()) {
// try {
// String sKey = (String) sKeys.nextElement();
// String sValue = (String) pProp.get(sKey);
// System.out.println(sKey + " : " + sValue);
//
// } catch (Exception ex) {
// // System.out.println(ex.getMessage());
// }
// }
// }
//
// public static void SwitchKeyValue(Properties pInProp, Properties pOutProp) {
// try {
// if (pOutProp == null) {
// pOutProp = new Properties();
// }
// Enumeration sKeys = pInProp.keys();
// while (sKeys.hasMoreElements()) {
// String sKey = (String) sKeys.nextElement();
// String sValue = (String) pInProp.get(sKey);
// pOutProp.put(sValue, sKey);
// // System.out.println(sKey + " : " + sValue);
// }
// } catch (Exception ex) {
// }
// }
// }
// Path: src/modules/Module.java
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Properties;
import java.util.logging.Logger;
import util.PropUtil;
/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package modules;
/**
*
* @author cristi
*/
public class Module extends Thread{
protected volatile Properties pAttributes = new Properties(); // The attributes of the current module, loaded from a file.
protected String sAttributesFile=""; // The file it is loaded from
protected String sName = ""; // The name of the instance of the module
protected ModulesManager mmManager = null; // The module manager
protected Logger logger = null; // The logger used
protected volatile boolean bReinitialize = false;
public void setAttributes(Properties pSetAttributes) {
pAttributes = pSetAttributes;
}
public void Initialize() {
}
public void Start() {
}
public void QueueTime() {
}
public void LoadConfig() {
LoadTxtConfig();
}
void LoadTxtConfig() {
| PropUtil.LoadFromFile(pAttributes, sAttributesFile);
|
SMXCore/SMXCore_NG | src/modules/ATemplateModule.java | // Path: src/util/PropUtil.java
// public class PropUtil {
//
// public static Properties LoadFromFile(Properties pProp, String sFile) {
// try {
// if (pProp == null) {
// pProp = new Properties();
// }
// if (sFile.endsWith(".xml")) {
// pProp.loadFromXML(new FileInputStream(sFile));
// } else {
// pProp.load(new FileInputStream(sFile));
// }
//
// } catch (Exception ex) {
// //ex.printStackTrace();
// }
// return pProp;
// }
//
// public static void SaveToFile(Properties pProp, String sFile, String sComment) {
// try {
// if (sFile.endsWith(".xml")) {
// pProp.storeToXML(new FileOutputStream(sFile), sComment);
// } else {
// pProp.store(new FileOutputStream(sFile), sComment);
// }
//
// } catch (Exception ex) {
// // ex.printStackTrace();
// }
// }
//
// public static int GetInt(Properties pProp, String sKey, int iDefault) {
// try {
// return Integer.parseInt(pProp.getProperty(sKey, "").trim());
// } catch (Exception ex) {
//
// }
// return iDefault;
// }
//
// public static long GetLong(Properties pProp, String sKey, long lDefault) {
// try {
// return Long.parseLong(pProp.getProperty(sKey, "").trim());
// } catch (Exception ex) {
//
// }
// return lDefault;
// }
//
// public static double GetDouble(Properties pProp, String sKey, double lDefault) {
// try {
// return Double.parseDouble(pProp.getProperty(sKey, "").trim());
// } catch (Exception ex) {
//
// }
// return lDefault;
// }
//
// public static String GetString(Properties pProp, String sKey, String sDefault) {
// try {
// return pProp.getProperty(sKey, sDefault);
// } catch (Exception ex) {
// }
// return sDefault;
// }
// public static SimpleDateFormat sdfDate = new SimpleDateFormat("MM/dd/yyyy HH:mm:ss");
//
// public static Date GetDate(Properties pProp, String sKey, Date dtDefault) {
// Date dtRet;
// try {
// dtRet = sdfDate.parse(pProp.getProperty(sKey, ""));
// } catch (Exception ex) {
// dtRet = dtDefault;
// }
// return dtRet;
// }
//
// public static void PrintProp(Properties pProp) {
//
// Enumeration sKeys = pProp.keys();
// while (sKeys.hasMoreElements()) {
// try {
// String sKey = (String) sKeys.nextElement();
// String sValue = (String) pProp.get(sKey);
// System.out.println(sKey + " : " + sValue);
//
// } catch (Exception ex) {
// // System.out.println(ex.getMessage());
// }
// }
// }
//
// public static void SwitchKeyValue(Properties pInProp, Properties pOutProp) {
// try {
// if (pOutProp == null) {
// pOutProp = new Properties();
// }
// Enumeration sKeys = pInProp.keys();
// while (sKeys.hasMoreElements()) {
// String sKey = (String) sKeys.nextElement();
// String sValue = (String) pInProp.get(sKey);
// pOutProp.put(sValue, sKey);
// // System.out.println(sKey + " : " + sValue);
// }
// } catch (Exception ex) {
// }
// }
// }
| import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Properties;
import util.PropUtil;
import java.io.BufferedWriter;
import java.io.FileWriter;
import java.util.Enumeration;
| /*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package modules;
/**
*
* @author cristi
*/
public class ATemplateModule extends Module {
@Override
public void Initialize() {
| // Path: src/util/PropUtil.java
// public class PropUtil {
//
// public static Properties LoadFromFile(Properties pProp, String sFile) {
// try {
// if (pProp == null) {
// pProp = new Properties();
// }
// if (sFile.endsWith(".xml")) {
// pProp.loadFromXML(new FileInputStream(sFile));
// } else {
// pProp.load(new FileInputStream(sFile));
// }
//
// } catch (Exception ex) {
// //ex.printStackTrace();
// }
// return pProp;
// }
//
// public static void SaveToFile(Properties pProp, String sFile, String sComment) {
// try {
// if (sFile.endsWith(".xml")) {
// pProp.storeToXML(new FileOutputStream(sFile), sComment);
// } else {
// pProp.store(new FileOutputStream(sFile), sComment);
// }
//
// } catch (Exception ex) {
// // ex.printStackTrace();
// }
// }
//
// public static int GetInt(Properties pProp, String sKey, int iDefault) {
// try {
// return Integer.parseInt(pProp.getProperty(sKey, "").trim());
// } catch (Exception ex) {
//
// }
// return iDefault;
// }
//
// public static long GetLong(Properties pProp, String sKey, long lDefault) {
// try {
// return Long.parseLong(pProp.getProperty(sKey, "").trim());
// } catch (Exception ex) {
//
// }
// return lDefault;
// }
//
// public static double GetDouble(Properties pProp, String sKey, double lDefault) {
// try {
// return Double.parseDouble(pProp.getProperty(sKey, "").trim());
// } catch (Exception ex) {
//
// }
// return lDefault;
// }
//
// public static String GetString(Properties pProp, String sKey, String sDefault) {
// try {
// return pProp.getProperty(sKey, sDefault);
// } catch (Exception ex) {
// }
// return sDefault;
// }
// public static SimpleDateFormat sdfDate = new SimpleDateFormat("MM/dd/yyyy HH:mm:ss");
//
// public static Date GetDate(Properties pProp, String sKey, Date dtDefault) {
// Date dtRet;
// try {
// dtRet = sdfDate.parse(pProp.getProperty(sKey, ""));
// } catch (Exception ex) {
// dtRet = dtDefault;
// }
// return dtRet;
// }
//
// public static void PrintProp(Properties pProp) {
//
// Enumeration sKeys = pProp.keys();
// while (sKeys.hasMoreElements()) {
// try {
// String sKey = (String) sKeys.nextElement();
// String sValue = (String) pProp.get(sKey);
// System.out.println(sKey + " : " + sValue);
//
// } catch (Exception ex) {
// // System.out.println(ex.getMessage());
// }
// }
// }
//
// public static void SwitchKeyValue(Properties pInProp, Properties pOutProp) {
// try {
// if (pOutProp == null) {
// pOutProp = new Properties();
// }
// Enumeration sKeys = pInProp.keys();
// while (sKeys.hasMoreElements()) {
// String sKey = (String) sKeys.nextElement();
// String sValue = (String) pInProp.get(sKey);
// pOutProp.put(sValue, sKey);
// // System.out.println(sKey + " : " + sValue);
// }
// } catch (Exception ex) {
// }
// }
// }
// Path: src/modules/ATemplateModule.java
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Properties;
import util.PropUtil;
import java.io.BufferedWriter;
import java.io.FileWriter;
import java.util.Enumeration;
/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package modules;
/**
*
* @author cristi
*/
public class ATemplateModule extends Module {
@Override
public void Initialize() {
| pDataSet = mmManager.getSharedData(PropUtil.GetString(pAttributes, "pDataSet", sName));
|
SMXCore/SMXCore_NG | src/modules/DataSet.java | // Path: src/util/PropUtil.java
// public class PropUtil {
//
// public static Properties LoadFromFile(Properties pProp, String sFile) {
// try {
// if (pProp == null) {
// pProp = new Properties();
// }
// if (sFile.endsWith(".xml")) {
// pProp.loadFromXML(new FileInputStream(sFile));
// } else {
// pProp.load(new FileInputStream(sFile));
// }
//
// } catch (Exception ex) {
// //ex.printStackTrace();
// }
// return pProp;
// }
//
// public static void SaveToFile(Properties pProp, String sFile, String sComment) {
// try {
// if (sFile.endsWith(".xml")) {
// pProp.storeToXML(new FileOutputStream(sFile), sComment);
// } else {
// pProp.store(new FileOutputStream(sFile), sComment);
// }
//
// } catch (Exception ex) {
// // ex.printStackTrace();
// }
// }
//
// public static int GetInt(Properties pProp, String sKey, int iDefault) {
// try {
// return Integer.parseInt(pProp.getProperty(sKey, "").trim());
// } catch (Exception ex) {
//
// }
// return iDefault;
// }
//
// public static long GetLong(Properties pProp, String sKey, long lDefault) {
// try {
// return Long.parseLong(pProp.getProperty(sKey, "").trim());
// } catch (Exception ex) {
//
// }
// return lDefault;
// }
//
// public static double GetDouble(Properties pProp, String sKey, double lDefault) {
// try {
// return Double.parseDouble(pProp.getProperty(sKey, "").trim());
// } catch (Exception ex) {
//
// }
// return lDefault;
// }
//
// public static String GetString(Properties pProp, String sKey, String sDefault) {
// try {
// return pProp.getProperty(sKey, sDefault);
// } catch (Exception ex) {
// }
// return sDefault;
// }
// public static SimpleDateFormat sdfDate = new SimpleDateFormat("MM/dd/yyyy HH:mm:ss");
//
// public static Date GetDate(Properties pProp, String sKey, Date dtDefault) {
// Date dtRet;
// try {
// dtRet = sdfDate.parse(pProp.getProperty(sKey, ""));
// } catch (Exception ex) {
// dtRet = dtDefault;
// }
// return dtRet;
// }
//
// public static void PrintProp(Properties pProp) {
//
// Enumeration sKeys = pProp.keys();
// while (sKeys.hasMoreElements()) {
// try {
// String sKey = (String) sKeys.nextElement();
// String sValue = (String) pProp.get(sKey);
// System.out.println(sKey + " : " + sValue);
//
// } catch (Exception ex) {
// // System.out.println(ex.getMessage());
// }
// }
// }
//
// public static void SwitchKeyValue(Properties pInProp, Properties pOutProp) {
// try {
// if (pOutProp == null) {
// pOutProp = new Properties();
// }
// Enumeration sKeys = pInProp.keys();
// while (sKeys.hasMoreElements()) {
// String sKey = (String) sKeys.nextElement();
// String sValue = (String) pInProp.get(sKey);
// pOutProp.put(sValue, sKey);
// // System.out.println(sKey + " : " + sValue);
// }
// } catch (Exception ex) {
// }
// }
// }
| import com.sun.management.OperatingSystemMXBean;
import java.io.FileInputStream;
import java.lang.management.ManagementFactory;
import java.net.InetAddress;
import java.net.NetworkInterface;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.Iterator;
import java.util.Map;
import java.util.Properties;
import java.util.TimeZone;
import javax.json.Json;
import javax.json.JsonNumber;
import javax.json.JsonObject;
import javax.json.JsonReader;
import javax.json.JsonString;
import javax.json.JsonValue;
import util.PropUtil;
import com.pi4j.system.SystemInfo;
| } else {
pDataSet.put(prefix + '/' + name, ss);
logger.finest("Found value for " + prefix + '/' + name + ": " + ss);
}
}
logger.finest("Decomposed object " + prefix);
} catch(Exception ex) {
logger.warning(ex.getMessage());
}
}
} catch(Exception ex) {
System.out.println("DataSet.decomposeObject.Error");
logger.warning(ex.getMessage());
}
}
@Override
public void Initialize() {
System.out.println("DataSet.Initialize");
pDataSet = mmManager.getSharedData(sName);
if(sAttributesFile.endsWith("json")) {
try {
JsonReader jsr = Json.createReader(new FileInputStream(sAttributesFile));
JsonObject jso = jsr.readObject();
decomposeObject("", jso);
} catch(Exception ex) {
System.out.println("DataSet.Initialize.Error");
logger.warning(ex.getMessage());
}
} else {
| // Path: src/util/PropUtil.java
// public class PropUtil {
//
// public static Properties LoadFromFile(Properties pProp, String sFile) {
// try {
// if (pProp == null) {
// pProp = new Properties();
// }
// if (sFile.endsWith(".xml")) {
// pProp.loadFromXML(new FileInputStream(sFile));
// } else {
// pProp.load(new FileInputStream(sFile));
// }
//
// } catch (Exception ex) {
// //ex.printStackTrace();
// }
// return pProp;
// }
//
// public static void SaveToFile(Properties pProp, String sFile, String sComment) {
// try {
// if (sFile.endsWith(".xml")) {
// pProp.storeToXML(new FileOutputStream(sFile), sComment);
// } else {
// pProp.store(new FileOutputStream(sFile), sComment);
// }
//
// } catch (Exception ex) {
// // ex.printStackTrace();
// }
// }
//
// public static int GetInt(Properties pProp, String sKey, int iDefault) {
// try {
// return Integer.parseInt(pProp.getProperty(sKey, "").trim());
// } catch (Exception ex) {
//
// }
// return iDefault;
// }
//
// public static long GetLong(Properties pProp, String sKey, long lDefault) {
// try {
// return Long.parseLong(pProp.getProperty(sKey, "").trim());
// } catch (Exception ex) {
//
// }
// return lDefault;
// }
//
// public static double GetDouble(Properties pProp, String sKey, double lDefault) {
// try {
// return Double.parseDouble(pProp.getProperty(sKey, "").trim());
// } catch (Exception ex) {
//
// }
// return lDefault;
// }
//
// public static String GetString(Properties pProp, String sKey, String sDefault) {
// try {
// return pProp.getProperty(sKey, sDefault);
// } catch (Exception ex) {
// }
// return sDefault;
// }
// public static SimpleDateFormat sdfDate = new SimpleDateFormat("MM/dd/yyyy HH:mm:ss");
//
// public static Date GetDate(Properties pProp, String sKey, Date dtDefault) {
// Date dtRet;
// try {
// dtRet = sdfDate.parse(pProp.getProperty(sKey, ""));
// } catch (Exception ex) {
// dtRet = dtDefault;
// }
// return dtRet;
// }
//
// public static void PrintProp(Properties pProp) {
//
// Enumeration sKeys = pProp.keys();
// while (sKeys.hasMoreElements()) {
// try {
// String sKey = (String) sKeys.nextElement();
// String sValue = (String) pProp.get(sKey);
// System.out.println(sKey + " : " + sValue);
//
// } catch (Exception ex) {
// // System.out.println(ex.getMessage());
// }
// }
// }
//
// public static void SwitchKeyValue(Properties pInProp, Properties pOutProp) {
// try {
// if (pOutProp == null) {
// pOutProp = new Properties();
// }
// Enumeration sKeys = pInProp.keys();
// while (sKeys.hasMoreElements()) {
// String sKey = (String) sKeys.nextElement();
// String sValue = (String) pInProp.get(sKey);
// pOutProp.put(sValue, sKey);
// // System.out.println(sKey + " : " + sValue);
// }
// } catch (Exception ex) {
// }
// }
// }
// Path: src/modules/DataSet.java
import com.sun.management.OperatingSystemMXBean;
import java.io.FileInputStream;
import java.lang.management.ManagementFactory;
import java.net.InetAddress;
import java.net.NetworkInterface;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.Iterator;
import java.util.Map;
import java.util.Properties;
import java.util.TimeZone;
import javax.json.Json;
import javax.json.JsonNumber;
import javax.json.JsonObject;
import javax.json.JsonReader;
import javax.json.JsonString;
import javax.json.JsonValue;
import util.PropUtil;
import com.pi4j.system.SystemInfo;
} else {
pDataSet.put(prefix + '/' + name, ss);
logger.finest("Found value for " + prefix + '/' + name + ": " + ss);
}
}
logger.finest("Decomposed object " + prefix);
} catch(Exception ex) {
logger.warning(ex.getMessage());
}
}
} catch(Exception ex) {
System.out.println("DataSet.decomposeObject.Error");
logger.warning(ex.getMessage());
}
}
@Override
public void Initialize() {
System.out.println("DataSet.Initialize");
pDataSet = mmManager.getSharedData(sName);
if(sAttributesFile.endsWith("json")) {
try {
JsonReader jsr = Json.createReader(new FileInputStream(sAttributesFile));
JsonObject jso = jsr.readObject();
decomposeObject("", jso);
} catch(Exception ex) {
System.out.println("DataSet.Initialize.Error");
logger.warning(ex.getMessage());
}
} else {
| PropUtil.LoadFromFile(pDataSet, sAttributesFile);
|
SMXCore/SMXCore_NG | src/modules/RunProccess.java | // Path: src/util/PropUtil.java
// public class PropUtil {
//
// public static Properties LoadFromFile(Properties pProp, String sFile) {
// try {
// if (pProp == null) {
// pProp = new Properties();
// }
// if (sFile.endsWith(".xml")) {
// pProp.loadFromXML(new FileInputStream(sFile));
// } else {
// pProp.load(new FileInputStream(sFile));
// }
//
// } catch (Exception ex) {
// //ex.printStackTrace();
// }
// return pProp;
// }
//
// public static void SaveToFile(Properties pProp, String sFile, String sComment) {
// try {
// if (sFile.endsWith(".xml")) {
// pProp.storeToXML(new FileOutputStream(sFile), sComment);
// } else {
// pProp.store(new FileOutputStream(sFile), sComment);
// }
//
// } catch (Exception ex) {
// // ex.printStackTrace();
// }
// }
//
// public static int GetInt(Properties pProp, String sKey, int iDefault) {
// try {
// return Integer.parseInt(pProp.getProperty(sKey, "").trim());
// } catch (Exception ex) {
//
// }
// return iDefault;
// }
//
// public static long GetLong(Properties pProp, String sKey, long lDefault) {
// try {
// return Long.parseLong(pProp.getProperty(sKey, "").trim());
// } catch (Exception ex) {
//
// }
// return lDefault;
// }
//
// public static double GetDouble(Properties pProp, String sKey, double lDefault) {
// try {
// return Double.parseDouble(pProp.getProperty(sKey, "").trim());
// } catch (Exception ex) {
//
// }
// return lDefault;
// }
//
// public static String GetString(Properties pProp, String sKey, String sDefault) {
// try {
// return pProp.getProperty(sKey, sDefault);
// } catch (Exception ex) {
// }
// return sDefault;
// }
// public static SimpleDateFormat sdfDate = new SimpleDateFormat("MM/dd/yyyy HH:mm:ss");
//
// public static Date GetDate(Properties pProp, String sKey, Date dtDefault) {
// Date dtRet;
// try {
// dtRet = sdfDate.parse(pProp.getProperty(sKey, ""));
// } catch (Exception ex) {
// dtRet = dtDefault;
// }
// return dtRet;
// }
//
// public static void PrintProp(Properties pProp) {
//
// Enumeration sKeys = pProp.keys();
// while (sKeys.hasMoreElements()) {
// try {
// String sKey = (String) sKeys.nextElement();
// String sValue = (String) pProp.get(sKey);
// System.out.println(sKey + " : " + sValue);
//
// } catch (Exception ex) {
// // System.out.println(ex.getMessage());
// }
// }
// }
//
// public static void SwitchKeyValue(Properties pInProp, Properties pOutProp) {
// try {
// if (pOutProp == null) {
// pOutProp = new Properties();
// }
// Enumeration sKeys = pInProp.keys();
// while (sKeys.hasMoreElements()) {
// String sKey = (String) sKeys.nextElement();
// String sValue = (String) pInProp.get(sKey);
// pOutProp.put(sValue, sKey);
// // System.out.println(sKey + " : " + sValue);
// }
// } catch (Exception ex) {
// }
// }
// }
| import java.io.BufferedReader;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Properties;
import util.PropUtil;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileWriter;
import java.io.InputStreamReader;
import java.util.Enumeration;
| /*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package modules;
/**
*
* @author cristi
*/
public class RunProccess extends Module {
@Override
public void Initialize() {
| // Path: src/util/PropUtil.java
// public class PropUtil {
//
// public static Properties LoadFromFile(Properties pProp, String sFile) {
// try {
// if (pProp == null) {
// pProp = new Properties();
// }
// if (sFile.endsWith(".xml")) {
// pProp.loadFromXML(new FileInputStream(sFile));
// } else {
// pProp.load(new FileInputStream(sFile));
// }
//
// } catch (Exception ex) {
// //ex.printStackTrace();
// }
// return pProp;
// }
//
// public static void SaveToFile(Properties pProp, String sFile, String sComment) {
// try {
// if (sFile.endsWith(".xml")) {
// pProp.storeToXML(new FileOutputStream(sFile), sComment);
// } else {
// pProp.store(new FileOutputStream(sFile), sComment);
// }
//
// } catch (Exception ex) {
// // ex.printStackTrace();
// }
// }
//
// public static int GetInt(Properties pProp, String sKey, int iDefault) {
// try {
// return Integer.parseInt(pProp.getProperty(sKey, "").trim());
// } catch (Exception ex) {
//
// }
// return iDefault;
// }
//
// public static long GetLong(Properties pProp, String sKey, long lDefault) {
// try {
// return Long.parseLong(pProp.getProperty(sKey, "").trim());
// } catch (Exception ex) {
//
// }
// return lDefault;
// }
//
// public static double GetDouble(Properties pProp, String sKey, double lDefault) {
// try {
// return Double.parseDouble(pProp.getProperty(sKey, "").trim());
// } catch (Exception ex) {
//
// }
// return lDefault;
// }
//
// public static String GetString(Properties pProp, String sKey, String sDefault) {
// try {
// return pProp.getProperty(sKey, sDefault);
// } catch (Exception ex) {
// }
// return sDefault;
// }
// public static SimpleDateFormat sdfDate = new SimpleDateFormat("MM/dd/yyyy HH:mm:ss");
//
// public static Date GetDate(Properties pProp, String sKey, Date dtDefault) {
// Date dtRet;
// try {
// dtRet = sdfDate.parse(pProp.getProperty(sKey, ""));
// } catch (Exception ex) {
// dtRet = dtDefault;
// }
// return dtRet;
// }
//
// public static void PrintProp(Properties pProp) {
//
// Enumeration sKeys = pProp.keys();
// while (sKeys.hasMoreElements()) {
// try {
// String sKey = (String) sKeys.nextElement();
// String sValue = (String) pProp.get(sKey);
// System.out.println(sKey + " : " + sValue);
//
// } catch (Exception ex) {
// // System.out.println(ex.getMessage());
// }
// }
// }
//
// public static void SwitchKeyValue(Properties pInProp, Properties pOutProp) {
// try {
// if (pOutProp == null) {
// pOutProp = new Properties();
// }
// Enumeration sKeys = pInProp.keys();
// while (sKeys.hasMoreElements()) {
// String sKey = (String) sKeys.nextElement();
// String sValue = (String) pInProp.get(sKey);
// pOutProp.put(sValue, sKey);
// // System.out.println(sKey + " : " + sValue);
// }
// } catch (Exception ex) {
// }
// }
// }
// Path: src/modules/RunProccess.java
import java.io.BufferedReader;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Properties;
import util.PropUtil;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileWriter;
import java.io.InputStreamReader;
import java.util.Enumeration;
/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package modules;
/**
*
* @author cristi
*/
public class RunProccess extends Module {
@Override
public void Initialize() {
| pDataSet = mmManager.getSharedData(PropUtil.GetString(pAttributes, "pDataSet", sName));
|
SMXCore/SMXCore_NG | src/modules/contrib/S4G_LESSAg.java | // Path: src/util/PropUtil.java
// public class PropUtil {
//
// public static Properties LoadFromFile(Properties pProp, String sFile) {
// try {
// if (pProp == null) {
// pProp = new Properties();
// }
// if (sFile.endsWith(".xml")) {
// pProp.loadFromXML(new FileInputStream(sFile));
// } else {
// pProp.load(new FileInputStream(sFile));
// }
//
// } catch (Exception ex) {
// //ex.printStackTrace();
// }
// return pProp;
// }
//
// public static void SaveToFile(Properties pProp, String sFile, String sComment) {
// try {
// if (sFile.endsWith(".xml")) {
// pProp.storeToXML(new FileOutputStream(sFile), sComment);
// } else {
// pProp.store(new FileOutputStream(sFile), sComment);
// }
//
// } catch (Exception ex) {
// // ex.printStackTrace();
// }
// }
//
// public static int GetInt(Properties pProp, String sKey, int iDefault) {
// try {
// return Integer.parseInt(pProp.getProperty(sKey, "").trim());
// } catch (Exception ex) {
//
// }
// return iDefault;
// }
//
// public static long GetLong(Properties pProp, String sKey, long lDefault) {
// try {
// return Long.parseLong(pProp.getProperty(sKey, "").trim());
// } catch (Exception ex) {
//
// }
// return lDefault;
// }
//
// public static double GetDouble(Properties pProp, String sKey, double lDefault) {
// try {
// return Double.parseDouble(pProp.getProperty(sKey, "").trim());
// } catch (Exception ex) {
//
// }
// return lDefault;
// }
//
// public static String GetString(Properties pProp, String sKey, String sDefault) {
// try {
// return pProp.getProperty(sKey, sDefault);
// } catch (Exception ex) {
// }
// return sDefault;
// }
// public static SimpleDateFormat sdfDate = new SimpleDateFormat("MM/dd/yyyy HH:mm:ss");
//
// public static Date GetDate(Properties pProp, String sKey, Date dtDefault) {
// Date dtRet;
// try {
// dtRet = sdfDate.parse(pProp.getProperty(sKey, ""));
// } catch (Exception ex) {
// dtRet = dtDefault;
// }
// return dtRet;
// }
//
// public static void PrintProp(Properties pProp) {
//
// Enumeration sKeys = pProp.keys();
// while (sKeys.hasMoreElements()) {
// try {
// String sKey = (String) sKeys.nextElement();
// String sValue = (String) pProp.get(sKey);
// System.out.println(sKey + " : " + sValue);
//
// } catch (Exception ex) {
// // System.out.println(ex.getMessage());
// }
// }
// }
//
// public static void SwitchKeyValue(Properties pInProp, Properties pOutProp) {
// try {
// if (pOutProp == null) {
// pOutProp = new Properties();
// }
// Enumeration sKeys = pInProp.keys();
// while (sKeys.hasMoreElements()) {
// String sKey = (String) sKeys.nextElement();
// String sValue = (String) pInProp.get(sKey);
// pOutProp.put(sValue, sKey);
// // System.out.println(sKey + " : " + sValue);
// }
// } catch (Exception ex) {
// }
// }
// }
//
// Path: src/modules/Module.java
// public class Module extends Thread{
//
// protected volatile Properties pAttributes = new Properties(); // The attributes of the current module, loaded from a file.
// protected String sAttributesFile=""; // The file it is loaded from
// protected String sName = ""; // The name of the instance of the module
// protected ModulesManager mmManager = null; // The module manager
// protected Logger logger = null; // The logger used
// protected volatile boolean bReinitialize = false;
//
// public void setAttributes(Properties pSetAttributes) {
// pAttributes = pSetAttributes;
// }
//
// public void Initialize() {
//
// }
//
// public void Start() {
//
// }
//
// public void QueueTime() {
//
// }
//
// public void LoadConfig() {
// LoadTxtConfig();
// }
//
// void LoadTxtConfig() {
// PropUtil.LoadFromFile(pAttributes, sAttributesFile);
// }
//
// }
| import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Properties;
import util.PropUtil;
import java.io.BufferedWriter;
import java.io.FileWriter;
import java.util.Enumeration;
import modules.Module;
| /*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package modules.contrib;
/**
*
* @author mihai
*/
public class S4G_LESSAg extends Module {
@Override
public void Initialize() {
| // Path: src/util/PropUtil.java
// public class PropUtil {
//
// public static Properties LoadFromFile(Properties pProp, String sFile) {
// try {
// if (pProp == null) {
// pProp = new Properties();
// }
// if (sFile.endsWith(".xml")) {
// pProp.loadFromXML(new FileInputStream(sFile));
// } else {
// pProp.load(new FileInputStream(sFile));
// }
//
// } catch (Exception ex) {
// //ex.printStackTrace();
// }
// return pProp;
// }
//
// public static void SaveToFile(Properties pProp, String sFile, String sComment) {
// try {
// if (sFile.endsWith(".xml")) {
// pProp.storeToXML(new FileOutputStream(sFile), sComment);
// } else {
// pProp.store(new FileOutputStream(sFile), sComment);
// }
//
// } catch (Exception ex) {
// // ex.printStackTrace();
// }
// }
//
// public static int GetInt(Properties pProp, String sKey, int iDefault) {
// try {
// return Integer.parseInt(pProp.getProperty(sKey, "").trim());
// } catch (Exception ex) {
//
// }
// return iDefault;
// }
//
// public static long GetLong(Properties pProp, String sKey, long lDefault) {
// try {
// return Long.parseLong(pProp.getProperty(sKey, "").trim());
// } catch (Exception ex) {
//
// }
// return lDefault;
// }
//
// public static double GetDouble(Properties pProp, String sKey, double lDefault) {
// try {
// return Double.parseDouble(pProp.getProperty(sKey, "").trim());
// } catch (Exception ex) {
//
// }
// return lDefault;
// }
//
// public static String GetString(Properties pProp, String sKey, String sDefault) {
// try {
// return pProp.getProperty(sKey, sDefault);
// } catch (Exception ex) {
// }
// return sDefault;
// }
// public static SimpleDateFormat sdfDate = new SimpleDateFormat("MM/dd/yyyy HH:mm:ss");
//
// public static Date GetDate(Properties pProp, String sKey, Date dtDefault) {
// Date dtRet;
// try {
// dtRet = sdfDate.parse(pProp.getProperty(sKey, ""));
// } catch (Exception ex) {
// dtRet = dtDefault;
// }
// return dtRet;
// }
//
// public static void PrintProp(Properties pProp) {
//
// Enumeration sKeys = pProp.keys();
// while (sKeys.hasMoreElements()) {
// try {
// String sKey = (String) sKeys.nextElement();
// String sValue = (String) pProp.get(sKey);
// System.out.println(sKey + " : " + sValue);
//
// } catch (Exception ex) {
// // System.out.println(ex.getMessage());
// }
// }
// }
//
// public static void SwitchKeyValue(Properties pInProp, Properties pOutProp) {
// try {
// if (pOutProp == null) {
// pOutProp = new Properties();
// }
// Enumeration sKeys = pInProp.keys();
// while (sKeys.hasMoreElements()) {
// String sKey = (String) sKeys.nextElement();
// String sValue = (String) pInProp.get(sKey);
// pOutProp.put(sValue, sKey);
// // System.out.println(sKey + " : " + sValue);
// }
// } catch (Exception ex) {
// }
// }
// }
//
// Path: src/modules/Module.java
// public class Module extends Thread{
//
// protected volatile Properties pAttributes = new Properties(); // The attributes of the current module, loaded from a file.
// protected String sAttributesFile=""; // The file it is loaded from
// protected String sName = ""; // The name of the instance of the module
// protected ModulesManager mmManager = null; // The module manager
// protected Logger logger = null; // The logger used
// protected volatile boolean bReinitialize = false;
//
// public void setAttributes(Properties pSetAttributes) {
// pAttributes = pSetAttributes;
// }
//
// public void Initialize() {
//
// }
//
// public void Start() {
//
// }
//
// public void QueueTime() {
//
// }
//
// public void LoadConfig() {
// LoadTxtConfig();
// }
//
// void LoadTxtConfig() {
// PropUtil.LoadFromFile(pAttributes, sAttributesFile);
// }
//
// }
// Path: src/modules/contrib/S4G_LESSAg.java
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Properties;
import util.PropUtil;
import java.io.BufferedWriter;
import java.io.FileWriter;
import java.util.Enumeration;
import modules.Module;
/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package modules.contrib;
/**
*
* @author mihai
*/
public class S4G_LESSAg extends Module {
@Override
public void Initialize() {
| pDataSet = mmManager.getSharedData(PropUtil.GetString(pAttributes, "pDataSet", sName));
|
SMXCore/SMXCore_NG | src/modules/SMXGPIO_RPi.java | // Path: src/util/PropUtil.java
// public class PropUtil {
//
// public static Properties LoadFromFile(Properties pProp, String sFile) {
// try {
// if (pProp == null) {
// pProp = new Properties();
// }
// if (sFile.endsWith(".xml")) {
// pProp.loadFromXML(new FileInputStream(sFile));
// } else {
// pProp.load(new FileInputStream(sFile));
// }
//
// } catch (Exception ex) {
// //ex.printStackTrace();
// }
// return pProp;
// }
//
// public static void SaveToFile(Properties pProp, String sFile, String sComment) {
// try {
// if (sFile.endsWith(".xml")) {
// pProp.storeToXML(new FileOutputStream(sFile), sComment);
// } else {
// pProp.store(new FileOutputStream(sFile), sComment);
// }
//
// } catch (Exception ex) {
// // ex.printStackTrace();
// }
// }
//
// public static int GetInt(Properties pProp, String sKey, int iDefault) {
// try {
// return Integer.parseInt(pProp.getProperty(sKey, "").trim());
// } catch (Exception ex) {
//
// }
// return iDefault;
// }
//
// public static long GetLong(Properties pProp, String sKey, long lDefault) {
// try {
// return Long.parseLong(pProp.getProperty(sKey, "").trim());
// } catch (Exception ex) {
//
// }
// return lDefault;
// }
//
// public static double GetDouble(Properties pProp, String sKey, double lDefault) {
// try {
// return Double.parseDouble(pProp.getProperty(sKey, "").trim());
// } catch (Exception ex) {
//
// }
// return lDefault;
// }
//
// public static String GetString(Properties pProp, String sKey, String sDefault) {
// try {
// return pProp.getProperty(sKey, sDefault);
// } catch (Exception ex) {
// }
// return sDefault;
// }
// public static SimpleDateFormat sdfDate = new SimpleDateFormat("MM/dd/yyyy HH:mm:ss");
//
// public static Date GetDate(Properties pProp, String sKey, Date dtDefault) {
// Date dtRet;
// try {
// dtRet = sdfDate.parse(pProp.getProperty(sKey, ""));
// } catch (Exception ex) {
// dtRet = dtDefault;
// }
// return dtRet;
// }
//
// public static void PrintProp(Properties pProp) {
//
// Enumeration sKeys = pProp.keys();
// while (sKeys.hasMoreElements()) {
// try {
// String sKey = (String) sKeys.nextElement();
// String sValue = (String) pProp.get(sKey);
// System.out.println(sKey + " : " + sValue);
//
// } catch (Exception ex) {
// // System.out.println(ex.getMessage());
// }
// }
// }
//
// public static void SwitchKeyValue(Properties pInProp, Properties pOutProp) {
// try {
// if (pOutProp == null) {
// pOutProp = new Properties();
// }
// Enumeration sKeys = pInProp.keys();
// while (sKeys.hasMoreElements()) {
// String sKey = (String) sKeys.nextElement();
// String sValue = (String) pInProp.get(sKey);
// pOutProp.put(sValue, sKey);
// // System.out.println(sKey + " : " + sValue);
// }
// } catch (Exception ex) {
// }
// }
// }
| import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Properties;
import util.PropUtil;
import java.io.BufferedWriter;
import java.io.FileWriter;
import java.util.Enumeration;
import java.util.Date;
import java.util.Map;
import java.util.HashMap;
import java.text.DateFormat;
import com.pi4j.io.gpio.*;
import com.pi4j.io.gpio.event.GpioPinDigitalStateChangeEvent;
import com.pi4j.io.gpio.event.GpioPinListenerDigital;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.Hashtable;
import java.io.PrintWriter;
import java.nio.file.FileSystems;
import java.nio.file.FileVisitResult;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.PathMatcher;
import java.nio.file.Paths;
import java.nio.file.SimpleFileVisitor;
import java.nio.file.attribute.BasicFileAttributes;
| Map<String, PinState> input_pins_state = new HashMap();
Map<String, Integer> input_pins_cntr = new HashMap();
Date refreshFile() {
DateFormat df = new SimpleDateFormat("yyyyMMdd");
Date date = new Date();
if(!df.format(date).equals(lastDate)) {
try {
DateFormat dateFormat = new SimpleDateFormat("yyyy.MM.dd.");
FileWriter fw = new FileWriter(filePath + dateFormat.format(date) + fileName, true);
BufferedWriter bw = new BufferedWriter(fw);
file = new PrintWriter(bw);
fileworks = true;
} catch (Exception e) {
e.printStackTrace();
fileworks = false;
}
}
return date;
}
void printToFile(String s) {
DateFormat df = new SimpleDateFormat("yyyy/MM/dd\tHH:mm:ss:SSS\t");
Date date = refreshFile();
file.println(df.format(date) + s);
file.flush();
}
@Override
public void Initialize() {
| // Path: src/util/PropUtil.java
// public class PropUtil {
//
// public static Properties LoadFromFile(Properties pProp, String sFile) {
// try {
// if (pProp == null) {
// pProp = new Properties();
// }
// if (sFile.endsWith(".xml")) {
// pProp.loadFromXML(new FileInputStream(sFile));
// } else {
// pProp.load(new FileInputStream(sFile));
// }
//
// } catch (Exception ex) {
// //ex.printStackTrace();
// }
// return pProp;
// }
//
// public static void SaveToFile(Properties pProp, String sFile, String sComment) {
// try {
// if (sFile.endsWith(".xml")) {
// pProp.storeToXML(new FileOutputStream(sFile), sComment);
// } else {
// pProp.store(new FileOutputStream(sFile), sComment);
// }
//
// } catch (Exception ex) {
// // ex.printStackTrace();
// }
// }
//
// public static int GetInt(Properties pProp, String sKey, int iDefault) {
// try {
// return Integer.parseInt(pProp.getProperty(sKey, "").trim());
// } catch (Exception ex) {
//
// }
// return iDefault;
// }
//
// public static long GetLong(Properties pProp, String sKey, long lDefault) {
// try {
// return Long.parseLong(pProp.getProperty(sKey, "").trim());
// } catch (Exception ex) {
//
// }
// return lDefault;
// }
//
// public static double GetDouble(Properties pProp, String sKey, double lDefault) {
// try {
// return Double.parseDouble(pProp.getProperty(sKey, "").trim());
// } catch (Exception ex) {
//
// }
// return lDefault;
// }
//
// public static String GetString(Properties pProp, String sKey, String sDefault) {
// try {
// return pProp.getProperty(sKey, sDefault);
// } catch (Exception ex) {
// }
// return sDefault;
// }
// public static SimpleDateFormat sdfDate = new SimpleDateFormat("MM/dd/yyyy HH:mm:ss");
//
// public static Date GetDate(Properties pProp, String sKey, Date dtDefault) {
// Date dtRet;
// try {
// dtRet = sdfDate.parse(pProp.getProperty(sKey, ""));
// } catch (Exception ex) {
// dtRet = dtDefault;
// }
// return dtRet;
// }
//
// public static void PrintProp(Properties pProp) {
//
// Enumeration sKeys = pProp.keys();
// while (sKeys.hasMoreElements()) {
// try {
// String sKey = (String) sKeys.nextElement();
// String sValue = (String) pProp.get(sKey);
// System.out.println(sKey + " : " + sValue);
//
// } catch (Exception ex) {
// // System.out.println(ex.getMessage());
// }
// }
// }
//
// public static void SwitchKeyValue(Properties pInProp, Properties pOutProp) {
// try {
// if (pOutProp == null) {
// pOutProp = new Properties();
// }
// Enumeration sKeys = pInProp.keys();
// while (sKeys.hasMoreElements()) {
// String sKey = (String) sKeys.nextElement();
// String sValue = (String) pInProp.get(sKey);
// pOutProp.put(sValue, sKey);
// // System.out.println(sKey + " : " + sValue);
// }
// } catch (Exception ex) {
// }
// }
// }
// Path: src/modules/SMXGPIO_RPi.java
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Properties;
import util.PropUtil;
import java.io.BufferedWriter;
import java.io.FileWriter;
import java.util.Enumeration;
import java.util.Date;
import java.util.Map;
import java.util.HashMap;
import java.text.DateFormat;
import com.pi4j.io.gpio.*;
import com.pi4j.io.gpio.event.GpioPinDigitalStateChangeEvent;
import com.pi4j.io.gpio.event.GpioPinListenerDigital;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.Hashtable;
import java.io.PrintWriter;
import java.nio.file.FileSystems;
import java.nio.file.FileVisitResult;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.PathMatcher;
import java.nio.file.Paths;
import java.nio.file.SimpleFileVisitor;
import java.nio.file.attribute.BasicFileAttributes;
Map<String, PinState> input_pins_state = new HashMap();
Map<String, Integer> input_pins_cntr = new HashMap();
Date refreshFile() {
DateFormat df = new SimpleDateFormat("yyyyMMdd");
Date date = new Date();
if(!df.format(date).equals(lastDate)) {
try {
DateFormat dateFormat = new SimpleDateFormat("yyyy.MM.dd.");
FileWriter fw = new FileWriter(filePath + dateFormat.format(date) + fileName, true);
BufferedWriter bw = new BufferedWriter(fw);
file = new PrintWriter(bw);
fileworks = true;
} catch (Exception e) {
e.printStackTrace();
fileworks = false;
}
}
return date;
}
void printToFile(String s) {
DateFormat df = new SimpleDateFormat("yyyy/MM/dd\tHH:mm:ss:SSS\t");
Date date = refreshFile();
file.println(df.format(date) + s);
file.flush();
}
@Override
public void Initialize() {
| pDataSet = mmManager.getSharedData(PropUtil.GetString(pAttributes, "pDataSet", sName));
|
chenyihan/Simple-SQLite-ORM-Android | src/org/cyy/fw/android/dborm/AnnotationORMapper.java | // Path: src/org/cyy/fw/android/dborm/ORMapInfo.java
// public static class AssociateInfo {
// private String field;
// private String sourceField;
// private Class<?> target;
// private String targetField;
//
// public String getField() {
// return field;
// }
//
// public String getSourceField() {
// return sourceField;
// }
//
// public Class<?> getTarget() {
// return target;
// }
//
// public String getTargetField() {
// return targetField;
// }
//
// public void setField(String field) {
// this.field = field;
// }
//
// public void setSourceField(String sourceField) {
// this.sourceField = sourceField;
// }
//
// public void setTarget(Class<?> target) {
// this.target = target;
// }
//
// public void setTargetField(String targetField) {
// this.targetField = targetField;
// }
//
// }
| import java.lang.reflect.Field;
import java.lang.reflect.ParameterizedType;
import java.util.ArrayList;
import java.util.Collection;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Vector;
import org.cyy.fw.android.dborm.ORMapInfo.AssociateInfo;
import android.text.TextUtils;
import android.util.Log; | if (paraType == null) {
throw new POJOClassDefineException(
"@OneToMany has not enough info.");
}
Class<?> paraTypeClass = (Class<?>) paraType
.getActualTypeArguments()[0];
targetClass = paraTypeClass;
}
// Obtain the declare type of complex type attribute
else if (!fieldType.isAssignableFrom(Collection.class)
&& !fieldType.isArray()
&& !fieldType.isAssignableFrom(Map.class)) {
targetClass = fieldType;
}
}
if (targetClass == null) {
throw new POJOClassDefineException(
"@OneToMany has not enough info.");
}
String targetField = assAnno.targetField();
String sourceField = assAnno.sourceField();
// use primary key as source relation attribute
if (TextUtils.isEmpty(sourceField)) {
sourceField = mapInfo.getPrimaryKeyField();
}
if (TextUtils.isEmpty(sourceField)) {
throw new POJOClassDefineException(
"@OneToMany hasn't sourceField attribute or the POJO hasn't PrimaryKey annotation.");
} | // Path: src/org/cyy/fw/android/dborm/ORMapInfo.java
// public static class AssociateInfo {
// private String field;
// private String sourceField;
// private Class<?> target;
// private String targetField;
//
// public String getField() {
// return field;
// }
//
// public String getSourceField() {
// return sourceField;
// }
//
// public Class<?> getTarget() {
// return target;
// }
//
// public String getTargetField() {
// return targetField;
// }
//
// public void setField(String field) {
// this.field = field;
// }
//
// public void setSourceField(String sourceField) {
// this.sourceField = sourceField;
// }
//
// public void setTarget(Class<?> target) {
// this.target = target;
// }
//
// public void setTargetField(String targetField) {
// this.targetField = targetField;
// }
//
// }
// Path: src/org/cyy/fw/android/dborm/AnnotationORMapper.java
import java.lang.reflect.Field;
import java.lang.reflect.ParameterizedType;
import java.util.ArrayList;
import java.util.Collection;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Vector;
import org.cyy.fw.android.dborm.ORMapInfo.AssociateInfo;
import android.text.TextUtils;
import android.util.Log;
if (paraType == null) {
throw new POJOClassDefineException(
"@OneToMany has not enough info.");
}
Class<?> paraTypeClass = (Class<?>) paraType
.getActualTypeArguments()[0];
targetClass = paraTypeClass;
}
// Obtain the declare type of complex type attribute
else if (!fieldType.isAssignableFrom(Collection.class)
&& !fieldType.isArray()
&& !fieldType.isAssignableFrom(Map.class)) {
targetClass = fieldType;
}
}
if (targetClass == null) {
throw new POJOClassDefineException(
"@OneToMany has not enough info.");
}
String targetField = assAnno.targetField();
String sourceField = assAnno.sourceField();
// use primary key as source relation attribute
if (TextUtils.isEmpty(sourceField)) {
sourceField = mapInfo.getPrimaryKeyField();
}
if (TextUtils.isEmpty(sourceField)) {
throw new POJOClassDefineException(
"@OneToMany hasn't sourceField attribute or the POJO hasn't PrimaryKey annotation.");
} | Map<Class<?>, AssociateInfo> assInfoMap = mapInfo |
chenyihan/Simple-SQLite-ORM-Android | src/org/cyy/fw/android/dborm/sqlite/QueryDataLogic.java | // Path: src/org/cyy/fw/android/dborm/ORMapper.java
// public interface ORMapper {
// /**
// *
// * generate all the O-R mapping information<BR>
// * One POJO class may be mapped to several tables
// *
// * @param clazz
// * POJO class
// * @return mapping info
// */
// ORMapInfo[] generateAllTableColumnMap(Class<?> clazz);
//
// /**
// *
// * generate one O-R mapping object, if the class class is mapped to more
// * than one tables, return the first table<BR>
// *
// * @param clazz
// * POJO class
// * @deprecated It's suggested to use
// * {@link #generateColumnMap(Class, String)} instead
// * @return mapping info
// */
// ORMapInfo generateColumnMap(Class<?> clazz);
//
// /**
// *
// * generate mapping info of specified table<BR>
// *
// * @param clazz
// * POJO class
// * @param tableName
// * The specified table name, the first table's info will be
// * returned if this parameter is null
// * @return mapping info
// */
// ORMapInfo generateColumnMap(Class<?> clazz, String tableName);
// }
//
// Path: src/org/cyy/fw/android/dborm/sqlite/DBAccessTemplate.java
// public static interface IDBAccessLogic<T> {
// /**
// *
// * Access DB core logic<BR>
// *
// * @param db
// * DB instance
// * @return result
// */
// T doAccessLogic(SQLiteDatabase db);
//
// /**
// *
// * If need to open transaction while access the DB<BR>
// * In general case, it's true for writing logic and false for reading
// * logic
// *
// * @return true: need transaction,false: need not
// */
// boolean isOpenTransaction();
// }
//
// Path: src/org/cyy/fw/android/dborm/sqlite/SQLBuilder.java
// static class QuerySql {
// StringBuffer from = new StringBuffer();
//
// QueryColumns queryColumns = new QueryColumns();
//
// // StringBuffer select = new StringBuffer();
// WhereObject whereObject = new WhereObject();
//
// private QueryAidParameter aidParameter;
//
// String combineSqlFragment() {
// StringBuffer sql = new StringBuffer();
// StringBuffer select = this.buildSelectSegment();
// if (select.toString().endsWith(COMMA)) {
// select.replace(select.length() - 1, select.length(), "");
// }
// if (from.toString().endsWith(COMMA)) {
// from.replace(from.length() - 1, from.length(), "");
// }
// if (select.length() <= 0) {
// return null;
// }
// sql.append(" select ");
// if (isDistinct()) {
// sql.append(" distinct ");
// }
// sql.append(select);
// sql.append(" from ");
// sql.append(from);
//
// arrangeWherePart(whereObject, aidParameter);
// arrangeWhereArgValues(whereObject, aidParameter);
//
// if (whereObject.whereArg != null
// && whereObject.whereArg.length() > 0) {
// sql.append(" where ");
// sql.append(whereObject.whereArg);
// }
//
// String aidPart = appendAidParam();
// sql.append(aidPart);
//
// return sql.toString();
// }
//
// private boolean isDistinct() {
// return aidParameter != null && aidParameter.isDistinct();
// }
//
// private String appendAidParam() {
// StringBuffer sb = new StringBuffer();
// if (aidParameter == null) {
// return sb.toString();
// }
// if (!TextUtils.isEmpty(aidParameter.getGroupBy())) {
// sb.append(" group by ");
// sb.append(aidParameter.getGroupBy());
// sb.append(BLANK);
// if (!TextUtils.isEmpty(aidParameter.getHaving())) {
// sb.append(" having ");
// sb.append(aidParameter.getHaving());
// sb.append(BLANK);
// }
// }
// if (!TextUtils.isEmpty(aidParameter.getOrderBy())) {
// sb.append(" order by ");
// sb.append(aidParameter.getOrderBy());
// sb.append(BLANK);
// }
// if (!TextUtils.isEmpty(aidParameter.getLimit())) {
// sb.append(" limit ");
// sb.append(aidParameter.getLimit());
// }
// return sb.toString();
// }
//
// void setAidParameter(QueryAidParameter aidParameter) {
// this.aidParameter = aidParameter;
// }
//
// private StringBuffer buildSelectSegment() {
// StringBuffer select = new StringBuffer();
// if (this.queryColumns == null) {
// return select;
// }
// for (QueryColumn column : this.queryColumns) {
// String tableName = column.tableName;
// String columnName = column.column;
// select.append(BLANK);
// select.append(tableName);
// select.append(DOT);
// select.append(columnName);
// select.append(COMMA);
// }
// return select;
// }
// }
| import java.util.Map;
import org.cyy.fw.android.dborm.ORMapper;
import org.cyy.fw.android.dborm.sqlite.DBAccessTemplate.IDBAccessLogic;
import org.cyy.fw.android.dborm.sqlite.SQLBuilder.QuerySql;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.util.Log; | package org.cyy.fw.android.dborm.sqlite;
class QueryDataLogic<T> implements IDBAccessLogic<T[]> {
private Class<T> clazz;
private Map<Class<?>, String> tableMap; | // Path: src/org/cyy/fw/android/dborm/ORMapper.java
// public interface ORMapper {
// /**
// *
// * generate all the O-R mapping information<BR>
// * One POJO class may be mapped to several tables
// *
// * @param clazz
// * POJO class
// * @return mapping info
// */
// ORMapInfo[] generateAllTableColumnMap(Class<?> clazz);
//
// /**
// *
// * generate one O-R mapping object, if the class class is mapped to more
// * than one tables, return the first table<BR>
// *
// * @param clazz
// * POJO class
// * @deprecated It's suggested to use
// * {@link #generateColumnMap(Class, String)} instead
// * @return mapping info
// */
// ORMapInfo generateColumnMap(Class<?> clazz);
//
// /**
// *
// * generate mapping info of specified table<BR>
// *
// * @param clazz
// * POJO class
// * @param tableName
// * The specified table name, the first table's info will be
// * returned if this parameter is null
// * @return mapping info
// */
// ORMapInfo generateColumnMap(Class<?> clazz, String tableName);
// }
//
// Path: src/org/cyy/fw/android/dborm/sqlite/DBAccessTemplate.java
// public static interface IDBAccessLogic<T> {
// /**
// *
// * Access DB core logic<BR>
// *
// * @param db
// * DB instance
// * @return result
// */
// T doAccessLogic(SQLiteDatabase db);
//
// /**
// *
// * If need to open transaction while access the DB<BR>
// * In general case, it's true for writing logic and false for reading
// * logic
// *
// * @return true: need transaction,false: need not
// */
// boolean isOpenTransaction();
// }
//
// Path: src/org/cyy/fw/android/dborm/sqlite/SQLBuilder.java
// static class QuerySql {
// StringBuffer from = new StringBuffer();
//
// QueryColumns queryColumns = new QueryColumns();
//
// // StringBuffer select = new StringBuffer();
// WhereObject whereObject = new WhereObject();
//
// private QueryAidParameter aidParameter;
//
// String combineSqlFragment() {
// StringBuffer sql = new StringBuffer();
// StringBuffer select = this.buildSelectSegment();
// if (select.toString().endsWith(COMMA)) {
// select.replace(select.length() - 1, select.length(), "");
// }
// if (from.toString().endsWith(COMMA)) {
// from.replace(from.length() - 1, from.length(), "");
// }
// if (select.length() <= 0) {
// return null;
// }
// sql.append(" select ");
// if (isDistinct()) {
// sql.append(" distinct ");
// }
// sql.append(select);
// sql.append(" from ");
// sql.append(from);
//
// arrangeWherePart(whereObject, aidParameter);
// arrangeWhereArgValues(whereObject, aidParameter);
//
// if (whereObject.whereArg != null
// && whereObject.whereArg.length() > 0) {
// sql.append(" where ");
// sql.append(whereObject.whereArg);
// }
//
// String aidPart = appendAidParam();
// sql.append(aidPart);
//
// return sql.toString();
// }
//
// private boolean isDistinct() {
// return aidParameter != null && aidParameter.isDistinct();
// }
//
// private String appendAidParam() {
// StringBuffer sb = new StringBuffer();
// if (aidParameter == null) {
// return sb.toString();
// }
// if (!TextUtils.isEmpty(aidParameter.getGroupBy())) {
// sb.append(" group by ");
// sb.append(aidParameter.getGroupBy());
// sb.append(BLANK);
// if (!TextUtils.isEmpty(aidParameter.getHaving())) {
// sb.append(" having ");
// sb.append(aidParameter.getHaving());
// sb.append(BLANK);
// }
// }
// if (!TextUtils.isEmpty(aidParameter.getOrderBy())) {
// sb.append(" order by ");
// sb.append(aidParameter.getOrderBy());
// sb.append(BLANK);
// }
// if (!TextUtils.isEmpty(aidParameter.getLimit())) {
// sb.append(" limit ");
// sb.append(aidParameter.getLimit());
// }
// return sb.toString();
// }
//
// void setAidParameter(QueryAidParameter aidParameter) {
// this.aidParameter = aidParameter;
// }
//
// private StringBuffer buildSelectSegment() {
// StringBuffer select = new StringBuffer();
// if (this.queryColumns == null) {
// return select;
// }
// for (QueryColumn column : this.queryColumns) {
// String tableName = column.tableName;
// String columnName = column.column;
// select.append(BLANK);
// select.append(tableName);
// select.append(DOT);
// select.append(columnName);
// select.append(COMMA);
// }
// return select;
// }
// }
// Path: src/org/cyy/fw/android/dborm/sqlite/QueryDataLogic.java
import java.util.Map;
import org.cyy.fw.android.dborm.ORMapper;
import org.cyy.fw.android.dborm.sqlite.DBAccessTemplate.IDBAccessLogic;
import org.cyy.fw.android.dborm.sqlite.SQLBuilder.QuerySql;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.util.Log;
package org.cyy.fw.android.dborm.sqlite;
class QueryDataLogic<T> implements IDBAccessLogic<T[]> {
private Class<T> clazz;
private Map<Class<?>, String> tableMap; | private QuerySql querySql; |
chenyihan/Simple-SQLite-ORM-Android | src/org/cyy/fw/android/dborm/sqlite/QueryDataLogic.java | // Path: src/org/cyy/fw/android/dborm/ORMapper.java
// public interface ORMapper {
// /**
// *
// * generate all the O-R mapping information<BR>
// * One POJO class may be mapped to several tables
// *
// * @param clazz
// * POJO class
// * @return mapping info
// */
// ORMapInfo[] generateAllTableColumnMap(Class<?> clazz);
//
// /**
// *
// * generate one O-R mapping object, if the class class is mapped to more
// * than one tables, return the first table<BR>
// *
// * @param clazz
// * POJO class
// * @deprecated It's suggested to use
// * {@link #generateColumnMap(Class, String)} instead
// * @return mapping info
// */
// ORMapInfo generateColumnMap(Class<?> clazz);
//
// /**
// *
// * generate mapping info of specified table<BR>
// *
// * @param clazz
// * POJO class
// * @param tableName
// * The specified table name, the first table's info will be
// * returned if this parameter is null
// * @return mapping info
// */
// ORMapInfo generateColumnMap(Class<?> clazz, String tableName);
// }
//
// Path: src/org/cyy/fw/android/dborm/sqlite/DBAccessTemplate.java
// public static interface IDBAccessLogic<T> {
// /**
// *
// * Access DB core logic<BR>
// *
// * @param db
// * DB instance
// * @return result
// */
// T doAccessLogic(SQLiteDatabase db);
//
// /**
// *
// * If need to open transaction while access the DB<BR>
// * In general case, it's true for writing logic and false for reading
// * logic
// *
// * @return true: need transaction,false: need not
// */
// boolean isOpenTransaction();
// }
//
// Path: src/org/cyy/fw/android/dborm/sqlite/SQLBuilder.java
// static class QuerySql {
// StringBuffer from = new StringBuffer();
//
// QueryColumns queryColumns = new QueryColumns();
//
// // StringBuffer select = new StringBuffer();
// WhereObject whereObject = new WhereObject();
//
// private QueryAidParameter aidParameter;
//
// String combineSqlFragment() {
// StringBuffer sql = new StringBuffer();
// StringBuffer select = this.buildSelectSegment();
// if (select.toString().endsWith(COMMA)) {
// select.replace(select.length() - 1, select.length(), "");
// }
// if (from.toString().endsWith(COMMA)) {
// from.replace(from.length() - 1, from.length(), "");
// }
// if (select.length() <= 0) {
// return null;
// }
// sql.append(" select ");
// if (isDistinct()) {
// sql.append(" distinct ");
// }
// sql.append(select);
// sql.append(" from ");
// sql.append(from);
//
// arrangeWherePart(whereObject, aidParameter);
// arrangeWhereArgValues(whereObject, aidParameter);
//
// if (whereObject.whereArg != null
// && whereObject.whereArg.length() > 0) {
// sql.append(" where ");
// sql.append(whereObject.whereArg);
// }
//
// String aidPart = appendAidParam();
// sql.append(aidPart);
//
// return sql.toString();
// }
//
// private boolean isDistinct() {
// return aidParameter != null && aidParameter.isDistinct();
// }
//
// private String appendAidParam() {
// StringBuffer sb = new StringBuffer();
// if (aidParameter == null) {
// return sb.toString();
// }
// if (!TextUtils.isEmpty(aidParameter.getGroupBy())) {
// sb.append(" group by ");
// sb.append(aidParameter.getGroupBy());
// sb.append(BLANK);
// if (!TextUtils.isEmpty(aidParameter.getHaving())) {
// sb.append(" having ");
// sb.append(aidParameter.getHaving());
// sb.append(BLANK);
// }
// }
// if (!TextUtils.isEmpty(aidParameter.getOrderBy())) {
// sb.append(" order by ");
// sb.append(aidParameter.getOrderBy());
// sb.append(BLANK);
// }
// if (!TextUtils.isEmpty(aidParameter.getLimit())) {
// sb.append(" limit ");
// sb.append(aidParameter.getLimit());
// }
// return sb.toString();
// }
//
// void setAidParameter(QueryAidParameter aidParameter) {
// this.aidParameter = aidParameter;
// }
//
// private StringBuffer buildSelectSegment() {
// StringBuffer select = new StringBuffer();
// if (this.queryColumns == null) {
// return select;
// }
// for (QueryColumn column : this.queryColumns) {
// String tableName = column.tableName;
// String columnName = column.column;
// select.append(BLANK);
// select.append(tableName);
// select.append(DOT);
// select.append(columnName);
// select.append(COMMA);
// }
// return select;
// }
// }
| import java.util.Map;
import org.cyy.fw.android.dborm.ORMapper;
import org.cyy.fw.android.dborm.sqlite.DBAccessTemplate.IDBAccessLogic;
import org.cyy.fw.android.dborm.sqlite.SQLBuilder.QuerySql;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.util.Log; | package org.cyy.fw.android.dborm.sqlite;
class QueryDataLogic<T> implements IDBAccessLogic<T[]> {
private Class<T> clazz;
private Map<Class<?>, String> tableMap;
private QuerySql querySql; | // Path: src/org/cyy/fw/android/dborm/ORMapper.java
// public interface ORMapper {
// /**
// *
// * generate all the O-R mapping information<BR>
// * One POJO class may be mapped to several tables
// *
// * @param clazz
// * POJO class
// * @return mapping info
// */
// ORMapInfo[] generateAllTableColumnMap(Class<?> clazz);
//
// /**
// *
// * generate one O-R mapping object, if the class class is mapped to more
// * than one tables, return the first table<BR>
// *
// * @param clazz
// * POJO class
// * @deprecated It's suggested to use
// * {@link #generateColumnMap(Class, String)} instead
// * @return mapping info
// */
// ORMapInfo generateColumnMap(Class<?> clazz);
//
// /**
// *
// * generate mapping info of specified table<BR>
// *
// * @param clazz
// * POJO class
// * @param tableName
// * The specified table name, the first table's info will be
// * returned if this parameter is null
// * @return mapping info
// */
// ORMapInfo generateColumnMap(Class<?> clazz, String tableName);
// }
//
// Path: src/org/cyy/fw/android/dborm/sqlite/DBAccessTemplate.java
// public static interface IDBAccessLogic<T> {
// /**
// *
// * Access DB core logic<BR>
// *
// * @param db
// * DB instance
// * @return result
// */
// T doAccessLogic(SQLiteDatabase db);
//
// /**
// *
// * If need to open transaction while access the DB<BR>
// * In general case, it's true for writing logic and false for reading
// * logic
// *
// * @return true: need transaction,false: need not
// */
// boolean isOpenTransaction();
// }
//
// Path: src/org/cyy/fw/android/dborm/sqlite/SQLBuilder.java
// static class QuerySql {
// StringBuffer from = new StringBuffer();
//
// QueryColumns queryColumns = new QueryColumns();
//
// // StringBuffer select = new StringBuffer();
// WhereObject whereObject = new WhereObject();
//
// private QueryAidParameter aidParameter;
//
// String combineSqlFragment() {
// StringBuffer sql = new StringBuffer();
// StringBuffer select = this.buildSelectSegment();
// if (select.toString().endsWith(COMMA)) {
// select.replace(select.length() - 1, select.length(), "");
// }
// if (from.toString().endsWith(COMMA)) {
// from.replace(from.length() - 1, from.length(), "");
// }
// if (select.length() <= 0) {
// return null;
// }
// sql.append(" select ");
// if (isDistinct()) {
// sql.append(" distinct ");
// }
// sql.append(select);
// sql.append(" from ");
// sql.append(from);
//
// arrangeWherePart(whereObject, aidParameter);
// arrangeWhereArgValues(whereObject, aidParameter);
//
// if (whereObject.whereArg != null
// && whereObject.whereArg.length() > 0) {
// sql.append(" where ");
// sql.append(whereObject.whereArg);
// }
//
// String aidPart = appendAidParam();
// sql.append(aidPart);
//
// return sql.toString();
// }
//
// private boolean isDistinct() {
// return aidParameter != null && aidParameter.isDistinct();
// }
//
// private String appendAidParam() {
// StringBuffer sb = new StringBuffer();
// if (aidParameter == null) {
// return sb.toString();
// }
// if (!TextUtils.isEmpty(aidParameter.getGroupBy())) {
// sb.append(" group by ");
// sb.append(aidParameter.getGroupBy());
// sb.append(BLANK);
// if (!TextUtils.isEmpty(aidParameter.getHaving())) {
// sb.append(" having ");
// sb.append(aidParameter.getHaving());
// sb.append(BLANK);
// }
// }
// if (!TextUtils.isEmpty(aidParameter.getOrderBy())) {
// sb.append(" order by ");
// sb.append(aidParameter.getOrderBy());
// sb.append(BLANK);
// }
// if (!TextUtils.isEmpty(aidParameter.getLimit())) {
// sb.append(" limit ");
// sb.append(aidParameter.getLimit());
// }
// return sb.toString();
// }
//
// void setAidParameter(QueryAidParameter aidParameter) {
// this.aidParameter = aidParameter;
// }
//
// private StringBuffer buildSelectSegment() {
// StringBuffer select = new StringBuffer();
// if (this.queryColumns == null) {
// return select;
// }
// for (QueryColumn column : this.queryColumns) {
// String tableName = column.tableName;
// String columnName = column.column;
// select.append(BLANK);
// select.append(tableName);
// select.append(DOT);
// select.append(columnName);
// select.append(COMMA);
// }
// return select;
// }
// }
// Path: src/org/cyy/fw/android/dborm/sqlite/QueryDataLogic.java
import java.util.Map;
import org.cyy.fw.android.dborm.ORMapper;
import org.cyy.fw.android.dborm.sqlite.DBAccessTemplate.IDBAccessLogic;
import org.cyy.fw.android.dborm.sqlite.SQLBuilder.QuerySql;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.util.Log;
package org.cyy.fw.android.dborm.sqlite;
class QueryDataLogic<T> implements IDBAccessLogic<T[]> {
private Class<T> clazz;
private Map<Class<?>, String> tableMap;
private QuerySql querySql; | private ORMapper orMapper; |
chenyihan/Simple-SQLite-ORM-Android | src/org/cyy/fw/android/dborm/sqlite/DBAccessTemplate.java | // Path: src/org/cyy/fw/android/dborm/DBAccessException.java
// public class DBAccessException extends RuntimeException {
//
// /**
// * serialVersionUID
// */
// private static final long serialVersionUID = -1042916009553988694L;
//
// public DBAccessException() {
// super();
// }
//
// public DBAccessException(String detailMessage) {
// super(detailMessage);
// }
//
// public DBAccessException(String detailMessage, Throwable throwable) {
// super(detailMessage, throwable);
// }
//
// public DBAccessException(Throwable throwable) {
// super(throwable);
// }
//
// }
| import org.cyy.fw.android.dborm.DBAccessException;
import android.database.SQLException;
import android.database.sqlite.SQLiteDatabase;
import android.util.Log;
| package org.cyy.fw.android.dborm.sqlite;
/**
*
* DB Accessing template<BR>
* Extract some common codes for accessing DB, such as will call
* {@link android.database.sqlite.SQLiteDatabase#beginTransaction()} when begin
* to access table, will call
* {@link android.database.sqlite.SQLiteDatabase#setTransactionSuccessful()}
* after accessing successfully, and will call
* {@link android.database.sqlite.SQLiteDatabase#endTransaction()} to end the
* logic. The user's code only need to implement the {@link IDBAccessLogic}
* interface. It's the sample code as follow:
*
* <pre>
* DBAccessTemplate dbAccessTemplate = new DBAccessTemplate();
* dbAccessTemplate.accessDb(this.database, new IDBAccessLogic<Void>() {
* @Override
* public Void doAccessLogic(SQLiteDatabase db) throws Exception {
* String createSql = generateCreateSql(clazz);
* database.execSQL(createSql);
* return null;
* }
* });
* </pre>
*
* @author cyy
* @version [V1.0, 2012-11-5]
*/
public final class DBAccessTemplate {
/**
* DB Accessing logic<BR>
*
* @author cyy
* @version [V1.0, 2012-11-5]
* @param <T>
*/
public static interface IDBAccessLogic<T> {
/**
*
* Access DB core logic<BR>
*
* @param db
* DB instance
* @return result
*/
T doAccessLogic(SQLiteDatabase db);
/**
*
* If need to open transaction while access the DB<BR>
* In general case, it's true for writing logic and false for reading
* logic
*
* @return true: need transaction,false: need not
*/
boolean isOpenTransaction();
}
private static final String TAG = "DBAccessTemplate";
/**
*
* Access DB<BR>
*
* @param db
* DB instance
* @param logic
* accessing logic
* @param <T>
*
* @return result
*/
public <T> T accessDb(SQLiteDatabase db, IDBAccessLogic<T> logic) {
if (logic.isOpenTransaction()) {
return accessDBOpenTransaction(db, logic);
}
return accessDBWithoutOpenTransaction(db, logic);
}
private <T> T accessDBWithoutOpenTransaction(SQLiteDatabase db,
IDBAccessLogic<T> logic) {
Log.d(TAG, "accessDBWithoutOpenTransaction");
T result = null;
try {
result = logic.doAccessLogic(db);
} catch (SQLException e) {
Log.e(TAG, e.getMessage(), e);
| // Path: src/org/cyy/fw/android/dborm/DBAccessException.java
// public class DBAccessException extends RuntimeException {
//
// /**
// * serialVersionUID
// */
// private static final long serialVersionUID = -1042916009553988694L;
//
// public DBAccessException() {
// super();
// }
//
// public DBAccessException(String detailMessage) {
// super(detailMessage);
// }
//
// public DBAccessException(String detailMessage, Throwable throwable) {
// super(detailMessage, throwable);
// }
//
// public DBAccessException(Throwable throwable) {
// super(throwable);
// }
//
// }
// Path: src/org/cyy/fw/android/dborm/sqlite/DBAccessTemplate.java
import org.cyy.fw.android.dborm.DBAccessException;
import android.database.SQLException;
import android.database.sqlite.SQLiteDatabase;
import android.util.Log;
package org.cyy.fw.android.dborm.sqlite;
/**
*
* DB Accessing template<BR>
* Extract some common codes for accessing DB, such as will call
* {@link android.database.sqlite.SQLiteDatabase#beginTransaction()} when begin
* to access table, will call
* {@link android.database.sqlite.SQLiteDatabase#setTransactionSuccessful()}
* after accessing successfully, and will call
* {@link android.database.sqlite.SQLiteDatabase#endTransaction()} to end the
* logic. The user's code only need to implement the {@link IDBAccessLogic}
* interface. It's the sample code as follow:
*
* <pre>
* DBAccessTemplate dbAccessTemplate = new DBAccessTemplate();
* dbAccessTemplate.accessDb(this.database, new IDBAccessLogic<Void>() {
* @Override
* public Void doAccessLogic(SQLiteDatabase db) throws Exception {
* String createSql = generateCreateSql(clazz);
* database.execSQL(createSql);
* return null;
* }
* });
* </pre>
*
* @author cyy
* @version [V1.0, 2012-11-5]
*/
public final class DBAccessTemplate {
/**
* DB Accessing logic<BR>
*
* @author cyy
* @version [V1.0, 2012-11-5]
* @param <T>
*/
public static interface IDBAccessLogic<T> {
/**
*
* Access DB core logic<BR>
*
* @param db
* DB instance
* @return result
*/
T doAccessLogic(SQLiteDatabase db);
/**
*
* If need to open transaction while access the DB<BR>
* In general case, it's true for writing logic and false for reading
* logic
*
* @return true: need transaction,false: need not
*/
boolean isOpenTransaction();
}
private static final String TAG = "DBAccessTemplate";
/**
*
* Access DB<BR>
*
* @param db
* DB instance
* @param logic
* accessing logic
* @param <T>
*
* @return result
*/
public <T> T accessDb(SQLiteDatabase db, IDBAccessLogic<T> logic) {
if (logic.isOpenTransaction()) {
return accessDBOpenTransaction(db, logic);
}
return accessDBWithoutOpenTransaction(db, logic);
}
private <T> T accessDBWithoutOpenTransaction(SQLiteDatabase db,
IDBAccessLogic<T> logic) {
Log.d(TAG, "accessDBWithoutOpenTransaction");
T result = null;
try {
result = logic.doAccessLogic(db);
} catch (SQLException e) {
Log.e(TAG, e.getMessage(), e);
| throw new DBAccessException(e);
|
AlanCheen/PracticeDemo | PracticeDemos/app/src/main/java/yifeiyuan/practice/practicedemos/service/ServiceActivity.java | // Path: PracticeDemos/app/src/main/java/yifeiyuan/practice/practicedemos/DownloadService.java
// public class DownloadService extends IntentService {
//
// public static final String TAG = "DownloadService";
//
// public static final String EXTRA_PATH = "yfy.practice.filepath";
//
// public DownloadService() {
// super("DownloadService");
// }
//
// String mUrl;
//
// @Override
// protected void onHandleIntent(Intent intent) {
// mUrl = intent.getStringExtra(EXTRA_PATH);
// if (TextUtils.isEmpty(mUrl)) {
// stopSelf();
// } else {
// download();
// }
// }
//
// private void download() {
//
// try {
// //file:/storage/emulated/0/test.apk
// File file = new File(Environment.getExternalStorageDirectory(), "test.apk");
// Log.d(TAG, "download: file:" + file.getPath());
// URL url = new URL(mUrl);
// HttpURLConnection connection = (HttpURLConnection) url.openConnection();
// connection.setRequestMethod("GET");
// InputStream in = connection.getInputStream();
// BufferedInputStream bis = new BufferedInputStream(in);
// if (!file.exists()) {
// file.createNewFile();
// } else {
// file.delete();
// file.createNewFile();
// }
// FileOutputStream fos = new FileOutputStream(file);
//
// byte[] buffer = new byte[1024];
// int size = -1;
// while ((size = bis.read(buffer)) != -1) {
// fos.write(buffer, 0, size);
// }
//
// fos.flush();
// fos.close();
// bis.close();
// connection.disconnect();
// } catch (MalformedURLException e) {
// e.printStackTrace();
// } catch (IOException e) {
// e.printStackTrace();
// }
// }
//
// @Override
// public void setIntentRedelivery(boolean enabled) {
// super.setIntentRedelivery(enabled);
// Log.d(TAG, "setIntentRedelivery() called with: " + "enabled = [" + enabled + "]");
// }
//
// @Override
// public void onCreate() {
// super.onCreate();
// Log.d(TAG, "onCreate: ");
// }
//
// @Override
// public void onStart(Intent intent, int startId) {
// super.onStart(intent, startId);
// Log.d(TAG, "onStart() called with: " + "intent = [" + intent + "], startId = [" + startId + "]");
// }
//
// // onStartCommand 里调用了onstart
// @Override
// public int onStartCommand(Intent intent, int flags, int startId) {
// Log.d(TAG, "onStartCommand() called with: " + "flags = [" + flags + "], startId = [" + startId + "]");
// return super.onStartCommand(intent, flags, startId);
// }
//
// @Override
// public void onDestroy() {
// super.onDestroy();
// Log.d(TAG, "onDestroy() called with: " + "");
// }
//
// @Override
// public IBinder onBind(Intent intent) {
// Log.d(TAG, "onBind() called with: " + "intent = [" + intent + "]");
// return super.onBind(intent);
// }
// }
| import android.app.Service;
import android.content.ComponentName;
import android.content.Intent;
import android.content.ServiceConnection;
import android.os.Bundle;
import android.os.IBinder;
import android.support.design.widget.FloatingActionButton;
import android.support.design.widget.Snackbar;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;
import android.util.Log;
import android.view.View;
import android.widget.TextView;
import butterknife.ButterKnife;
import butterknife.InjectView;
import butterknife.OnClick;
import yifeiyuan.practice.practicedemos.DownloadService;
import yifeiyuan.practice.practicedemos.R; | package yifeiyuan.practice.practicedemos.service;
public class ServiceActivity extends AppCompatActivity {
public static final String TAG = "MyService";
@InjectView(R.id.start_service)
TextView mStartService;
@InjectView(R.id.stop_service)
TextView mStopService;
@InjectView(R.id.bind_service)
TextView mBindService;
@InjectView(R.id.unbind_service)
TextView mUnbindService;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_service);
ButterKnife.inject(this);
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
FloatingActionButton fab = (FloatingActionButton) findViewById(R.id.fab);
fab.setOnClickListener(view -> Snackbar.make(view, "Replace with your own action", Snackbar.LENGTH_LONG)
.setAction("Action", v -> {
Intent intent = new Intent(); | // Path: PracticeDemos/app/src/main/java/yifeiyuan/practice/practicedemos/DownloadService.java
// public class DownloadService extends IntentService {
//
// public static final String TAG = "DownloadService";
//
// public static final String EXTRA_PATH = "yfy.practice.filepath";
//
// public DownloadService() {
// super("DownloadService");
// }
//
// String mUrl;
//
// @Override
// protected void onHandleIntent(Intent intent) {
// mUrl = intent.getStringExtra(EXTRA_PATH);
// if (TextUtils.isEmpty(mUrl)) {
// stopSelf();
// } else {
// download();
// }
// }
//
// private void download() {
//
// try {
// //file:/storage/emulated/0/test.apk
// File file = new File(Environment.getExternalStorageDirectory(), "test.apk");
// Log.d(TAG, "download: file:" + file.getPath());
// URL url = new URL(mUrl);
// HttpURLConnection connection = (HttpURLConnection) url.openConnection();
// connection.setRequestMethod("GET");
// InputStream in = connection.getInputStream();
// BufferedInputStream bis = new BufferedInputStream(in);
// if (!file.exists()) {
// file.createNewFile();
// } else {
// file.delete();
// file.createNewFile();
// }
// FileOutputStream fos = new FileOutputStream(file);
//
// byte[] buffer = new byte[1024];
// int size = -1;
// while ((size = bis.read(buffer)) != -1) {
// fos.write(buffer, 0, size);
// }
//
// fos.flush();
// fos.close();
// bis.close();
// connection.disconnect();
// } catch (MalformedURLException e) {
// e.printStackTrace();
// } catch (IOException e) {
// e.printStackTrace();
// }
// }
//
// @Override
// public void setIntentRedelivery(boolean enabled) {
// super.setIntentRedelivery(enabled);
// Log.d(TAG, "setIntentRedelivery() called with: " + "enabled = [" + enabled + "]");
// }
//
// @Override
// public void onCreate() {
// super.onCreate();
// Log.d(TAG, "onCreate: ");
// }
//
// @Override
// public void onStart(Intent intent, int startId) {
// super.onStart(intent, startId);
// Log.d(TAG, "onStart() called with: " + "intent = [" + intent + "], startId = [" + startId + "]");
// }
//
// // onStartCommand 里调用了onstart
// @Override
// public int onStartCommand(Intent intent, int flags, int startId) {
// Log.d(TAG, "onStartCommand() called with: " + "flags = [" + flags + "], startId = [" + startId + "]");
// return super.onStartCommand(intent, flags, startId);
// }
//
// @Override
// public void onDestroy() {
// super.onDestroy();
// Log.d(TAG, "onDestroy() called with: " + "");
// }
//
// @Override
// public IBinder onBind(Intent intent) {
// Log.d(TAG, "onBind() called with: " + "intent = [" + intent + "]");
// return super.onBind(intent);
// }
// }
// Path: PracticeDemos/app/src/main/java/yifeiyuan/practice/practicedemos/service/ServiceActivity.java
import android.app.Service;
import android.content.ComponentName;
import android.content.Intent;
import android.content.ServiceConnection;
import android.os.Bundle;
import android.os.IBinder;
import android.support.design.widget.FloatingActionButton;
import android.support.design.widget.Snackbar;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;
import android.util.Log;
import android.view.View;
import android.widget.TextView;
import butterknife.ButterKnife;
import butterknife.InjectView;
import butterknife.OnClick;
import yifeiyuan.practice.practicedemos.DownloadService;
import yifeiyuan.practice.practicedemos.R;
package yifeiyuan.practice.practicedemos.service;
public class ServiceActivity extends AppCompatActivity {
public static final String TAG = "MyService";
@InjectView(R.id.start_service)
TextView mStartService;
@InjectView(R.id.stop_service)
TextView mStopService;
@InjectView(R.id.bind_service)
TextView mBindService;
@InjectView(R.id.unbind_service)
TextView mUnbindService;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_service);
ButterKnife.inject(this);
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
FloatingActionButton fab = (FloatingActionButton) findViewById(R.id.fab);
fab.setOnClickListener(view -> Snackbar.make(view, "Replace with your own action", Snackbar.LENGTH_LONG)
.setAction("Action", v -> {
Intent intent = new Intent(); | intent.putExtra(DownloadService.EXTRA_PATH, "http://download.fir.im/v2/app/install/559d229d692d791592000016?download_token=6adb9ccc081979064c9d453b1a9d7bf5"); |
AlanCheen/PracticeDemo | PracticeDemos/app/src/main/java/yifeiyuan/practice/practicedemos/materialsupport/ListFragment.java | // Path: PracticeDemos/app/src/main/java/yifeiyuan/practice/practicedemos/base/AboutMeActivity.java
// public class AboutMeActivity extends ToolbarActivity {
//
//
// // @InjectView(R.id.toolbar)
// // Toolbar mToolbar;
// // @InjectView(R.id.collapsing_toolbar)
// // CollapsingToolbarLayout mCollapsingToolbar;
// @InjectView(R.id.appbar)
// AppBarLayout mAppbar;
//
// public static Intent start(Context context) {
// Intent intent = new Intent(context, AboutMeActivity.class);
// return intent;
// }
//
// @Override
// protected void onCreate(Bundle savedInstanceState) {
// super.onCreate(savedInstanceState);
// setContentView(R.layout.fragment_info);
// }
//
// @Override
// protected void onTitleChanged(CharSequence title, int color) {
// super.onTitleChanged(title, color);
// //Notice 必须要自己设置
// mCollapsingToolbar.setTitle("程序亦非猿");
// }
//
// @Override
// public boolean onCreateOptionsMenu(Menu menu) {
// getMenuInflater().inflate(R.menu.menu_show_case, menu);
// return true;
// }
//
// @Override
// public boolean onOptionsItemSelected(MenuItem item) {
// int id = item.getItemId();
// if (id == R.id.action_settings) {
// return true;
// }
//
// return super.onOptionsItemSelected(item);
// }
// }
| import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.support.v4.widget.SwipeRefreshLayout;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import java.util.ArrayList;
import java.util.List;
import butterknife.ButterKnife;
import butterknife.InjectView;
import yifeiyuan.practice.practicedemos.R;
import yifeiyuan.practice.practicedemos.base.AboutMeActivity;
import yifeiyuan.practice.practicedemos.base.BaseFragment; | public ListAdapter(Context context,List<String> data){
mContext = context;
mDatas= data;
//android.graphics.drawable.StateListDrawable cannot be cast to android.support.v7.widget.RoundRectDrawableWithShadow
// context.getTheme().resolveAttribute(R.attr.selectableItemBackground, mTypedValue, true);
// mBackground = mTypedValue.resourceId;
}
@Override
public ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.material_list_item, parent, false);
// view.setBackgroundResource(mBackground);
view.setOnClickListener(this);
return new ViewHolder(view);
}
@Override
public void onBindViewHolder(ViewHolder holder, int position) {
}
@Override
public int getItemCount() {
return mDatas.size();
// return 20;
}
@Override
public void onClick(View v) { | // Path: PracticeDemos/app/src/main/java/yifeiyuan/practice/practicedemos/base/AboutMeActivity.java
// public class AboutMeActivity extends ToolbarActivity {
//
//
// // @InjectView(R.id.toolbar)
// // Toolbar mToolbar;
// // @InjectView(R.id.collapsing_toolbar)
// // CollapsingToolbarLayout mCollapsingToolbar;
// @InjectView(R.id.appbar)
// AppBarLayout mAppbar;
//
// public static Intent start(Context context) {
// Intent intent = new Intent(context, AboutMeActivity.class);
// return intent;
// }
//
// @Override
// protected void onCreate(Bundle savedInstanceState) {
// super.onCreate(savedInstanceState);
// setContentView(R.layout.fragment_info);
// }
//
// @Override
// protected void onTitleChanged(CharSequence title, int color) {
// super.onTitleChanged(title, color);
// //Notice 必须要自己设置
// mCollapsingToolbar.setTitle("程序亦非猿");
// }
//
// @Override
// public boolean onCreateOptionsMenu(Menu menu) {
// getMenuInflater().inflate(R.menu.menu_show_case, menu);
// return true;
// }
//
// @Override
// public boolean onOptionsItemSelected(MenuItem item) {
// int id = item.getItemId();
// if (id == R.id.action_settings) {
// return true;
// }
//
// return super.onOptionsItemSelected(item);
// }
// }
// Path: PracticeDemos/app/src/main/java/yifeiyuan/practice/practicedemos/materialsupport/ListFragment.java
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.support.v4.widget.SwipeRefreshLayout;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import java.util.ArrayList;
import java.util.List;
import butterknife.ButterKnife;
import butterknife.InjectView;
import yifeiyuan.practice.practicedemos.R;
import yifeiyuan.practice.practicedemos.base.AboutMeActivity;
import yifeiyuan.practice.practicedemos.base.BaseFragment;
public ListAdapter(Context context,List<String> data){
mContext = context;
mDatas= data;
//android.graphics.drawable.StateListDrawable cannot be cast to android.support.v7.widget.RoundRectDrawableWithShadow
// context.getTheme().resolveAttribute(R.attr.selectableItemBackground, mTypedValue, true);
// mBackground = mTypedValue.resourceId;
}
@Override
public ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.material_list_item, parent, false);
// view.setBackgroundResource(mBackground);
view.setOnClickListener(this);
return new ViewHolder(view);
}
@Override
public void onBindViewHolder(ViewHolder holder, int position) {
}
@Override
public int getItemCount() {
return mDatas.size();
// return 20;
}
@Override
public void onClick(View v) { | mContext.startActivity(new Intent(mContext, AboutMeActivity.class)); |
avarabyeu/restendpoint | src/main/java/com/github/avarabyeu/restendpoint/http/ErrorHandler.java | // Path: src/main/java/com/github/avarabyeu/restendpoint/http/exception/RestEndpointIOException.java
// public class RestEndpointIOException extends RuntimeException {
//
// private static final long serialVersionUID = -5339772980222891685L;
//
// public RestEndpointIOException(String message, Throwable e) {
// super(message, e);
// }
//
// public RestEndpointIOException(String message) {
// super(message);
// }
//
// }
| import com.github.avarabyeu.restendpoint.http.exception.RestEndpointIOException;
import com.google.common.io.ByteSource; | /*
* Copyright (C) 2014 Andrei Varabyeu
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.github.avarabyeu.restendpoint.http;
/**
* Error Handler for RestEndpoint
*
* @author Andrei Varabyeu
*/
public interface ErrorHandler {
/**
* Checks whether there is an error in response
*
* @param rs response instance
* @return TRUE if response contains error
*/
boolean hasError(Response<ByteSource> rs);
/**
* Handles response if there is an error
*
* @param rs response instance
* @throws com.github.avarabyeu.restendpoint.http.exception.RestEndpointIOException In case of error
*/ | // Path: src/main/java/com/github/avarabyeu/restendpoint/http/exception/RestEndpointIOException.java
// public class RestEndpointIOException extends RuntimeException {
//
// private static final long serialVersionUID = -5339772980222891685L;
//
// public RestEndpointIOException(String message, Throwable e) {
// super(message, e);
// }
//
// public RestEndpointIOException(String message) {
// super(message);
// }
//
// }
// Path: src/main/java/com/github/avarabyeu/restendpoint/http/ErrorHandler.java
import com.github.avarabyeu.restendpoint.http.exception.RestEndpointIOException;
import com.google.common.io.ByteSource;
/*
* Copyright (C) 2014 Andrei Varabyeu
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.github.avarabyeu.restendpoint.http;
/**
* Error Handler for RestEndpoint
*
* @author Andrei Varabyeu
*/
public interface ErrorHandler {
/**
* Checks whether there is an error in response
*
* @param rs response instance
* @return TRUE if response contains error
*/
boolean hasError(Response<ByteSource> rs);
/**
* Handles response if there is an error
*
* @param rs response instance
* @throws com.github.avarabyeu.restendpoint.http.exception.RestEndpointIOException In case of error
*/ | void handle(Response<ByteSource> rs) throws RestEndpointIOException; |
avarabyeu/restendpoint | src/main/java/com/github/avarabyeu/restendpoint/serializer/json/JacksonSerializer.java | // Path: src/main/java/com/github/avarabyeu/restendpoint/http/exception/SerializerException.java
// public class SerializerException extends RestEndpointIOException {
//
// private static final long serialVersionUID = 1L;
//
// public SerializerException(String message) {
// super(message);
// }
//
// public SerializerException(String message, Throwable e) {
// super(message, e);
// }
// }
| import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.github.avarabyeu.restendpoint.http.exception.SerializerException;
import java.io.IOException;
import java.lang.reflect.Type; | package com.github.avarabyeu.restendpoint.serializer.json;
/**
* JSON serializer using Jackson library
*
* @author Andrei Varabyeu
* @see <a href="http://wiki.fasterxml.com/JacksonHome/">Jackson Wiki</a>
*/
public class JacksonSerializer extends AbstractJsonSerializer {
private final ObjectMapper objectMapper;
public JacksonSerializer(ObjectMapper objectMapper) {
this.objectMapper = objectMapper;
}
public JacksonSerializer() {
this(new ObjectMapper());
}
@Override | // Path: src/main/java/com/github/avarabyeu/restendpoint/http/exception/SerializerException.java
// public class SerializerException extends RestEndpointIOException {
//
// private static final long serialVersionUID = 1L;
//
// public SerializerException(String message) {
// super(message);
// }
//
// public SerializerException(String message, Throwable e) {
// super(message, e);
// }
// }
// Path: src/main/java/com/github/avarabyeu/restendpoint/serializer/json/JacksonSerializer.java
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.github.avarabyeu.restendpoint.http.exception.SerializerException;
import java.io.IOException;
import java.lang.reflect.Type;
package com.github.avarabyeu.restendpoint.serializer.json;
/**
* JSON serializer using Jackson library
*
* @author Andrei Varabyeu
* @see <a href="http://wiki.fasterxml.com/JacksonHome/">Jackson Wiki</a>
*/
public class JacksonSerializer extends AbstractJsonSerializer {
private final ObjectMapper objectMapper;
public JacksonSerializer(ObjectMapper objectMapper) {
this.objectMapper = objectMapper;
}
public JacksonSerializer() {
this(new ObjectMapper());
}
@Override | public <T> byte[] serialize(T t) throws SerializerException { |
avarabyeu/restendpoint | src/main/java/com/github/avarabyeu/restendpoint/http/annotation/Request.java | // Path: src/main/java/com/github/avarabyeu/restendpoint/http/HttpMethod.java
// public enum HttpMethod {
// GET(false),
// POST(true),
// PUT(true),
// PATCH(true),
// DELETE(false);
//
// private final boolean hasBody;
//
// /**
// * @param hasBody Whether method contains body
// */
// HttpMethod(boolean hasBody) {
// this.hasBody = hasBody;
// }
//
// /**
// * @return TRUE if method contains body
// */
// boolean hasBody() {
// return hasBody;
// }
// }
| import com.github.avarabyeu.restendpoint.http.HttpMethod;
import java.lang.annotation.Documented;
import java.lang.annotation.Retention;
import java.lang.annotation.Target;
import static java.lang.annotation.ElementType.METHOD;
import static java.lang.annotation.RetentionPolicy.RUNTIME; | /*
* Copyright (C) 2014 Andrei Varabyeu
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.github.avarabyeu.restendpoint.http.annotation;
/**
* Method of REST client definition
*
* @author Andrey Vorobyov
*/
@Documented
@Target(METHOD)
@Retention(RUNTIME)
public @interface Request {
/**
* HTTP method type
*/ | // Path: src/main/java/com/github/avarabyeu/restendpoint/http/HttpMethod.java
// public enum HttpMethod {
// GET(false),
// POST(true),
// PUT(true),
// PATCH(true),
// DELETE(false);
//
// private final boolean hasBody;
//
// /**
// * @param hasBody Whether method contains body
// */
// HttpMethod(boolean hasBody) {
// this.hasBody = hasBody;
// }
//
// /**
// * @return TRUE if method contains body
// */
// boolean hasBody() {
// return hasBody;
// }
// }
// Path: src/main/java/com/github/avarabyeu/restendpoint/http/annotation/Request.java
import com.github.avarabyeu.restendpoint.http.HttpMethod;
import java.lang.annotation.Documented;
import java.lang.annotation.Retention;
import java.lang.annotation.Target;
import static java.lang.annotation.ElementType.METHOD;
import static java.lang.annotation.RetentionPolicy.RUNTIME;
/*
* Copyright (C) 2014 Andrei Varabyeu
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.github.avarabyeu.restendpoint.http.annotation;
/**
* Method of REST client definition
*
* @author Andrey Vorobyov
*/
@Documented
@Target(METHOD)
@Retention(RUNTIME)
public @interface Request {
/**
* HTTP method type
*/ | HttpMethod method(); |
avarabyeu/restendpoint | src/test/java/com/github/avarabyeu/restendpoint/http/StatusTypeTest.java | // Path: src/main/java/com/github/avarabyeu/restendpoint/http/StatusType.java
// public enum StatusType {
//
// /**
// * Informational Response
// */
// INFORMATIONAL(1),
// /**
// * Successful response
// */
// SUCCESSFUL(2),
// /**
// * Redirection response
// */
// REDIRECTION(3),
// /**
// * Client Error Response
// */
// CLIENT_ERROR(4),
// /**
// * Server Error Response
// */
// SERVER_ERROR(5);
//
// /**
// * First Symbol of HTTP response code
// */
// private final int value;
//
// StatusType(int value) {
// this.value = value;
// }
//
// public int value() {
// return this.value;
// }
//
// /**
// * Obrains {@link StatusType} from HTTP status code. If there are no status
// * defined throws {@link java.lang.IllegalArgumentException}
// *
// * @param status HTTP status code
// * @return HTTP Response Type
// */
// public static StatusType valueOf(int status) {
// int seriesCode = status / 100;
// for (StatusType series : values()) {
// if (series.value == seriesCode) {
// return series;
// }
// }
// throw new IllegalArgumentException("No matching constant for [" + status + "]");
// }
//
// }
| import com.smarttested.qa.smartassert.SmartAssert;
import com.smarttested.qa.smartassert.junit.SoftAssertVerifier;
import org.junit.Rule;
import org.junit.Test;
import static com.github.avarabyeu.restendpoint.http.StatusType.*;
import static org.hamcrest.CoreMatchers.is; | package com.github.avarabyeu.restendpoint.http;
/**
* Tests for {@link com.github.avarabyeu.restendpoint.http.StatusType}
*
* @author Andrei Varabyeu
*/
public class StatusTypeTest {
@Rule
public SoftAssertVerifier verifier = SoftAssertVerifier.instance();
@Test
public void testInformational() { | // Path: src/main/java/com/github/avarabyeu/restendpoint/http/StatusType.java
// public enum StatusType {
//
// /**
// * Informational Response
// */
// INFORMATIONAL(1),
// /**
// * Successful response
// */
// SUCCESSFUL(2),
// /**
// * Redirection response
// */
// REDIRECTION(3),
// /**
// * Client Error Response
// */
// CLIENT_ERROR(4),
// /**
// * Server Error Response
// */
// SERVER_ERROR(5);
//
// /**
// * First Symbol of HTTP response code
// */
// private final int value;
//
// StatusType(int value) {
// this.value = value;
// }
//
// public int value() {
// return this.value;
// }
//
// /**
// * Obrains {@link StatusType} from HTTP status code. If there are no status
// * defined throws {@link java.lang.IllegalArgumentException}
// *
// * @param status HTTP status code
// * @return HTTP Response Type
// */
// public static StatusType valueOf(int status) {
// int seriesCode = status / 100;
// for (StatusType series : values()) {
// if (series.value == seriesCode) {
// return series;
// }
// }
// throw new IllegalArgumentException("No matching constant for [" + status + "]");
// }
//
// }
// Path: src/test/java/com/github/avarabyeu/restendpoint/http/StatusTypeTest.java
import com.smarttested.qa.smartassert.SmartAssert;
import com.smarttested.qa.smartassert.junit.SoftAssertVerifier;
import org.junit.Rule;
import org.junit.Test;
import static com.github.avarabyeu.restendpoint.http.StatusType.*;
import static org.hamcrest.CoreMatchers.is;
package com.github.avarabyeu.restendpoint.http;
/**
* Tests for {@link com.github.avarabyeu.restendpoint.http.StatusType}
*
* @author Andrei Varabyeu
*/
public class StatusTypeTest {
@Rule
public SoftAssertVerifier verifier = SoftAssertVerifier.instance();
@Test
public void testInformational() { | SmartAssert.assertSoft(StatusType.valueOf(100), is(INFORMATIONAL), "'Continue' status is not parsed"); |
avarabyeu/restendpoint | src/main/java/com/github/avarabyeu/restendpoint/serializer/ByteArraySerializer.java | // Path: src/main/java/com/github/avarabyeu/restendpoint/http/exception/SerializerException.java
// public class SerializerException extends RestEndpointIOException {
//
// private static final long serialVersionUID = 1L;
//
// public SerializerException(String message) {
// super(message);
// }
//
// public SerializerException(String message, Throwable e) {
// super(message, e);
// }
// }
| import com.github.avarabyeu.restendpoint.http.exception.SerializerException;
import com.google.common.net.MediaType;
import com.google.common.reflect.TypeToken;
import java.lang.reflect.Type; | /*
* Copyright (C) 2014 Andrei Varabyeu
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.github.avarabyeu.restendpoint.serializer;
/**
* Byte array message converter. Actually, just placeholder to be able to work
* with byte arrays through {@link Serializer} interface
*
* @author Andrei Varabyeu
*/
public class ByteArraySerializer implements Serializer {
/*
* (non-Javadoc)
*
* @see
* Serializer#serialize(java.lang.Object)
*/
@Override | // Path: src/main/java/com/github/avarabyeu/restendpoint/http/exception/SerializerException.java
// public class SerializerException extends RestEndpointIOException {
//
// private static final long serialVersionUID = 1L;
//
// public SerializerException(String message) {
// super(message);
// }
//
// public SerializerException(String message, Throwable e) {
// super(message, e);
// }
// }
// Path: src/main/java/com/github/avarabyeu/restendpoint/serializer/ByteArraySerializer.java
import com.github.avarabyeu.restendpoint.http.exception.SerializerException;
import com.google.common.net.MediaType;
import com.google.common.reflect.TypeToken;
import java.lang.reflect.Type;
/*
* Copyright (C) 2014 Andrei Varabyeu
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.github.avarabyeu.restendpoint.serializer;
/**
* Byte array message converter. Actually, just placeholder to be able to work
* with byte arrays through {@link Serializer} interface
*
* @author Andrei Varabyeu
*/
public class ByteArraySerializer implements Serializer {
/*
* (non-Javadoc)
*
* @see
* Serializer#serialize(java.lang.Object)
*/
@Override | public final <T> byte[] serialize(T t) throws SerializerException { |
avarabyeu/restendpoint | src/main/java/com/github/avarabyeu/restendpoint/serializer/StringSerializer.java | // Path: src/main/java/com/github/avarabyeu/restendpoint/http/exception/SerializerException.java
// public class SerializerException extends RestEndpointIOException {
//
// private static final long serialVersionUID = 1L;
//
// public SerializerException(String message) {
// super(message);
// }
//
// public SerializerException(String message, Throwable e) {
// super(message, e);
// }
// }
| import com.github.avarabyeu.restendpoint.http.exception.SerializerException;
import com.google.common.base.Charsets;
import com.google.common.net.MediaType;
import com.google.common.reflect.TypeToken;
import javax.annotation.Nonnull;
import java.lang.reflect.Type; | /*
* Copyright (C) 2014 Andrei Varabyeu
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.github.avarabyeu.restendpoint.serializer;
/**
* Plain String serializer
*
* @author avarabyeu
* @deprecated In favor of {@link com.github.avarabyeu.restendpoint.serializer.TextSerializer}
*/
@Deprecated
public class StringSerializer implements Serializer {
/*
* (non-Javadoc)
*
* @see
* Serializer#serialize(java.lang.Object)
*/
@Override | // Path: src/main/java/com/github/avarabyeu/restendpoint/http/exception/SerializerException.java
// public class SerializerException extends RestEndpointIOException {
//
// private static final long serialVersionUID = 1L;
//
// public SerializerException(String message) {
// super(message);
// }
//
// public SerializerException(String message, Throwable e) {
// super(message, e);
// }
// }
// Path: src/main/java/com/github/avarabyeu/restendpoint/serializer/StringSerializer.java
import com.github.avarabyeu.restendpoint.http.exception.SerializerException;
import com.google.common.base.Charsets;
import com.google.common.net.MediaType;
import com.google.common.reflect.TypeToken;
import javax.annotation.Nonnull;
import java.lang.reflect.Type;
/*
* Copyright (C) 2014 Andrei Varabyeu
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.github.avarabyeu.restendpoint.serializer;
/**
* Plain String serializer
*
* @author avarabyeu
* @deprecated In favor of {@link com.github.avarabyeu.restendpoint.serializer.TextSerializer}
*/
@Deprecated
public class StringSerializer implements Serializer {
/*
* (non-Javadoc)
*
* @see
* Serializer#serialize(java.lang.Object)
*/
@Override | public <T> byte[] serialize(T t) throws SerializerException { |
avarabyeu/restendpoint | src/test/java/com/github/avarabyeu/restendpoint/serializer/json/JacksonSerializerTest.java | // Path: src/main/java/com/github/avarabyeu/restendpoint/http/exception/SerializerException.java
// public class SerializerException extends RestEndpointIOException {
//
// private static final long serialVersionUID = 1L;
//
// public SerializerException(String message) {
// super(message);
// }
//
// public SerializerException(String message, Throwable e) {
// super(message, e);
// }
// }
//
// Path: src/test/java/com/github/avarabyeu/restendpoint/serializer/DemoBean.java
// @XmlRootElement
// public class DemoBean {
//
// private String someField;
//
// public DemoBean() {
// }
//
// public DemoBean(String someField) {
// this.someField = someField;
// }
//
// public String getSomeField() {
// return someField;
// }
//
// public void setSomeField(String someField) {
// this.someField = someField;
// }
//
// @Override
// public boolean equals(Object o) {
// if (this == o)
// return true;
// if (o == null || getClass() != o.getClass())
// return false;
// DemoBean demoBean = (DemoBean) o;
// return Objects.equals(someField, demoBean.someField);
// }
//
// @Override
// public int hashCode() {
// return Objects.hash(someField);
// }
// }
| import com.github.avarabyeu.restendpoint.http.exception.SerializerException;
import com.github.avarabyeu.restendpoint.serializer.DemoBean;
import com.google.common.net.MediaType;
import com.smarttested.qa.smartassert.SmartAssert;
import org.hamcrest.CoreMatchers;
import org.junit.Test; | package com.github.avarabyeu.restendpoint.serializer.json;
/**
* @author Andrei Varabyeu
*/
//TODO refactor to avoid duplicating with GsonSerializerTest
public class JacksonSerializerTest {
private static final String TEST_STRING = "{\"someField\":\"someValue\"}"; | // Path: src/main/java/com/github/avarabyeu/restendpoint/http/exception/SerializerException.java
// public class SerializerException extends RestEndpointIOException {
//
// private static final long serialVersionUID = 1L;
//
// public SerializerException(String message) {
// super(message);
// }
//
// public SerializerException(String message, Throwable e) {
// super(message, e);
// }
// }
//
// Path: src/test/java/com/github/avarabyeu/restendpoint/serializer/DemoBean.java
// @XmlRootElement
// public class DemoBean {
//
// private String someField;
//
// public DemoBean() {
// }
//
// public DemoBean(String someField) {
// this.someField = someField;
// }
//
// public String getSomeField() {
// return someField;
// }
//
// public void setSomeField(String someField) {
// this.someField = someField;
// }
//
// @Override
// public boolean equals(Object o) {
// if (this == o)
// return true;
// if (o == null || getClass() != o.getClass())
// return false;
// DemoBean demoBean = (DemoBean) o;
// return Objects.equals(someField, demoBean.someField);
// }
//
// @Override
// public int hashCode() {
// return Objects.hash(someField);
// }
// }
// Path: src/test/java/com/github/avarabyeu/restendpoint/serializer/json/JacksonSerializerTest.java
import com.github.avarabyeu.restendpoint.http.exception.SerializerException;
import com.github.avarabyeu.restendpoint.serializer.DemoBean;
import com.google.common.net.MediaType;
import com.smarttested.qa.smartassert.SmartAssert;
import org.hamcrest.CoreMatchers;
import org.junit.Test;
package com.github.avarabyeu.restendpoint.serializer.json;
/**
* @author Andrei Varabyeu
*/
//TODO refactor to avoid duplicating with GsonSerializerTest
public class JacksonSerializerTest {
private static final String TEST_STRING = "{\"someField\":\"someValue\"}"; | private static final DemoBean TEST_BEAN = new DemoBean("someValue"); |
avarabyeu/restendpoint | src/test/java/com/github/avarabyeu/restendpoint/serializer/json/JacksonSerializerTest.java | // Path: src/main/java/com/github/avarabyeu/restendpoint/http/exception/SerializerException.java
// public class SerializerException extends RestEndpointIOException {
//
// private static final long serialVersionUID = 1L;
//
// public SerializerException(String message) {
// super(message);
// }
//
// public SerializerException(String message, Throwable e) {
// super(message, e);
// }
// }
//
// Path: src/test/java/com/github/avarabyeu/restendpoint/serializer/DemoBean.java
// @XmlRootElement
// public class DemoBean {
//
// private String someField;
//
// public DemoBean() {
// }
//
// public DemoBean(String someField) {
// this.someField = someField;
// }
//
// public String getSomeField() {
// return someField;
// }
//
// public void setSomeField(String someField) {
// this.someField = someField;
// }
//
// @Override
// public boolean equals(Object o) {
// if (this == o)
// return true;
// if (o == null || getClass() != o.getClass())
// return false;
// DemoBean demoBean = (DemoBean) o;
// return Objects.equals(someField, demoBean.someField);
// }
//
// @Override
// public int hashCode() {
// return Objects.hash(someField);
// }
// }
| import com.github.avarabyeu.restendpoint.http.exception.SerializerException;
import com.github.avarabyeu.restendpoint.serializer.DemoBean;
import com.google.common.net.MediaType;
import com.smarttested.qa.smartassert.SmartAssert;
import org.hamcrest.CoreMatchers;
import org.junit.Test; | package com.github.avarabyeu.restendpoint.serializer.json;
/**
* @author Andrei Varabyeu
*/
//TODO refactor to avoid duplicating with GsonSerializerTest
public class JacksonSerializerTest {
private static final String TEST_STRING = "{\"someField\":\"someValue\"}";
private static final DemoBean TEST_BEAN = new DemoBean("someValue");
private final JacksonSerializer serializer = new JacksonSerializer();
@Test | // Path: src/main/java/com/github/avarabyeu/restendpoint/http/exception/SerializerException.java
// public class SerializerException extends RestEndpointIOException {
//
// private static final long serialVersionUID = 1L;
//
// public SerializerException(String message) {
// super(message);
// }
//
// public SerializerException(String message, Throwable e) {
// super(message, e);
// }
// }
//
// Path: src/test/java/com/github/avarabyeu/restendpoint/serializer/DemoBean.java
// @XmlRootElement
// public class DemoBean {
//
// private String someField;
//
// public DemoBean() {
// }
//
// public DemoBean(String someField) {
// this.someField = someField;
// }
//
// public String getSomeField() {
// return someField;
// }
//
// public void setSomeField(String someField) {
// this.someField = someField;
// }
//
// @Override
// public boolean equals(Object o) {
// if (this == o)
// return true;
// if (o == null || getClass() != o.getClass())
// return false;
// DemoBean demoBean = (DemoBean) o;
// return Objects.equals(someField, demoBean.someField);
// }
//
// @Override
// public int hashCode() {
// return Objects.hash(someField);
// }
// }
// Path: src/test/java/com/github/avarabyeu/restendpoint/serializer/json/JacksonSerializerTest.java
import com.github.avarabyeu.restendpoint.http.exception.SerializerException;
import com.github.avarabyeu.restendpoint.serializer.DemoBean;
import com.google.common.net.MediaType;
import com.smarttested.qa.smartassert.SmartAssert;
import org.hamcrest.CoreMatchers;
import org.junit.Test;
package com.github.avarabyeu.restendpoint.serializer.json;
/**
* @author Andrei Varabyeu
*/
//TODO refactor to avoid duplicating with GsonSerializerTest
public class JacksonSerializerTest {
private static final String TEST_STRING = "{\"someField\":\"someValue\"}";
private static final DemoBean TEST_BEAN = new DemoBean("someValue");
private final JacksonSerializer serializer = new JacksonSerializer();
@Test | public void testSerialize() throws SerializerException { |
avarabyeu/restendpoint | src/main/java/com/github/avarabyeu/restendpoint/serializer/TextSerializer.java | // Path: src/main/java/com/github/avarabyeu/restendpoint/http/exception/SerializerException.java
// public class SerializerException extends RestEndpointIOException {
//
// private static final long serialVersionUID = 1L;
//
// public SerializerException(String message) {
// super(message);
// }
//
// public SerializerException(String message, Throwable e) {
// super(message, e);
// }
// }
| import com.github.avarabyeu.restendpoint.http.exception.SerializerException;
import com.google.common.base.Charsets;
import com.google.common.net.MediaType;
import com.google.common.reflect.TypeToken;
import org.apache.commons.beanutils.ConversionException;
import org.apache.commons.beanutils.ConvertUtilsBean;
import org.apache.commons.beanutils.Converter;
import java.lang.reflect.Type;
import java.util.Map; | package com.github.avarabyeu.restendpoint.serializer;
/**
* Text Serializer based on Apache Conversion Utils
*
* @author Andrei Varabyeu
* @see <a href="http://commons.apache.org/proper/commons-beanutils/">Apache BeanUtils</a>
*/
public class TextSerializer implements Serializer {
private final ConvertUtilsBean converter;
/**
* Creates TextSerializer with default configuration like throwing exceptions, using NULL as default value, etc
*/
public TextSerializer() {
this(true, true, 0);
}
/**
* Creates TextSerializer with custom configuration like throwing exceptions, using NULL as default value, etc
*
* @param throwException <code>true</code> if the converters should
* throw an exception when a conversion error occurs, otherwise
* <code>false</code> if a default value should be used.
* @param defaultNull <code>true</code>if the <i>standard</i> converters
* (see {@link ConvertUtilsBean#registerStandard(boolean, boolean)})
* should use a default value of <code>null</code>, otherwise <code>false</code>.
* N.B. This values is ignored if <code>throwException</code> is <code>true</code>
* @param defaultArraySize The size of the default array value for array converters
* (N.B. This values is ignored if <code>throwException</code> is <code>true</code>).
* Specifying a value less than zero causes a <code>null</code> value to be used for
* the default.
* @see org.apache.commons.beanutils.ConvertUtilsBean#register(boolean, boolean, int)
*/
public TextSerializer(boolean throwException, boolean defaultNull, int defaultArraySize) {
this.converter = new ConvertUtilsBean();
/* throw exception, default value is null, default array size is 0 */
this.converter.register(throwException, defaultNull, defaultArraySize);
/* DO NOT USE as byte array serializer since it produce wrong content type */
this.converter.deregister(byte[].class);
this.converter.deregister(Byte[].class);
}
/**
* Creates default TextSerializer and registers additional type converters
*
* @param typeConverters Map of type converters for serializer
*/
public TextSerializer(Map<Converter, Class<?>> typeConverters) {
this();
for (Map.Entry<Converter, Class<?>> typeConverter : typeConverters.entrySet()) {
this.converter.register(typeConverter.getKey(), typeConverter.getValue());
}
}
@Override | // Path: src/main/java/com/github/avarabyeu/restendpoint/http/exception/SerializerException.java
// public class SerializerException extends RestEndpointIOException {
//
// private static final long serialVersionUID = 1L;
//
// public SerializerException(String message) {
// super(message);
// }
//
// public SerializerException(String message, Throwable e) {
// super(message, e);
// }
// }
// Path: src/main/java/com/github/avarabyeu/restendpoint/serializer/TextSerializer.java
import com.github.avarabyeu.restendpoint.http.exception.SerializerException;
import com.google.common.base.Charsets;
import com.google.common.net.MediaType;
import com.google.common.reflect.TypeToken;
import org.apache.commons.beanutils.ConversionException;
import org.apache.commons.beanutils.ConvertUtilsBean;
import org.apache.commons.beanutils.Converter;
import java.lang.reflect.Type;
import java.util.Map;
package com.github.avarabyeu.restendpoint.serializer;
/**
* Text Serializer based on Apache Conversion Utils
*
* @author Andrei Varabyeu
* @see <a href="http://commons.apache.org/proper/commons-beanutils/">Apache BeanUtils</a>
*/
public class TextSerializer implements Serializer {
private final ConvertUtilsBean converter;
/**
* Creates TextSerializer with default configuration like throwing exceptions, using NULL as default value, etc
*/
public TextSerializer() {
this(true, true, 0);
}
/**
* Creates TextSerializer with custom configuration like throwing exceptions, using NULL as default value, etc
*
* @param throwException <code>true</code> if the converters should
* throw an exception when a conversion error occurs, otherwise
* <code>false</code> if a default value should be used.
* @param defaultNull <code>true</code>if the <i>standard</i> converters
* (see {@link ConvertUtilsBean#registerStandard(boolean, boolean)})
* should use a default value of <code>null</code>, otherwise <code>false</code>.
* N.B. This values is ignored if <code>throwException</code> is <code>true</code>
* @param defaultArraySize The size of the default array value for array converters
* (N.B. This values is ignored if <code>throwException</code> is <code>true</code>).
* Specifying a value less than zero causes a <code>null</code> value to be used for
* the default.
* @see org.apache.commons.beanutils.ConvertUtilsBean#register(boolean, boolean, int)
*/
public TextSerializer(boolean throwException, boolean defaultNull, int defaultArraySize) {
this.converter = new ConvertUtilsBean();
/* throw exception, default value is null, default array size is 0 */
this.converter.register(throwException, defaultNull, defaultArraySize);
/* DO NOT USE as byte array serializer since it produce wrong content type */
this.converter.deregister(byte[].class);
this.converter.deregister(Byte[].class);
}
/**
* Creates default TextSerializer and registers additional type converters
*
* @param typeConverters Map of type converters for serializer
*/
public TextSerializer(Map<Converter, Class<?>> typeConverters) {
this();
for (Map.Entry<Converter, Class<?>> typeConverter : typeConverters.entrySet()) {
this.converter.register(typeConverter.getKey(), typeConverter.getValue());
}
}
@Override | public <T> byte[] serialize(T t) throws SerializerException { |
avarabyeu/restendpoint | src/test/java/com/github/avarabyeu/restendpoint/serializer/json/GsonSerializerTest.java | // Path: src/main/java/com/github/avarabyeu/restendpoint/http/exception/SerializerException.java
// public class SerializerException extends RestEndpointIOException {
//
// private static final long serialVersionUID = 1L;
//
// public SerializerException(String message) {
// super(message);
// }
//
// public SerializerException(String message, Throwable e) {
// super(message, e);
// }
// }
//
// Path: src/test/java/com/github/avarabyeu/restendpoint/serializer/DemoBean.java
// @XmlRootElement
// public class DemoBean {
//
// private String someField;
//
// public DemoBean() {
// }
//
// public DemoBean(String someField) {
// this.someField = someField;
// }
//
// public String getSomeField() {
// return someField;
// }
//
// public void setSomeField(String someField) {
// this.someField = someField;
// }
//
// @Override
// public boolean equals(Object o) {
// if (this == o)
// return true;
// if (o == null || getClass() != o.getClass())
// return false;
// DemoBean demoBean = (DemoBean) o;
// return Objects.equals(someField, demoBean.someField);
// }
//
// @Override
// public int hashCode() {
// return Objects.hash(someField);
// }
// }
| import com.github.avarabyeu.restendpoint.http.exception.SerializerException;
import com.github.avarabyeu.restendpoint.serializer.DemoBean;
import com.google.common.net.MediaType;
import com.smarttested.qa.smartassert.SmartAssert;
import org.hamcrest.CoreMatchers;
import org.junit.Test; | /*
* Copyright (C) 2014 Andrei Varabyeu
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.github.avarabyeu.restendpoint.serializer.json;
/**
* @author Andrey Vorobyov
*/
public class GsonSerializerTest {
private static final String TEST_STRING = "{\"someField\":\"someValue\"}"; | // Path: src/main/java/com/github/avarabyeu/restendpoint/http/exception/SerializerException.java
// public class SerializerException extends RestEndpointIOException {
//
// private static final long serialVersionUID = 1L;
//
// public SerializerException(String message) {
// super(message);
// }
//
// public SerializerException(String message, Throwable e) {
// super(message, e);
// }
// }
//
// Path: src/test/java/com/github/avarabyeu/restendpoint/serializer/DemoBean.java
// @XmlRootElement
// public class DemoBean {
//
// private String someField;
//
// public DemoBean() {
// }
//
// public DemoBean(String someField) {
// this.someField = someField;
// }
//
// public String getSomeField() {
// return someField;
// }
//
// public void setSomeField(String someField) {
// this.someField = someField;
// }
//
// @Override
// public boolean equals(Object o) {
// if (this == o)
// return true;
// if (o == null || getClass() != o.getClass())
// return false;
// DemoBean demoBean = (DemoBean) o;
// return Objects.equals(someField, demoBean.someField);
// }
//
// @Override
// public int hashCode() {
// return Objects.hash(someField);
// }
// }
// Path: src/test/java/com/github/avarabyeu/restendpoint/serializer/json/GsonSerializerTest.java
import com.github.avarabyeu.restendpoint.http.exception.SerializerException;
import com.github.avarabyeu.restendpoint.serializer.DemoBean;
import com.google.common.net.MediaType;
import com.smarttested.qa.smartassert.SmartAssert;
import org.hamcrest.CoreMatchers;
import org.junit.Test;
/*
* Copyright (C) 2014 Andrei Varabyeu
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.github.avarabyeu.restendpoint.serializer.json;
/**
* @author Andrey Vorobyov
*/
public class GsonSerializerTest {
private static final String TEST_STRING = "{\"someField\":\"someValue\"}"; | private static final DemoBean TEST_BEAN = new DemoBean("someValue"); |
avarabyeu/restendpoint | src/test/java/com/github/avarabyeu/restendpoint/serializer/json/GsonSerializerTest.java | // Path: src/main/java/com/github/avarabyeu/restendpoint/http/exception/SerializerException.java
// public class SerializerException extends RestEndpointIOException {
//
// private static final long serialVersionUID = 1L;
//
// public SerializerException(String message) {
// super(message);
// }
//
// public SerializerException(String message, Throwable e) {
// super(message, e);
// }
// }
//
// Path: src/test/java/com/github/avarabyeu/restendpoint/serializer/DemoBean.java
// @XmlRootElement
// public class DemoBean {
//
// private String someField;
//
// public DemoBean() {
// }
//
// public DemoBean(String someField) {
// this.someField = someField;
// }
//
// public String getSomeField() {
// return someField;
// }
//
// public void setSomeField(String someField) {
// this.someField = someField;
// }
//
// @Override
// public boolean equals(Object o) {
// if (this == o)
// return true;
// if (o == null || getClass() != o.getClass())
// return false;
// DemoBean demoBean = (DemoBean) o;
// return Objects.equals(someField, demoBean.someField);
// }
//
// @Override
// public int hashCode() {
// return Objects.hash(someField);
// }
// }
| import com.github.avarabyeu.restendpoint.http.exception.SerializerException;
import com.github.avarabyeu.restendpoint.serializer.DemoBean;
import com.google.common.net.MediaType;
import com.smarttested.qa.smartassert.SmartAssert;
import org.hamcrest.CoreMatchers;
import org.junit.Test; | /*
* Copyright (C) 2014 Andrei Varabyeu
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.github.avarabyeu.restendpoint.serializer.json;
/**
* @author Andrey Vorobyov
*/
public class GsonSerializerTest {
private static final String TEST_STRING = "{\"someField\":\"someValue\"}";
private static final DemoBean TEST_BEAN = new DemoBean("someValue");
private static final GsonSerializer serializer = new GsonSerializer();
@Test | // Path: src/main/java/com/github/avarabyeu/restendpoint/http/exception/SerializerException.java
// public class SerializerException extends RestEndpointIOException {
//
// private static final long serialVersionUID = 1L;
//
// public SerializerException(String message) {
// super(message);
// }
//
// public SerializerException(String message, Throwable e) {
// super(message, e);
// }
// }
//
// Path: src/test/java/com/github/avarabyeu/restendpoint/serializer/DemoBean.java
// @XmlRootElement
// public class DemoBean {
//
// private String someField;
//
// public DemoBean() {
// }
//
// public DemoBean(String someField) {
// this.someField = someField;
// }
//
// public String getSomeField() {
// return someField;
// }
//
// public void setSomeField(String someField) {
// this.someField = someField;
// }
//
// @Override
// public boolean equals(Object o) {
// if (this == o)
// return true;
// if (o == null || getClass() != o.getClass())
// return false;
// DemoBean demoBean = (DemoBean) o;
// return Objects.equals(someField, demoBean.someField);
// }
//
// @Override
// public int hashCode() {
// return Objects.hash(someField);
// }
// }
// Path: src/test/java/com/github/avarabyeu/restendpoint/serializer/json/GsonSerializerTest.java
import com.github.avarabyeu.restendpoint.http.exception.SerializerException;
import com.github.avarabyeu.restendpoint.serializer.DemoBean;
import com.google.common.net.MediaType;
import com.smarttested.qa.smartassert.SmartAssert;
import org.hamcrest.CoreMatchers;
import org.junit.Test;
/*
* Copyright (C) 2014 Andrei Varabyeu
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.github.avarabyeu.restendpoint.serializer.json;
/**
* @author Andrey Vorobyov
*/
public class GsonSerializerTest {
private static final String TEST_STRING = "{\"someField\":\"someValue\"}";
private static final DemoBean TEST_BEAN = new DemoBean("someValue");
private static final GsonSerializer serializer = new GsonSerializer();
@Test | public void testSerialize() throws SerializerException { |
avarabyeu/restendpoint | src/test/java/com/github/avarabyeu/restendpoint/http/DefaultErrorHandlerTest.java | // Path: src/main/java/com/github/avarabyeu/restendpoint/http/exception/RestEndpointException.java
// public class RestEndpointException extends RuntimeException {
//
// private static final long serialVersionUID = 728718628763519460L;
//
// /**
// * Request URI
// */
// private final URI requestUri;
//
// /**
// * Request Method
// */
// private final HttpMethod requestMethod;
//
// /**
// * HTTP Status Code
// */
// private final int statusCode;
//
// /**
// * HTTP Status Message
// */
// private final String statusMessage;
//
// /**
// * HTTP Response Body
// */
// private final ByteSource content;
//
// public RestEndpointException(URI requestUri, HttpMethod requestMethod, int statusCode, String statusMessage,
// ByteSource content) {
// this.requestUri = requestUri;
// this.requestMethod = requestMethod;
// this.statusCode = statusCode;
// this.statusMessage = statusMessage;
// this.content = content;
// }
//
// public URI getRequestUri() {
// return requestUri;
// }
//
// public HttpMethod getRequestMethod() {
// return requestMethod;
// }
//
// public int getStatusCode() {
// return statusCode;
// }
//
// public String getStatusMessage() {
// return statusMessage;
// }
//
// public ByteSource getContent() {
// return content;
// }
//
// /*
// * (non-Javadoc)
// *
// * @see java.lang.Throwable#getMessage()
// */
// @Override
// public String getMessage() {
// return new StringBuilder()
// .append("Request [").append(requestMethod.toString()).append("] ")
// .append("to URL: ").append(requestUri).append(" has failed with ")
// .append("Status code: ")
// .append(statusCode).append('\n')
// .append("Status message: ")
// .append(statusMessage).append('\n')
// .append("Content: '").append(content).append('\'')
// .toString();
// }
//
// }
//
// Path: src/main/java/com/github/avarabyeu/restendpoint/http/exception/RestEndpointIOException.java
// public class RestEndpointIOException extends RuntimeException {
//
// private static final long serialVersionUID = -5339772980222891685L;
//
// public RestEndpointIOException(String message, Throwable e) {
// super(message, e);
// }
//
// public RestEndpointIOException(String message) {
// super(message);
// }
//
// }
| import com.github.avarabyeu.restendpoint.http.exception.RestEndpointException;
import com.github.avarabyeu.restendpoint.http.exception.RestEndpointIOException;
import com.google.common.base.Charsets;
import com.google.common.collect.ImmutableMultimap;
import com.google.common.io.ByteSource;
import com.google.inject.Key;
import org.apache.http.client.methods.HttpUriRequest;
import org.junit.Assert;
import org.junit.Test;
import org.mockito.Mockito;
import java.net.URI;
import java.net.URISyntaxException; | @Test
public void errorHandlerCheckClientError() {
Response<ByteSource> response = getHttpResponse(404, "Not Found");
Assert.assertTrue("Client Error is not handled", handler.hasError(response));
}
@Test
public void errorHandlerCheckServerError() {
Response<ByteSource> response = getHttpResponse(500, "Internal Server Error");
Assert.assertTrue("Server Error is not handled", handler.hasError(response));
}
@Test
public void errorHandlerCheckInformationalResponse() {
Response<ByteSource> response = getHttpResponse(100, "Continue");
Assert.assertFalse("Infromation response is handled", handler.hasError(response));
}
@Test
public void errorHandlerCheckSuccessResponse() {
Response<ByteSource> response = getHttpResponse(200, "Success");
Assert.assertFalse("Success response is handled", handler.hasError(response));
}
@Test
public void errorHandlerCheckRedirectionResponse() {
Response<ByteSource> response = getHttpResponse(302, "Found");
Assert.assertFalse("Redirection response is handled", handler.hasError(response));
}
| // Path: src/main/java/com/github/avarabyeu/restendpoint/http/exception/RestEndpointException.java
// public class RestEndpointException extends RuntimeException {
//
// private static final long serialVersionUID = 728718628763519460L;
//
// /**
// * Request URI
// */
// private final URI requestUri;
//
// /**
// * Request Method
// */
// private final HttpMethod requestMethod;
//
// /**
// * HTTP Status Code
// */
// private final int statusCode;
//
// /**
// * HTTP Status Message
// */
// private final String statusMessage;
//
// /**
// * HTTP Response Body
// */
// private final ByteSource content;
//
// public RestEndpointException(URI requestUri, HttpMethod requestMethod, int statusCode, String statusMessage,
// ByteSource content) {
// this.requestUri = requestUri;
// this.requestMethod = requestMethod;
// this.statusCode = statusCode;
// this.statusMessage = statusMessage;
// this.content = content;
// }
//
// public URI getRequestUri() {
// return requestUri;
// }
//
// public HttpMethod getRequestMethod() {
// return requestMethod;
// }
//
// public int getStatusCode() {
// return statusCode;
// }
//
// public String getStatusMessage() {
// return statusMessage;
// }
//
// public ByteSource getContent() {
// return content;
// }
//
// /*
// * (non-Javadoc)
// *
// * @see java.lang.Throwable#getMessage()
// */
// @Override
// public String getMessage() {
// return new StringBuilder()
// .append("Request [").append(requestMethod.toString()).append("] ")
// .append("to URL: ").append(requestUri).append(" has failed with ")
// .append("Status code: ")
// .append(statusCode).append('\n')
// .append("Status message: ")
// .append(statusMessage).append('\n')
// .append("Content: '").append(content).append('\'')
// .toString();
// }
//
// }
//
// Path: src/main/java/com/github/avarabyeu/restendpoint/http/exception/RestEndpointIOException.java
// public class RestEndpointIOException extends RuntimeException {
//
// private static final long serialVersionUID = -5339772980222891685L;
//
// public RestEndpointIOException(String message, Throwable e) {
// super(message, e);
// }
//
// public RestEndpointIOException(String message) {
// super(message);
// }
//
// }
// Path: src/test/java/com/github/avarabyeu/restendpoint/http/DefaultErrorHandlerTest.java
import com.github.avarabyeu.restendpoint.http.exception.RestEndpointException;
import com.github.avarabyeu.restendpoint.http.exception.RestEndpointIOException;
import com.google.common.base.Charsets;
import com.google.common.collect.ImmutableMultimap;
import com.google.common.io.ByteSource;
import com.google.inject.Key;
import org.apache.http.client.methods.HttpUriRequest;
import org.junit.Assert;
import org.junit.Test;
import org.mockito.Mockito;
import java.net.URI;
import java.net.URISyntaxException;
@Test
public void errorHandlerCheckClientError() {
Response<ByteSource> response = getHttpResponse(404, "Not Found");
Assert.assertTrue("Client Error is not handled", handler.hasError(response));
}
@Test
public void errorHandlerCheckServerError() {
Response<ByteSource> response = getHttpResponse(500, "Internal Server Error");
Assert.assertTrue("Server Error is not handled", handler.hasError(response));
}
@Test
public void errorHandlerCheckInformationalResponse() {
Response<ByteSource> response = getHttpResponse(100, "Continue");
Assert.assertFalse("Infromation response is handled", handler.hasError(response));
}
@Test
public void errorHandlerCheckSuccessResponse() {
Response<ByteSource> response = getHttpResponse(200, "Success");
Assert.assertFalse("Success response is handled", handler.hasError(response));
}
@Test
public void errorHandlerCheckRedirectionResponse() {
Response<ByteSource> response = getHttpResponse(302, "Found");
Assert.assertFalse("Redirection response is handled", handler.hasError(response));
}
| @Test(expected = RestEndpointException.class) |
avarabyeu/restendpoint | src/test/java/com/github/avarabyeu/restendpoint/http/DefaultErrorHandlerTest.java | // Path: src/main/java/com/github/avarabyeu/restendpoint/http/exception/RestEndpointException.java
// public class RestEndpointException extends RuntimeException {
//
// private static final long serialVersionUID = 728718628763519460L;
//
// /**
// * Request URI
// */
// private final URI requestUri;
//
// /**
// * Request Method
// */
// private final HttpMethod requestMethod;
//
// /**
// * HTTP Status Code
// */
// private final int statusCode;
//
// /**
// * HTTP Status Message
// */
// private final String statusMessage;
//
// /**
// * HTTP Response Body
// */
// private final ByteSource content;
//
// public RestEndpointException(URI requestUri, HttpMethod requestMethod, int statusCode, String statusMessage,
// ByteSource content) {
// this.requestUri = requestUri;
// this.requestMethod = requestMethod;
// this.statusCode = statusCode;
// this.statusMessage = statusMessage;
// this.content = content;
// }
//
// public URI getRequestUri() {
// return requestUri;
// }
//
// public HttpMethod getRequestMethod() {
// return requestMethod;
// }
//
// public int getStatusCode() {
// return statusCode;
// }
//
// public String getStatusMessage() {
// return statusMessage;
// }
//
// public ByteSource getContent() {
// return content;
// }
//
// /*
// * (non-Javadoc)
// *
// * @see java.lang.Throwable#getMessage()
// */
// @Override
// public String getMessage() {
// return new StringBuilder()
// .append("Request [").append(requestMethod.toString()).append("] ")
// .append("to URL: ").append(requestUri).append(" has failed with ")
// .append("Status code: ")
// .append(statusCode).append('\n')
// .append("Status message: ")
// .append(statusMessage).append('\n')
// .append("Content: '").append(content).append('\'')
// .toString();
// }
//
// }
//
// Path: src/main/java/com/github/avarabyeu/restendpoint/http/exception/RestEndpointIOException.java
// public class RestEndpointIOException extends RuntimeException {
//
// private static final long serialVersionUID = -5339772980222891685L;
//
// public RestEndpointIOException(String message, Throwable e) {
// super(message, e);
// }
//
// public RestEndpointIOException(String message) {
// super(message);
// }
//
// }
| import com.github.avarabyeu.restendpoint.http.exception.RestEndpointException;
import com.github.avarabyeu.restendpoint.http.exception.RestEndpointIOException;
import com.google.common.base.Charsets;
import com.google.common.collect.ImmutableMultimap;
import com.google.common.io.ByteSource;
import com.google.inject.Key;
import org.apache.http.client.methods.HttpUriRequest;
import org.junit.Assert;
import org.junit.Test;
import org.mockito.Mockito;
import java.net.URI;
import java.net.URISyntaxException; | public void errorHandlerCheckClientError() {
Response<ByteSource> response = getHttpResponse(404, "Not Found");
Assert.assertTrue("Client Error is not handled", handler.hasError(response));
}
@Test
public void errorHandlerCheckServerError() {
Response<ByteSource> response = getHttpResponse(500, "Internal Server Error");
Assert.assertTrue("Server Error is not handled", handler.hasError(response));
}
@Test
public void errorHandlerCheckInformationalResponse() {
Response<ByteSource> response = getHttpResponse(100, "Continue");
Assert.assertFalse("Infromation response is handled", handler.hasError(response));
}
@Test
public void errorHandlerCheckSuccessResponse() {
Response<ByteSource> response = getHttpResponse(200, "Success");
Assert.assertFalse("Success response is handled", handler.hasError(response));
}
@Test
public void errorHandlerCheckRedirectionResponse() {
Response<ByteSource> response = getHttpResponse(302, "Found");
Assert.assertFalse("Redirection response is handled", handler.hasError(response));
}
@Test(expected = RestEndpointException.class) | // Path: src/main/java/com/github/avarabyeu/restendpoint/http/exception/RestEndpointException.java
// public class RestEndpointException extends RuntimeException {
//
// private static final long serialVersionUID = 728718628763519460L;
//
// /**
// * Request URI
// */
// private final URI requestUri;
//
// /**
// * Request Method
// */
// private final HttpMethod requestMethod;
//
// /**
// * HTTP Status Code
// */
// private final int statusCode;
//
// /**
// * HTTP Status Message
// */
// private final String statusMessage;
//
// /**
// * HTTP Response Body
// */
// private final ByteSource content;
//
// public RestEndpointException(URI requestUri, HttpMethod requestMethod, int statusCode, String statusMessage,
// ByteSource content) {
// this.requestUri = requestUri;
// this.requestMethod = requestMethod;
// this.statusCode = statusCode;
// this.statusMessage = statusMessage;
// this.content = content;
// }
//
// public URI getRequestUri() {
// return requestUri;
// }
//
// public HttpMethod getRequestMethod() {
// return requestMethod;
// }
//
// public int getStatusCode() {
// return statusCode;
// }
//
// public String getStatusMessage() {
// return statusMessage;
// }
//
// public ByteSource getContent() {
// return content;
// }
//
// /*
// * (non-Javadoc)
// *
// * @see java.lang.Throwable#getMessage()
// */
// @Override
// public String getMessage() {
// return new StringBuilder()
// .append("Request [").append(requestMethod.toString()).append("] ")
// .append("to URL: ").append(requestUri).append(" has failed with ")
// .append("Status code: ")
// .append(statusCode).append('\n')
// .append("Status message: ")
// .append(statusMessage).append('\n')
// .append("Content: '").append(content).append('\'')
// .toString();
// }
//
// }
//
// Path: src/main/java/com/github/avarabyeu/restendpoint/http/exception/RestEndpointIOException.java
// public class RestEndpointIOException extends RuntimeException {
//
// private static final long serialVersionUID = -5339772980222891685L;
//
// public RestEndpointIOException(String message, Throwable e) {
// super(message, e);
// }
//
// public RestEndpointIOException(String message) {
// super(message);
// }
//
// }
// Path: src/test/java/com/github/avarabyeu/restendpoint/http/DefaultErrorHandlerTest.java
import com.github.avarabyeu.restendpoint.http.exception.RestEndpointException;
import com.github.avarabyeu.restendpoint.http.exception.RestEndpointIOException;
import com.google.common.base.Charsets;
import com.google.common.collect.ImmutableMultimap;
import com.google.common.io.ByteSource;
import com.google.inject.Key;
import org.apache.http.client.methods.HttpUriRequest;
import org.junit.Assert;
import org.junit.Test;
import org.mockito.Mockito;
import java.net.URI;
import java.net.URISyntaxException;
public void errorHandlerCheckClientError() {
Response<ByteSource> response = getHttpResponse(404, "Not Found");
Assert.assertTrue("Client Error is not handled", handler.hasError(response));
}
@Test
public void errorHandlerCheckServerError() {
Response<ByteSource> response = getHttpResponse(500, "Internal Server Error");
Assert.assertTrue("Server Error is not handled", handler.hasError(response));
}
@Test
public void errorHandlerCheckInformationalResponse() {
Response<ByteSource> response = getHttpResponse(100, "Continue");
Assert.assertFalse("Infromation response is handled", handler.hasError(response));
}
@Test
public void errorHandlerCheckSuccessResponse() {
Response<ByteSource> response = getHttpResponse(200, "Success");
Assert.assertFalse("Success response is handled", handler.hasError(response));
}
@Test
public void errorHandlerCheckRedirectionResponse() {
Response<ByteSource> response = getHttpResponse(302, "Found");
Assert.assertFalse("Redirection response is handled", handler.hasError(response));
}
@Test(expected = RestEndpointException.class) | public void testErrorHandlerClientError() throws RestEndpointIOException { |
avarabyeu/restendpoint | src/main/java/com/github/avarabyeu/restendpoint/http/DefaultErrorHandler.java | // Path: src/main/java/com/github/avarabyeu/restendpoint/http/exception/RestEndpointException.java
// public class RestEndpointException extends RuntimeException {
//
// private static final long serialVersionUID = 728718628763519460L;
//
// /**
// * Request URI
// */
// private final URI requestUri;
//
// /**
// * Request Method
// */
// private final HttpMethod requestMethod;
//
// /**
// * HTTP Status Code
// */
// private final int statusCode;
//
// /**
// * HTTP Status Message
// */
// private final String statusMessage;
//
// /**
// * HTTP Response Body
// */
// private final ByteSource content;
//
// public RestEndpointException(URI requestUri, HttpMethod requestMethod, int statusCode, String statusMessage,
// ByteSource content) {
// this.requestUri = requestUri;
// this.requestMethod = requestMethod;
// this.statusCode = statusCode;
// this.statusMessage = statusMessage;
// this.content = content;
// }
//
// public URI getRequestUri() {
// return requestUri;
// }
//
// public HttpMethod getRequestMethod() {
// return requestMethod;
// }
//
// public int getStatusCode() {
// return statusCode;
// }
//
// public String getStatusMessage() {
// return statusMessage;
// }
//
// public ByteSource getContent() {
// return content;
// }
//
// /*
// * (non-Javadoc)
// *
// * @see java.lang.Throwable#getMessage()
// */
// @Override
// public String getMessage() {
// return new StringBuilder()
// .append("Request [").append(requestMethod.toString()).append("] ")
// .append("to URL: ").append(requestUri).append(" has failed with ")
// .append("Status code: ")
// .append(statusCode).append('\n')
// .append("Status message: ")
// .append(statusMessage).append('\n')
// .append("Content: '").append(content).append('\'')
// .toString();
// }
//
// }
//
// Path: src/main/java/com/github/avarabyeu/restendpoint/http/exception/RestEndpointIOException.java
// public class RestEndpointIOException extends RuntimeException {
//
// private static final long serialVersionUID = -5339772980222891685L;
//
// public RestEndpointIOException(String message, Throwable e) {
// super(message, e);
// }
//
// public RestEndpointIOException(String message) {
// super(message);
// }
//
// }
| import com.github.avarabyeu.restendpoint.http.exception.RestEndpointException;
import com.github.avarabyeu.restendpoint.http.exception.RestEndpointIOException;
import com.google.common.io.ByteSource;
import java.net.URI; | /*
* Copyright (C) 2014 Andrei Varabyeu
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.github.avarabyeu.restendpoint.http;
/**
* Default implementation of
* {@link ErrorHandler}
*
* @author Andrei Varabyeu
*/
public class DefaultErrorHandler implements ErrorHandler {
/**
* Returns TRUE in case status code of response starts with 4 or 5
*/
@Override
public boolean hasError(Response<ByteSource> rs) {
StatusType statusType = StatusType.valueOf(rs.getStatus());
return (statusType == StatusType.CLIENT_ERROR || statusType == StatusType.SERVER_ERROR);
}
/**
* Default implementation. May be overridden in subclasses<br>
* Throws
* {@link com.github.avarabyeu.restendpoint.http.exception.RestEndpointException}
* if Response status code starts from 4xx or 5xx
* <p>
* Throwed exceptions may be overridden in handle* methods
*/
@Override | // Path: src/main/java/com/github/avarabyeu/restendpoint/http/exception/RestEndpointException.java
// public class RestEndpointException extends RuntimeException {
//
// private static final long serialVersionUID = 728718628763519460L;
//
// /**
// * Request URI
// */
// private final URI requestUri;
//
// /**
// * Request Method
// */
// private final HttpMethod requestMethod;
//
// /**
// * HTTP Status Code
// */
// private final int statusCode;
//
// /**
// * HTTP Status Message
// */
// private final String statusMessage;
//
// /**
// * HTTP Response Body
// */
// private final ByteSource content;
//
// public RestEndpointException(URI requestUri, HttpMethod requestMethod, int statusCode, String statusMessage,
// ByteSource content) {
// this.requestUri = requestUri;
// this.requestMethod = requestMethod;
// this.statusCode = statusCode;
// this.statusMessage = statusMessage;
// this.content = content;
// }
//
// public URI getRequestUri() {
// return requestUri;
// }
//
// public HttpMethod getRequestMethod() {
// return requestMethod;
// }
//
// public int getStatusCode() {
// return statusCode;
// }
//
// public String getStatusMessage() {
// return statusMessage;
// }
//
// public ByteSource getContent() {
// return content;
// }
//
// /*
// * (non-Javadoc)
// *
// * @see java.lang.Throwable#getMessage()
// */
// @Override
// public String getMessage() {
// return new StringBuilder()
// .append("Request [").append(requestMethod.toString()).append("] ")
// .append("to URL: ").append(requestUri).append(" has failed with ")
// .append("Status code: ")
// .append(statusCode).append('\n')
// .append("Status message: ")
// .append(statusMessage).append('\n')
// .append("Content: '").append(content).append('\'')
// .toString();
// }
//
// }
//
// Path: src/main/java/com/github/avarabyeu/restendpoint/http/exception/RestEndpointIOException.java
// public class RestEndpointIOException extends RuntimeException {
//
// private static final long serialVersionUID = -5339772980222891685L;
//
// public RestEndpointIOException(String message, Throwable e) {
// super(message, e);
// }
//
// public RestEndpointIOException(String message) {
// super(message);
// }
//
// }
// Path: src/main/java/com/github/avarabyeu/restendpoint/http/DefaultErrorHandler.java
import com.github.avarabyeu.restendpoint.http.exception.RestEndpointException;
import com.github.avarabyeu.restendpoint.http.exception.RestEndpointIOException;
import com.google.common.io.ByteSource;
import java.net.URI;
/*
* Copyright (C) 2014 Andrei Varabyeu
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.github.avarabyeu.restendpoint.http;
/**
* Default implementation of
* {@link ErrorHandler}
*
* @author Andrei Varabyeu
*/
public class DefaultErrorHandler implements ErrorHandler {
/**
* Returns TRUE in case status code of response starts with 4 or 5
*/
@Override
public boolean hasError(Response<ByteSource> rs) {
StatusType statusType = StatusType.valueOf(rs.getStatus());
return (statusType == StatusType.CLIENT_ERROR || statusType == StatusType.SERVER_ERROR);
}
/**
* Default implementation. May be overridden in subclasses<br>
* Throws
* {@link com.github.avarabyeu.restendpoint.http.exception.RestEndpointException}
* if Response status code starts from 4xx or 5xx
* <p>
* Throwed exceptions may be overridden in handle* methods
*/
@Override | public void handle(Response<ByteSource> rs) throws RestEndpointIOException { |
avarabyeu/restendpoint | src/main/java/com/github/avarabyeu/restendpoint/http/DefaultErrorHandler.java | // Path: src/main/java/com/github/avarabyeu/restendpoint/http/exception/RestEndpointException.java
// public class RestEndpointException extends RuntimeException {
//
// private static final long serialVersionUID = 728718628763519460L;
//
// /**
// * Request URI
// */
// private final URI requestUri;
//
// /**
// * Request Method
// */
// private final HttpMethod requestMethod;
//
// /**
// * HTTP Status Code
// */
// private final int statusCode;
//
// /**
// * HTTP Status Message
// */
// private final String statusMessage;
//
// /**
// * HTTP Response Body
// */
// private final ByteSource content;
//
// public RestEndpointException(URI requestUri, HttpMethod requestMethod, int statusCode, String statusMessage,
// ByteSource content) {
// this.requestUri = requestUri;
// this.requestMethod = requestMethod;
// this.statusCode = statusCode;
// this.statusMessage = statusMessage;
// this.content = content;
// }
//
// public URI getRequestUri() {
// return requestUri;
// }
//
// public HttpMethod getRequestMethod() {
// return requestMethod;
// }
//
// public int getStatusCode() {
// return statusCode;
// }
//
// public String getStatusMessage() {
// return statusMessage;
// }
//
// public ByteSource getContent() {
// return content;
// }
//
// /*
// * (non-Javadoc)
// *
// * @see java.lang.Throwable#getMessage()
// */
// @Override
// public String getMessage() {
// return new StringBuilder()
// .append("Request [").append(requestMethod.toString()).append("] ")
// .append("to URL: ").append(requestUri).append(" has failed with ")
// .append("Status code: ")
// .append(statusCode).append('\n')
// .append("Status message: ")
// .append(statusMessage).append('\n')
// .append("Content: '").append(content).append('\'')
// .toString();
// }
//
// }
//
// Path: src/main/java/com/github/avarabyeu/restendpoint/http/exception/RestEndpointIOException.java
// public class RestEndpointIOException extends RuntimeException {
//
// private static final long serialVersionUID = -5339772980222891685L;
//
// public RestEndpointIOException(String message, Throwable e) {
// super(message, e);
// }
//
// public RestEndpointIOException(String message) {
// super(message);
// }
//
// }
| import com.github.avarabyeu.restendpoint.http.exception.RestEndpointException;
import com.github.avarabyeu.restendpoint.http.exception.RestEndpointIOException;
import com.google.common.io.ByteSource;
import java.net.URI; | /*
* Copyright (C) 2014 Andrei Varabyeu
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.github.avarabyeu.restendpoint.http;
/**
* Default implementation of
* {@link ErrorHandler}
*
* @author Andrei Varabyeu
*/
public class DefaultErrorHandler implements ErrorHandler {
/**
* Returns TRUE in case status code of response starts with 4 or 5
*/
@Override
public boolean hasError(Response<ByteSource> rs) {
StatusType statusType = StatusType.valueOf(rs.getStatus());
return (statusType == StatusType.CLIENT_ERROR || statusType == StatusType.SERVER_ERROR);
}
/**
* Default implementation. May be overridden in subclasses<br>
* Throws
* {@link com.github.avarabyeu.restendpoint.http.exception.RestEndpointException}
* if Response status code starts from 4xx or 5xx
* <p>
* Throwed exceptions may be overridden in handle* methods
*/
@Override
public void handle(Response<ByteSource> rs) throws RestEndpointIOException {
if (!hasError(rs)) {
return;
}
handleError(rs.getUri(), rs.getHttpMethod(), rs.getStatus(), rs.getReason(), rs.getBody());
}
/**
* Handler methods for HTTP client errors
*
* @param requestUri - Request URI
* @param requestMethod - Request HTTP Method
* @param statusCode - HTTP status code
* @param statusMessage - HTTP status message
* @param errorBody - HTTP response body
*/
protected void handleError(URI requestUri, HttpMethod requestMethod, int statusCode, String statusMessage,
ByteSource errorBody) throws RestEndpointIOException { | // Path: src/main/java/com/github/avarabyeu/restendpoint/http/exception/RestEndpointException.java
// public class RestEndpointException extends RuntimeException {
//
// private static final long serialVersionUID = 728718628763519460L;
//
// /**
// * Request URI
// */
// private final URI requestUri;
//
// /**
// * Request Method
// */
// private final HttpMethod requestMethod;
//
// /**
// * HTTP Status Code
// */
// private final int statusCode;
//
// /**
// * HTTP Status Message
// */
// private final String statusMessage;
//
// /**
// * HTTP Response Body
// */
// private final ByteSource content;
//
// public RestEndpointException(URI requestUri, HttpMethod requestMethod, int statusCode, String statusMessage,
// ByteSource content) {
// this.requestUri = requestUri;
// this.requestMethod = requestMethod;
// this.statusCode = statusCode;
// this.statusMessage = statusMessage;
// this.content = content;
// }
//
// public URI getRequestUri() {
// return requestUri;
// }
//
// public HttpMethod getRequestMethod() {
// return requestMethod;
// }
//
// public int getStatusCode() {
// return statusCode;
// }
//
// public String getStatusMessage() {
// return statusMessage;
// }
//
// public ByteSource getContent() {
// return content;
// }
//
// /*
// * (non-Javadoc)
// *
// * @see java.lang.Throwable#getMessage()
// */
// @Override
// public String getMessage() {
// return new StringBuilder()
// .append("Request [").append(requestMethod.toString()).append("] ")
// .append("to URL: ").append(requestUri).append(" has failed with ")
// .append("Status code: ")
// .append(statusCode).append('\n')
// .append("Status message: ")
// .append(statusMessage).append('\n')
// .append("Content: '").append(content).append('\'')
// .toString();
// }
//
// }
//
// Path: src/main/java/com/github/avarabyeu/restendpoint/http/exception/RestEndpointIOException.java
// public class RestEndpointIOException extends RuntimeException {
//
// private static final long serialVersionUID = -5339772980222891685L;
//
// public RestEndpointIOException(String message, Throwable e) {
// super(message, e);
// }
//
// public RestEndpointIOException(String message) {
// super(message);
// }
//
// }
// Path: src/main/java/com/github/avarabyeu/restendpoint/http/DefaultErrorHandler.java
import com.github.avarabyeu.restendpoint.http.exception.RestEndpointException;
import com.github.avarabyeu.restendpoint.http.exception.RestEndpointIOException;
import com.google.common.io.ByteSource;
import java.net.URI;
/*
* Copyright (C) 2014 Andrei Varabyeu
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.github.avarabyeu.restendpoint.http;
/**
* Default implementation of
* {@link ErrorHandler}
*
* @author Andrei Varabyeu
*/
public class DefaultErrorHandler implements ErrorHandler {
/**
* Returns TRUE in case status code of response starts with 4 or 5
*/
@Override
public boolean hasError(Response<ByteSource> rs) {
StatusType statusType = StatusType.valueOf(rs.getStatus());
return (statusType == StatusType.CLIENT_ERROR || statusType == StatusType.SERVER_ERROR);
}
/**
* Default implementation. May be overridden in subclasses<br>
* Throws
* {@link com.github.avarabyeu.restendpoint.http.exception.RestEndpointException}
* if Response status code starts from 4xx or 5xx
* <p>
* Throwed exceptions may be overridden in handle* methods
*/
@Override
public void handle(Response<ByteSource> rs) throws RestEndpointIOException {
if (!hasError(rs)) {
return;
}
handleError(rs.getUri(), rs.getHttpMethod(), rs.getStatus(), rs.getReason(), rs.getBody());
}
/**
* Handler methods for HTTP client errors
*
* @param requestUri - Request URI
* @param requestMethod - Request HTTP Method
* @param statusCode - HTTP status code
* @param statusMessage - HTTP status message
* @param errorBody - HTTP response body
*/
protected void handleError(URI requestUri, HttpMethod requestMethod, int statusCode, String statusMessage,
ByteSource errorBody) throws RestEndpointIOException { | throw new RestEndpointException(requestUri, requestMethod, statusCode, statusMessage, errorBody); |
avarabyeu/restendpoint | src/main/java/com/github/avarabyeu/restendpoint/http/NoopErrorHandler.java | // Path: src/main/java/com/github/avarabyeu/restendpoint/http/exception/RestEndpointIOException.java
// public class RestEndpointIOException extends RuntimeException {
//
// private static final long serialVersionUID = -5339772980222891685L;
//
// public RestEndpointIOException(String message, Throwable e) {
// super(message, e);
// }
//
// public RestEndpointIOException(String message) {
// super(message);
// }
//
// }
| import com.github.avarabyeu.restendpoint.http.exception.RestEndpointIOException;
import com.google.common.io.ByteSource; | /*
* Copyright (C) 2014 Andrei Varabyeu
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.github.avarabyeu.restendpoint.http;
/**
* NOP implementation of error handler. Does not throw any exceptions
*
* @author Andrei Varabyeu
*/
public class NoopErrorHandler implements ErrorHandler {
@Override
public boolean hasError(Response<ByteSource> rs) {
return false;
}
@Override | // Path: src/main/java/com/github/avarabyeu/restendpoint/http/exception/RestEndpointIOException.java
// public class RestEndpointIOException extends RuntimeException {
//
// private static final long serialVersionUID = -5339772980222891685L;
//
// public RestEndpointIOException(String message, Throwable e) {
// super(message, e);
// }
//
// public RestEndpointIOException(String message) {
// super(message);
// }
//
// }
// Path: src/main/java/com/github/avarabyeu/restendpoint/http/NoopErrorHandler.java
import com.github.avarabyeu.restendpoint.http.exception.RestEndpointIOException;
import com.google.common.io.ByteSource;
/*
* Copyright (C) 2014 Andrei Varabyeu
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.github.avarabyeu.restendpoint.http;
/**
* NOP implementation of error handler. Does not throw any exceptions
*
* @author Andrei Varabyeu
*/
public class NoopErrorHandler implements ErrorHandler {
@Override
public boolean hasError(Response<ByteSource> rs) {
return false;
}
@Override | public void handle(Response<ByteSource> rs) throws RestEndpointIOException { |
avarabyeu/restendpoint | src/test/java/com/github/avarabyeu/restendpoint/serializer/TextSerializerTest.java | // Path: src/main/java/com/github/avarabyeu/restendpoint/http/exception/SerializerException.java
// public class SerializerException extends RestEndpointIOException {
//
// private static final long serialVersionUID = 1L;
//
// public SerializerException(String message) {
// super(message);
// }
//
// public SerializerException(String message, Throwable e) {
// super(message, e);
// }
// }
| import com.github.avarabyeu.restendpoint.http.exception.SerializerException;
import com.google.common.net.MediaType;
import com.smarttested.qa.smartassert.SmartAssert;
import org.hamcrest.CoreMatchers;
import org.junit.Test;
import java.util.Calendar; | package com.github.avarabyeu.restendpoint.serializer;
/**
* Tests for {@link com.github.avarabyeu.restendpoint.serializer.TextSerializer}
* @author avarabyeu
*/
public class TextSerializerTest {
public static final String TEST_STRING = "test";
private TextSerializer serializer = new TextSerializer();
@Test | // Path: src/main/java/com/github/avarabyeu/restendpoint/http/exception/SerializerException.java
// public class SerializerException extends RestEndpointIOException {
//
// private static final long serialVersionUID = 1L;
//
// public SerializerException(String message) {
// super(message);
// }
//
// public SerializerException(String message, Throwable e) {
// super(message, e);
// }
// }
// Path: src/test/java/com/github/avarabyeu/restendpoint/serializer/TextSerializerTest.java
import com.github.avarabyeu.restendpoint.http.exception.SerializerException;
import com.google.common.net.MediaType;
import com.smarttested.qa.smartassert.SmartAssert;
import org.hamcrest.CoreMatchers;
import org.junit.Test;
import java.util.Calendar;
package com.github.avarabyeu.restendpoint.serializer;
/**
* Tests for {@link com.github.avarabyeu.restendpoint.serializer.TextSerializer}
* @author avarabyeu
*/
public class TextSerializerTest {
public static final String TEST_STRING = "test";
private TextSerializer serializer = new TextSerializer();
@Test | public void testSerialize() throws SerializerException { |
avarabyeu/restendpoint | src/test/java/com/github/avarabyeu/restendpoint/serializer/xml/JaxbSerializerTest.java | // Path: src/main/java/com/github/avarabyeu/restendpoint/http/exception/SerializerException.java
// public class SerializerException extends RestEndpointIOException {
//
// private static final long serialVersionUID = 1L;
//
// public SerializerException(String message) {
// super(message);
// }
//
// public SerializerException(String message, Throwable e) {
// super(message, e);
// }
// }
//
// Path: src/test/java/com/github/avarabyeu/restendpoint/serializer/DemoBean.java
// @XmlRootElement
// public class DemoBean {
//
// private String someField;
//
// public DemoBean() {
// }
//
// public DemoBean(String someField) {
// this.someField = someField;
// }
//
// public String getSomeField() {
// return someField;
// }
//
// public void setSomeField(String someField) {
// this.someField = someField;
// }
//
// @Override
// public boolean equals(Object o) {
// if (this == o)
// return true;
// if (o == null || getClass() != o.getClass())
// return false;
// DemoBean demoBean = (DemoBean) o;
// return Objects.equals(someField, demoBean.someField);
// }
//
// @Override
// public int hashCode() {
// return Objects.hash(someField);
// }
// }
| import com.github.avarabyeu.restendpoint.http.exception.SerializerException;
import com.github.avarabyeu.restendpoint.serializer.DemoBean;
import com.google.common.net.MediaType;
import com.smarttested.qa.smartassert.SmartAssert;
import org.hamcrest.CoreMatchers;
import org.junit.BeforeClass;
import org.junit.Test; | package com.github.avarabyeu.restendpoint.serializer.xml;
/**
* @author Andrei Varabyeu
*/
public class JaxbSerializerTest {
private static final String TEST_STRING = "<?xml version=\"1.0\" encoding=\"UTF-8\" standalone=\"yes\"?><demoBean><someField>someValue</someField></demoBean>"; | // Path: src/main/java/com/github/avarabyeu/restendpoint/http/exception/SerializerException.java
// public class SerializerException extends RestEndpointIOException {
//
// private static final long serialVersionUID = 1L;
//
// public SerializerException(String message) {
// super(message);
// }
//
// public SerializerException(String message, Throwable e) {
// super(message, e);
// }
// }
//
// Path: src/test/java/com/github/avarabyeu/restendpoint/serializer/DemoBean.java
// @XmlRootElement
// public class DemoBean {
//
// private String someField;
//
// public DemoBean() {
// }
//
// public DemoBean(String someField) {
// this.someField = someField;
// }
//
// public String getSomeField() {
// return someField;
// }
//
// public void setSomeField(String someField) {
// this.someField = someField;
// }
//
// @Override
// public boolean equals(Object o) {
// if (this == o)
// return true;
// if (o == null || getClass() != o.getClass())
// return false;
// DemoBean demoBean = (DemoBean) o;
// return Objects.equals(someField, demoBean.someField);
// }
//
// @Override
// public int hashCode() {
// return Objects.hash(someField);
// }
// }
// Path: src/test/java/com/github/avarabyeu/restendpoint/serializer/xml/JaxbSerializerTest.java
import com.github.avarabyeu.restendpoint.http.exception.SerializerException;
import com.github.avarabyeu.restendpoint.serializer.DemoBean;
import com.google.common.net.MediaType;
import com.smarttested.qa.smartassert.SmartAssert;
import org.hamcrest.CoreMatchers;
import org.junit.BeforeClass;
import org.junit.Test;
package com.github.avarabyeu.restendpoint.serializer.xml;
/**
* @author Andrei Varabyeu
*/
public class JaxbSerializerTest {
private static final String TEST_STRING = "<?xml version=\"1.0\" encoding=\"UTF-8\" standalone=\"yes\"?><demoBean><someField>someValue</someField></demoBean>"; | private static final DemoBean TEST_BEAN = new DemoBean("someValue"); |
avarabyeu/restendpoint | src/test/java/com/github/avarabyeu/restendpoint/serializer/xml/JaxbSerializerTest.java | // Path: src/main/java/com/github/avarabyeu/restendpoint/http/exception/SerializerException.java
// public class SerializerException extends RestEndpointIOException {
//
// private static final long serialVersionUID = 1L;
//
// public SerializerException(String message) {
// super(message);
// }
//
// public SerializerException(String message, Throwable e) {
// super(message, e);
// }
// }
//
// Path: src/test/java/com/github/avarabyeu/restendpoint/serializer/DemoBean.java
// @XmlRootElement
// public class DemoBean {
//
// private String someField;
//
// public DemoBean() {
// }
//
// public DemoBean(String someField) {
// this.someField = someField;
// }
//
// public String getSomeField() {
// return someField;
// }
//
// public void setSomeField(String someField) {
// this.someField = someField;
// }
//
// @Override
// public boolean equals(Object o) {
// if (this == o)
// return true;
// if (o == null || getClass() != o.getClass())
// return false;
// DemoBean demoBean = (DemoBean) o;
// return Objects.equals(someField, demoBean.someField);
// }
//
// @Override
// public int hashCode() {
// return Objects.hash(someField);
// }
// }
| import com.github.avarabyeu.restendpoint.http.exception.SerializerException;
import com.github.avarabyeu.restendpoint.serializer.DemoBean;
import com.google.common.net.MediaType;
import com.smarttested.qa.smartassert.SmartAssert;
import org.hamcrest.CoreMatchers;
import org.junit.BeforeClass;
import org.junit.Test; | package com.github.avarabyeu.restendpoint.serializer.xml;
/**
* @author Andrei Varabyeu
*/
public class JaxbSerializerTest {
private static final String TEST_STRING = "<?xml version=\"1.0\" encoding=\"UTF-8\" standalone=\"yes\"?><demoBean><someField>someValue</someField></demoBean>";
private static final DemoBean TEST_BEAN = new DemoBean("someValue");
private static JaxbSerializer serializer;
@BeforeClass | // Path: src/main/java/com/github/avarabyeu/restendpoint/http/exception/SerializerException.java
// public class SerializerException extends RestEndpointIOException {
//
// private static final long serialVersionUID = 1L;
//
// public SerializerException(String message) {
// super(message);
// }
//
// public SerializerException(String message, Throwable e) {
// super(message, e);
// }
// }
//
// Path: src/test/java/com/github/avarabyeu/restendpoint/serializer/DemoBean.java
// @XmlRootElement
// public class DemoBean {
//
// private String someField;
//
// public DemoBean() {
// }
//
// public DemoBean(String someField) {
// this.someField = someField;
// }
//
// public String getSomeField() {
// return someField;
// }
//
// public void setSomeField(String someField) {
// this.someField = someField;
// }
//
// @Override
// public boolean equals(Object o) {
// if (this == o)
// return true;
// if (o == null || getClass() != o.getClass())
// return false;
// DemoBean demoBean = (DemoBean) o;
// return Objects.equals(someField, demoBean.someField);
// }
//
// @Override
// public int hashCode() {
// return Objects.hash(someField);
// }
// }
// Path: src/test/java/com/github/avarabyeu/restendpoint/serializer/xml/JaxbSerializerTest.java
import com.github.avarabyeu.restendpoint.http.exception.SerializerException;
import com.github.avarabyeu.restendpoint.serializer.DemoBean;
import com.google.common.net.MediaType;
import com.smarttested.qa.smartassert.SmartAssert;
import org.hamcrest.CoreMatchers;
import org.junit.BeforeClass;
import org.junit.Test;
package com.github.avarabyeu.restendpoint.serializer.xml;
/**
* @author Andrei Varabyeu
*/
public class JaxbSerializerTest {
private static final String TEST_STRING = "<?xml version=\"1.0\" encoding=\"UTF-8\" standalone=\"yes\"?><demoBean><someField>someValue</someField></demoBean>";
private static final DemoBean TEST_BEAN = new DemoBean("someValue");
private static JaxbSerializer serializer;
@BeforeClass | public static void prepare() throws SerializerException { |
avarabyeu/restendpoint | src/main/java/com/github/avarabyeu/restendpoint/serializer/VoidSerializer.java | // Path: src/main/java/com/github/avarabyeu/restendpoint/http/exception/SerializerException.java
// public class SerializerException extends RestEndpointIOException {
//
// private static final long serialVersionUID = 1L;
//
// public SerializerException(String message) {
// super(message);
// }
//
// public SerializerException(String message, Throwable e) {
// super(message, e);
// }
// }
| import com.github.avarabyeu.restendpoint.http.exception.SerializerException;
import com.google.common.net.MediaType;
import com.google.common.reflect.TypeToken;
import java.lang.reflect.Type; | package com.github.avarabyeu.restendpoint.serializer;
/**
* @author Andrei Varabyeu
*/
public class VoidSerializer implements Serializer {
@Override | // Path: src/main/java/com/github/avarabyeu/restendpoint/http/exception/SerializerException.java
// public class SerializerException extends RestEndpointIOException {
//
// private static final long serialVersionUID = 1L;
//
// public SerializerException(String message) {
// super(message);
// }
//
// public SerializerException(String message, Throwable e) {
// super(message, e);
// }
// }
// Path: src/main/java/com/github/avarabyeu/restendpoint/serializer/VoidSerializer.java
import com.github.avarabyeu.restendpoint.http.exception.SerializerException;
import com.google.common.net.MediaType;
import com.google.common.reflect.TypeToken;
import java.lang.reflect.Type;
package com.github.avarabyeu.restendpoint.serializer;
/**
* @author Andrei Varabyeu
*/
public class VoidSerializer implements Serializer {
@Override | public final <T> byte[] serialize(T t) throws SerializerException { |
avarabyeu/restendpoint | src/main/java/com/github/avarabyeu/restendpoint/serializer/json/GsonSerializer.java | // Path: src/main/java/com/github/avarabyeu/restendpoint/http/IOUtils.java
// public final class IOUtils {
//
// /**
// * Do not need to create instance
// */
// private IOUtils() {
// }
//
// /**
// * Closes Resource without throwing any errors
// *
// * @param closeable {@link Closeable} to close
// */
// public static void closeQuietly(Closeable closeable) {
// try {
// if (closeable != null) {
// closeable.close();
// }
// } catch (IOException ioe) {
// // ignore
// }
// }
//
// /**
// * Check whether provided url string is a valid java {@link java.net.URL}
// *
// * @param url URL to be validated
// * @return TRUE if URL is valid
// */
// public static boolean isValidUrl(String url) {
// try {
// if (Strings.isNullOrEmpty(url)) {
// return false;
// }
// new URL(url);
// return true;
// } catch (MalformedURLException e) {
// return false;
// }
// }
//
// /**
// * Loads keystore
// *
// * @param keyStore Keystore InputStream
// * @param password Keystore password
// * @return Loaded Keystore
// * @throws CertificateException In case of Certificate error
// * @throws NoSuchAlgorithmException If no such algorithm present
// * @throws IOException In case if some IO errors
// * @throws KeyStoreException If there is some error with KeyStore
// */
// public static KeyStore loadKeyStore(InputStream keyStore, String password)
// throws CertificateException, NoSuchAlgorithmException, IOException, KeyStoreException {
// try {
// KeyStore trustStore = KeyStore.getInstance("JKS");
// trustStore.load(keyStore, password.toCharArray());
// return trustStore;
// } finally {
// IOUtils.closeQuietly(keyStore);
// }
// }
// }
//
// Path: src/main/java/com/github/avarabyeu/restendpoint/http/exception/SerializerException.java
// public class SerializerException extends RestEndpointIOException {
//
// private static final long serialVersionUID = 1L;
//
// public SerializerException(String message) {
// super(message);
// }
//
// public SerializerException(String message, Throwable e) {
// super(message, e);
// }
// }
| import com.github.avarabyeu.restendpoint.http.IOUtils;
import com.github.avarabyeu.restendpoint.http.exception.SerializerException;
import com.google.common.base.Charsets;
import com.google.common.io.ByteSource;
import com.google.gson.Gson;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.lang.reflect.Type; | /*
* Copyright (C) 2014 Andrei Varabyeu
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.github.avarabyeu.restendpoint.serializer.json;
/**
* JSON serializer using GSON library
*
* @author Andrei Varabyeu
* @see <a href="https://code.google.com/p/google-gson/">GSON</a>
*/
public class GsonSerializer extends AbstractJsonSerializer {
private final Gson gson;
/**
* Creates serializer with provided GSON
*
* @param gson Gson object
*/
public GsonSerializer(Gson gson) {
this.gson = gson;
}
/**
* Creates serializer with default GSON
*/
public GsonSerializer() {
this(new Gson());
}
@Override | // Path: src/main/java/com/github/avarabyeu/restendpoint/http/IOUtils.java
// public final class IOUtils {
//
// /**
// * Do not need to create instance
// */
// private IOUtils() {
// }
//
// /**
// * Closes Resource without throwing any errors
// *
// * @param closeable {@link Closeable} to close
// */
// public static void closeQuietly(Closeable closeable) {
// try {
// if (closeable != null) {
// closeable.close();
// }
// } catch (IOException ioe) {
// // ignore
// }
// }
//
// /**
// * Check whether provided url string is a valid java {@link java.net.URL}
// *
// * @param url URL to be validated
// * @return TRUE if URL is valid
// */
// public static boolean isValidUrl(String url) {
// try {
// if (Strings.isNullOrEmpty(url)) {
// return false;
// }
// new URL(url);
// return true;
// } catch (MalformedURLException e) {
// return false;
// }
// }
//
// /**
// * Loads keystore
// *
// * @param keyStore Keystore InputStream
// * @param password Keystore password
// * @return Loaded Keystore
// * @throws CertificateException In case of Certificate error
// * @throws NoSuchAlgorithmException If no such algorithm present
// * @throws IOException In case if some IO errors
// * @throws KeyStoreException If there is some error with KeyStore
// */
// public static KeyStore loadKeyStore(InputStream keyStore, String password)
// throws CertificateException, NoSuchAlgorithmException, IOException, KeyStoreException {
// try {
// KeyStore trustStore = KeyStore.getInstance("JKS");
// trustStore.load(keyStore, password.toCharArray());
// return trustStore;
// } finally {
// IOUtils.closeQuietly(keyStore);
// }
// }
// }
//
// Path: src/main/java/com/github/avarabyeu/restendpoint/http/exception/SerializerException.java
// public class SerializerException extends RestEndpointIOException {
//
// private static final long serialVersionUID = 1L;
//
// public SerializerException(String message) {
// super(message);
// }
//
// public SerializerException(String message, Throwable e) {
// super(message, e);
// }
// }
// Path: src/main/java/com/github/avarabyeu/restendpoint/serializer/json/GsonSerializer.java
import com.github.avarabyeu.restendpoint.http.IOUtils;
import com.github.avarabyeu.restendpoint.http.exception.SerializerException;
import com.google.common.base.Charsets;
import com.google.common.io.ByteSource;
import com.google.gson.Gson;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.lang.reflect.Type;
/*
* Copyright (C) 2014 Andrei Varabyeu
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.github.avarabyeu.restendpoint.serializer.json;
/**
* JSON serializer using GSON library
*
* @author Andrei Varabyeu
* @see <a href="https://code.google.com/p/google-gson/">GSON</a>
*/
public class GsonSerializer extends AbstractJsonSerializer {
private final Gson gson;
/**
* Creates serializer with provided GSON
*
* @param gson Gson object
*/
public GsonSerializer(Gson gson) {
this.gson = gson;
}
/**
* Creates serializer with default GSON
*/
public GsonSerializer() {
this(new Gson());
}
@Override | public <T> byte[] serialize(T t) throws SerializerException { |
avarabyeu/restendpoint | src/main/java/com/github/avarabyeu/restendpoint/serializer/json/GsonSerializer.java | // Path: src/main/java/com/github/avarabyeu/restendpoint/http/IOUtils.java
// public final class IOUtils {
//
// /**
// * Do not need to create instance
// */
// private IOUtils() {
// }
//
// /**
// * Closes Resource without throwing any errors
// *
// * @param closeable {@link Closeable} to close
// */
// public static void closeQuietly(Closeable closeable) {
// try {
// if (closeable != null) {
// closeable.close();
// }
// } catch (IOException ioe) {
// // ignore
// }
// }
//
// /**
// * Check whether provided url string is a valid java {@link java.net.URL}
// *
// * @param url URL to be validated
// * @return TRUE if URL is valid
// */
// public static boolean isValidUrl(String url) {
// try {
// if (Strings.isNullOrEmpty(url)) {
// return false;
// }
// new URL(url);
// return true;
// } catch (MalformedURLException e) {
// return false;
// }
// }
//
// /**
// * Loads keystore
// *
// * @param keyStore Keystore InputStream
// * @param password Keystore password
// * @return Loaded Keystore
// * @throws CertificateException In case of Certificate error
// * @throws NoSuchAlgorithmException If no such algorithm present
// * @throws IOException In case if some IO errors
// * @throws KeyStoreException If there is some error with KeyStore
// */
// public static KeyStore loadKeyStore(InputStream keyStore, String password)
// throws CertificateException, NoSuchAlgorithmException, IOException, KeyStoreException {
// try {
// KeyStore trustStore = KeyStore.getInstance("JKS");
// trustStore.load(keyStore, password.toCharArray());
// return trustStore;
// } finally {
// IOUtils.closeQuietly(keyStore);
// }
// }
// }
//
// Path: src/main/java/com/github/avarabyeu/restendpoint/http/exception/SerializerException.java
// public class SerializerException extends RestEndpointIOException {
//
// private static final long serialVersionUID = 1L;
//
// public SerializerException(String message) {
// super(message);
// }
//
// public SerializerException(String message, Throwable e) {
// super(message, e);
// }
// }
| import com.github.avarabyeu.restendpoint.http.IOUtils;
import com.github.avarabyeu.restendpoint.http.exception.SerializerException;
import com.google.common.base.Charsets;
import com.google.common.io.ByteSource;
import com.google.gson.Gson;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.lang.reflect.Type; | /*
* Copyright (C) 2014 Andrei Varabyeu
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.github.avarabyeu.restendpoint.serializer.json;
/**
* JSON serializer using GSON library
*
* @author Andrei Varabyeu
* @see <a href="https://code.google.com/p/google-gson/">GSON</a>
*/
public class GsonSerializer extends AbstractJsonSerializer {
private final Gson gson;
/**
* Creates serializer with provided GSON
*
* @param gson Gson object
*/
public GsonSerializer(Gson gson) {
this.gson = gson;
}
/**
* Creates serializer with default GSON
*/
public GsonSerializer() {
this(new Gson());
}
@Override
public <T> byte[] serialize(T t) throws SerializerException {
try {
return gson.toJson(t).getBytes(Charsets.UTF_8.name());
} catch (UnsupportedEncodingException e) {
throw new SerializerException("UTF-8 is not supported", e);
}
}
@Override
public <T> T deserialize(byte[] content, Class<T> clazz) throws SerializerException {
BufferedReader is = null;
try {
is = ByteSource.wrap(content).asCharSource(Charsets.UTF_8).openBufferedStream();
return gson.fromJson(is, clazz);
} catch (IOException e) {
throw new SerializerException("Unable to serialize content", e);
} finally { | // Path: src/main/java/com/github/avarabyeu/restendpoint/http/IOUtils.java
// public final class IOUtils {
//
// /**
// * Do not need to create instance
// */
// private IOUtils() {
// }
//
// /**
// * Closes Resource without throwing any errors
// *
// * @param closeable {@link Closeable} to close
// */
// public static void closeQuietly(Closeable closeable) {
// try {
// if (closeable != null) {
// closeable.close();
// }
// } catch (IOException ioe) {
// // ignore
// }
// }
//
// /**
// * Check whether provided url string is a valid java {@link java.net.URL}
// *
// * @param url URL to be validated
// * @return TRUE if URL is valid
// */
// public static boolean isValidUrl(String url) {
// try {
// if (Strings.isNullOrEmpty(url)) {
// return false;
// }
// new URL(url);
// return true;
// } catch (MalformedURLException e) {
// return false;
// }
// }
//
// /**
// * Loads keystore
// *
// * @param keyStore Keystore InputStream
// * @param password Keystore password
// * @return Loaded Keystore
// * @throws CertificateException In case of Certificate error
// * @throws NoSuchAlgorithmException If no such algorithm present
// * @throws IOException In case if some IO errors
// * @throws KeyStoreException If there is some error with KeyStore
// */
// public static KeyStore loadKeyStore(InputStream keyStore, String password)
// throws CertificateException, NoSuchAlgorithmException, IOException, KeyStoreException {
// try {
// KeyStore trustStore = KeyStore.getInstance("JKS");
// trustStore.load(keyStore, password.toCharArray());
// return trustStore;
// } finally {
// IOUtils.closeQuietly(keyStore);
// }
// }
// }
//
// Path: src/main/java/com/github/avarabyeu/restendpoint/http/exception/SerializerException.java
// public class SerializerException extends RestEndpointIOException {
//
// private static final long serialVersionUID = 1L;
//
// public SerializerException(String message) {
// super(message);
// }
//
// public SerializerException(String message, Throwable e) {
// super(message, e);
// }
// }
// Path: src/main/java/com/github/avarabyeu/restendpoint/serializer/json/GsonSerializer.java
import com.github.avarabyeu.restendpoint.http.IOUtils;
import com.github.avarabyeu.restendpoint.http.exception.SerializerException;
import com.google.common.base.Charsets;
import com.google.common.io.ByteSource;
import com.google.gson.Gson;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.lang.reflect.Type;
/*
* Copyright (C) 2014 Andrei Varabyeu
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.github.avarabyeu.restendpoint.serializer.json;
/**
* JSON serializer using GSON library
*
* @author Andrei Varabyeu
* @see <a href="https://code.google.com/p/google-gson/">GSON</a>
*/
public class GsonSerializer extends AbstractJsonSerializer {
private final Gson gson;
/**
* Creates serializer with provided GSON
*
* @param gson Gson object
*/
public GsonSerializer(Gson gson) {
this.gson = gson;
}
/**
* Creates serializer with default GSON
*/
public GsonSerializer() {
this(new Gson());
}
@Override
public <T> byte[] serialize(T t) throws SerializerException {
try {
return gson.toJson(t).getBytes(Charsets.UTF_8.name());
} catch (UnsupportedEncodingException e) {
throw new SerializerException("UTF-8 is not supported", e);
}
}
@Override
public <T> T deserialize(byte[] content, Class<T> clazz) throws SerializerException {
BufferedReader is = null;
try {
is = ByteSource.wrap(content).asCharSource(Charsets.UTF_8).openBufferedStream();
return gson.fromJson(is, clazz);
} catch (IOException e) {
throw new SerializerException("Unable to serialize content", e);
} finally { | IOUtils.closeQuietly(is); |
avarabyeu/restendpoint | src/test/java/com/github/avarabyeu/restendpoint/http/RestEndpointUrlBuilderTest.java | // Path: src/main/java/com/github/avarabyeu/restendpoint/http/exception/RestEndpointIOException.java
// public class RestEndpointIOException extends RuntimeException {
//
// private static final long serialVersionUID = -5339772980222891685L;
//
// public RestEndpointIOException(String message, Throwable e) {
// super(message, e);
// }
//
// public RestEndpointIOException(String message) {
// super(message);
// }
//
// }
| import com.github.avarabyeu.restendpoint.http.exception.RestEndpointIOException;
import com.google.common.collect.ImmutableMap;
import com.smarttested.qa.smartassert.SmartAssert;
import org.hamcrest.CoreMatchers;
import org.junit.Test;
import java.net.URI; | package com.github.avarabyeu.restendpoint.http;
/**
* @author Andrei Varabyeu
*/
public class RestEndpointUrlBuilderTest {
@Test | // Path: src/main/java/com/github/avarabyeu/restendpoint/http/exception/RestEndpointIOException.java
// public class RestEndpointIOException extends RuntimeException {
//
// private static final long serialVersionUID = -5339772980222891685L;
//
// public RestEndpointIOException(String message, Throwable e) {
// super(message, e);
// }
//
// public RestEndpointIOException(String message) {
// super(message);
// }
//
// }
// Path: src/test/java/com/github/avarabyeu/restendpoint/http/RestEndpointUrlBuilderTest.java
import com.github.avarabyeu.restendpoint.http.exception.RestEndpointIOException;
import com.google.common.collect.ImmutableMap;
import com.smarttested.qa.smartassert.SmartAssert;
import org.hamcrest.CoreMatchers;
import org.junit.Test;
import java.net.URI;
package com.github.avarabyeu.restendpoint.http;
/**
* @author Andrei Varabyeu
*/
public class RestEndpointUrlBuilderTest {
@Test | public void testWithPathInBaseUrl() throws RestEndpointIOException { |
avarabyeu/restendpoint | src/test/java/com/github/avarabyeu/restendpoint/http/proxy/RestMethodInfoTest.java | // Path: src/main/java/com/github/avarabyeu/restendpoint/http/proxy/RestMethodInfo.java
// static boolean isAsynchronous(Invokable<?, ?> method) {
// return Maybe.class.isAssignableFrom(method.getReturnType().getRawType());
// }
| import com.google.common.reflect.Invokable;
import com.smarttested.qa.smartassert.SmartAssert;
import com.smarttested.qa.smartassert.junit.SoftAssertVerifier;
import io.reactivex.Maybe;
import org.junit.Rule;
import org.junit.Test;
import static com.github.avarabyeu.restendpoint.http.proxy.RestMethodInfo.isAsynchronous;
import static org.hamcrest.CoreMatchers.is; | /*
* Copyright (C) 2014 Andrei Varabyeu
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.github.avarabyeu.restendpoint.http.proxy;
/**
* @author Andrei Varabyeu
*/
public class RestMethodInfoTest {
@Rule
public SoftAssertVerifier verifier = SoftAssertVerifier.instance();
@Test
public void testSynchronousParser() throws NoSuchMethodException {
Invokable<?, Object> testSyncronousMethod = Invokable.from(this.getClass().getDeclaredMethod("testSyncronousMethod"));
Invokable<?, Object> testAsyncronousMethod = Invokable.from(this.getClass().getDeclaredMethod("testAsyncronousMethod"));
Invokable<?, Object> testVoidMethod = Invokable.from(this.getClass().getDeclaredMethod("testVoidMethod")); | // Path: src/main/java/com/github/avarabyeu/restendpoint/http/proxy/RestMethodInfo.java
// static boolean isAsynchronous(Invokable<?, ?> method) {
// return Maybe.class.isAssignableFrom(method.getReturnType().getRawType());
// }
// Path: src/test/java/com/github/avarabyeu/restendpoint/http/proxy/RestMethodInfoTest.java
import com.google.common.reflect.Invokable;
import com.smarttested.qa.smartassert.SmartAssert;
import com.smarttested.qa.smartassert.junit.SoftAssertVerifier;
import io.reactivex.Maybe;
import org.junit.Rule;
import org.junit.Test;
import static com.github.avarabyeu.restendpoint.http.proxy.RestMethodInfo.isAsynchronous;
import static org.hamcrest.CoreMatchers.is;
/*
* Copyright (C) 2014 Andrei Varabyeu
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.github.avarabyeu.restendpoint.http.proxy;
/**
* @author Andrei Varabyeu
*/
public class RestMethodInfoTest {
@Rule
public SoftAssertVerifier verifier = SoftAssertVerifier.instance();
@Test
public void testSynchronousParser() throws NoSuchMethodException {
Invokable<?, Object> testSyncronousMethod = Invokable.from(this.getClass().getDeclaredMethod("testSyncronousMethod"));
Invokable<?, Object> testAsyncronousMethod = Invokable.from(this.getClass().getDeclaredMethod("testAsyncronousMethod"));
Invokable<?, Object> testVoidMethod = Invokable.from(this.getClass().getDeclaredMethod("testVoidMethod")); | System.out.println(isAsynchronous(testSyncronousMethod)); |
avarabyeu/restendpoint | src/test/java/com/github/avarabyeu/restendpoint/serializer/StringSerializerTest.java | // Path: src/main/java/com/github/avarabyeu/restendpoint/http/exception/SerializerException.java
// public class SerializerException extends RestEndpointIOException {
//
// private static final long serialVersionUID = 1L;
//
// public SerializerException(String message) {
// super(message);
// }
//
// public SerializerException(String message, Throwable e) {
// super(message, e);
// }
// }
| import com.github.avarabyeu.restendpoint.http.exception.SerializerException;
import com.google.common.net.MediaType;
import com.smarttested.qa.smartassert.SmartAssert;
import org.hamcrest.CoreMatchers;
import org.junit.Test; | /*
* Copyright (C) 2014 Andrei Varabyeu
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.github.avarabyeu.restendpoint.serializer;
/**
* @author Andrey Vorobyov
*/
public class StringSerializerTest {
public static final String TEST_STRING = "test";
private StringSerializer serializer = new StringSerializer();
@Test | // Path: src/main/java/com/github/avarabyeu/restendpoint/http/exception/SerializerException.java
// public class SerializerException extends RestEndpointIOException {
//
// private static final long serialVersionUID = 1L;
//
// public SerializerException(String message) {
// super(message);
// }
//
// public SerializerException(String message, Throwable e) {
// super(message, e);
// }
// }
// Path: src/test/java/com/github/avarabyeu/restendpoint/serializer/StringSerializerTest.java
import com.github.avarabyeu.restendpoint.http.exception.SerializerException;
import com.google.common.net.MediaType;
import com.smarttested.qa.smartassert.SmartAssert;
import org.hamcrest.CoreMatchers;
import org.junit.Test;
/*
* Copyright (C) 2014 Andrei Varabyeu
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.github.avarabyeu.restendpoint.serializer;
/**
* @author Andrey Vorobyov
*/
public class StringSerializerTest {
public static final String TEST_STRING = "test";
private StringSerializer serializer = new StringSerializer();
@Test | public void testSerialize() throws SerializerException { |
avarabyeu/restendpoint | src/main/java/com/github/avarabyeu/restendpoint/http/exception/RestEndpointException.java | // Path: src/main/java/com/github/avarabyeu/restendpoint/http/HttpMethod.java
// public enum HttpMethod {
// GET(false),
// POST(true),
// PUT(true),
// PATCH(true),
// DELETE(false);
//
// private final boolean hasBody;
//
// /**
// * @param hasBody Whether method contains body
// */
// HttpMethod(boolean hasBody) {
// this.hasBody = hasBody;
// }
//
// /**
// * @return TRUE if method contains body
// */
// boolean hasBody() {
// return hasBody;
// }
// }
| import com.github.avarabyeu.restendpoint.http.HttpMethod;
import com.google.common.io.ByteSource;
import java.net.URI; | /*
* Copyright (C) 2014 Andrei Varabyeu
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.github.avarabyeu.restendpoint.http.exception;
/**
* Base HTTP error representation
*
* @author Andrei Varabyeu
*/
public class RestEndpointException extends RuntimeException {
private static final long serialVersionUID = 728718628763519460L;
/**
* Request URI
*/
private final URI requestUri;
/**
* Request Method
*/ | // Path: src/main/java/com/github/avarabyeu/restendpoint/http/HttpMethod.java
// public enum HttpMethod {
// GET(false),
// POST(true),
// PUT(true),
// PATCH(true),
// DELETE(false);
//
// private final boolean hasBody;
//
// /**
// * @param hasBody Whether method contains body
// */
// HttpMethod(boolean hasBody) {
// this.hasBody = hasBody;
// }
//
// /**
// * @return TRUE if method contains body
// */
// boolean hasBody() {
// return hasBody;
// }
// }
// Path: src/main/java/com/github/avarabyeu/restendpoint/http/exception/RestEndpointException.java
import com.github.avarabyeu.restendpoint.http.HttpMethod;
import com.google.common.io.ByteSource;
import java.net.URI;
/*
* Copyright (C) 2014 Andrei Varabyeu
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.github.avarabyeu.restendpoint.http.exception;
/**
* Base HTTP error representation
*
* @author Andrei Varabyeu
*/
public class RestEndpointException extends RuntimeException {
private static final long serialVersionUID = 728718628763519460L;
/**
* Request URI
*/
private final URI requestUri;
/**
* Request Method
*/ | private final HttpMethod requestMethod; |
avarabyeu/restendpoint | src/test/java/com/github/avarabyeu/restendpoint/serializer/ByteArraySerializerTest.java | // Path: src/main/java/com/github/avarabyeu/restendpoint/http/exception/SerializerException.java
// public class SerializerException extends RestEndpointIOException {
//
// private static final long serialVersionUID = 1L;
//
// public SerializerException(String message) {
// super(message);
// }
//
// public SerializerException(String message, Throwable e) {
// super(message, e);
// }
// }
| import com.github.avarabyeu.restendpoint.http.exception.SerializerException;
import com.google.common.net.MediaType;
import com.google.common.reflect.TypeToken;
import com.smarttested.qa.smartassert.SmartAssert;
import org.hamcrest.CoreMatchers;
import org.junit.Test; | /*
* Copyright (C) 2014 Andrei Varabyeu
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.github.avarabyeu.restendpoint.serializer;
/**
* @author Andrei Varabyeu
*/
public class ByteArraySerializerTest {
private static final String TEST_STRING = "test";
private static final ByteArraySerializer serializer = new ByteArraySerializer();
@Test | // Path: src/main/java/com/github/avarabyeu/restendpoint/http/exception/SerializerException.java
// public class SerializerException extends RestEndpointIOException {
//
// private static final long serialVersionUID = 1L;
//
// public SerializerException(String message) {
// super(message);
// }
//
// public SerializerException(String message, Throwable e) {
// super(message, e);
// }
// }
// Path: src/test/java/com/github/avarabyeu/restendpoint/serializer/ByteArraySerializerTest.java
import com.github.avarabyeu.restendpoint.http.exception.SerializerException;
import com.google.common.net.MediaType;
import com.google.common.reflect.TypeToken;
import com.smarttested.qa.smartassert.SmartAssert;
import org.hamcrest.CoreMatchers;
import org.junit.Test;
/*
* Copyright (C) 2014 Andrei Varabyeu
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.github.avarabyeu.restendpoint.serializer;
/**
* @author Andrei Varabyeu
*/
public class ByteArraySerializerTest {
private static final String TEST_STRING = "test";
private static final ByteArraySerializer serializer = new ByteArraySerializer();
@Test | public void testSerialize() throws SerializerException { |
mbredel/distributed-systems | mqtt/publisher/src/main/java/de/hda/fbi/ds/mbredel/mqtt/Publisher.java | // Path: udp-socket/socket-client/sources/src/main/java/de/hda/fbi/ds/mbredel/configuration/CliParameters.java
// public class CliParameters {
//
// /** The one and only instance of CLI parameters. */
// private static CliParameters instance;
//
// /** The port of the UDP socket server. Initially set to the default port. */
// private int port = Defaults.PORT;
// /** The message that is published. */
// private String message = Defaults.MESSAGE;
// /** The destination host to connect to. */
// private String destination = Defaults.DST_HOST;
//
// /**
// * The static getter for the CLI parameters instance.
// *
// * @return The CLI parameters instance.
// */
// public static CliParameters getInstance() {
// if (instance == null)
// instance = new CliParameters();
// return instance;
// }
//
// //
// // Getter and Setter
// //
//
// public int getPort() {
// return this.port;
// }
//
// public void setPort(String port) {
// this.port = Integer.parseInt(port);
// }
//
// public String getMessage() {
// return this.message;
// }
//
// public void setMessage(List<String> args) {
// StringBuilder sb = new StringBuilder();
// for (String arg: args) {
// sb.append(arg);
// sb.append(" ");
// }
// this.message = sb.toString().trim();
// }
//
// public String getDestination() {
// return this.destination;
// }
//
// public void setDestination(String destination) {
// this.destination = destination;
// }
//
// /**
// * A private constructor to avoid
// * instantiation.
// */
// private CliParameters() {}
// }
//
// Path: mqtt/subscriber/src/main/java/de/hda/fbi/ds/mbredel/configuration/Constants.java
// public abstract class Constants {
//
// /** The exit code if the procedure succeeded. */
// public static final int EXIT_CODE_SUCCESS = 0;
// /** The exit code of the procedure failed. */
// public static final int EXIT_CODE_ERROR = 1;
//
// }
| import de.hda.fbi.ds.mbredel.configuration.CliParameters;
import de.hda.fbi.ds.mbredel.configuration.Constants;
import org.eclipse.paho.client.mqttv3.MqttClient;
import org.eclipse.paho.client.mqttv3.MqttConnectOptions;
import org.eclipse.paho.client.mqttv3.MqttException;
import org.eclipse.paho.client.mqttv3.MqttMessage;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory; | /*
Copyright (c) 2017, Michael Bredel, H-DA
ALL RIGHTS RESERVED.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
Neither the name of the H-DA and Michael Bredel
nor the names of its contributors may be used to endorse or promote
products derived from this software without specific prior written
permission.
*/
package de.hda.fbi.ds.mbredel.mqtt;
/**
* The MQTT publisher that connects to a
* broker and publishes messages on a
* specific topic.
*
* @author Michael Bredel
*/
public class Publisher {
/** The logger. */
private static final Logger LOGGER = LoggerFactory.getLogger(Publisher.class);
/** The global CLI parameters that have been parsed in Main. */
private CliParameters cliParameters;
/** The broker URL. */
private String broker;
/**
* Default constructor that initializes
* various class attributes.
*/
public Publisher() {
// Get the CLI parameters.
cliParameters = CliParameters.getInstance();
// Create the broker string from command line arguments.
broker =
cliParameters.getBrokerProtocol() + "://" +
cliParameters.getBrokerAddress() + ":" +
cliParameters.getBrokerPort();
}
/**
* Runs the MQTT client and publishes a message.
*/
public void run() {
// Create some MQTT connection options.
MqttConnectOptions mqttConnectOpts = new MqttConnectOptions();
mqttConnectOpts.setCleanSession(true);
try {
MqttClient client = new MqttClient(broker, MqttClient.generateClientId());
// Connect to the MQTT broker using the connection options.
client.connect(mqttConnectOpts);
LOGGER.info("Connected to MQTT broker: " + client.getServerURI());
// Create the message and set a quality-of-service parameter.
MqttMessage message = new MqttMessage(cliParameters.getMessage().getBytes()); | // Path: udp-socket/socket-client/sources/src/main/java/de/hda/fbi/ds/mbredel/configuration/CliParameters.java
// public class CliParameters {
//
// /** The one and only instance of CLI parameters. */
// private static CliParameters instance;
//
// /** The port of the UDP socket server. Initially set to the default port. */
// private int port = Defaults.PORT;
// /** The message that is published. */
// private String message = Defaults.MESSAGE;
// /** The destination host to connect to. */
// private String destination = Defaults.DST_HOST;
//
// /**
// * The static getter for the CLI parameters instance.
// *
// * @return The CLI parameters instance.
// */
// public static CliParameters getInstance() {
// if (instance == null)
// instance = new CliParameters();
// return instance;
// }
//
// //
// // Getter and Setter
// //
//
// public int getPort() {
// return this.port;
// }
//
// public void setPort(String port) {
// this.port = Integer.parseInt(port);
// }
//
// public String getMessage() {
// return this.message;
// }
//
// public void setMessage(List<String> args) {
// StringBuilder sb = new StringBuilder();
// for (String arg: args) {
// sb.append(arg);
// sb.append(" ");
// }
// this.message = sb.toString().trim();
// }
//
// public String getDestination() {
// return this.destination;
// }
//
// public void setDestination(String destination) {
// this.destination = destination;
// }
//
// /**
// * A private constructor to avoid
// * instantiation.
// */
// private CliParameters() {}
// }
//
// Path: mqtt/subscriber/src/main/java/de/hda/fbi/ds/mbredel/configuration/Constants.java
// public abstract class Constants {
//
// /** The exit code if the procedure succeeded. */
// public static final int EXIT_CODE_SUCCESS = 0;
// /** The exit code of the procedure failed. */
// public static final int EXIT_CODE_ERROR = 1;
//
// }
// Path: mqtt/publisher/src/main/java/de/hda/fbi/ds/mbredel/mqtt/Publisher.java
import de.hda.fbi.ds.mbredel.configuration.CliParameters;
import de.hda.fbi.ds.mbredel.configuration.Constants;
import org.eclipse.paho.client.mqttv3.MqttClient;
import org.eclipse.paho.client.mqttv3.MqttConnectOptions;
import org.eclipse.paho.client.mqttv3.MqttException;
import org.eclipse.paho.client.mqttv3.MqttMessage;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
/*
Copyright (c) 2017, Michael Bredel, H-DA
ALL RIGHTS RESERVED.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
Neither the name of the H-DA and Michael Bredel
nor the names of its contributors may be used to endorse or promote
products derived from this software without specific prior written
permission.
*/
package de.hda.fbi.ds.mbredel.mqtt;
/**
* The MQTT publisher that connects to a
* broker and publishes messages on a
* specific topic.
*
* @author Michael Bredel
*/
public class Publisher {
/** The logger. */
private static final Logger LOGGER = LoggerFactory.getLogger(Publisher.class);
/** The global CLI parameters that have been parsed in Main. */
private CliParameters cliParameters;
/** The broker URL. */
private String broker;
/**
* Default constructor that initializes
* various class attributes.
*/
public Publisher() {
// Get the CLI parameters.
cliParameters = CliParameters.getInstance();
// Create the broker string from command line arguments.
broker =
cliParameters.getBrokerProtocol() + "://" +
cliParameters.getBrokerAddress() + ":" +
cliParameters.getBrokerPort();
}
/**
* Runs the MQTT client and publishes a message.
*/
public void run() {
// Create some MQTT connection options.
MqttConnectOptions mqttConnectOpts = new MqttConnectOptions();
mqttConnectOpts.setCleanSession(true);
try {
MqttClient client = new MqttClient(broker, MqttClient.generateClientId());
// Connect to the MQTT broker using the connection options.
client.connect(mqttConnectOpts);
LOGGER.info("Connected to MQTT broker: " + client.getServerURI());
// Create the message and set a quality-of-service parameter.
MqttMessage message = new MqttMessage(cliParameters.getMessage().getBytes()); | message.setQos(Constants.QOS_EXACTLY_ONCE); |
mbredel/distributed-systems | rest/java/src/main/java/de/hda/fbi/ds/mbredel/configuration/cfg4j/Cfg4jConfiguration.java | // Path: udp-socket/socket-client/sources/src/main/java/de/hda/fbi/ds/mbredel/configuration/CliParameters.java
// public class CliParameters {
//
// /** The one and only instance of CLI parameters. */
// private static CliParameters instance;
//
// /** The port of the UDP socket server. Initially set to the default port. */
// private int port = Defaults.PORT;
// /** The message that is published. */
// private String message = Defaults.MESSAGE;
// /** The destination host to connect to. */
// private String destination = Defaults.DST_HOST;
//
// /**
// * The static getter for the CLI parameters instance.
// *
// * @return The CLI parameters instance.
// */
// public static CliParameters getInstance() {
// if (instance == null)
// instance = new CliParameters();
// return instance;
// }
//
// //
// // Getter and Setter
// //
//
// public int getPort() {
// return this.port;
// }
//
// public void setPort(String port) {
// this.port = Integer.parseInt(port);
// }
//
// public String getMessage() {
// return this.message;
// }
//
// public void setMessage(List<String> args) {
// StringBuilder sb = new StringBuilder();
// for (String arg: args) {
// sb.append(arg);
// sb.append(" ");
// }
// this.message = sb.toString().trim();
// }
//
// public String getDestination() {
// return this.destination;
// }
//
// public void setDestination(String destination) {
// this.destination = destination;
// }
//
// /**
// * A private constructor to avoid
// * instantiation.
// */
// private CliParameters() {}
// }
//
// Path: rest/java/src/main/java/de/hda/fbi/ds/mbredel/configuration/ConfigurationService.java
// public interface ConfigurationService {
// /**
// * Get a configuration property of a given basic {@code type}.
// *
// * @param key The configuration key.
// * @param <T> The property type.
// * @throws NoSuchElementException When the provided {@code key} doesn't have a corresponding config value
// * @throws IllegalArgumentException When property can't be converted to {@code type}
// * @throws IllegalStateException When provider is unable to fetch configuration value for the given {@code key}
// */
// @Nullable
// <T> T getProperty(String key, Class<T> type);
//
// /**
// * Get a configuration property of a given basic {@code type}.
// *
// * @param key The configuration key.
// * @param defaultValue The default value. Has to be the same type as property type.
// * @param <T> The property type.
// * @throws IllegalArgumentException When property can't be converted to {@code type}
// */
// @Nonnull
// <T> T getProperty(String key, Object defaultValue, Class<T> type);
// }
//
// Path: rest/java/src/main/java/de/hda/fbi/ds/mbredel/core/Constants.java
// public class Constants {
// /** The exit code if the procedure succeeded. */
// public static final int EXIT_CODE_SUCCESS = 0;
// /** The exit code of the procedure failed. */
// public static final int EXIT_CODE_ERROR = 1;
//
// /** The HTTP port to listen to. */
// public static final int HTTP_PORT = 4567;
//
// /**
// * A private constructor to avoid
// * instantiation.
// */
// private Constants() {}
// }
| import org.cfg4j.source.files.FilesConfigurationSource;
import javax.annotation.Nonnull;
import javax.annotation.Nullable;
import javax.inject.Singleton;
import java.net.URI;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.Collections;
import java.util.NoSuchElementException;
import de.hda.fbi.ds.mbredel.configuration.CliParameters;
import de.hda.fbi.ds.mbredel.configuration.ConfigurationService;
import de.hda.fbi.ds.mbredel.core.Constants;
import org.cfg4j.provider.ConfigurationProvider;
import org.cfg4j.provider.ConfigurationProviderBuilder;
import org.cfg4j.source.ConfigurationSource;
import org.cfg4j.source.context.environment.Environment;
import org.cfg4j.source.context.environment.ImmutableEnvironment;
import org.cfg4j.source.context.filesprovider.ConfigFilesProvider; | /*
Copyright (c) 2017, Michael Bredel, H-DA
ALL RIGHTS RESERVED.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
Neither the name of the H-DA and Michael Bredel
nor the names of its contributors may be used to endorse or promote
products derived from this software without specific prior written
permission.
*/
package de.hda.fbi.ds.mbredel.configuration.cfg4j;
/**
* An implementation of the configuration service interface
* based on cfg4j.
*
* @author Michael Bredel
*/
@Singleton
public class Cfg4jConfiguration implements ConfigurationService {
/** The path to the default configuration file. */
private static final String DEFAULT_CONFIG_FILE = "./src/main/resources/config.yaml";
/** The configuration provider. */
private ConfigurationProvider configurationProvider;
/**
* Default constructor used by Guice.
*/
public Cfg4jConfiguration() {
URI uri;
try { | // Path: udp-socket/socket-client/sources/src/main/java/de/hda/fbi/ds/mbredel/configuration/CliParameters.java
// public class CliParameters {
//
// /** The one and only instance of CLI parameters. */
// private static CliParameters instance;
//
// /** The port of the UDP socket server. Initially set to the default port. */
// private int port = Defaults.PORT;
// /** The message that is published. */
// private String message = Defaults.MESSAGE;
// /** The destination host to connect to. */
// private String destination = Defaults.DST_HOST;
//
// /**
// * The static getter for the CLI parameters instance.
// *
// * @return The CLI parameters instance.
// */
// public static CliParameters getInstance() {
// if (instance == null)
// instance = new CliParameters();
// return instance;
// }
//
// //
// // Getter and Setter
// //
//
// public int getPort() {
// return this.port;
// }
//
// public void setPort(String port) {
// this.port = Integer.parseInt(port);
// }
//
// public String getMessage() {
// return this.message;
// }
//
// public void setMessage(List<String> args) {
// StringBuilder sb = new StringBuilder();
// for (String arg: args) {
// sb.append(arg);
// sb.append(" ");
// }
// this.message = sb.toString().trim();
// }
//
// public String getDestination() {
// return this.destination;
// }
//
// public void setDestination(String destination) {
// this.destination = destination;
// }
//
// /**
// * A private constructor to avoid
// * instantiation.
// */
// private CliParameters() {}
// }
//
// Path: rest/java/src/main/java/de/hda/fbi/ds/mbredel/configuration/ConfigurationService.java
// public interface ConfigurationService {
// /**
// * Get a configuration property of a given basic {@code type}.
// *
// * @param key The configuration key.
// * @param <T> The property type.
// * @throws NoSuchElementException When the provided {@code key} doesn't have a corresponding config value
// * @throws IllegalArgumentException When property can't be converted to {@code type}
// * @throws IllegalStateException When provider is unable to fetch configuration value for the given {@code key}
// */
// @Nullable
// <T> T getProperty(String key, Class<T> type);
//
// /**
// * Get a configuration property of a given basic {@code type}.
// *
// * @param key The configuration key.
// * @param defaultValue The default value. Has to be the same type as property type.
// * @param <T> The property type.
// * @throws IllegalArgumentException When property can't be converted to {@code type}
// */
// @Nonnull
// <T> T getProperty(String key, Object defaultValue, Class<T> type);
// }
//
// Path: rest/java/src/main/java/de/hda/fbi/ds/mbredel/core/Constants.java
// public class Constants {
// /** The exit code if the procedure succeeded. */
// public static final int EXIT_CODE_SUCCESS = 0;
// /** The exit code of the procedure failed. */
// public static final int EXIT_CODE_ERROR = 1;
//
// /** The HTTP port to listen to. */
// public static final int HTTP_PORT = 4567;
//
// /**
// * A private constructor to avoid
// * instantiation.
// */
// private Constants() {}
// }
// Path: rest/java/src/main/java/de/hda/fbi/ds/mbredel/configuration/cfg4j/Cfg4jConfiguration.java
import org.cfg4j.source.files.FilesConfigurationSource;
import javax.annotation.Nonnull;
import javax.annotation.Nullable;
import javax.inject.Singleton;
import java.net.URI;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.Collections;
import java.util.NoSuchElementException;
import de.hda.fbi.ds.mbredel.configuration.CliParameters;
import de.hda.fbi.ds.mbredel.configuration.ConfigurationService;
import de.hda.fbi.ds.mbredel.core.Constants;
import org.cfg4j.provider.ConfigurationProvider;
import org.cfg4j.provider.ConfigurationProviderBuilder;
import org.cfg4j.source.ConfigurationSource;
import org.cfg4j.source.context.environment.Environment;
import org.cfg4j.source.context.environment.ImmutableEnvironment;
import org.cfg4j.source.context.filesprovider.ConfigFilesProvider;
/*
Copyright (c) 2017, Michael Bredel, H-DA
ALL RIGHTS RESERVED.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
Neither the name of the H-DA and Michael Bredel
nor the names of its contributors may be used to endorse or promote
products derived from this software without specific prior written
permission.
*/
package de.hda.fbi.ds.mbredel.configuration.cfg4j;
/**
* An implementation of the configuration service interface
* based on cfg4j.
*
* @author Michael Bredel
*/
@Singleton
public class Cfg4jConfiguration implements ConfigurationService {
/** The path to the default configuration file. */
private static final String DEFAULT_CONFIG_FILE = "./src/main/resources/config.yaml";
/** The configuration provider. */
private ConfigurationProvider configurationProvider;
/**
* Default constructor used by Guice.
*/
public Cfg4jConfiguration() {
URI uri;
try { | uri = URI.create(CliParameters.getInstance().getUri()); |
mbredel/distributed-systems | rest/java/src/main/java/de/hda/fbi/ds/mbredel/configuration/cfg4j/Cfg4jConfiguration.java | // Path: udp-socket/socket-client/sources/src/main/java/de/hda/fbi/ds/mbredel/configuration/CliParameters.java
// public class CliParameters {
//
// /** The one and only instance of CLI parameters. */
// private static CliParameters instance;
//
// /** The port of the UDP socket server. Initially set to the default port. */
// private int port = Defaults.PORT;
// /** The message that is published. */
// private String message = Defaults.MESSAGE;
// /** The destination host to connect to. */
// private String destination = Defaults.DST_HOST;
//
// /**
// * The static getter for the CLI parameters instance.
// *
// * @return The CLI parameters instance.
// */
// public static CliParameters getInstance() {
// if (instance == null)
// instance = new CliParameters();
// return instance;
// }
//
// //
// // Getter and Setter
// //
//
// public int getPort() {
// return this.port;
// }
//
// public void setPort(String port) {
// this.port = Integer.parseInt(port);
// }
//
// public String getMessage() {
// return this.message;
// }
//
// public void setMessage(List<String> args) {
// StringBuilder sb = new StringBuilder();
// for (String arg: args) {
// sb.append(arg);
// sb.append(" ");
// }
// this.message = sb.toString().trim();
// }
//
// public String getDestination() {
// return this.destination;
// }
//
// public void setDestination(String destination) {
// this.destination = destination;
// }
//
// /**
// * A private constructor to avoid
// * instantiation.
// */
// private CliParameters() {}
// }
//
// Path: rest/java/src/main/java/de/hda/fbi/ds/mbredel/configuration/ConfigurationService.java
// public interface ConfigurationService {
// /**
// * Get a configuration property of a given basic {@code type}.
// *
// * @param key The configuration key.
// * @param <T> The property type.
// * @throws NoSuchElementException When the provided {@code key} doesn't have a corresponding config value
// * @throws IllegalArgumentException When property can't be converted to {@code type}
// * @throws IllegalStateException When provider is unable to fetch configuration value for the given {@code key}
// */
// @Nullable
// <T> T getProperty(String key, Class<T> type);
//
// /**
// * Get a configuration property of a given basic {@code type}.
// *
// * @param key The configuration key.
// * @param defaultValue The default value. Has to be the same type as property type.
// * @param <T> The property type.
// * @throws IllegalArgumentException When property can't be converted to {@code type}
// */
// @Nonnull
// <T> T getProperty(String key, Object defaultValue, Class<T> type);
// }
//
// Path: rest/java/src/main/java/de/hda/fbi/ds/mbredel/core/Constants.java
// public class Constants {
// /** The exit code if the procedure succeeded. */
// public static final int EXIT_CODE_SUCCESS = 0;
// /** The exit code of the procedure failed. */
// public static final int EXIT_CODE_ERROR = 1;
//
// /** The HTTP port to listen to. */
// public static final int HTTP_PORT = 4567;
//
// /**
// * A private constructor to avoid
// * instantiation.
// */
// private Constants() {}
// }
| import org.cfg4j.source.files.FilesConfigurationSource;
import javax.annotation.Nonnull;
import javax.annotation.Nullable;
import javax.inject.Singleton;
import java.net.URI;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.Collections;
import java.util.NoSuchElementException;
import de.hda.fbi.ds.mbredel.configuration.CliParameters;
import de.hda.fbi.ds.mbredel.configuration.ConfigurationService;
import de.hda.fbi.ds.mbredel.core.Constants;
import org.cfg4j.provider.ConfigurationProvider;
import org.cfg4j.provider.ConfigurationProviderBuilder;
import org.cfg4j.source.ConfigurationSource;
import org.cfg4j.source.context.environment.Environment;
import org.cfg4j.source.context.environment.ImmutableEnvironment;
import org.cfg4j.source.context.filesprovider.ConfigFilesProvider; | }
/**
* Sets up the a remote configuration.
*
* @param uri The URI to the configuration file.
*/
private void setupRemoteConfig(URI uri) {
throw new UnsupportedOperationException();
}
/**
* Sets up the file-based configuration.
*
* @param uri The URI to the configuration file.
*/
private void setupFileConfig(URI uri) {
Path path = Paths.get(uri.getPath());
if (path.toFile().exists() && path.toFile().isFile()) {
String configFile = path.getFileName().toString();
String configPath = path.getParent().toString();
Environment environment = new ImmutableEnvironment(configPath);
ConfigFilesProvider configFilesProvider = () -> Collections.singletonList(Paths.get(configFile));
ConfigurationSource configurationSource = new FilesConfigurationSource(configFilesProvider);
this.configurationProvider = new ConfigurationProviderBuilder()
.withEnvironment(environment)
.withConfigurationSource(configurationSource)
.build();
} else {
System.err.println("Could not find configuration file: " + path); | // Path: udp-socket/socket-client/sources/src/main/java/de/hda/fbi/ds/mbredel/configuration/CliParameters.java
// public class CliParameters {
//
// /** The one and only instance of CLI parameters. */
// private static CliParameters instance;
//
// /** The port of the UDP socket server. Initially set to the default port. */
// private int port = Defaults.PORT;
// /** The message that is published. */
// private String message = Defaults.MESSAGE;
// /** The destination host to connect to. */
// private String destination = Defaults.DST_HOST;
//
// /**
// * The static getter for the CLI parameters instance.
// *
// * @return The CLI parameters instance.
// */
// public static CliParameters getInstance() {
// if (instance == null)
// instance = new CliParameters();
// return instance;
// }
//
// //
// // Getter and Setter
// //
//
// public int getPort() {
// return this.port;
// }
//
// public void setPort(String port) {
// this.port = Integer.parseInt(port);
// }
//
// public String getMessage() {
// return this.message;
// }
//
// public void setMessage(List<String> args) {
// StringBuilder sb = new StringBuilder();
// for (String arg: args) {
// sb.append(arg);
// sb.append(" ");
// }
// this.message = sb.toString().trim();
// }
//
// public String getDestination() {
// return this.destination;
// }
//
// public void setDestination(String destination) {
// this.destination = destination;
// }
//
// /**
// * A private constructor to avoid
// * instantiation.
// */
// private CliParameters() {}
// }
//
// Path: rest/java/src/main/java/de/hda/fbi/ds/mbredel/configuration/ConfigurationService.java
// public interface ConfigurationService {
// /**
// * Get a configuration property of a given basic {@code type}.
// *
// * @param key The configuration key.
// * @param <T> The property type.
// * @throws NoSuchElementException When the provided {@code key} doesn't have a corresponding config value
// * @throws IllegalArgumentException When property can't be converted to {@code type}
// * @throws IllegalStateException When provider is unable to fetch configuration value for the given {@code key}
// */
// @Nullable
// <T> T getProperty(String key, Class<T> type);
//
// /**
// * Get a configuration property of a given basic {@code type}.
// *
// * @param key The configuration key.
// * @param defaultValue The default value. Has to be the same type as property type.
// * @param <T> The property type.
// * @throws IllegalArgumentException When property can't be converted to {@code type}
// */
// @Nonnull
// <T> T getProperty(String key, Object defaultValue, Class<T> type);
// }
//
// Path: rest/java/src/main/java/de/hda/fbi/ds/mbredel/core/Constants.java
// public class Constants {
// /** The exit code if the procedure succeeded. */
// public static final int EXIT_CODE_SUCCESS = 0;
// /** The exit code of the procedure failed. */
// public static final int EXIT_CODE_ERROR = 1;
//
// /** The HTTP port to listen to. */
// public static final int HTTP_PORT = 4567;
//
// /**
// * A private constructor to avoid
// * instantiation.
// */
// private Constants() {}
// }
// Path: rest/java/src/main/java/de/hda/fbi/ds/mbredel/configuration/cfg4j/Cfg4jConfiguration.java
import org.cfg4j.source.files.FilesConfigurationSource;
import javax.annotation.Nonnull;
import javax.annotation.Nullable;
import javax.inject.Singleton;
import java.net.URI;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.Collections;
import java.util.NoSuchElementException;
import de.hda.fbi.ds.mbredel.configuration.CliParameters;
import de.hda.fbi.ds.mbredel.configuration.ConfigurationService;
import de.hda.fbi.ds.mbredel.core.Constants;
import org.cfg4j.provider.ConfigurationProvider;
import org.cfg4j.provider.ConfigurationProviderBuilder;
import org.cfg4j.source.ConfigurationSource;
import org.cfg4j.source.context.environment.Environment;
import org.cfg4j.source.context.environment.ImmutableEnvironment;
import org.cfg4j.source.context.filesprovider.ConfigFilesProvider;
}
/**
* Sets up the a remote configuration.
*
* @param uri The URI to the configuration file.
*/
private void setupRemoteConfig(URI uri) {
throw new UnsupportedOperationException();
}
/**
* Sets up the file-based configuration.
*
* @param uri The URI to the configuration file.
*/
private void setupFileConfig(URI uri) {
Path path = Paths.get(uri.getPath());
if (path.toFile().exists() && path.toFile().isFile()) {
String configFile = path.getFileName().toString();
String configPath = path.getParent().toString();
Environment environment = new ImmutableEnvironment(configPath);
ConfigFilesProvider configFilesProvider = () -> Collections.singletonList(Paths.get(configFile));
ConfigurationSource configurationSource = new FilesConfigurationSource(configFilesProvider);
this.configurationProvider = new ConfigurationProviderBuilder()
.withEnvironment(environment)
.withConfigurationSource(configurationSource)
.build();
} else {
System.err.println("Could not find configuration file: " + path); | System.exit(Constants.EXIT_CODE_ERROR); |
mbredel/distributed-systems | rest/java/src/main/java/de/hda/fbi/ds/mbredel/store/StoreService.java | // Path: rest/java/src/main/java/de/hda/fbi/ds/mbredel/model/User.java
// public class User {
// public String name;
// public String surname;
// public String username;
// public String password;
// }
| import de.hda.fbi.ds.mbredel.model.User;
import javax.annotation.Nonnull;
import javax.annotation.Nullable;
import javax.persistence.PersistenceException;
import java.util.Collection; | /*
Copyright (c) 2017, Michael Bredel, H-DA
ALL RIGHTS RESERVED.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
Neither the name of the H-DA and Michael Bredel
nor the names of its contributors may be used to endorse or promote
products derived from this software without specific prior written
permission.
*/
package de.hda.fbi.ds.mbredel.store;
/**
* Interface that must be implemented by the
* store module that actually stores the user
* to a persistent storage, such as disk.
*
* @author Michael Bredel
*/
public interface StoreService {
/**
* Extracts the uploaded file form the HTTP
* request and stores it using the filename.
*
* @param user The user object to store.
* @return The username as the primary key of the user object.
* @throws PersistenceException When the file cannot be stored.
* @throws IllegalArgumentException When at least one of the arguments is null.
*/
@Nonnull | // Path: rest/java/src/main/java/de/hda/fbi/ds/mbredel/model/User.java
// public class User {
// public String name;
// public String surname;
// public String username;
// public String password;
// }
// Path: rest/java/src/main/java/de/hda/fbi/ds/mbredel/store/StoreService.java
import de.hda.fbi.ds.mbredel.model.User;
import javax.annotation.Nonnull;
import javax.annotation.Nullable;
import javax.persistence.PersistenceException;
import java.util.Collection;
/*
Copyright (c) 2017, Michael Bredel, H-DA
ALL RIGHTS RESERVED.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
Neither the name of the H-DA and Michael Bredel
nor the names of its contributors may be used to endorse or promote
products derived from this software without specific prior written
permission.
*/
package de.hda.fbi.ds.mbredel.store;
/**
* Interface that must be implemented by the
* store module that actually stores the user
* to a persistent storage, such as disk.
*
* @author Michael Bredel
*/
public interface StoreService {
/**
* Extracts the uploaded file form the HTTP
* request and stores it using the filename.
*
* @param user The user object to store.
* @return The username as the primary key of the user object.
* @throws PersistenceException When the file cannot be stored.
* @throws IllegalArgumentException When at least one of the arguments is null.
*/
@Nonnull | String create(User user) throws PersistenceException, IllegalArgumentException; |
mbredel/distributed-systems | rest/java/src/main/java/de/hda/fbi/ds/mbredel/controller/UserController.java | // Path: rest/java/src/main/java/de/hda/fbi/ds/mbredel/configuration/ConfigurationService.java
// public interface ConfigurationService {
// /**
// * Get a configuration property of a given basic {@code type}.
// *
// * @param key The configuration key.
// * @param <T> The property type.
// * @throws NoSuchElementException When the provided {@code key} doesn't have a corresponding config value
// * @throws IllegalArgumentException When property can't be converted to {@code type}
// * @throws IllegalStateException When provider is unable to fetch configuration value for the given {@code key}
// */
// @Nullable
// <T> T getProperty(String key, Class<T> type);
//
// /**
// * Get a configuration property of a given basic {@code type}.
// *
// * @param key The configuration key.
// * @param defaultValue The default value. Has to be the same type as property type.
// * @param <T> The property type.
// * @throws IllegalArgumentException When property can't be converted to {@code type}
// */
// @Nonnull
// <T> T getProperty(String key, Object defaultValue, Class<T> type);
// }
//
// Path: rest/java/src/main/java/de/hda/fbi/ds/mbredel/model/User.java
// public class User {
// public String name;
// public String surname;
// public String username;
// public String password;
// }
//
// Path: rest/java/src/main/java/de/hda/fbi/ds/mbredel/store/StoreService.java
// public interface StoreService {
// /**
// * Extracts the uploaded file form the HTTP
// * request and stores it using the filename.
// *
// * @param user The user object to store.
// * @return The username as the primary key of the user object.
// * @throws PersistenceException When the file cannot be stored.
// * @throws IllegalArgumentException When at least one of the arguments is null.
// */
// @Nonnull
// String create(User user) throws PersistenceException, IllegalArgumentException;
//
// /**
// * Read and return a file by its file name.
// *
// * @param username The username that acts as primary key.
// * @return The user.
// * @throws IllegalArgumentException When the arguments is null.
// */
// @Nullable
// User read(String username) throws IllegalArgumentException;
//
// /**
// * Read and return all users stored in
// * the image store.
// *
// * @return A list of all users in the store. The list might be empty.
// */
// @Nonnull
// Collection<User> readAll();
//
// /**
// * Delete the file by its file name.
// *
// * @param username The username that acts as primary key.
// * @return The name of the file that has been deleted successfully.
// * @throws PersistenceException When the file cannot be deleted.
// * @throws IllegalArgumentException When the arguments is null.
// */
// @Nonnull
// User delete(String username) throws PersistenceException, IllegalArgumentException;
// }
| import javax.inject.Inject;
import java.io.IOException;
import static spark.Spark.halt;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import de.hda.fbi.ds.mbredel.configuration.ConfigurationService;
import de.hda.fbi.ds.mbredel.model.User;
import de.hda.fbi.ds.mbredel.store.StoreService;
import org.apache.http.HttpStatus;
import spark.Request;
import spark.Response; | /*
Copyright (c) 2017, Michael Bredel, H-DA
ALL RIGHTS RESERVED.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
Neither the name of the H-DA and Michael Bredel
nor the names of its contributors may be used to endorse or promote
products derived from this software without specific prior written
permission.
*/
package de.hda.fbi.ds.mbredel.controller;
/**
* @author Michael Bredel
*/
public class UserController {
/** The configuration service. */
@SuppressWarnings("unused")
private ConfigurationService configurationService;
/** The store service to store and retrieve users. */
private StoreService storeService;
/**
* The default constructor used by Guice. Since
* the constructor is package-private UserController
* objects can (and should) only be instantiated
* using the UserController factory.
*
* @param configurationService The configuration service injected by Guice.
* @param storeService The store service injected by Guice.
*/
@Inject
UserController(
ConfigurationService configurationService,
StoreService storeService
) {
this.configurationService = configurationService;
this.storeService = storeService;
}
/**
* Gets a list of user stored in the system.
*
* @param req The HTTP request information.
* @param res The HTTP response information.
* @return The HTTP status and, in case of success, the list of users.
*/
public String getUsers(Request req, Response res) {
String result = "[]";
ObjectMapper mapper = new ObjectMapper();
try {
result = mapper.writeValueAsString(this.storeService.readAll());
} catch (JsonProcessingException e) {
e.printStackTrace();
}
return result;
}
/**
* Gets a single user stored in the system.
*
* @param req The HTTP request information.
* @param res The HTTP response information.
* @return The HTTP status and, in case of success, the user.
*/
public String getUser(Request req, Response res) {
String username = req.params(":username"); | // Path: rest/java/src/main/java/de/hda/fbi/ds/mbredel/configuration/ConfigurationService.java
// public interface ConfigurationService {
// /**
// * Get a configuration property of a given basic {@code type}.
// *
// * @param key The configuration key.
// * @param <T> The property type.
// * @throws NoSuchElementException When the provided {@code key} doesn't have a corresponding config value
// * @throws IllegalArgumentException When property can't be converted to {@code type}
// * @throws IllegalStateException When provider is unable to fetch configuration value for the given {@code key}
// */
// @Nullable
// <T> T getProperty(String key, Class<T> type);
//
// /**
// * Get a configuration property of a given basic {@code type}.
// *
// * @param key The configuration key.
// * @param defaultValue The default value. Has to be the same type as property type.
// * @param <T> The property type.
// * @throws IllegalArgumentException When property can't be converted to {@code type}
// */
// @Nonnull
// <T> T getProperty(String key, Object defaultValue, Class<T> type);
// }
//
// Path: rest/java/src/main/java/de/hda/fbi/ds/mbredel/model/User.java
// public class User {
// public String name;
// public String surname;
// public String username;
// public String password;
// }
//
// Path: rest/java/src/main/java/de/hda/fbi/ds/mbredel/store/StoreService.java
// public interface StoreService {
// /**
// * Extracts the uploaded file form the HTTP
// * request and stores it using the filename.
// *
// * @param user The user object to store.
// * @return The username as the primary key of the user object.
// * @throws PersistenceException When the file cannot be stored.
// * @throws IllegalArgumentException When at least one of the arguments is null.
// */
// @Nonnull
// String create(User user) throws PersistenceException, IllegalArgumentException;
//
// /**
// * Read and return a file by its file name.
// *
// * @param username The username that acts as primary key.
// * @return The user.
// * @throws IllegalArgumentException When the arguments is null.
// */
// @Nullable
// User read(String username) throws IllegalArgumentException;
//
// /**
// * Read and return all users stored in
// * the image store.
// *
// * @return A list of all users in the store. The list might be empty.
// */
// @Nonnull
// Collection<User> readAll();
//
// /**
// * Delete the file by its file name.
// *
// * @param username The username that acts as primary key.
// * @return The name of the file that has been deleted successfully.
// * @throws PersistenceException When the file cannot be deleted.
// * @throws IllegalArgumentException When the arguments is null.
// */
// @Nonnull
// User delete(String username) throws PersistenceException, IllegalArgumentException;
// }
// Path: rest/java/src/main/java/de/hda/fbi/ds/mbredel/controller/UserController.java
import javax.inject.Inject;
import java.io.IOException;
import static spark.Spark.halt;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import de.hda.fbi.ds.mbredel.configuration.ConfigurationService;
import de.hda.fbi.ds.mbredel.model.User;
import de.hda.fbi.ds.mbredel.store.StoreService;
import org.apache.http.HttpStatus;
import spark.Request;
import spark.Response;
/*
Copyright (c) 2017, Michael Bredel, H-DA
ALL RIGHTS RESERVED.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
Neither the name of the H-DA and Michael Bredel
nor the names of its contributors may be used to endorse or promote
products derived from this software without specific prior written
permission.
*/
package de.hda.fbi.ds.mbredel.controller;
/**
* @author Michael Bredel
*/
public class UserController {
/** The configuration service. */
@SuppressWarnings("unused")
private ConfigurationService configurationService;
/** The store service to store and retrieve users. */
private StoreService storeService;
/**
* The default constructor used by Guice. Since
* the constructor is package-private UserController
* objects can (and should) only be instantiated
* using the UserController factory.
*
* @param configurationService The configuration service injected by Guice.
* @param storeService The store service injected by Guice.
*/
@Inject
UserController(
ConfigurationService configurationService,
StoreService storeService
) {
this.configurationService = configurationService;
this.storeService = storeService;
}
/**
* Gets a list of user stored in the system.
*
* @param req The HTTP request information.
* @param res The HTTP response information.
* @return The HTTP status and, in case of success, the list of users.
*/
public String getUsers(Request req, Response res) {
String result = "[]";
ObjectMapper mapper = new ObjectMapper();
try {
result = mapper.writeValueAsString(this.storeService.readAll());
} catch (JsonProcessingException e) {
e.printStackTrace();
}
return result;
}
/**
* Gets a single user stored in the system.
*
* @param req The HTTP request information.
* @param res The HTTP response information.
* @return The HTTP status and, in case of success, the user.
*/
public String getUser(Request req, Response res) {
String username = req.params(":username"); | User user = this.storeService.read(username); |
mbredel/distributed-systems | udp-socket/socket-server/sources/src/main/java/de/hda/fbi/ds/mbredel/Main.java | // Path: udp-socket/socket-client/sources/src/main/java/de/hda/fbi/ds/mbredel/configuration/CliProcessor.java
// public class CliProcessor {
//
// /** The logger. */
// private static final Logger LOGGER = LoggerFactory.getLogger(CliProcessor.class);
//
// /** The help message. */
// private static final String HELP_MSG = "socket-client.sh [OPTIONS] [MESSAGE]";
//
// /** The one and only instance of CLI processor. */
// private static CliProcessor instance;
//
// /** The CLI parameters store object. */
// private CliParameters cliParameters;
//
// /**
// * The static getter for the CLI processor instance.
// *
// * @return The CLI processor instance.
// */
// public static CliProcessor getInstance() {
// if (instance == null)
// instance = new CliProcessor();
// return instance;
// }
//
// public void parseCliOptions(String[] args) {
// // Command line options.
// Options options = createCliOptions();
// // Command line parser.
// CommandLineParser parser = new DefaultParser();
//
// try {
// // Parse the command line arguments.
// CommandLine line = parser.parse(options, args);
//
// if (line.hasOption("h")) {
// printHelp(options);
// System.exit(Defaults.EXIT_CODE_SUCCESS);
// }
// if (line.hasOption("p")) {
// this.cliParameters.setPort(line.getOptionValue('p'));
// }
// if (line.hasOption("d")) {
// this.cliParameters.setDestination(line.getOptionValue('d'));
// }
// // Get whatever ist left, after the options have been processed.
// if (line.getArgList() == null || line.getArgList().isEmpty()) {
// LOGGER.info("No message given; using the default message.");
// } else {
// this.cliParameters.setMessage(line.getArgList());
// }
// } catch (MissingOptionException | MissingArgumentException | NumberFormatException e) {
// LOGGER.error("ERROR: " + e.getMessage() + "\n");
// printHelp(options);
// System.exit(Defaults.EXIT_CODE_ERROR);
// } catch (ParseException e) {
// // Oops, something went totally wrong.
// LOGGER.error("ERROR: Parsing failed. Reason: " + e.getMessage());
// }
// }
//
// /**
// * Creates the command line options for the
// * program.
// *
// * @return An Options object containing all the command line options of the program.
// */
// private Options createCliOptions() {
// // A helper option.
// Option help = Option.builder("h")
// .longOpt("help")
// .desc("Give this help list.")
// .build();
// // The port option.
// Option port = Option.builder("p")
// .longOpt("port")
// .desc("The server port.")
// .hasArg()
// .argName("PORT")
// .build();
// // The destination host option.
// Option destinationHost = Option.builder("d")
// .longOpt("destination")
// .desc("The destination host to connect to.")
// .hasArg()
// .argName("DEST_HOST")
// .build();
//
// // Create and add options.
// Options options = new Options();
// options.addOption(help);
// options.addOption(port);
// options.addOption(destinationHost);
//
// // Return options.
// return options;
// }
//
// /**
// * Prints the help of the command.
// *
// * @param options The command's options.
// */
// private void printHelp(Options options) {
// // A help formatter.
// HelpFormatter formatter = new HelpFormatter();
// // Print help.
// formatter.printHelp(HELP_MSG, options);
// }
//
// /**
// * A private constructor to avoid
// * instantiation.
// */
// private CliProcessor() {
// this.cliParameters = CliParameters.getInstance();
// }
// }
| import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import de.hda.fbi.ds.mbredel.configuration.CliProcessor; | /*
Copyright (c) 2018, Michael Bredel, H-DA
ALL RIGHTS RESERVED.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
Neither the name of the H-DA and Michael Bredel
nor the names of its contributors may be used to endorse or promote
products derived from this software without specific prior written
permission.
*/
package de.hda.fbi.ds.mbredel;
/**
* The main class that contains the
* main method that starts the server.
*
* @author Michael Bredel
*/
public class Main {
/** The logger. */
@SuppressWarnings("unused")
private static final Logger LOGGER = LoggerFactory.getLogger(Main.class);
/**
* The main method that starts the
* whole server. Thus, it creates
* a UDP socket server and starts
* the run-method that listens to
* the socket.
*
* @param args Command-line arguments.
*/
public static void main(String[] args) {
// Parse the command line arguments. | // Path: udp-socket/socket-client/sources/src/main/java/de/hda/fbi/ds/mbredel/configuration/CliProcessor.java
// public class CliProcessor {
//
// /** The logger. */
// private static final Logger LOGGER = LoggerFactory.getLogger(CliProcessor.class);
//
// /** The help message. */
// private static final String HELP_MSG = "socket-client.sh [OPTIONS] [MESSAGE]";
//
// /** The one and only instance of CLI processor. */
// private static CliProcessor instance;
//
// /** The CLI parameters store object. */
// private CliParameters cliParameters;
//
// /**
// * The static getter for the CLI processor instance.
// *
// * @return The CLI processor instance.
// */
// public static CliProcessor getInstance() {
// if (instance == null)
// instance = new CliProcessor();
// return instance;
// }
//
// public void parseCliOptions(String[] args) {
// // Command line options.
// Options options = createCliOptions();
// // Command line parser.
// CommandLineParser parser = new DefaultParser();
//
// try {
// // Parse the command line arguments.
// CommandLine line = parser.parse(options, args);
//
// if (line.hasOption("h")) {
// printHelp(options);
// System.exit(Defaults.EXIT_CODE_SUCCESS);
// }
// if (line.hasOption("p")) {
// this.cliParameters.setPort(line.getOptionValue('p'));
// }
// if (line.hasOption("d")) {
// this.cliParameters.setDestination(line.getOptionValue('d'));
// }
// // Get whatever ist left, after the options have been processed.
// if (line.getArgList() == null || line.getArgList().isEmpty()) {
// LOGGER.info("No message given; using the default message.");
// } else {
// this.cliParameters.setMessage(line.getArgList());
// }
// } catch (MissingOptionException | MissingArgumentException | NumberFormatException e) {
// LOGGER.error("ERROR: " + e.getMessage() + "\n");
// printHelp(options);
// System.exit(Defaults.EXIT_CODE_ERROR);
// } catch (ParseException e) {
// // Oops, something went totally wrong.
// LOGGER.error("ERROR: Parsing failed. Reason: " + e.getMessage());
// }
// }
//
// /**
// * Creates the command line options for the
// * program.
// *
// * @return An Options object containing all the command line options of the program.
// */
// private Options createCliOptions() {
// // A helper option.
// Option help = Option.builder("h")
// .longOpt("help")
// .desc("Give this help list.")
// .build();
// // The port option.
// Option port = Option.builder("p")
// .longOpt("port")
// .desc("The server port.")
// .hasArg()
// .argName("PORT")
// .build();
// // The destination host option.
// Option destinationHost = Option.builder("d")
// .longOpt("destination")
// .desc("The destination host to connect to.")
// .hasArg()
// .argName("DEST_HOST")
// .build();
//
// // Create and add options.
// Options options = new Options();
// options.addOption(help);
// options.addOption(port);
// options.addOption(destinationHost);
//
// // Return options.
// return options;
// }
//
// /**
// * Prints the help of the command.
// *
// * @param options The command's options.
// */
// private void printHelp(Options options) {
// // A help formatter.
// HelpFormatter formatter = new HelpFormatter();
// // Print help.
// formatter.printHelp(HELP_MSG, options);
// }
//
// /**
// * A private constructor to avoid
// * instantiation.
// */
// private CliProcessor() {
// this.cliParameters = CliParameters.getInstance();
// }
// }
// Path: udp-socket/socket-server/sources/src/main/java/de/hda/fbi/ds/mbredel/Main.java
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import de.hda.fbi.ds.mbredel.configuration.CliProcessor;
/*
Copyright (c) 2018, Michael Bredel, H-DA
ALL RIGHTS RESERVED.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
Neither the name of the H-DA and Michael Bredel
nor the names of its contributors may be used to endorse or promote
products derived from this software without specific prior written
permission.
*/
package de.hda.fbi.ds.mbredel;
/**
* The main class that contains the
* main method that starts the server.
*
* @author Michael Bredel
*/
public class Main {
/** The logger. */
@SuppressWarnings("unused")
private static final Logger LOGGER = LoggerFactory.getLogger(Main.class);
/**
* The main method that starts the
* whole server. Thus, it creates
* a UDP socket server and starts
* the run-method that listens to
* the socket.
*
* @param args Command-line arguments.
*/
public static void main(String[] args) {
// Parse the command line arguments. | CliProcessor.getInstance().parseCliOptions(args); |
mbredel/distributed-systems | rest/java/src/main/java/de/hda/fbi/ds/mbredel/store/StoreModule.java | // Path: rest/java/src/main/java/de/hda/fbi/ds/mbredel/store/simpleStore/InMemoryStore.java
// public class InMemoryStore implements StoreService {
//
// /** The in-memory user store. */
// private ConcurrentHashMap<String, User> store;
//
// /**
// * Default constructor used by Guice.
// */
// public InMemoryStore() {
// this.store = new ConcurrentHashMap<String, User>();
// }
//
// @Nonnull
// @Override
// public String create(User user) throws PersistenceException, IllegalArgumentException {
// this.store.put(user.username, user);
// return user.username;
// }
//
// @Nullable
// @Override
// public User read(String username) throws IllegalArgumentException {
// return this.store.get(username);
// }
//
// @Nonnull
// @Override
// public Collection<User> readAll() {
// return this.store.values();
// }
//
// @Nonnull
// @Override
// public User delete(String username) throws PersistenceException, IllegalArgumentException {
// if (username == null) {
// throw new IllegalArgumentException();
// }
//
// User user = this.store.remove(username);
//
// if (user != null) {
// return user;
// } else {
// throw new PersistenceException("User does not exist.");
// }
// }
// }
| import de.hda.fbi.ds.mbredel.store.simpleStore.InMemoryStore;
import com.google.inject.AbstractModule; | /*
Copyright (c) 2017, Michael Bredel, H-DA
ALL RIGHTS RESERVED.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
Neither the name of the H-DA and Michael Bredel
nor the names of its contributors may be used to endorse or promote
products derived from this software without specific prior written
permission.
*/
package de.hda.fbi.ds.mbredel.store;
/**
* The Guice module that binds the store service to
* a default store implementation.
*
* @author Michael Bredel
*/
public class StoreModule extends AbstractModule {
@Override
protected void configure() {
bind(StoreService.class) | // Path: rest/java/src/main/java/de/hda/fbi/ds/mbredel/store/simpleStore/InMemoryStore.java
// public class InMemoryStore implements StoreService {
//
// /** The in-memory user store. */
// private ConcurrentHashMap<String, User> store;
//
// /**
// * Default constructor used by Guice.
// */
// public InMemoryStore() {
// this.store = new ConcurrentHashMap<String, User>();
// }
//
// @Nonnull
// @Override
// public String create(User user) throws PersistenceException, IllegalArgumentException {
// this.store.put(user.username, user);
// return user.username;
// }
//
// @Nullable
// @Override
// public User read(String username) throws IllegalArgumentException {
// return this.store.get(username);
// }
//
// @Nonnull
// @Override
// public Collection<User> readAll() {
// return this.store.values();
// }
//
// @Nonnull
// @Override
// public User delete(String username) throws PersistenceException, IllegalArgumentException {
// if (username == null) {
// throw new IllegalArgumentException();
// }
//
// User user = this.store.remove(username);
//
// if (user != null) {
// return user;
// } else {
// throw new PersistenceException("User does not exist.");
// }
// }
// }
// Path: rest/java/src/main/java/de/hda/fbi/ds/mbredel/store/StoreModule.java
import de.hda.fbi.ds.mbredel.store.simpleStore.InMemoryStore;
import com.google.inject.AbstractModule;
/*
Copyright (c) 2017, Michael Bredel, H-DA
ALL RIGHTS RESERVED.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
Neither the name of the H-DA and Michael Bredel
nor the names of its contributors may be used to endorse or promote
products derived from this software without specific prior written
permission.
*/
package de.hda.fbi.ds.mbredel.store;
/**
* The Guice module that binds the store service to
* a default store implementation.
*
* @author Michael Bredel
*/
public class StoreModule extends AbstractModule {
@Override
protected void configure() {
bind(StoreService.class) | .to(InMemoryStore.class) |
mbredel/distributed-systems | rest/java/src/main/java/de/hda/fbi/ds/mbredel/configuration/ConfigurationModule.java | // Path: rest/java/src/main/java/de/hda/fbi/ds/mbredel/configuration/cfg4j/Cfg4jConfiguration.java
// @Singleton
// public class Cfg4jConfiguration implements ConfigurationService {
//
// /** The path to the default configuration file. */
// private static final String DEFAULT_CONFIG_FILE = "./src/main/resources/config.yaml";
//
// /** The configuration provider. */
// private ConfigurationProvider configurationProvider;
//
// /**
// * Default constructor used by Guice.
// */
// public Cfg4jConfiguration() {
// URI uri;
// try {
// uri = URI.create(CliParameters.getInstance().getUri());
// } catch (NoSuchElementException e) {
// uri = URI.create(DEFAULT_CONFIG_FILE);
// }
//
// if (uri.getScheme() != null && (uri.getScheme().equalsIgnoreCase("http") || uri.getScheme().equalsIgnoreCase("https"))) {
// // Process a remote configuration.
// this.setupRemoteConfig(uri);
// } else {
// // Process a local file configuration.
// this.setupFileConfig(uri);
// }
// }
//
// /**
// * Sets up the a remote configuration.
// *
// * @param uri The URI to the configuration file.
// */
// private void setupRemoteConfig(URI uri) {
// throw new UnsupportedOperationException();
// }
//
// /**
// * Sets up the file-based configuration.
// *
// * @param uri The URI to the configuration file.
// */
// private void setupFileConfig(URI uri) {
// Path path = Paths.get(uri.getPath());
// if (path.toFile().exists() && path.toFile().isFile()) {
// String configFile = path.getFileName().toString();
// String configPath = path.getParent().toString();
// Environment environment = new ImmutableEnvironment(configPath);
// ConfigFilesProvider configFilesProvider = () -> Collections.singletonList(Paths.get(configFile));
// ConfigurationSource configurationSource = new FilesConfigurationSource(configFilesProvider);
// this.configurationProvider = new ConfigurationProviderBuilder()
// .withEnvironment(environment)
// .withConfigurationSource(configurationSource)
// .build();
// } else {
// System.err.println("Could not find configuration file: " + path);
// System.exit(Constants.EXIT_CODE_ERROR);
// }
// }
//
// @Override
// @Nullable
// public <T> T getProperty(String key, Class<T> type) {
// return this.configurationProvider.getProperty(key, type);
// }
//
// @Override
// @Nonnull
// public <T> T getProperty(String key, Object defaultValue, Class<T> type) {
// try {
// return this.configurationProvider.getProperty(key, type);
// } catch (Exception e) {
// if (defaultValue != null && type.isInstance(defaultValue))
// return (T) defaultValue;
// else
// throw e;
// }
// }
// }
| import de.hda.fbi.ds.mbredel.configuration.cfg4j.Cfg4jConfiguration;
import com.google.inject.AbstractModule; | /*
Copyright (c) 2017, Michael Bredel, H-DA
ALL RIGHTS RESERVED.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
Neither the name of the H-DA and Michael Bredel
nor the names of its contributors may be used to endorse or promote
products derived from this software without specific prior written
permission.
*/
package de.hda.fbi.ds.mbredel.configuration;
/**
* The Guice module that binds the configuration service to
* a default configuration implementation.
*
* @author Michael Bredel
*/
public class ConfigurationModule extends AbstractModule {
@Override
protected void configure() {
bind(ConfigurationService.class) | // Path: rest/java/src/main/java/de/hda/fbi/ds/mbredel/configuration/cfg4j/Cfg4jConfiguration.java
// @Singleton
// public class Cfg4jConfiguration implements ConfigurationService {
//
// /** The path to the default configuration file. */
// private static final String DEFAULT_CONFIG_FILE = "./src/main/resources/config.yaml";
//
// /** The configuration provider. */
// private ConfigurationProvider configurationProvider;
//
// /**
// * Default constructor used by Guice.
// */
// public Cfg4jConfiguration() {
// URI uri;
// try {
// uri = URI.create(CliParameters.getInstance().getUri());
// } catch (NoSuchElementException e) {
// uri = URI.create(DEFAULT_CONFIG_FILE);
// }
//
// if (uri.getScheme() != null && (uri.getScheme().equalsIgnoreCase("http") || uri.getScheme().equalsIgnoreCase("https"))) {
// // Process a remote configuration.
// this.setupRemoteConfig(uri);
// } else {
// // Process a local file configuration.
// this.setupFileConfig(uri);
// }
// }
//
// /**
// * Sets up the a remote configuration.
// *
// * @param uri The URI to the configuration file.
// */
// private void setupRemoteConfig(URI uri) {
// throw new UnsupportedOperationException();
// }
//
// /**
// * Sets up the file-based configuration.
// *
// * @param uri The URI to the configuration file.
// */
// private void setupFileConfig(URI uri) {
// Path path = Paths.get(uri.getPath());
// if (path.toFile().exists() && path.toFile().isFile()) {
// String configFile = path.getFileName().toString();
// String configPath = path.getParent().toString();
// Environment environment = new ImmutableEnvironment(configPath);
// ConfigFilesProvider configFilesProvider = () -> Collections.singletonList(Paths.get(configFile));
// ConfigurationSource configurationSource = new FilesConfigurationSource(configFilesProvider);
// this.configurationProvider = new ConfigurationProviderBuilder()
// .withEnvironment(environment)
// .withConfigurationSource(configurationSource)
// .build();
// } else {
// System.err.println("Could not find configuration file: " + path);
// System.exit(Constants.EXIT_CODE_ERROR);
// }
// }
//
// @Override
// @Nullable
// public <T> T getProperty(String key, Class<T> type) {
// return this.configurationProvider.getProperty(key, type);
// }
//
// @Override
// @Nonnull
// public <T> T getProperty(String key, Object defaultValue, Class<T> type) {
// try {
// return this.configurationProvider.getProperty(key, type);
// } catch (Exception e) {
// if (defaultValue != null && type.isInstance(defaultValue))
// return (T) defaultValue;
// else
// throw e;
// }
// }
// }
// Path: rest/java/src/main/java/de/hda/fbi/ds/mbredel/configuration/ConfigurationModule.java
import de.hda.fbi.ds.mbredel.configuration.cfg4j.Cfg4jConfiguration;
import com.google.inject.AbstractModule;
/*
Copyright (c) 2017, Michael Bredel, H-DA
ALL RIGHTS RESERVED.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
Neither the name of the H-DA and Michael Bredel
nor the names of its contributors may be used to endorse or promote
products derived from this software without specific prior written
permission.
*/
package de.hda.fbi.ds.mbredel.configuration;
/**
* The Guice module that binds the configuration service to
* a default configuration implementation.
*
* @author Michael Bredel
*/
public class ConfigurationModule extends AbstractModule {
@Override
protected void configure() {
bind(ConfigurationService.class) | .to(Cfg4jConfiguration.class) |
mbredel/distributed-systems | rest/java/src/main/java/de/hda/fbi/ds/mbredel/core/ApplicationModule.java | // Path: rest/java/src/main/java/de/hda/fbi/ds/mbredel/controller/GeneralControllerFactory.java
// public interface GeneralControllerFactory {
// /**
// * Create a general controller object.
// *
// * @return A general controller.
// */
// GeneralController create();
// }
//
// Path: rest/java/src/main/java/de/hda/fbi/ds/mbredel/controller/UserControllerFactory.java
// public interface UserControllerFactory {
// /**
// * Create a user controller object.
// *
// * @return A user controller.
// */
// UserController create();
// }
| import com.google.inject.assistedinject.FactoryModuleBuilder;
import de.hda.fbi.ds.mbredel.controller.GeneralControllerFactory;
import de.hda.fbi.ds.mbredel.controller.UserControllerFactory;
import com.google.inject.AbstractModule; | /*
Copyright (c) 2017, Michael Bredel, H-DA
ALL RIGHTS RESERVED.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
Neither the name of the H-DA and Michael Bredel
nor the names of its contributors may be used to endorse or promote
products derived from this software without specific prior written
permission.
*/
package de.hda.fbi.ds.mbredel.core;
/**
* The basic module that binds the application-related
* factories and interfaces to their implementations.
*
* @author Michael Bredel
*/
public class ApplicationModule extends AbstractModule {
@Override
protected void configure() {
// Create a factory to inject UserController objects whenever needed. | // Path: rest/java/src/main/java/de/hda/fbi/ds/mbredel/controller/GeneralControllerFactory.java
// public interface GeneralControllerFactory {
// /**
// * Create a general controller object.
// *
// * @return A general controller.
// */
// GeneralController create();
// }
//
// Path: rest/java/src/main/java/de/hda/fbi/ds/mbredel/controller/UserControllerFactory.java
// public interface UserControllerFactory {
// /**
// * Create a user controller object.
// *
// * @return A user controller.
// */
// UserController create();
// }
// Path: rest/java/src/main/java/de/hda/fbi/ds/mbredel/core/ApplicationModule.java
import com.google.inject.assistedinject.FactoryModuleBuilder;
import de.hda.fbi.ds.mbredel.controller.GeneralControllerFactory;
import de.hda.fbi.ds.mbredel.controller.UserControllerFactory;
import com.google.inject.AbstractModule;
/*
Copyright (c) 2017, Michael Bredel, H-DA
ALL RIGHTS RESERVED.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
Neither the name of the H-DA and Michael Bredel
nor the names of its contributors may be used to endorse or promote
products derived from this software without specific prior written
permission.
*/
package de.hda.fbi.ds.mbredel.core;
/**
* The basic module that binds the application-related
* factories and interfaces to their implementations.
*
* @author Michael Bredel
*/
public class ApplicationModule extends AbstractModule {
@Override
protected void configure() {
// Create a factory to inject UserController objects whenever needed. | install(new FactoryModuleBuilder().build(UserControllerFactory.class)); |
mbredel/distributed-systems | rest/java/src/main/java/de/hda/fbi/ds/mbredel/core/ApplicationModule.java | // Path: rest/java/src/main/java/de/hda/fbi/ds/mbredel/controller/GeneralControllerFactory.java
// public interface GeneralControllerFactory {
// /**
// * Create a general controller object.
// *
// * @return A general controller.
// */
// GeneralController create();
// }
//
// Path: rest/java/src/main/java/de/hda/fbi/ds/mbredel/controller/UserControllerFactory.java
// public interface UserControllerFactory {
// /**
// * Create a user controller object.
// *
// * @return A user controller.
// */
// UserController create();
// }
| import com.google.inject.assistedinject.FactoryModuleBuilder;
import de.hda.fbi.ds.mbredel.controller.GeneralControllerFactory;
import de.hda.fbi.ds.mbredel.controller.UserControllerFactory;
import com.google.inject.AbstractModule; | /*
Copyright (c) 2017, Michael Bredel, H-DA
ALL RIGHTS RESERVED.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
Neither the name of the H-DA and Michael Bredel
nor the names of its contributors may be used to endorse or promote
products derived from this software without specific prior written
permission.
*/
package de.hda.fbi.ds.mbredel.core;
/**
* The basic module that binds the application-related
* factories and interfaces to their implementations.
*
* @author Michael Bredel
*/
public class ApplicationModule extends AbstractModule {
@Override
protected void configure() {
// Create a factory to inject UserController objects whenever needed.
install(new FactoryModuleBuilder().build(UserControllerFactory.class));
// Create a factory to inject GeneralController objects whenever needed. | // Path: rest/java/src/main/java/de/hda/fbi/ds/mbredel/controller/GeneralControllerFactory.java
// public interface GeneralControllerFactory {
// /**
// * Create a general controller object.
// *
// * @return A general controller.
// */
// GeneralController create();
// }
//
// Path: rest/java/src/main/java/de/hda/fbi/ds/mbredel/controller/UserControllerFactory.java
// public interface UserControllerFactory {
// /**
// * Create a user controller object.
// *
// * @return A user controller.
// */
// UserController create();
// }
// Path: rest/java/src/main/java/de/hda/fbi/ds/mbredel/core/ApplicationModule.java
import com.google.inject.assistedinject.FactoryModuleBuilder;
import de.hda.fbi.ds.mbredel.controller.GeneralControllerFactory;
import de.hda.fbi.ds.mbredel.controller.UserControllerFactory;
import com.google.inject.AbstractModule;
/*
Copyright (c) 2017, Michael Bredel, H-DA
ALL RIGHTS RESERVED.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
Neither the name of the H-DA and Michael Bredel
nor the names of its contributors may be used to endorse or promote
products derived from this software without specific prior written
permission.
*/
package de.hda.fbi.ds.mbredel.core;
/**
* The basic module that binds the application-related
* factories and interfaces to their implementations.
*
* @author Michael Bredel
*/
public class ApplicationModule extends AbstractModule {
@Override
protected void configure() {
// Create a factory to inject UserController objects whenever needed.
install(new FactoryModuleBuilder().build(UserControllerFactory.class));
// Create a factory to inject GeneralController objects whenever needed. | install(new FactoryModuleBuilder().build(GeneralControllerFactory.class)); |
mbredel/distributed-systems | udp-socket/socket-client/sources/src/main/java/de/hda/fbi/ds/mbredel/UDPSocketClient.java | // Path: udp-socket/socket-client/sources/src/main/java/de/hda/fbi/ds/mbredel/configuration/CliParameters.java
// public class CliParameters {
//
// /** The one and only instance of CLI parameters. */
// private static CliParameters instance;
//
// /** The port of the UDP socket server. Initially set to the default port. */
// private int port = Defaults.PORT;
// /** The message that is published. */
// private String message = Defaults.MESSAGE;
// /** The destination host to connect to. */
// private String destination = Defaults.DST_HOST;
//
// /**
// * The static getter for the CLI parameters instance.
// *
// * @return The CLI parameters instance.
// */
// public static CliParameters getInstance() {
// if (instance == null)
// instance = new CliParameters();
// return instance;
// }
//
// //
// // Getter and Setter
// //
//
// public int getPort() {
// return this.port;
// }
//
// public void setPort(String port) {
// this.port = Integer.parseInt(port);
// }
//
// public String getMessage() {
// return this.message;
// }
//
// public void setMessage(List<String> args) {
// StringBuilder sb = new StringBuilder();
// for (String arg: args) {
// sb.append(arg);
// sb.append(" ");
// }
// this.message = sb.toString().trim();
// }
//
// public String getDestination() {
// return this.destination;
// }
//
// public void setDestination(String destination) {
// this.destination = destination;
// }
//
// /**
// * A private constructor to avoid
// * instantiation.
// */
// private CliParameters() {}
// }
//
// Path: udp-socket/socket-client/sources/src/main/java/de/hda/fbi/ds/mbredel/configuration/Defaults.java
// public abstract class Defaults {
//
// /** The default port of the UDP socket server. */
// public static final int PORT = 6543;
// /** The exit code if the procedure succeeded. */
// public static final int EXIT_CODE_SUCCESS = 0;
// /** The exit code of the procedure failed. */
// public static final int EXIT_CODE_ERROR = 1;
//
// /** The default message sent to the server. */
// public static final String MESSAGE = "Hello World";
// /** The default host to connect to. */
// public static final String DST_HOST = "localhost";
//
// /**
// * Private constructor to hide the implicit public one
// * and to void any instantiation.
// */
// private Defaults() {
// throw new IllegalStateException("Utility class");
// }
//
// }
| import de.hda.fbi.ds.mbredel.configuration.CliParameters;
import de.hda.fbi.ds.mbredel.configuration.Defaults;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.io.IOException;
import java.net.*; | /*
Copyright (c) 2018, Michael Bredel, H-DA
ALL RIGHTS RESERVED.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
Neither the name of the H-DA and Michael Bredel
nor the names of its contributors may be used to endorse or promote
products derived from this software without specific prior written
permission.
*/
package de.hda.fbi.ds.mbredel;
/**
* The actual socket server that creates
* a UDP socket and waits for incoming
* datagram.
*
* @author Michael Bredel
*/
public class UDPSocketClient {
/** The logger. */
private static final Logger LOGGER = LoggerFactory.getLogger(UDPSocketClient.class);
/** The IP address the client connects to. */
private InetAddress address;
/**
* Default constructor that initializes Internet
* address the client connects to.
*/
public UDPSocketClient() {
// Try to set the destination host address.
try { | // Path: udp-socket/socket-client/sources/src/main/java/de/hda/fbi/ds/mbredel/configuration/CliParameters.java
// public class CliParameters {
//
// /** The one and only instance of CLI parameters. */
// private static CliParameters instance;
//
// /** The port of the UDP socket server. Initially set to the default port. */
// private int port = Defaults.PORT;
// /** The message that is published. */
// private String message = Defaults.MESSAGE;
// /** The destination host to connect to. */
// private String destination = Defaults.DST_HOST;
//
// /**
// * The static getter for the CLI parameters instance.
// *
// * @return The CLI parameters instance.
// */
// public static CliParameters getInstance() {
// if (instance == null)
// instance = new CliParameters();
// return instance;
// }
//
// //
// // Getter and Setter
// //
//
// public int getPort() {
// return this.port;
// }
//
// public void setPort(String port) {
// this.port = Integer.parseInt(port);
// }
//
// public String getMessage() {
// return this.message;
// }
//
// public void setMessage(List<String> args) {
// StringBuilder sb = new StringBuilder();
// for (String arg: args) {
// sb.append(arg);
// sb.append(" ");
// }
// this.message = sb.toString().trim();
// }
//
// public String getDestination() {
// return this.destination;
// }
//
// public void setDestination(String destination) {
// this.destination = destination;
// }
//
// /**
// * A private constructor to avoid
// * instantiation.
// */
// private CliParameters() {}
// }
//
// Path: udp-socket/socket-client/sources/src/main/java/de/hda/fbi/ds/mbredel/configuration/Defaults.java
// public abstract class Defaults {
//
// /** The default port of the UDP socket server. */
// public static final int PORT = 6543;
// /** The exit code if the procedure succeeded. */
// public static final int EXIT_CODE_SUCCESS = 0;
// /** The exit code of the procedure failed. */
// public static final int EXIT_CODE_ERROR = 1;
//
// /** The default message sent to the server. */
// public static final String MESSAGE = "Hello World";
// /** The default host to connect to. */
// public static final String DST_HOST = "localhost";
//
// /**
// * Private constructor to hide the implicit public one
// * and to void any instantiation.
// */
// private Defaults() {
// throw new IllegalStateException("Utility class");
// }
//
// }
// Path: udp-socket/socket-client/sources/src/main/java/de/hda/fbi/ds/mbredel/UDPSocketClient.java
import de.hda.fbi.ds.mbredel.configuration.CliParameters;
import de.hda.fbi.ds.mbredel.configuration.Defaults;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.io.IOException;
import java.net.*;
/*
Copyright (c) 2018, Michael Bredel, H-DA
ALL RIGHTS RESERVED.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
Neither the name of the H-DA and Michael Bredel
nor the names of its contributors may be used to endorse or promote
products derived from this software without specific prior written
permission.
*/
package de.hda.fbi.ds.mbredel;
/**
* The actual socket server that creates
* a UDP socket and waits for incoming
* datagram.
*
* @author Michael Bredel
*/
public class UDPSocketClient {
/** The logger. */
private static final Logger LOGGER = LoggerFactory.getLogger(UDPSocketClient.class);
/** The IP address the client connects to. */
private InetAddress address;
/**
* Default constructor that initializes Internet
* address the client connects to.
*/
public UDPSocketClient() {
// Try to set the destination host address.
try { | address = InetAddress.getByName(CliParameters.getInstance().getDestination()); |
mbredel/distributed-systems | udp-socket/socket-client/sources/src/main/java/de/hda/fbi/ds/mbredel/UDPSocketClient.java | // Path: udp-socket/socket-client/sources/src/main/java/de/hda/fbi/ds/mbredel/configuration/CliParameters.java
// public class CliParameters {
//
// /** The one and only instance of CLI parameters. */
// private static CliParameters instance;
//
// /** The port of the UDP socket server. Initially set to the default port. */
// private int port = Defaults.PORT;
// /** The message that is published. */
// private String message = Defaults.MESSAGE;
// /** The destination host to connect to. */
// private String destination = Defaults.DST_HOST;
//
// /**
// * The static getter for the CLI parameters instance.
// *
// * @return The CLI parameters instance.
// */
// public static CliParameters getInstance() {
// if (instance == null)
// instance = new CliParameters();
// return instance;
// }
//
// //
// // Getter and Setter
// //
//
// public int getPort() {
// return this.port;
// }
//
// public void setPort(String port) {
// this.port = Integer.parseInt(port);
// }
//
// public String getMessage() {
// return this.message;
// }
//
// public void setMessage(List<String> args) {
// StringBuilder sb = new StringBuilder();
// for (String arg: args) {
// sb.append(arg);
// sb.append(" ");
// }
// this.message = sb.toString().trim();
// }
//
// public String getDestination() {
// return this.destination;
// }
//
// public void setDestination(String destination) {
// this.destination = destination;
// }
//
// /**
// * A private constructor to avoid
// * instantiation.
// */
// private CliParameters() {}
// }
//
// Path: udp-socket/socket-client/sources/src/main/java/de/hda/fbi/ds/mbredel/configuration/Defaults.java
// public abstract class Defaults {
//
// /** The default port of the UDP socket server. */
// public static final int PORT = 6543;
// /** The exit code if the procedure succeeded. */
// public static final int EXIT_CODE_SUCCESS = 0;
// /** The exit code of the procedure failed. */
// public static final int EXIT_CODE_ERROR = 1;
//
// /** The default message sent to the server. */
// public static final String MESSAGE = "Hello World";
// /** The default host to connect to. */
// public static final String DST_HOST = "localhost";
//
// /**
// * Private constructor to hide the implicit public one
// * and to void any instantiation.
// */
// private Defaults() {
// throw new IllegalStateException("Utility class");
// }
//
// }
| import de.hda.fbi.ds.mbredel.configuration.CliParameters;
import de.hda.fbi.ds.mbredel.configuration.Defaults;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.io.IOException;
import java.net.*; | /*
Copyright (c) 2018, Michael Bredel, H-DA
ALL RIGHTS RESERVED.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
Neither the name of the H-DA and Michael Bredel
nor the names of its contributors may be used to endorse or promote
products derived from this software without specific prior written
permission.
*/
package de.hda.fbi.ds.mbredel;
/**
* The actual socket server that creates
* a UDP socket and waits for incoming
* datagram.
*
* @author Michael Bredel
*/
public class UDPSocketClient {
/** The logger. */
private static final Logger LOGGER = LoggerFactory.getLogger(UDPSocketClient.class);
/** The IP address the client connects to. */
private InetAddress address;
/**
* Default constructor that initializes Internet
* address the client connects to.
*/
public UDPSocketClient() {
// Try to set the destination host address.
try {
address = InetAddress.getByName(CliParameters.getInstance().getDestination());
} catch (UnknownHostException e) {
LOGGER.error("Can not parse the destination host address.\n{}", e.getMessage()); | // Path: udp-socket/socket-client/sources/src/main/java/de/hda/fbi/ds/mbredel/configuration/CliParameters.java
// public class CliParameters {
//
// /** The one and only instance of CLI parameters. */
// private static CliParameters instance;
//
// /** The port of the UDP socket server. Initially set to the default port. */
// private int port = Defaults.PORT;
// /** The message that is published. */
// private String message = Defaults.MESSAGE;
// /** The destination host to connect to. */
// private String destination = Defaults.DST_HOST;
//
// /**
// * The static getter for the CLI parameters instance.
// *
// * @return The CLI parameters instance.
// */
// public static CliParameters getInstance() {
// if (instance == null)
// instance = new CliParameters();
// return instance;
// }
//
// //
// // Getter and Setter
// //
//
// public int getPort() {
// return this.port;
// }
//
// public void setPort(String port) {
// this.port = Integer.parseInt(port);
// }
//
// public String getMessage() {
// return this.message;
// }
//
// public void setMessage(List<String> args) {
// StringBuilder sb = new StringBuilder();
// for (String arg: args) {
// sb.append(arg);
// sb.append(" ");
// }
// this.message = sb.toString().trim();
// }
//
// public String getDestination() {
// return this.destination;
// }
//
// public void setDestination(String destination) {
// this.destination = destination;
// }
//
// /**
// * A private constructor to avoid
// * instantiation.
// */
// private CliParameters() {}
// }
//
// Path: udp-socket/socket-client/sources/src/main/java/de/hda/fbi/ds/mbredel/configuration/Defaults.java
// public abstract class Defaults {
//
// /** The default port of the UDP socket server. */
// public static final int PORT = 6543;
// /** The exit code if the procedure succeeded. */
// public static final int EXIT_CODE_SUCCESS = 0;
// /** The exit code of the procedure failed. */
// public static final int EXIT_CODE_ERROR = 1;
//
// /** The default message sent to the server. */
// public static final String MESSAGE = "Hello World";
// /** The default host to connect to. */
// public static final String DST_HOST = "localhost";
//
// /**
// * Private constructor to hide the implicit public one
// * and to void any instantiation.
// */
// private Defaults() {
// throw new IllegalStateException("Utility class");
// }
//
// }
// Path: udp-socket/socket-client/sources/src/main/java/de/hda/fbi/ds/mbredel/UDPSocketClient.java
import de.hda.fbi.ds.mbredel.configuration.CliParameters;
import de.hda.fbi.ds.mbredel.configuration.Defaults;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.io.IOException;
import java.net.*;
/*
Copyright (c) 2018, Michael Bredel, H-DA
ALL RIGHTS RESERVED.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
Neither the name of the H-DA and Michael Bredel
nor the names of its contributors may be used to endorse or promote
products derived from this software without specific prior written
permission.
*/
package de.hda.fbi.ds.mbredel;
/**
* The actual socket server that creates
* a UDP socket and waits for incoming
* datagram.
*
* @author Michael Bredel
*/
public class UDPSocketClient {
/** The logger. */
private static final Logger LOGGER = LoggerFactory.getLogger(UDPSocketClient.class);
/** The IP address the client connects to. */
private InetAddress address;
/**
* Default constructor that initializes Internet
* address the client connects to.
*/
public UDPSocketClient() {
// Try to set the destination host address.
try {
address = InetAddress.getByName(CliParameters.getInstance().getDestination());
} catch (UnknownHostException e) {
LOGGER.error("Can not parse the destination host address.\n{}", e.getMessage()); | System.exit(Defaults.EXIT_CODE_ERROR); |
mbredel/distributed-systems | udp-socket/socket-server/sources/src/main/java/de/hda/fbi/ds/mbredel/UDPSocketServer.java | // Path: udp-socket/socket-client/sources/src/main/java/de/hda/fbi/ds/mbredel/configuration/CliParameters.java
// public class CliParameters {
//
// /** The one and only instance of CLI parameters. */
// private static CliParameters instance;
//
// /** The port of the UDP socket server. Initially set to the default port. */
// private int port = Defaults.PORT;
// /** The message that is published. */
// private String message = Defaults.MESSAGE;
// /** The destination host to connect to. */
// private String destination = Defaults.DST_HOST;
//
// /**
// * The static getter for the CLI parameters instance.
// *
// * @return The CLI parameters instance.
// */
// public static CliParameters getInstance() {
// if (instance == null)
// instance = new CliParameters();
// return instance;
// }
//
// //
// // Getter and Setter
// //
//
// public int getPort() {
// return this.port;
// }
//
// public void setPort(String port) {
// this.port = Integer.parseInt(port);
// }
//
// public String getMessage() {
// return this.message;
// }
//
// public void setMessage(List<String> args) {
// StringBuilder sb = new StringBuilder();
// for (String arg: args) {
// sb.append(arg);
// sb.append(" ");
// }
// this.message = sb.toString().trim();
// }
//
// public String getDestination() {
// return this.destination;
// }
//
// public void setDestination(String destination) {
// this.destination = destination;
// }
//
// /**
// * A private constructor to avoid
// * instantiation.
// */
// private CliParameters() {}
// }
| import java.util.Arrays;
import de.hda.fbi.ds.mbredel.configuration.CliParameters;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.io.IOException;
import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.InetAddress;
import java.net.SocketException; | /*
Copyright (c) 2018, Michael Bredel, H-DA
ALL RIGHTS RESERVED.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
Neither the name of the H-DA and Michael Bredel
nor the names of its contributors may be used to endorse or promote
products derived from this software without specific prior written
permission.
*/
package de.hda.fbi.ds.mbredel;
/**
* The actual socket server that creates
* a UDP socket and waits for incoming
* datagram.
*
* @author Michael Bredel
*/
public class UDPSocketServer {
/** The logger. */
private static final Logger LOGGER = LoggerFactory.getLogger(UDPSocketServer.class);
/** A buffer array to store the datagram information. */
private byte[] buf;
/** States the server running. */
private boolean running = true;
/**
* Default constructor that initializes the UDP
* buffer byte array with the given buffer size.
*/
public UDPSocketServer() {
// Initialize the UDP buffer. | // Path: udp-socket/socket-client/sources/src/main/java/de/hda/fbi/ds/mbredel/configuration/CliParameters.java
// public class CliParameters {
//
// /** The one and only instance of CLI parameters. */
// private static CliParameters instance;
//
// /** The port of the UDP socket server. Initially set to the default port. */
// private int port = Defaults.PORT;
// /** The message that is published. */
// private String message = Defaults.MESSAGE;
// /** The destination host to connect to. */
// private String destination = Defaults.DST_HOST;
//
// /**
// * The static getter for the CLI parameters instance.
// *
// * @return The CLI parameters instance.
// */
// public static CliParameters getInstance() {
// if (instance == null)
// instance = new CliParameters();
// return instance;
// }
//
// //
// // Getter and Setter
// //
//
// public int getPort() {
// return this.port;
// }
//
// public void setPort(String port) {
// this.port = Integer.parseInt(port);
// }
//
// public String getMessage() {
// return this.message;
// }
//
// public void setMessage(List<String> args) {
// StringBuilder sb = new StringBuilder();
// for (String arg: args) {
// sb.append(arg);
// sb.append(" ");
// }
// this.message = sb.toString().trim();
// }
//
// public String getDestination() {
// return this.destination;
// }
//
// public void setDestination(String destination) {
// this.destination = destination;
// }
//
// /**
// * A private constructor to avoid
// * instantiation.
// */
// private CliParameters() {}
// }
// Path: udp-socket/socket-server/sources/src/main/java/de/hda/fbi/ds/mbredel/UDPSocketServer.java
import java.util.Arrays;
import de.hda.fbi.ds.mbredel.configuration.CliParameters;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.io.IOException;
import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.InetAddress;
import java.net.SocketException;
/*
Copyright (c) 2018, Michael Bredel, H-DA
ALL RIGHTS RESERVED.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
Neither the name of the H-DA and Michael Bredel
nor the names of its contributors may be used to endorse or promote
products derived from this software without specific prior written
permission.
*/
package de.hda.fbi.ds.mbredel;
/**
* The actual socket server that creates
* a UDP socket and waits for incoming
* datagram.
*
* @author Michael Bredel
*/
public class UDPSocketServer {
/** The logger. */
private static final Logger LOGGER = LoggerFactory.getLogger(UDPSocketServer.class);
/** A buffer array to store the datagram information. */
private byte[] buf;
/** States the server running. */
private boolean running = true;
/**
* Default constructor that initializes the UDP
* buffer byte array with the given buffer size.
*/
public UDPSocketServer() {
// Initialize the UDP buffer. | buf = new byte[CliParameters.getInstance().getBufferSize()]; |
mbredel/distributed-systems | rest/java/src/main/java/de/hda/fbi/ds/mbredel/Main.java | // Path: udp-socket/socket-client/sources/src/main/java/de/hda/fbi/ds/mbredel/configuration/CliParameters.java
// public class CliParameters {
//
// /** The one and only instance of CLI parameters. */
// private static CliParameters instance;
//
// /** The port of the UDP socket server. Initially set to the default port. */
// private int port = Defaults.PORT;
// /** The message that is published. */
// private String message = Defaults.MESSAGE;
// /** The destination host to connect to. */
// private String destination = Defaults.DST_HOST;
//
// /**
// * The static getter for the CLI parameters instance.
// *
// * @return The CLI parameters instance.
// */
// public static CliParameters getInstance() {
// if (instance == null)
// instance = new CliParameters();
// return instance;
// }
//
// //
// // Getter and Setter
// //
//
// public int getPort() {
// return this.port;
// }
//
// public void setPort(String port) {
// this.port = Integer.parseInt(port);
// }
//
// public String getMessage() {
// return this.message;
// }
//
// public void setMessage(List<String> args) {
// StringBuilder sb = new StringBuilder();
// for (String arg: args) {
// sb.append(arg);
// sb.append(" ");
// }
// this.message = sb.toString().trim();
// }
//
// public String getDestination() {
// return this.destination;
// }
//
// public void setDestination(String destination) {
// this.destination = destination;
// }
//
// /**
// * A private constructor to avoid
// * instantiation.
// */
// private CliParameters() {}
// }
//
// Path: rest/java/src/main/java/de/hda/fbi/ds/mbredel/configuration/ConfigurationModule.java
// public class ConfigurationModule extends AbstractModule {
// @Override
// protected void configure() {
// bind(ConfigurationService.class)
// .to(Cfg4jConfiguration.class)
// .asEagerSingleton();
// }
// }
//
// Path: rest/java/src/main/java/de/hda/fbi/ds/mbredel/core/Application.java
// @Singleton
// public class Application {
//
// /** The user controller that handles requests related to users. */
// private UserController userController;
// /** The general controller. */
// private GeneralController generalController;
//
// @Inject
// public Application(
// GeneralControllerFactory generalControllerFactory,
// UserControllerFactory userControllerFactory
// ) {
// this.generalController = generalControllerFactory.create();
// this.userController = userControllerFactory.create();
// }
//
// /**
// * Start listening to routes.
// */
// public void start() {
//
// // Set the HTTP port to listen to.
// port(Constants.HTTP_PORT);
//
// // Standard GET.
// get(Routes.ROOT, generalController::get);
//
// head(Routes.ROOT, generalController::head);
//
// trace(Routes.ROOT, generalController::trace);
//
// // User handling.
// path(Routes.USERS, () -> {
//
// // Post a new user.
// post("", userController::postUsers);
//
// // Get a list of available users.
// get("", userController::getUsers);
//
// // Get a single user.
// get("/:username", userController::getUser);
//
// // Delete a single user.
// delete("/:username", userController::deleteUser);
//
// });
// }
// }
//
// Path: rest/java/src/main/java/de/hda/fbi/ds/mbredel/core/ApplicationModule.java
// public class ApplicationModule extends AbstractModule {
// @Override
// protected void configure() {
//
// // Create a factory to inject UserController objects whenever needed.
// install(new FactoryModuleBuilder().build(UserControllerFactory.class));
//
// // Create a factory to inject GeneralController objects whenever needed.
// install(new FactoryModuleBuilder().build(GeneralControllerFactory.class));
//
// }
// }
//
// Path: rest/java/src/main/java/de/hda/fbi/ds/mbredel/core/Constants.java
// public class Constants {
// /** The exit code if the procedure succeeded. */
// public static final int EXIT_CODE_SUCCESS = 0;
// /** The exit code of the procedure failed. */
// public static final int EXIT_CODE_ERROR = 1;
//
// /** The HTTP port to listen to. */
// public static final int HTTP_PORT = 4567;
//
// /**
// * A private constructor to avoid
// * instantiation.
// */
// private Constants() {}
// }
//
// Path: rest/java/src/main/java/de/hda/fbi/ds/mbredel/store/StoreModule.java
// public class StoreModule extends AbstractModule {
// @Override
// protected void configure() {
// bind(StoreService.class)
// .to(InMemoryStore.class)
// .asEagerSingleton();
// }
// }
| import org.apache.commons.cli.*;
import akka.actor.ActorSystem;
import com.google.inject.Guice;
import com.google.inject.Injector;
import de.hda.fbi.ds.mbredel.configuration.CliParameters;
import de.hda.fbi.ds.mbredel.configuration.ConfigurationModule;
import de.hda.fbi.ds.mbredel.core.Application;
import de.hda.fbi.ds.mbredel.core.ApplicationModule;
import de.hda.fbi.ds.mbredel.core.Constants;
import de.hda.fbi.ds.mbredel.store.StoreModule; | Options options = new Options();
options.addOption(help);
options.addOption(config);
options.addOption(username);
options.addOption(password);
// Return options.
return options;
}
/**
* Parses the command line arguments.
*
* @param args The command line arguments.
*/
private static void parseCliOptions(String[] args) {
// Command line options.
Options options = createCliOptions();
// Command line parser.
CommandLineParser parser = new DefaultParser();
try {
// Parse the command line arguments
CommandLine line = parser.parse(options, args);
if (line.hasOption('h')) {
printHelp(options);
System.exit(0);
}
if (line.hasOption('c')) { | // Path: udp-socket/socket-client/sources/src/main/java/de/hda/fbi/ds/mbredel/configuration/CliParameters.java
// public class CliParameters {
//
// /** The one and only instance of CLI parameters. */
// private static CliParameters instance;
//
// /** The port of the UDP socket server. Initially set to the default port. */
// private int port = Defaults.PORT;
// /** The message that is published. */
// private String message = Defaults.MESSAGE;
// /** The destination host to connect to. */
// private String destination = Defaults.DST_HOST;
//
// /**
// * The static getter for the CLI parameters instance.
// *
// * @return The CLI parameters instance.
// */
// public static CliParameters getInstance() {
// if (instance == null)
// instance = new CliParameters();
// return instance;
// }
//
// //
// // Getter and Setter
// //
//
// public int getPort() {
// return this.port;
// }
//
// public void setPort(String port) {
// this.port = Integer.parseInt(port);
// }
//
// public String getMessage() {
// return this.message;
// }
//
// public void setMessage(List<String> args) {
// StringBuilder sb = new StringBuilder();
// for (String arg: args) {
// sb.append(arg);
// sb.append(" ");
// }
// this.message = sb.toString().trim();
// }
//
// public String getDestination() {
// return this.destination;
// }
//
// public void setDestination(String destination) {
// this.destination = destination;
// }
//
// /**
// * A private constructor to avoid
// * instantiation.
// */
// private CliParameters() {}
// }
//
// Path: rest/java/src/main/java/de/hda/fbi/ds/mbredel/configuration/ConfigurationModule.java
// public class ConfigurationModule extends AbstractModule {
// @Override
// protected void configure() {
// bind(ConfigurationService.class)
// .to(Cfg4jConfiguration.class)
// .asEagerSingleton();
// }
// }
//
// Path: rest/java/src/main/java/de/hda/fbi/ds/mbredel/core/Application.java
// @Singleton
// public class Application {
//
// /** The user controller that handles requests related to users. */
// private UserController userController;
// /** The general controller. */
// private GeneralController generalController;
//
// @Inject
// public Application(
// GeneralControllerFactory generalControllerFactory,
// UserControllerFactory userControllerFactory
// ) {
// this.generalController = generalControllerFactory.create();
// this.userController = userControllerFactory.create();
// }
//
// /**
// * Start listening to routes.
// */
// public void start() {
//
// // Set the HTTP port to listen to.
// port(Constants.HTTP_PORT);
//
// // Standard GET.
// get(Routes.ROOT, generalController::get);
//
// head(Routes.ROOT, generalController::head);
//
// trace(Routes.ROOT, generalController::trace);
//
// // User handling.
// path(Routes.USERS, () -> {
//
// // Post a new user.
// post("", userController::postUsers);
//
// // Get a list of available users.
// get("", userController::getUsers);
//
// // Get a single user.
// get("/:username", userController::getUser);
//
// // Delete a single user.
// delete("/:username", userController::deleteUser);
//
// });
// }
// }
//
// Path: rest/java/src/main/java/de/hda/fbi/ds/mbredel/core/ApplicationModule.java
// public class ApplicationModule extends AbstractModule {
// @Override
// protected void configure() {
//
// // Create a factory to inject UserController objects whenever needed.
// install(new FactoryModuleBuilder().build(UserControllerFactory.class));
//
// // Create a factory to inject GeneralController objects whenever needed.
// install(new FactoryModuleBuilder().build(GeneralControllerFactory.class));
//
// }
// }
//
// Path: rest/java/src/main/java/de/hda/fbi/ds/mbredel/core/Constants.java
// public class Constants {
// /** The exit code if the procedure succeeded. */
// public static final int EXIT_CODE_SUCCESS = 0;
// /** The exit code of the procedure failed. */
// public static final int EXIT_CODE_ERROR = 1;
//
// /** The HTTP port to listen to. */
// public static final int HTTP_PORT = 4567;
//
// /**
// * A private constructor to avoid
// * instantiation.
// */
// private Constants() {}
// }
//
// Path: rest/java/src/main/java/de/hda/fbi/ds/mbredel/store/StoreModule.java
// public class StoreModule extends AbstractModule {
// @Override
// protected void configure() {
// bind(StoreService.class)
// .to(InMemoryStore.class)
// .asEagerSingleton();
// }
// }
// Path: rest/java/src/main/java/de/hda/fbi/ds/mbredel/Main.java
import org.apache.commons.cli.*;
import akka.actor.ActorSystem;
import com.google.inject.Guice;
import com.google.inject.Injector;
import de.hda.fbi.ds.mbredel.configuration.CliParameters;
import de.hda.fbi.ds.mbredel.configuration.ConfigurationModule;
import de.hda.fbi.ds.mbredel.core.Application;
import de.hda.fbi.ds.mbredel.core.ApplicationModule;
import de.hda.fbi.ds.mbredel.core.Constants;
import de.hda.fbi.ds.mbredel.store.StoreModule;
Options options = new Options();
options.addOption(help);
options.addOption(config);
options.addOption(username);
options.addOption(password);
// Return options.
return options;
}
/**
* Parses the command line arguments.
*
* @param args The command line arguments.
*/
private static void parseCliOptions(String[] args) {
// Command line options.
Options options = createCliOptions();
// Command line parser.
CommandLineParser parser = new DefaultParser();
try {
// Parse the command line arguments
CommandLine line = parser.parse(options, args);
if (line.hasOption('h')) {
printHelp(options);
System.exit(0);
}
if (line.hasOption('c')) { | CliParameters.getInstance().setUri(line.getOptionValue('c')); |
pjq/rpi | android/app/src/main/java/me/pjq/rpicar/widget/RadarView.java | // Path: android/app/src/main/java/me/pjq/rpicar/utils/Utils.java
// public class Utils {
// public static int[] Getrandomarray(int i, int i1) {
// int size = 11;
// int[] value = new int[size];
// for (int j = 0; j < size; j++) {
// value[j] = j;
// }
//
// return value;
// }
// }
| import android.content.Context;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Matrix;
import android.graphics.Paint;
import android.graphics.Shader;
import android.graphics.SweepGradient;
import android.support.annotation.IntDef;
import android.util.AttributeSet;
import android.widget.FrameLayout;
import me.pjq.rpicar.utils.Utils; | // TODO Auto-generated method stub
setBackgroundColor(Color.TRANSPARENT);
//宽度=5,抗锯齿,描边效果的白色画笔
mPaintLine = new Paint();
mPaintLine.setStrokeWidth(5);
mPaintLine.setAntiAlias(true);
mPaintLine.setStyle(Paint.Style.STROKE);
mPaintLine.setColor(Color.WHITE);
//宽度=5,抗锯齿,描边效果的浅绿色画笔
mPaintCircle = new Paint();
mPaintCircle.setStrokeWidth(5);
mPaintCircle.setAntiAlias(true);
mPaintCircle.setStyle(Paint.Style.FILL);
mPaintCircle.setColor(0x99000000);
//暗绿色的画笔
mPaintSector = new Paint();
mPaintSector.setColor(0x9D00ff00);
mPaintSector.setAntiAlias(true);
mShader = new SweepGradient(viewSize / 2, viewSize / 2, Color.TRANSPARENT, Color.GREEN);
mPaintSector.setShader(mShader);
//白色实心画笔
mPaintPoint=new Paint();
mPaintPoint.setColor(Color.WHITE);
mPaintPoint.setStyle(Paint.Style.FILL);
//随机生成的点,模拟雷达扫描结果 | // Path: android/app/src/main/java/me/pjq/rpicar/utils/Utils.java
// public class Utils {
// public static int[] Getrandomarray(int i, int i1) {
// int size = 11;
// int[] value = new int[size];
// for (int j = 0; j < size; j++) {
// value[j] = j;
// }
//
// return value;
// }
// }
// Path: android/app/src/main/java/me/pjq/rpicar/widget/RadarView.java
import android.content.Context;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Matrix;
import android.graphics.Paint;
import android.graphics.Shader;
import android.graphics.SweepGradient;
import android.support.annotation.IntDef;
import android.util.AttributeSet;
import android.widget.FrameLayout;
import me.pjq.rpicar.utils.Utils;
// TODO Auto-generated method stub
setBackgroundColor(Color.TRANSPARENT);
//宽度=5,抗锯齿,描边效果的白色画笔
mPaintLine = new Paint();
mPaintLine.setStrokeWidth(5);
mPaintLine.setAntiAlias(true);
mPaintLine.setStyle(Paint.Style.STROKE);
mPaintLine.setColor(Color.WHITE);
//宽度=5,抗锯齿,描边效果的浅绿色画笔
mPaintCircle = new Paint();
mPaintCircle.setStrokeWidth(5);
mPaintCircle.setAntiAlias(true);
mPaintCircle.setStyle(Paint.Style.FILL);
mPaintCircle.setColor(0x99000000);
//暗绿色的画笔
mPaintSector = new Paint();
mPaintSector.setColor(0x9D00ff00);
mPaintSector.setAntiAlias(true);
mShader = new SweepGradient(viewSize / 2, viewSize / 2, Color.TRANSPARENT, Color.GREEN);
mPaintSector.setShader(mShader);
//白色实心画笔
mPaintPoint=new Paint();
mPaintPoint.setColor(Color.WHITE);
mPaintPoint.setStyle(Paint.Style.FILL);
//随机生成的点,模拟雷达扫描结果 | point_x = Utils.Getrandomarray(15, 300); |
pjq/rpi | spring-server/src/main/java/me/pjq/Constants.java | // Path: spring-server/src/main/java/me/pjq/Utils/Log.java
// public class Log {
// static String dateFormat = "yyyy-MM-dd hh:mm:ss";
// static SimpleDateFormat fm = new SimpleDateFormat("yyyy-MM-dd hh:mm:ss.SSS");
// static boolean showLog = true;
//
// public static void log(String tag, String msg) {
// if (showLog) {
// String source = null;
// try {
// StackTraceElement st = Thread.currentThread().getStackTrace()[2];
// source = "[" + st.getFileName() + "] - " + st.getMethodName() + "("
// + st.getLineNumber() + ")";
// } catch (Exception e) {
// }
//
// System.out.println(fm.format(new Date()) + " - " + source + ":" + msg);
// }
// }
// }
//
// Path: spring-server/src/main/java/me/pjq/model/Config.java
// public class Config {
// public String deviceName;
// public String productKey;
// public String secret;
// public String pubTopic;
// public String subTopic;
//
// public String accessKeyId;
// public String accessKeySecret;
// public String phone;
// public String signName;
// public String templateCode;
// //10 seconds, interval for SensorStatus update.
// public long SENSOR_STATUS_UPDATE_INTERVAL;
// // duration for auto turn off the power via relay control
// public long RELAY_OFF_INTERVAL;
//
// public Config(String deviceName, String productKey, String secret) {
// this.deviceName = deviceName;
// this.productKey = productKey;
// this.secret = secret;
// //用于测试的topic
// pubTopic = "/" + productKey + "/" + deviceName + "/update";
// subTopic = "/" + productKey + "/" + deviceName + "/get";
// }
//
// public static Config getConfigRpiCarHome() {
// String deviceName = "RpiCarHome";
// String productKey = "tKB3pmbLvnA";
// String secret = "fT9ryVgfucZNs2g0VZkj8kzV3eNjY55E";
//
// return new Config(deviceName, productKey, secret);
// }
//
// public static Config getConfigRpiCarClient() {
// String deviceName = "RpiCarClient";
// String productKey = "tKB3pmbLvnA";
// String secret = "w7TT5kvx1xdzfVogH7RfUUto4kWoSCq4";
//
// return new Config(deviceName, productKey, secret);
// }
// }
| import me.pjq.Utils.Log;
import me.pjq.model.Config;
import java.io.*;
import java.util.Enumeration;
import java.util.HashMap;
import java.util.Properties; | package me.pjq;
public enum Constants {
INSTANCE;
private static final String TAG = "Constants";
// public static String deviceName = "RpiCarHome";
// public static String productKey = "tKB3pmbLvnA";
// public static String secret = "fT9ryVgfucZNs2g0VZkj8kzV3eNjY55E";
// public static String deviceName = "RpiCarClient";
// public static String productKey = "tKB3pmbLvnA";
// public static String secret = "w7TT5kvx1xdzfVogH7RfUUto4kWoSCq4";
// public static String aK1="LTAICKNMlWB";
// public static String aK2="xm7GR";
// public static String accessKeyId = aK1+aK2;
// public static String accessKeySecret = "cMgi0pjAewppBdpESDlI3CXZpAKFwc";
// public static String phone = "18621517768";
// public static String signName = "树霉派IoT";
// public static String templateCode = "SMS_110310049";
//10 seconds, interval for SensorStatus update.
// public static long SENSOR_STATUS_UPDATE_INTERVAL = 10000;
// duration for auto turn off the power via relay control
// public static long RELAY_OFF_INTERVAL = 30 * 1000;
// public static String pubTopic = "/" + productKey + "/" + deviceName + "/update";
//用于测试的topic
// public static String subTopic = "/" + productKey + "/" + deviceName + "/get";
private static final String CONFIG_FILE = "config.properties";
private static final String CONFIG_FILE_DEFAULT = "./src/main/resources/config.properties"; | // Path: spring-server/src/main/java/me/pjq/Utils/Log.java
// public class Log {
// static String dateFormat = "yyyy-MM-dd hh:mm:ss";
// static SimpleDateFormat fm = new SimpleDateFormat("yyyy-MM-dd hh:mm:ss.SSS");
// static boolean showLog = true;
//
// public static void log(String tag, String msg) {
// if (showLog) {
// String source = null;
// try {
// StackTraceElement st = Thread.currentThread().getStackTrace()[2];
// source = "[" + st.getFileName() + "] - " + st.getMethodName() + "("
// + st.getLineNumber() + ")";
// } catch (Exception e) {
// }
//
// System.out.println(fm.format(new Date()) + " - " + source + ":" + msg);
// }
// }
// }
//
// Path: spring-server/src/main/java/me/pjq/model/Config.java
// public class Config {
// public String deviceName;
// public String productKey;
// public String secret;
// public String pubTopic;
// public String subTopic;
//
// public String accessKeyId;
// public String accessKeySecret;
// public String phone;
// public String signName;
// public String templateCode;
// //10 seconds, interval for SensorStatus update.
// public long SENSOR_STATUS_UPDATE_INTERVAL;
// // duration for auto turn off the power via relay control
// public long RELAY_OFF_INTERVAL;
//
// public Config(String deviceName, String productKey, String secret) {
// this.deviceName = deviceName;
// this.productKey = productKey;
// this.secret = secret;
// //用于测试的topic
// pubTopic = "/" + productKey + "/" + deviceName + "/update";
// subTopic = "/" + productKey + "/" + deviceName + "/get";
// }
//
// public static Config getConfigRpiCarHome() {
// String deviceName = "RpiCarHome";
// String productKey = "tKB3pmbLvnA";
// String secret = "fT9ryVgfucZNs2g0VZkj8kzV3eNjY55E";
//
// return new Config(deviceName, productKey, secret);
// }
//
// public static Config getConfigRpiCarClient() {
// String deviceName = "RpiCarClient";
// String productKey = "tKB3pmbLvnA";
// String secret = "w7TT5kvx1xdzfVogH7RfUUto4kWoSCq4";
//
// return new Config(deviceName, productKey, secret);
// }
// }
// Path: spring-server/src/main/java/me/pjq/Constants.java
import me.pjq.Utils.Log;
import me.pjq.model.Config;
import java.io.*;
import java.util.Enumeration;
import java.util.HashMap;
import java.util.Properties;
package me.pjq;
public enum Constants {
INSTANCE;
private static final String TAG = "Constants";
// public static String deviceName = "RpiCarHome";
// public static String productKey = "tKB3pmbLvnA";
// public static String secret = "fT9ryVgfucZNs2g0VZkj8kzV3eNjY55E";
// public static String deviceName = "RpiCarClient";
// public static String productKey = "tKB3pmbLvnA";
// public static String secret = "w7TT5kvx1xdzfVogH7RfUUto4kWoSCq4";
// public static String aK1="LTAICKNMlWB";
// public static String aK2="xm7GR";
// public static String accessKeyId = aK1+aK2;
// public static String accessKeySecret = "cMgi0pjAewppBdpESDlI3CXZpAKFwc";
// public static String phone = "18621517768";
// public static String signName = "树霉派IoT";
// public static String templateCode = "SMS_110310049";
//10 seconds, interval for SensorStatus update.
// public static long SENSOR_STATUS_UPDATE_INTERVAL = 10000;
// duration for auto turn off the power via relay control
// public static long RELAY_OFF_INTERVAL = 30 * 1000;
// public static String pubTopic = "/" + productKey + "/" + deviceName + "/update";
//用于测试的topic
// public static String subTopic = "/" + productKey + "/" + deviceName + "/get";
private static final String CONFIG_FILE = "config.properties";
private static final String CONFIG_FILE_DEFAULT = "./src/main/resources/config.properties"; | private Config config; |
pjq/rpi | spring-server/src/main/java/me/pjq/Constants.java | // Path: spring-server/src/main/java/me/pjq/Utils/Log.java
// public class Log {
// static String dateFormat = "yyyy-MM-dd hh:mm:ss";
// static SimpleDateFormat fm = new SimpleDateFormat("yyyy-MM-dd hh:mm:ss.SSS");
// static boolean showLog = true;
//
// public static void log(String tag, String msg) {
// if (showLog) {
// String source = null;
// try {
// StackTraceElement st = Thread.currentThread().getStackTrace()[2];
// source = "[" + st.getFileName() + "] - " + st.getMethodName() + "("
// + st.getLineNumber() + ")";
// } catch (Exception e) {
// }
//
// System.out.println(fm.format(new Date()) + " - " + source + ":" + msg);
// }
// }
// }
//
// Path: spring-server/src/main/java/me/pjq/model/Config.java
// public class Config {
// public String deviceName;
// public String productKey;
// public String secret;
// public String pubTopic;
// public String subTopic;
//
// public String accessKeyId;
// public String accessKeySecret;
// public String phone;
// public String signName;
// public String templateCode;
// //10 seconds, interval for SensorStatus update.
// public long SENSOR_STATUS_UPDATE_INTERVAL;
// // duration for auto turn off the power via relay control
// public long RELAY_OFF_INTERVAL;
//
// public Config(String deviceName, String productKey, String secret) {
// this.deviceName = deviceName;
// this.productKey = productKey;
// this.secret = secret;
// //用于测试的topic
// pubTopic = "/" + productKey + "/" + deviceName + "/update";
// subTopic = "/" + productKey + "/" + deviceName + "/get";
// }
//
// public static Config getConfigRpiCarHome() {
// String deviceName = "RpiCarHome";
// String productKey = "tKB3pmbLvnA";
// String secret = "fT9ryVgfucZNs2g0VZkj8kzV3eNjY55E";
//
// return new Config(deviceName, productKey, secret);
// }
//
// public static Config getConfigRpiCarClient() {
// String deviceName = "RpiCarClient";
// String productKey = "tKB3pmbLvnA";
// String secret = "w7TT5kvx1xdzfVogH7RfUUto4kWoSCq4";
//
// return new Config(deviceName, productKey, secret);
// }
// }
| import me.pjq.Utils.Log;
import me.pjq.model.Config;
import java.io.*;
import java.util.Enumeration;
import java.util.HashMap;
import java.util.Properties; | package me.pjq;
public enum Constants {
INSTANCE;
private static final String TAG = "Constants";
// public static String deviceName = "RpiCarHome";
// public static String productKey = "tKB3pmbLvnA";
// public static String secret = "fT9ryVgfucZNs2g0VZkj8kzV3eNjY55E";
// public static String deviceName = "RpiCarClient";
// public static String productKey = "tKB3pmbLvnA";
// public static String secret = "w7TT5kvx1xdzfVogH7RfUUto4kWoSCq4";
// public static String aK1="LTAICKNMlWB";
// public static String aK2="xm7GR";
// public static String accessKeyId = aK1+aK2;
// public static String accessKeySecret = "cMgi0pjAewppBdpESDlI3CXZpAKFwc";
// public static String phone = "18621517768";
// public static String signName = "树霉派IoT";
// public static String templateCode = "SMS_110310049";
//10 seconds, interval for SensorStatus update.
// public static long SENSOR_STATUS_UPDATE_INTERVAL = 10000;
// duration for auto turn off the power via relay control
// public static long RELAY_OFF_INTERVAL = 30 * 1000;
// public static String pubTopic = "/" + productKey + "/" + deviceName + "/update";
//用于测试的topic
// public static String subTopic = "/" + productKey + "/" + deviceName + "/get";
private static final String CONFIG_FILE = "config.properties";
private static final String CONFIG_FILE_DEFAULT = "./src/main/resources/config.properties";
private Config config;
public Config getConfig() {
return config;
}
private Constants() {
try {
config = getAllProperties();
} catch (IOException e) {
e.printStackTrace();
}
}
//读取Properties的全部信息
public static HashMap<String, String> getAllProperties(String filePath) throws IOException {
Properties pps = new Properties();
InputStream in = new BufferedInputStream(new FileInputStream(filePath));
pps.load(in);
Enumeration en = pps.propertyNames(); //得到配置文件的名字
HashMap<String, String> map = new HashMap<>();
while (en.hasMoreElements()) {
String strKey = (String) en.nextElement();
String strValue = pps.getProperty(strKey);
strValue = new String(strValue.getBytes("ISO-8859-1"), "utf-8"); | // Path: spring-server/src/main/java/me/pjq/Utils/Log.java
// public class Log {
// static String dateFormat = "yyyy-MM-dd hh:mm:ss";
// static SimpleDateFormat fm = new SimpleDateFormat("yyyy-MM-dd hh:mm:ss.SSS");
// static boolean showLog = true;
//
// public static void log(String tag, String msg) {
// if (showLog) {
// String source = null;
// try {
// StackTraceElement st = Thread.currentThread().getStackTrace()[2];
// source = "[" + st.getFileName() + "] - " + st.getMethodName() + "("
// + st.getLineNumber() + ")";
// } catch (Exception e) {
// }
//
// System.out.println(fm.format(new Date()) + " - " + source + ":" + msg);
// }
// }
// }
//
// Path: spring-server/src/main/java/me/pjq/model/Config.java
// public class Config {
// public String deviceName;
// public String productKey;
// public String secret;
// public String pubTopic;
// public String subTopic;
//
// public String accessKeyId;
// public String accessKeySecret;
// public String phone;
// public String signName;
// public String templateCode;
// //10 seconds, interval for SensorStatus update.
// public long SENSOR_STATUS_UPDATE_INTERVAL;
// // duration for auto turn off the power via relay control
// public long RELAY_OFF_INTERVAL;
//
// public Config(String deviceName, String productKey, String secret) {
// this.deviceName = deviceName;
// this.productKey = productKey;
// this.secret = secret;
// //用于测试的topic
// pubTopic = "/" + productKey + "/" + deviceName + "/update";
// subTopic = "/" + productKey + "/" + deviceName + "/get";
// }
//
// public static Config getConfigRpiCarHome() {
// String deviceName = "RpiCarHome";
// String productKey = "tKB3pmbLvnA";
// String secret = "fT9ryVgfucZNs2g0VZkj8kzV3eNjY55E";
//
// return new Config(deviceName, productKey, secret);
// }
//
// public static Config getConfigRpiCarClient() {
// String deviceName = "RpiCarClient";
// String productKey = "tKB3pmbLvnA";
// String secret = "w7TT5kvx1xdzfVogH7RfUUto4kWoSCq4";
//
// return new Config(deviceName, productKey, secret);
// }
// }
// Path: spring-server/src/main/java/me/pjq/Constants.java
import me.pjq.Utils.Log;
import me.pjq.model.Config;
import java.io.*;
import java.util.Enumeration;
import java.util.HashMap;
import java.util.Properties;
package me.pjq;
public enum Constants {
INSTANCE;
private static final String TAG = "Constants";
// public static String deviceName = "RpiCarHome";
// public static String productKey = "tKB3pmbLvnA";
// public static String secret = "fT9ryVgfucZNs2g0VZkj8kzV3eNjY55E";
// public static String deviceName = "RpiCarClient";
// public static String productKey = "tKB3pmbLvnA";
// public static String secret = "w7TT5kvx1xdzfVogH7RfUUto4kWoSCq4";
// public static String aK1="LTAICKNMlWB";
// public static String aK2="xm7GR";
// public static String accessKeyId = aK1+aK2;
// public static String accessKeySecret = "cMgi0pjAewppBdpESDlI3CXZpAKFwc";
// public static String phone = "18621517768";
// public static String signName = "树霉派IoT";
// public static String templateCode = "SMS_110310049";
//10 seconds, interval for SensorStatus update.
// public static long SENSOR_STATUS_UPDATE_INTERVAL = 10000;
// duration for auto turn off the power via relay control
// public static long RELAY_OFF_INTERVAL = 30 * 1000;
// public static String pubTopic = "/" + productKey + "/" + deviceName + "/update";
//用于测试的topic
// public static String subTopic = "/" + productKey + "/" + deviceName + "/get";
private static final String CONFIG_FILE = "config.properties";
private static final String CONFIG_FILE_DEFAULT = "./src/main/resources/config.properties";
private Config config;
public Config getConfig() {
return config;
}
private Constants() {
try {
config = getAllProperties();
} catch (IOException e) {
e.printStackTrace();
}
}
//读取Properties的全部信息
public static HashMap<String, String> getAllProperties(String filePath) throws IOException {
Properties pps = new Properties();
InputStream in = new BufferedInputStream(new FileInputStream(filePath));
pps.load(in);
Enumeration en = pps.propertyNames(); //得到配置文件的名字
HashMap<String, String> map = new HashMap<>();
while (en.hasMoreElements()) {
String strKey = (String) en.nextElement();
String strValue = pps.getProperty(strKey);
strValue = new String(strValue.getBytes("ISO-8859-1"), "utf-8"); | Log.log(TAG, strKey + "=" + strValue); |
pjq/rpi | android/app/src/main/java/me/pjq/rpicar/Constants.java | // Path: android/app/src/main/java/me/pjq/rpicar/utils/Log.java
// public class Log {
// static String dateFormat = "yyyy-MM-dd hh:mm:ss";
// static SimpleDateFormat fm = new SimpleDateFormat("yyyy-MM-dd hh:mm:ss.SSS");
// static boolean showLog = true;
//
// public static void log(String tag, String msg) {
// if (showLog) {
// String source = null;
// try {
// StackTraceElement st = Thread.currentThread().getStackTrace()[2];
// source = "[" + st.getFileName() + "] - " + st.getMethodName() + "("
// + st.getLineNumber() + ")";
// } catch (Exception e) {
// }
//
// System.out.println(fm.format(new Date()) + " - " + source + ":" + msg);
// }
// }
// }
| import java.io.*;
import java.util.Enumeration;
import java.util.HashMap;
import java.util.Properties;
import me.pjq.rpicar.utils.Log; | package me.pjq.rpicar;
public enum Constants {
INSTANCE;
private static final String TAG = "Constants";
public static String deviceName = "RpiCarHome";
public static String productKey = "tKB3pmbLvnA";
public static String secret = "fT9ryVgfucZNs2g0VZkj8kzV3eNjY55E";
// public static String deviceName = "RpiCarClient";
// public static String productKey = "tKB3pmbLvnA";
// public static String secret = "w7TT5kvx1xdzfVogH7RfUUto4kWoSCq4";
public static String aK1="LTAICKNMlWB";
public static String aK2="xm7GR";
public static String accessKeyId = "LTAICKNMlWBxm7GR";
public static String accessKeySecret = "cMgi0pjAewppBdpESDlI3CXZpAKFwc";
public static String phone = "18621517768";
public static String signName = "树霉派IoT";
public static String templateCode = "SMS_110310049";
public static String pubTopic = "/" + productKey + "/" + deviceName + "/update";
//用于测试的topic
public static String subTopic = "/" + productKey + "/" + deviceName + "/get";
// private static final String CONFIG_FILE = "./src/main/resources/config.properties";
private static final String CONFIG_FILE = "config.properties";
//10 seconds, interval for SensorStatus update.
public static final long SENSOR_STATUS_UPDATE_INTERVAL = 10000;
// long RELAY_OFF_INTERVAL = 5 * 60 * 1000;
// duration for auto turn off the power via relay control
public static long RELAY_OFF_INTERVAL = 30 * 1000;
private Constants() {
try { | // Path: android/app/src/main/java/me/pjq/rpicar/utils/Log.java
// public class Log {
// static String dateFormat = "yyyy-MM-dd hh:mm:ss";
// static SimpleDateFormat fm = new SimpleDateFormat("yyyy-MM-dd hh:mm:ss.SSS");
// static boolean showLog = true;
//
// public static void log(String tag, String msg) {
// if (showLog) {
// String source = null;
// try {
// StackTraceElement st = Thread.currentThread().getStackTrace()[2];
// source = "[" + st.getFileName() + "] - " + st.getMethodName() + "("
// + st.getLineNumber() + ")";
// } catch (Exception e) {
// }
//
// System.out.println(fm.format(new Date()) + " - " + source + ":" + msg);
// }
// }
// }
// Path: android/app/src/main/java/me/pjq/rpicar/Constants.java
import java.io.*;
import java.util.Enumeration;
import java.util.HashMap;
import java.util.Properties;
import me.pjq.rpicar.utils.Log;
package me.pjq.rpicar;
public enum Constants {
INSTANCE;
private static final String TAG = "Constants";
public static String deviceName = "RpiCarHome";
public static String productKey = "tKB3pmbLvnA";
public static String secret = "fT9ryVgfucZNs2g0VZkj8kzV3eNjY55E";
// public static String deviceName = "RpiCarClient";
// public static String productKey = "tKB3pmbLvnA";
// public static String secret = "w7TT5kvx1xdzfVogH7RfUUto4kWoSCq4";
public static String aK1="LTAICKNMlWB";
public static String aK2="xm7GR";
public static String accessKeyId = "LTAICKNMlWBxm7GR";
public static String accessKeySecret = "cMgi0pjAewppBdpESDlI3CXZpAKFwc";
public static String phone = "18621517768";
public static String signName = "树霉派IoT";
public static String templateCode = "SMS_110310049";
public static String pubTopic = "/" + productKey + "/" + deviceName + "/update";
//用于测试的topic
public static String subTopic = "/" + productKey + "/" + deviceName + "/get";
// private static final String CONFIG_FILE = "./src/main/resources/config.properties";
private static final String CONFIG_FILE = "config.properties";
//10 seconds, interval for SensorStatus update.
public static final long SENSOR_STATUS_UPDATE_INTERVAL = 10000;
// long RELAY_OFF_INTERVAL = 5 * 60 * 1000;
// duration for auto turn off the power via relay control
public static long RELAY_OFF_INTERVAL = 30 * 1000;
private Constants() {
try { | Log.log(TAG, "init: " + CONFIG_FILE); |
RomRaider/RomRaider | src/main/java/com/romraider/logger/ecu/definition/EcuParameterConvertorImpl.java | // Path: src/main/java/com/romraider/util/JEPUtil.java
// public static synchronized double evaluate(String expression, double value) {
// JEP parser = parserCache.get(expression);
// if (parser == null) {
// parser = new JEP();
// parser.addStandardFunctions();
// parser.addFunction("BitWise", new BitWise());
// parser.initSymTab(); // clear the contents of the symbol table
// parser.addVariable("x", value);
// parser.parseExpression(expression);
// parserCache.put(expression, parser);
// } else {
// parser.setVarValue("x", value);
// }
// return parser.getValue();
// }
| import com.romraider.Settings;
import com.romraider.logger.ecu.ui.handler.dash.GaugeMinMax;
import static com.romraider.logger.ecu.definition.xml.ConverterMaxMinDefaults.getDefault;
import static com.romraider.util.ByteUtil.asUnsignedInt;
import static com.romraider.util.JEPUtil.evaluate;
import static com.romraider.util.ParamChecker.checkNotNull;
import static com.romraider.util.ParamChecker.checkNotNullOrEmpty;
import java.nio.ByteBuffer;
import java.nio.ByteOrder;
import java.text.DecimalFormat;
import java.util.HashMap;
import java.util.Map; |
public EcuParameterConvertorImpl(String units, String expression,
String format, int bit, String dataType, Settings.Endian endian,
Map<String, String> replaceMap, GaugeMinMax gaugeMinMax) {
checkNotNullOrEmpty(units, "units");
checkNotNullOrEmpty(expression, "expression");
checkNotNullOrEmpty(format, "format");
checkNotNull(replaceMap, "replaceMap");
this.units = units;
this.expression = expression;
this.format = new DecimalFormat(format);
this.bit = bit;
this.dataType = (dataType == null ? "uint8" : dataType);
this.endian = endian;
this.replaceMap = replaceMap;
this.gaugeMinMax = gaugeMinMax;
}
public double convert(byte[] bytes) {
final ByteBuffer bb = ByteBuffer.wrap(bytes);
if (endian == Settings.Endian.LITTLE) {
bb.order(ByteOrder.LITTLE_ENDIAN);
}
double result = 0;
if (bit >= 0 && bit <= 31) {
return (asUnsignedInt(bytes) & (1 << bit)) != 0 ? 1 : 0;
}
else if (dataType.equalsIgnoreCase(FLOAT)) { | // Path: src/main/java/com/romraider/util/JEPUtil.java
// public static synchronized double evaluate(String expression, double value) {
// JEP parser = parserCache.get(expression);
// if (parser == null) {
// parser = new JEP();
// parser.addStandardFunctions();
// parser.addFunction("BitWise", new BitWise());
// parser.initSymTab(); // clear the contents of the symbol table
// parser.addVariable("x", value);
// parser.parseExpression(expression);
// parserCache.put(expression, parser);
// } else {
// parser.setVarValue("x", value);
// }
// return parser.getValue();
// }
// Path: src/main/java/com/romraider/logger/ecu/definition/EcuParameterConvertorImpl.java
import com.romraider.Settings;
import com.romraider.logger.ecu.ui.handler.dash.GaugeMinMax;
import static com.romraider.logger.ecu.definition.xml.ConverterMaxMinDefaults.getDefault;
import static com.romraider.util.ByteUtil.asUnsignedInt;
import static com.romraider.util.JEPUtil.evaluate;
import static com.romraider.util.ParamChecker.checkNotNull;
import static com.romraider.util.ParamChecker.checkNotNullOrEmpty;
import java.nio.ByteBuffer;
import java.nio.ByteOrder;
import java.text.DecimalFormat;
import java.util.HashMap;
import java.util.Map;
public EcuParameterConvertorImpl(String units, String expression,
String format, int bit, String dataType, Settings.Endian endian,
Map<String, String> replaceMap, GaugeMinMax gaugeMinMax) {
checkNotNullOrEmpty(units, "units");
checkNotNullOrEmpty(expression, "expression");
checkNotNullOrEmpty(format, "format");
checkNotNull(replaceMap, "replaceMap");
this.units = units;
this.expression = expression;
this.format = new DecimalFormat(format);
this.bit = bit;
this.dataType = (dataType == null ? "uint8" : dataType);
this.endian = endian;
this.replaceMap = replaceMap;
this.gaugeMinMax = gaugeMinMax;
}
public double convert(byte[] bytes) {
final ByteBuffer bb = ByteBuffer.wrap(bytes);
if (endian == Settings.Endian.LITTLE) {
bb.order(ByteOrder.LITTLE_ENDIAN);
}
double result = 0;
if (bit >= 0 && bit <= 31) {
return (asUnsignedInt(bytes) & (1 << bit)) != 0 ? 1 : 0;
}
else if (dataType.equalsIgnoreCase(FLOAT)) { | result = evaluate(expression, bb.getFloat()); |
RomRaider/RomRaider | src/main/java/com/romraider/maps/DataCellView.java | // Path: src/main/java/com/romraider/util/JEPUtil.java
// public final class JEPUtil {
// @SuppressWarnings("serial")
// static class LRUCache<K, V> extends LinkedHashMap<K, V> {
// private int cacheSize;
//
// public LRUCache(int cacheSize) {
// super(32, 0.75f, true);
// this.cacheSize = cacheSize;
// }
//
// @Override
// protected boolean removeEldestEntry(Map.Entry<K, V> eldest) {
// return size() >= cacheSize;
// }
// };
//
// private static final Map<String, JEP> parserCache =
// Collections.synchronizedMap(new LRUCache<String, JEP>(32));
//
// public static synchronized double evaluate(String expression, double value) {
// JEP parser = parserCache.get(expression);
// if (parser == null) {
// parser = new JEP();
// parser.addStandardFunctions();
// parser.addFunction("BitWise", new BitWise());
// parser.initSymTab(); // clear the contents of the symbol table
// parser.addVariable("x", value);
// parser.parseExpression(expression);
// parserCache.put(expression, parser);
// } else {
// parser.setVarValue("x", value);
// }
// return parser.getValue();
// }
//
// public static synchronized double evaluate(String expression, Map<String, Double> valueMap) {
// JEP parser = parserCache.get(expression);
// if (parser == null) {
// parser = new JEP();
// parser.initSymTab(); // clear the contents of the symbol table
// for (String id : valueMap.keySet()) {
// parser.addVariable(id, valueMap.get(id));
// }
// parser.parseExpression(expression);
// parserCache.put(expression, parser);
// }
// else {
// for (String id : valueMap.keySet()) {
// parser.setVarValue(id, valueMap.get(id));
// }
// }
// return parser.getValue();
// }
// }
//
// Path: src/main/java/com/romraider/util/NumberUtil.java
// public final class NumberUtil {
// private static final NumberFormat NUM_FORMATTER = NumberFormat.getInstance(Locale.getDefault());
// private static final String NAN = "NaN";
// static {
// ((DecimalFormat) NUM_FORMATTER).applyPattern("0.0#################");
// }
//
// private NumberUtil() {
// }
//
// /**
// * Returns the separator based on the current locale (. or ,)
// * @return The separation character
// */
// public static char getSeperator(){
// return ((DecimalFormat) NUM_FORMATTER).getDecimalFormatSymbols().getDecimalSeparator();
// }
//
// /**
// * Returns the value of the specified number in the default locale as a double.
// * @param str - string to be converted.
// * @return the numeric value represented by this object after conversion
// * to type double.
// * @exception ParseException is thrown when parse errors are encountered.
// */
// public static double doubleValue(String str) throws ParseException {
// return NUM_FORMATTER.parse(str).doubleValue();
// }
//
// /**
// * Format a double using the current Locale
// * @param value to format
// * @return the number as a String
// */
// public static String stringValue(double value) {
// return Double.isNaN(value) ? NAN : NUM_FORMATTER.format(value);
// }
// }
| import javax.swing.JLabel;
import javax.swing.border.Border;
import com.romraider.Settings;
import com.romraider.editor.ecu.ECUEditorManager;
import com.romraider.util.JEPUtil;
import com.romraider.util.NumberUtil;
import com.romraider.util.SettingsManager;
import static com.romraider.util.ColorScaler.getScaledColor;
import static com.romraider.util.ParamChecker.isNullOrEmpty;
import static javax.swing.BorderFactory.createLineBorder;
import java.awt.Color;
import java.awt.Font;
import java.awt.event.MouseEvent;
import java.awt.event.MouseListener;
import java.io.Serializable;
import java.text.DecimalFormat; | drawCell();
}
}
public boolean isHighlighted() {
return highlighted;
}
public void setLiveDataTrace(boolean trace) {
if(traced != trace) {
traced = trace;
drawCell();
}
}
public void setPreviousLiveDataTrace(boolean trace) {
if(tracedStale != trace) {
tracedStale = trace;
drawCell();
}
}
private String getLiveValueString(String currentValue) {
return currentValue + (isNullOrEmpty(dataCell.getLiveValue()) ? Settings.BLANK : (':' + dataCell.getLiveValue()));
}
public String getStaticText() {
String displayString = null;
try {
FORMATTER.applyPattern(tableView.getTable().getCurrentScale().getFormat()); | // Path: src/main/java/com/romraider/util/JEPUtil.java
// public final class JEPUtil {
// @SuppressWarnings("serial")
// static class LRUCache<K, V> extends LinkedHashMap<K, V> {
// private int cacheSize;
//
// public LRUCache(int cacheSize) {
// super(32, 0.75f, true);
// this.cacheSize = cacheSize;
// }
//
// @Override
// protected boolean removeEldestEntry(Map.Entry<K, V> eldest) {
// return size() >= cacheSize;
// }
// };
//
// private static final Map<String, JEP> parserCache =
// Collections.synchronizedMap(new LRUCache<String, JEP>(32));
//
// public static synchronized double evaluate(String expression, double value) {
// JEP parser = parserCache.get(expression);
// if (parser == null) {
// parser = new JEP();
// parser.addStandardFunctions();
// parser.addFunction("BitWise", new BitWise());
// parser.initSymTab(); // clear the contents of the symbol table
// parser.addVariable("x", value);
// parser.parseExpression(expression);
// parserCache.put(expression, parser);
// } else {
// parser.setVarValue("x", value);
// }
// return parser.getValue();
// }
//
// public static synchronized double evaluate(String expression, Map<String, Double> valueMap) {
// JEP parser = parserCache.get(expression);
// if (parser == null) {
// parser = new JEP();
// parser.initSymTab(); // clear the contents of the symbol table
// for (String id : valueMap.keySet()) {
// parser.addVariable(id, valueMap.get(id));
// }
// parser.parseExpression(expression);
// parserCache.put(expression, parser);
// }
// else {
// for (String id : valueMap.keySet()) {
// parser.setVarValue(id, valueMap.get(id));
// }
// }
// return parser.getValue();
// }
// }
//
// Path: src/main/java/com/romraider/util/NumberUtil.java
// public final class NumberUtil {
// private static final NumberFormat NUM_FORMATTER = NumberFormat.getInstance(Locale.getDefault());
// private static final String NAN = "NaN";
// static {
// ((DecimalFormat) NUM_FORMATTER).applyPattern("0.0#################");
// }
//
// private NumberUtil() {
// }
//
// /**
// * Returns the separator based on the current locale (. or ,)
// * @return The separation character
// */
// public static char getSeperator(){
// return ((DecimalFormat) NUM_FORMATTER).getDecimalFormatSymbols().getDecimalSeparator();
// }
//
// /**
// * Returns the value of the specified number in the default locale as a double.
// * @param str - string to be converted.
// * @return the numeric value represented by this object after conversion
// * to type double.
// * @exception ParseException is thrown when parse errors are encountered.
// */
// public static double doubleValue(String str) throws ParseException {
// return NUM_FORMATTER.parse(str).doubleValue();
// }
//
// /**
// * Format a double using the current Locale
// * @param value to format
// * @return the number as a String
// */
// public static String stringValue(double value) {
// return Double.isNaN(value) ? NAN : NUM_FORMATTER.format(value);
// }
// }
// Path: src/main/java/com/romraider/maps/DataCellView.java
import javax.swing.JLabel;
import javax.swing.border.Border;
import com.romraider.Settings;
import com.romraider.editor.ecu.ECUEditorManager;
import com.romraider.util.JEPUtil;
import com.romraider.util.NumberUtil;
import com.romraider.util.SettingsManager;
import static com.romraider.util.ColorScaler.getScaledColor;
import static com.romraider.util.ParamChecker.isNullOrEmpty;
import static javax.swing.BorderFactory.createLineBorder;
import java.awt.Color;
import java.awt.Font;
import java.awt.event.MouseEvent;
import java.awt.event.MouseListener;
import java.io.Serializable;
import java.text.DecimalFormat;
drawCell();
}
}
public boolean isHighlighted() {
return highlighted;
}
public void setLiveDataTrace(boolean trace) {
if(traced != trace) {
traced = trace;
drawCell();
}
}
public void setPreviousLiveDataTrace(boolean trace) {
if(tracedStale != trace) {
tracedStale = trace;
drawCell();
}
}
private String getLiveValueString(String currentValue) {
return currentValue + (isNullOrEmpty(dataCell.getLiveValue()) ? Settings.BLANK : (':' + dataCell.getLiveValue()));
}
public String getStaticText() {
String displayString = null;
try {
FORMATTER.applyPattern(tableView.getTable().getCurrentScale().getFormat()); | double staticDouble = NumberUtil.doubleValue(dataCell.getStaticText()); |
RomRaider/RomRaider | src/main/java/com/romraider/maps/DataCellView.java | // Path: src/main/java/com/romraider/util/JEPUtil.java
// public final class JEPUtil {
// @SuppressWarnings("serial")
// static class LRUCache<K, V> extends LinkedHashMap<K, V> {
// private int cacheSize;
//
// public LRUCache(int cacheSize) {
// super(32, 0.75f, true);
// this.cacheSize = cacheSize;
// }
//
// @Override
// protected boolean removeEldestEntry(Map.Entry<K, V> eldest) {
// return size() >= cacheSize;
// }
// };
//
// private static final Map<String, JEP> parserCache =
// Collections.synchronizedMap(new LRUCache<String, JEP>(32));
//
// public static synchronized double evaluate(String expression, double value) {
// JEP parser = parserCache.get(expression);
// if (parser == null) {
// parser = new JEP();
// parser.addStandardFunctions();
// parser.addFunction("BitWise", new BitWise());
// parser.initSymTab(); // clear the contents of the symbol table
// parser.addVariable("x", value);
// parser.parseExpression(expression);
// parserCache.put(expression, parser);
// } else {
// parser.setVarValue("x", value);
// }
// return parser.getValue();
// }
//
// public static synchronized double evaluate(String expression, Map<String, Double> valueMap) {
// JEP parser = parserCache.get(expression);
// if (parser == null) {
// parser = new JEP();
// parser.initSymTab(); // clear the contents of the symbol table
// for (String id : valueMap.keySet()) {
// parser.addVariable(id, valueMap.get(id));
// }
// parser.parseExpression(expression);
// parserCache.put(expression, parser);
// }
// else {
// for (String id : valueMap.keySet()) {
// parser.setVarValue(id, valueMap.get(id));
// }
// }
// return parser.getValue();
// }
// }
//
// Path: src/main/java/com/romraider/util/NumberUtil.java
// public final class NumberUtil {
// private static final NumberFormat NUM_FORMATTER = NumberFormat.getInstance(Locale.getDefault());
// private static final String NAN = "NaN";
// static {
// ((DecimalFormat) NUM_FORMATTER).applyPattern("0.0#################");
// }
//
// private NumberUtil() {
// }
//
// /**
// * Returns the separator based on the current locale (. or ,)
// * @return The separation character
// */
// public static char getSeperator(){
// return ((DecimalFormat) NUM_FORMATTER).getDecimalFormatSymbols().getDecimalSeparator();
// }
//
// /**
// * Returns the value of the specified number in the default locale as a double.
// * @param str - string to be converted.
// * @return the numeric value represented by this object after conversion
// * to type double.
// * @exception ParseException is thrown when parse errors are encountered.
// */
// public static double doubleValue(String str) throws ParseException {
// return NUM_FORMATTER.parse(str).doubleValue();
// }
//
// /**
// * Format a double using the current Locale
// * @param value to format
// * @return the number as a String
// */
// public static String stringValue(double value) {
// return Double.isNaN(value) ? NAN : NUM_FORMATTER.format(value);
// }
// }
| import javax.swing.JLabel;
import javax.swing.border.Border;
import com.romraider.Settings;
import com.romraider.editor.ecu.ECUEditorManager;
import com.romraider.util.JEPUtil;
import com.romraider.util.NumberUtil;
import com.romraider.util.SettingsManager;
import static com.romraider.util.ColorScaler.getScaledColor;
import static com.romraider.util.ParamChecker.isNullOrEmpty;
import static javax.swing.BorderFactory.createLineBorder;
import java.awt.Color;
import java.awt.Font;
import java.awt.event.MouseEvent;
import java.awt.event.MouseListener;
import java.io.Serializable;
import java.text.DecimalFormat; | }
}
public boolean isHighlighted() {
return highlighted;
}
public void setLiveDataTrace(boolean trace) {
if(traced != trace) {
traced = trace;
drawCell();
}
}
public void setPreviousLiveDataTrace(boolean trace) {
if(tracedStale != trace) {
tracedStale = trace;
drawCell();
}
}
private String getLiveValueString(String currentValue) {
return currentValue + (isNullOrEmpty(dataCell.getLiveValue()) ? Settings.BLANK : (':' + dataCell.getLiveValue()));
}
public String getStaticText() {
String displayString = null;
try {
FORMATTER.applyPattern(tableView.getTable().getCurrentScale().getFormat());
double staticDouble = NumberUtil.doubleValue(dataCell.getStaticText()); | // Path: src/main/java/com/romraider/util/JEPUtil.java
// public final class JEPUtil {
// @SuppressWarnings("serial")
// static class LRUCache<K, V> extends LinkedHashMap<K, V> {
// private int cacheSize;
//
// public LRUCache(int cacheSize) {
// super(32, 0.75f, true);
// this.cacheSize = cacheSize;
// }
//
// @Override
// protected boolean removeEldestEntry(Map.Entry<K, V> eldest) {
// return size() >= cacheSize;
// }
// };
//
// private static final Map<String, JEP> parserCache =
// Collections.synchronizedMap(new LRUCache<String, JEP>(32));
//
// public static synchronized double evaluate(String expression, double value) {
// JEP parser = parserCache.get(expression);
// if (parser == null) {
// parser = new JEP();
// parser.addStandardFunctions();
// parser.addFunction("BitWise", new BitWise());
// parser.initSymTab(); // clear the contents of the symbol table
// parser.addVariable("x", value);
// parser.parseExpression(expression);
// parserCache.put(expression, parser);
// } else {
// parser.setVarValue("x", value);
// }
// return parser.getValue();
// }
//
// public static synchronized double evaluate(String expression, Map<String, Double> valueMap) {
// JEP parser = parserCache.get(expression);
// if (parser == null) {
// parser = new JEP();
// parser.initSymTab(); // clear the contents of the symbol table
// for (String id : valueMap.keySet()) {
// parser.addVariable(id, valueMap.get(id));
// }
// parser.parseExpression(expression);
// parserCache.put(expression, parser);
// }
// else {
// for (String id : valueMap.keySet()) {
// parser.setVarValue(id, valueMap.get(id));
// }
// }
// return parser.getValue();
// }
// }
//
// Path: src/main/java/com/romraider/util/NumberUtil.java
// public final class NumberUtil {
// private static final NumberFormat NUM_FORMATTER = NumberFormat.getInstance(Locale.getDefault());
// private static final String NAN = "NaN";
// static {
// ((DecimalFormat) NUM_FORMATTER).applyPattern("0.0#################");
// }
//
// private NumberUtil() {
// }
//
// /**
// * Returns the separator based on the current locale (. or ,)
// * @return The separation character
// */
// public static char getSeperator(){
// return ((DecimalFormat) NUM_FORMATTER).getDecimalFormatSymbols().getDecimalSeparator();
// }
//
// /**
// * Returns the value of the specified number in the default locale as a double.
// * @param str - string to be converted.
// * @return the numeric value represented by this object after conversion
// * to type double.
// * @exception ParseException is thrown when parse errors are encountered.
// */
// public static double doubleValue(String str) throws ParseException {
// return NUM_FORMATTER.parse(str).doubleValue();
// }
//
// /**
// * Format a double using the current Locale
// * @param value to format
// * @return the number as a String
// */
// public static String stringValue(double value) {
// return Double.isNaN(value) ? NAN : NUM_FORMATTER.format(value);
// }
// }
// Path: src/main/java/com/romraider/maps/DataCellView.java
import javax.swing.JLabel;
import javax.swing.border.Border;
import com.romraider.Settings;
import com.romraider.editor.ecu.ECUEditorManager;
import com.romraider.util.JEPUtil;
import com.romraider.util.NumberUtil;
import com.romraider.util.SettingsManager;
import static com.romraider.util.ColorScaler.getScaledColor;
import static com.romraider.util.ParamChecker.isNullOrEmpty;
import static javax.swing.BorderFactory.createLineBorder;
import java.awt.Color;
import java.awt.Font;
import java.awt.event.MouseEvent;
import java.awt.event.MouseListener;
import java.io.Serializable;
import java.text.DecimalFormat;
}
}
public boolean isHighlighted() {
return highlighted;
}
public void setLiveDataTrace(boolean trace) {
if(traced != trace) {
traced = trace;
drawCell();
}
}
public void setPreviousLiveDataTrace(boolean trace) {
if(tracedStale != trace) {
tracedStale = trace;
drawCell();
}
}
private String getLiveValueString(String currentValue) {
return currentValue + (isNullOrEmpty(dataCell.getLiveValue()) ? Settings.BLANK : (':' + dataCell.getLiveValue()));
}
public String getStaticText() {
String displayString = null;
try {
FORMATTER.applyPattern(tableView.getTable().getCurrentScale().getFormat());
double staticDouble = NumberUtil.doubleValue(dataCell.getStaticText()); | displayString = FORMATTER.format(JEPUtil.evaluate(tableView.getTable().getCurrentScale().getExpression(), staticDouble)); |
RomRaider/RomRaider | src/main/java/com/romraider/io/protocol/ncs/iso14230/NCSProtocol.java | // Path: src/main/java/com/romraider/io/protocol/ProtocolNCS.java
// public interface ProtocolNCS extends Protocol {
//
// byte[] constructEcuFastInitRequest(Module module);
//
// byte[] constructReadSidPidRequest(Module module, byte sid, byte[][] pid);
//
// byte[] constructLoadAddressRequest(Map<byte[], Integer> queryMap);
//
// void validateLoadAddressResponse(byte[] response);
//
// byte[] checkValidSidPidResponse(byte[] response);
//
// byte[] constructReadAddressRequest(Module module, byte[][] bs,
// PollingState pollState);
//
// byte[] constructEcuIdRequest(Module module);
//
// byte[] constructEcuStopRequest(Module module);
//
// byte[] constructStartDiagRequest(Module module);
//
// byte[] constructElevatedDiagRequest(Module module);
//
// byte[] constructReadMemoryRequest(Module module, byte[][] address, int numBytes);
// }
//
// Path: src/main/java/com/romraider/logger/ecu/comms/query/EcuInit.java
// public interface EcuInit {
//
// /**
// * Get the module ID string.
// * @return ID string
// */
// String getEcuId();
//
// /**
// * Get the module initialization sequence.
// * @return byte array of the module initialization sequence
// */
// byte[] getEcuInitBytes();
//
// }
| import com.romraider.io.protocol.ProtocolNCS;
import com.romraider.logger.ecu.comms.manager.PollingState;
import com.romraider.logger.ecu.comms.query.EcuInit;
import com.romraider.logger.ecu.comms.query.NCSEcuInit;
import com.romraider.logger.ecu.definition.Module;
import com.romraider.logger.ecu.exception.InvalidResponseException;
import com.romraider.logger.ecu.exception.UnsupportedProtocolException;
import static com.romraider.io.protocol.ncs.iso14230.NCSChecksumCalculator.calculateChecksum;
import static com.romraider.util.HexUtil.asHex;
import static com.romraider.util.ParamChecker.checkNotNull;
import static com.romraider.util.ParamChecker.checkNotNullOrEmpty;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.util.Map;
import com.romraider.io.connection.ConnectionProperties;
import com.romraider.io.connection.KwpConnectionProperties; | }
else {
// read one response of previously loaded addresses
// len 0x21 0x81 0x04 0x01 checksum
opt_byte3 = (byte) 0x04;
}
return buildRequest(
READ_LOAD_COMMAND, true, new byte[]{(byte) 0x81, opt_byte3, (byte) 0x01});
}
@Override
public byte[] preprocessResponse(
byte[] request, byte[] response, PollingState pollState) {
return NCSResponseProcessor.filterRequestFromResponse(
request, response, pollState);
}
@Override
public byte[] parseResponseData(byte[] processedResponse) {
checkNotNullOrEmpty(processedResponse, "processedResponse");
return NCSResponseProcessor.extractResponseData(processedResponse);
}
@Override
public void checkValidEcuInitResponse(byte[] processedResponse) {
checkNotNullOrEmpty(processedResponse, "processedResponse");
NCSResponseProcessor.validateResponse(processedResponse);
}
@Override | // Path: src/main/java/com/romraider/io/protocol/ProtocolNCS.java
// public interface ProtocolNCS extends Protocol {
//
// byte[] constructEcuFastInitRequest(Module module);
//
// byte[] constructReadSidPidRequest(Module module, byte sid, byte[][] pid);
//
// byte[] constructLoadAddressRequest(Map<byte[], Integer> queryMap);
//
// void validateLoadAddressResponse(byte[] response);
//
// byte[] checkValidSidPidResponse(byte[] response);
//
// byte[] constructReadAddressRequest(Module module, byte[][] bs,
// PollingState pollState);
//
// byte[] constructEcuIdRequest(Module module);
//
// byte[] constructEcuStopRequest(Module module);
//
// byte[] constructStartDiagRequest(Module module);
//
// byte[] constructElevatedDiagRequest(Module module);
//
// byte[] constructReadMemoryRequest(Module module, byte[][] address, int numBytes);
// }
//
// Path: src/main/java/com/romraider/logger/ecu/comms/query/EcuInit.java
// public interface EcuInit {
//
// /**
// * Get the module ID string.
// * @return ID string
// */
// String getEcuId();
//
// /**
// * Get the module initialization sequence.
// * @return byte array of the module initialization sequence
// */
// byte[] getEcuInitBytes();
//
// }
// Path: src/main/java/com/romraider/io/protocol/ncs/iso14230/NCSProtocol.java
import com.romraider.io.protocol.ProtocolNCS;
import com.romraider.logger.ecu.comms.manager.PollingState;
import com.romraider.logger.ecu.comms.query.EcuInit;
import com.romraider.logger.ecu.comms.query.NCSEcuInit;
import com.romraider.logger.ecu.definition.Module;
import com.romraider.logger.ecu.exception.InvalidResponseException;
import com.romraider.logger.ecu.exception.UnsupportedProtocolException;
import static com.romraider.io.protocol.ncs.iso14230.NCSChecksumCalculator.calculateChecksum;
import static com.romraider.util.HexUtil.asHex;
import static com.romraider.util.ParamChecker.checkNotNull;
import static com.romraider.util.ParamChecker.checkNotNullOrEmpty;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.util.Map;
import com.romraider.io.connection.ConnectionProperties;
import com.romraider.io.connection.KwpConnectionProperties;
}
else {
// read one response of previously loaded addresses
// len 0x21 0x81 0x04 0x01 checksum
opt_byte3 = (byte) 0x04;
}
return buildRequest(
READ_LOAD_COMMAND, true, new byte[]{(byte) 0x81, opt_byte3, (byte) 0x01});
}
@Override
public byte[] preprocessResponse(
byte[] request, byte[] response, PollingState pollState) {
return NCSResponseProcessor.filterRequestFromResponse(
request, response, pollState);
}
@Override
public byte[] parseResponseData(byte[] processedResponse) {
checkNotNullOrEmpty(processedResponse, "processedResponse");
return NCSResponseProcessor.extractResponseData(processedResponse);
}
@Override
public void checkValidEcuInitResponse(byte[] processedResponse) {
checkNotNullOrEmpty(processedResponse, "processedResponse");
NCSResponseProcessor.validateResponse(processedResponse);
}
@Override | public EcuInit parseEcuInitResponse(byte[] processedResponse) { |
RomRaider/RomRaider | src/main/java/com/romraider/maps/checksum/CalculateSTD.java | // Path: src/main/java/com/romraider/maps/checksum/NissanChecksum.java
// public static final String END = "end";
//
// Path: src/main/java/com/romraider/maps/checksum/NissanChecksum.java
// public static final String START = "start";
//
// Path: src/main/java/com/romraider/maps/checksum/NissanChecksum.java
// public static final String SUMLOC = "sumloc";
//
// Path: src/main/java/com/romraider/maps/checksum/NissanChecksum.java
// public static final String SUMT = "sumt";
//
// Path: src/main/java/com/romraider/maps/checksum/NissanChecksum.java
// public static final String XORLOC = "xorloc";
//
// Path: src/main/java/com/romraider/maps/checksum/NissanChecksum.java
// public static final String XORT = "xort";
| import static com.romraider.maps.checksum.NissanChecksum.END;
import static com.romraider.maps.checksum.NissanChecksum.START;
import static com.romraider.maps.checksum.NissanChecksum.SUMLOC;
import static com.romraider.maps.checksum.NissanChecksum.SUMT;
import static com.romraider.maps.checksum.NissanChecksum.XORLOC;
import static com.romraider.maps.checksum.NissanChecksum.XORT;
import static com.romraider.xml.RomAttributeParser.parseByteValue;
import java.util.Map;
import com.romraider.Settings; | /*
* RomRaider Open-Source Tuning, Logging and Reflashing
* Copyright (C) 2006-2019 RomRaider.com
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License along
* with this program; if not, write to the Free Software Foundation, Inc.,
* 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
*/
package com.romraider.maps.checksum;
public final class CalculateSTD implements Calculator {
public CalculateSTD() {
}
public final void calculate(
Map<String, Integer> range,
byte[] binData,
Map<String, Integer> results) {
int sumt = 0;
int xort = 0;
int dw = 0; | // Path: src/main/java/com/romraider/maps/checksum/NissanChecksum.java
// public static final String END = "end";
//
// Path: src/main/java/com/romraider/maps/checksum/NissanChecksum.java
// public static final String START = "start";
//
// Path: src/main/java/com/romraider/maps/checksum/NissanChecksum.java
// public static final String SUMLOC = "sumloc";
//
// Path: src/main/java/com/romraider/maps/checksum/NissanChecksum.java
// public static final String SUMT = "sumt";
//
// Path: src/main/java/com/romraider/maps/checksum/NissanChecksum.java
// public static final String XORLOC = "xorloc";
//
// Path: src/main/java/com/romraider/maps/checksum/NissanChecksum.java
// public static final String XORT = "xort";
// Path: src/main/java/com/romraider/maps/checksum/CalculateSTD.java
import static com.romraider.maps.checksum.NissanChecksum.END;
import static com.romraider.maps.checksum.NissanChecksum.START;
import static com.romraider.maps.checksum.NissanChecksum.SUMLOC;
import static com.romraider.maps.checksum.NissanChecksum.SUMT;
import static com.romraider.maps.checksum.NissanChecksum.XORLOC;
import static com.romraider.maps.checksum.NissanChecksum.XORT;
import static com.romraider.xml.RomAttributeParser.parseByteValue;
import java.util.Map;
import com.romraider.Settings;
/*
* RomRaider Open-Source Tuning, Logging and Reflashing
* Copyright (C) 2006-2019 RomRaider.com
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License along
* with this program; if not, write to the Free Software Foundation, Inc.,
* 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
*/
package com.romraider.maps.checksum;
public final class CalculateSTD implements Calculator {
public CalculateSTD() {
}
public final void calculate(
Map<String, Integer> range,
byte[] binData,
Map<String, Integer> results) {
int sumt = 0;
int xort = 0;
int dw = 0; | for (int i = range.get(START); i < range.get(END); i += 4) { |
RomRaider/RomRaider | src/main/java/com/romraider/maps/checksum/CalculateSTD.java | // Path: src/main/java/com/romraider/maps/checksum/NissanChecksum.java
// public static final String END = "end";
//
// Path: src/main/java/com/romraider/maps/checksum/NissanChecksum.java
// public static final String START = "start";
//
// Path: src/main/java/com/romraider/maps/checksum/NissanChecksum.java
// public static final String SUMLOC = "sumloc";
//
// Path: src/main/java/com/romraider/maps/checksum/NissanChecksum.java
// public static final String SUMT = "sumt";
//
// Path: src/main/java/com/romraider/maps/checksum/NissanChecksum.java
// public static final String XORLOC = "xorloc";
//
// Path: src/main/java/com/romraider/maps/checksum/NissanChecksum.java
// public static final String XORT = "xort";
| import static com.romraider.maps.checksum.NissanChecksum.END;
import static com.romraider.maps.checksum.NissanChecksum.START;
import static com.romraider.maps.checksum.NissanChecksum.SUMLOC;
import static com.romraider.maps.checksum.NissanChecksum.SUMT;
import static com.romraider.maps.checksum.NissanChecksum.XORLOC;
import static com.romraider.maps.checksum.NissanChecksum.XORT;
import static com.romraider.xml.RomAttributeParser.parseByteValue;
import java.util.Map;
import com.romraider.Settings; | /*
* RomRaider Open-Source Tuning, Logging and Reflashing
* Copyright (C) 2006-2019 RomRaider.com
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License along
* with this program; if not, write to the Free Software Foundation, Inc.,
* 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
*/
package com.romraider.maps.checksum;
public final class CalculateSTD implements Calculator {
public CalculateSTD() {
}
public final void calculate(
Map<String, Integer> range,
byte[] binData,
Map<String, Integer> results) {
int sumt = 0;
int xort = 0;
int dw = 0; | // Path: src/main/java/com/romraider/maps/checksum/NissanChecksum.java
// public static final String END = "end";
//
// Path: src/main/java/com/romraider/maps/checksum/NissanChecksum.java
// public static final String START = "start";
//
// Path: src/main/java/com/romraider/maps/checksum/NissanChecksum.java
// public static final String SUMLOC = "sumloc";
//
// Path: src/main/java/com/romraider/maps/checksum/NissanChecksum.java
// public static final String SUMT = "sumt";
//
// Path: src/main/java/com/romraider/maps/checksum/NissanChecksum.java
// public static final String XORLOC = "xorloc";
//
// Path: src/main/java/com/romraider/maps/checksum/NissanChecksum.java
// public static final String XORT = "xort";
// Path: src/main/java/com/romraider/maps/checksum/CalculateSTD.java
import static com.romraider.maps.checksum.NissanChecksum.END;
import static com.romraider.maps.checksum.NissanChecksum.START;
import static com.romraider.maps.checksum.NissanChecksum.SUMLOC;
import static com.romraider.maps.checksum.NissanChecksum.SUMT;
import static com.romraider.maps.checksum.NissanChecksum.XORLOC;
import static com.romraider.maps.checksum.NissanChecksum.XORT;
import static com.romraider.xml.RomAttributeParser.parseByteValue;
import java.util.Map;
import com.romraider.Settings;
/*
* RomRaider Open-Source Tuning, Logging and Reflashing
* Copyright (C) 2006-2019 RomRaider.com
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License along
* with this program; if not, write to the Free Software Foundation, Inc.,
* 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
*/
package com.romraider.maps.checksum;
public final class CalculateSTD implements Calculator {
public CalculateSTD() {
}
public final void calculate(
Map<String, Integer> range,
byte[] binData,
Map<String, Integer> results) {
int sumt = 0;
int xort = 0;
int dw = 0; | for (int i = range.get(START); i < range.get(END); i += 4) { |
RomRaider/RomRaider | src/main/java/com/romraider/maps/checksum/CalculateSTD.java | // Path: src/main/java/com/romraider/maps/checksum/NissanChecksum.java
// public static final String END = "end";
//
// Path: src/main/java/com/romraider/maps/checksum/NissanChecksum.java
// public static final String START = "start";
//
// Path: src/main/java/com/romraider/maps/checksum/NissanChecksum.java
// public static final String SUMLOC = "sumloc";
//
// Path: src/main/java/com/romraider/maps/checksum/NissanChecksum.java
// public static final String SUMT = "sumt";
//
// Path: src/main/java/com/romraider/maps/checksum/NissanChecksum.java
// public static final String XORLOC = "xorloc";
//
// Path: src/main/java/com/romraider/maps/checksum/NissanChecksum.java
// public static final String XORT = "xort";
| import static com.romraider.maps.checksum.NissanChecksum.END;
import static com.romraider.maps.checksum.NissanChecksum.START;
import static com.romraider.maps.checksum.NissanChecksum.SUMLOC;
import static com.romraider.maps.checksum.NissanChecksum.SUMT;
import static com.romraider.maps.checksum.NissanChecksum.XORLOC;
import static com.romraider.maps.checksum.NissanChecksum.XORT;
import static com.romraider.xml.RomAttributeParser.parseByteValue;
import java.util.Map;
import com.romraider.Settings; | /*
* RomRaider Open-Source Tuning, Logging and Reflashing
* Copyright (C) 2006-2019 RomRaider.com
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License along
* with this program; if not, write to the Free Software Foundation, Inc.,
* 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
*/
package com.romraider.maps.checksum;
public final class CalculateSTD implements Calculator {
public CalculateSTD() {
}
public final void calculate(
Map<String, Integer> range,
byte[] binData,
Map<String, Integer> results) {
int sumt = 0;
int xort = 0;
int dw = 0;
for (int i = range.get(START); i < range.get(END); i += 4) { | // Path: src/main/java/com/romraider/maps/checksum/NissanChecksum.java
// public static final String END = "end";
//
// Path: src/main/java/com/romraider/maps/checksum/NissanChecksum.java
// public static final String START = "start";
//
// Path: src/main/java/com/romraider/maps/checksum/NissanChecksum.java
// public static final String SUMLOC = "sumloc";
//
// Path: src/main/java/com/romraider/maps/checksum/NissanChecksum.java
// public static final String SUMT = "sumt";
//
// Path: src/main/java/com/romraider/maps/checksum/NissanChecksum.java
// public static final String XORLOC = "xorloc";
//
// Path: src/main/java/com/romraider/maps/checksum/NissanChecksum.java
// public static final String XORT = "xort";
// Path: src/main/java/com/romraider/maps/checksum/CalculateSTD.java
import static com.romraider.maps.checksum.NissanChecksum.END;
import static com.romraider.maps.checksum.NissanChecksum.START;
import static com.romraider.maps.checksum.NissanChecksum.SUMLOC;
import static com.romraider.maps.checksum.NissanChecksum.SUMT;
import static com.romraider.maps.checksum.NissanChecksum.XORLOC;
import static com.romraider.maps.checksum.NissanChecksum.XORT;
import static com.romraider.xml.RomAttributeParser.parseByteValue;
import java.util.Map;
import com.romraider.Settings;
/*
* RomRaider Open-Source Tuning, Logging and Reflashing
* Copyright (C) 2006-2019 RomRaider.com
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License along
* with this program; if not, write to the Free Software Foundation, Inc.,
* 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
*/
package com.romraider.maps.checksum;
public final class CalculateSTD implements Calculator {
public CalculateSTD() {
}
public final void calculate(
Map<String, Integer> range,
byte[] binData,
Map<String, Integer> results) {
int sumt = 0;
int xort = 0;
int dw = 0;
for (int i = range.get(START); i < range.get(END); i += 4) { | if ((i == range.get(SUMLOC)) || (i == range.get(XORLOC))) continue; |
RomRaider/RomRaider | src/main/java/com/romraider/maps/checksum/CalculateSTD.java | // Path: src/main/java/com/romraider/maps/checksum/NissanChecksum.java
// public static final String END = "end";
//
// Path: src/main/java/com/romraider/maps/checksum/NissanChecksum.java
// public static final String START = "start";
//
// Path: src/main/java/com/romraider/maps/checksum/NissanChecksum.java
// public static final String SUMLOC = "sumloc";
//
// Path: src/main/java/com/romraider/maps/checksum/NissanChecksum.java
// public static final String SUMT = "sumt";
//
// Path: src/main/java/com/romraider/maps/checksum/NissanChecksum.java
// public static final String XORLOC = "xorloc";
//
// Path: src/main/java/com/romraider/maps/checksum/NissanChecksum.java
// public static final String XORT = "xort";
| import static com.romraider.maps.checksum.NissanChecksum.END;
import static com.romraider.maps.checksum.NissanChecksum.START;
import static com.romraider.maps.checksum.NissanChecksum.SUMLOC;
import static com.romraider.maps.checksum.NissanChecksum.SUMT;
import static com.romraider.maps.checksum.NissanChecksum.XORLOC;
import static com.romraider.maps.checksum.NissanChecksum.XORT;
import static com.romraider.xml.RomAttributeParser.parseByteValue;
import java.util.Map;
import com.romraider.Settings; | /*
* RomRaider Open-Source Tuning, Logging and Reflashing
* Copyright (C) 2006-2019 RomRaider.com
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License along
* with this program; if not, write to the Free Software Foundation, Inc.,
* 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
*/
package com.romraider.maps.checksum;
public final class CalculateSTD implements Calculator {
public CalculateSTD() {
}
public final void calculate(
Map<String, Integer> range,
byte[] binData,
Map<String, Integer> results) {
int sumt = 0;
int xort = 0;
int dw = 0;
for (int i = range.get(START); i < range.get(END); i += 4) { | // Path: src/main/java/com/romraider/maps/checksum/NissanChecksum.java
// public static final String END = "end";
//
// Path: src/main/java/com/romraider/maps/checksum/NissanChecksum.java
// public static final String START = "start";
//
// Path: src/main/java/com/romraider/maps/checksum/NissanChecksum.java
// public static final String SUMLOC = "sumloc";
//
// Path: src/main/java/com/romraider/maps/checksum/NissanChecksum.java
// public static final String SUMT = "sumt";
//
// Path: src/main/java/com/romraider/maps/checksum/NissanChecksum.java
// public static final String XORLOC = "xorloc";
//
// Path: src/main/java/com/romraider/maps/checksum/NissanChecksum.java
// public static final String XORT = "xort";
// Path: src/main/java/com/romraider/maps/checksum/CalculateSTD.java
import static com.romraider.maps.checksum.NissanChecksum.END;
import static com.romraider.maps.checksum.NissanChecksum.START;
import static com.romraider.maps.checksum.NissanChecksum.SUMLOC;
import static com.romraider.maps.checksum.NissanChecksum.SUMT;
import static com.romraider.maps.checksum.NissanChecksum.XORLOC;
import static com.romraider.maps.checksum.NissanChecksum.XORT;
import static com.romraider.xml.RomAttributeParser.parseByteValue;
import java.util.Map;
import com.romraider.Settings;
/*
* RomRaider Open-Source Tuning, Logging and Reflashing
* Copyright (C) 2006-2019 RomRaider.com
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License along
* with this program; if not, write to the Free Software Foundation, Inc.,
* 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
*/
package com.romraider.maps.checksum;
public final class CalculateSTD implements Calculator {
public CalculateSTD() {
}
public final void calculate(
Map<String, Integer> range,
byte[] binData,
Map<String, Integer> results) {
int sumt = 0;
int xort = 0;
int dw = 0;
for (int i = range.get(START); i < range.get(END); i += 4) { | if ((i == range.get(SUMLOC)) || (i == range.get(XORLOC))) continue; |
RomRaider/RomRaider | src/main/java/com/romraider/maps/checksum/CalculateSTD.java | // Path: src/main/java/com/romraider/maps/checksum/NissanChecksum.java
// public static final String END = "end";
//
// Path: src/main/java/com/romraider/maps/checksum/NissanChecksum.java
// public static final String START = "start";
//
// Path: src/main/java/com/romraider/maps/checksum/NissanChecksum.java
// public static final String SUMLOC = "sumloc";
//
// Path: src/main/java/com/romraider/maps/checksum/NissanChecksum.java
// public static final String SUMT = "sumt";
//
// Path: src/main/java/com/romraider/maps/checksum/NissanChecksum.java
// public static final String XORLOC = "xorloc";
//
// Path: src/main/java/com/romraider/maps/checksum/NissanChecksum.java
// public static final String XORT = "xort";
| import static com.romraider.maps.checksum.NissanChecksum.END;
import static com.romraider.maps.checksum.NissanChecksum.START;
import static com.romraider.maps.checksum.NissanChecksum.SUMLOC;
import static com.romraider.maps.checksum.NissanChecksum.SUMT;
import static com.romraider.maps.checksum.NissanChecksum.XORLOC;
import static com.romraider.maps.checksum.NissanChecksum.XORT;
import static com.romraider.xml.RomAttributeParser.parseByteValue;
import java.util.Map;
import com.romraider.Settings; | /*
* RomRaider Open-Source Tuning, Logging and Reflashing
* Copyright (C) 2006-2019 RomRaider.com
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License along
* with this program; if not, write to the Free Software Foundation, Inc.,
* 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
*/
package com.romraider.maps.checksum;
public final class CalculateSTD implements Calculator {
public CalculateSTD() {
}
public final void calculate(
Map<String, Integer> range,
byte[] binData,
Map<String, Integer> results) {
int sumt = 0;
int xort = 0;
int dw = 0;
for (int i = range.get(START); i < range.get(END); i += 4) {
if ((i == range.get(SUMLOC)) || (i == range.get(XORLOC))) continue;
dw = (int)parseByteValue(binData, Settings.Endian.BIG, i, 4, true);
sumt += dw;
xort ^= dw;
} | // Path: src/main/java/com/romraider/maps/checksum/NissanChecksum.java
// public static final String END = "end";
//
// Path: src/main/java/com/romraider/maps/checksum/NissanChecksum.java
// public static final String START = "start";
//
// Path: src/main/java/com/romraider/maps/checksum/NissanChecksum.java
// public static final String SUMLOC = "sumloc";
//
// Path: src/main/java/com/romraider/maps/checksum/NissanChecksum.java
// public static final String SUMT = "sumt";
//
// Path: src/main/java/com/romraider/maps/checksum/NissanChecksum.java
// public static final String XORLOC = "xorloc";
//
// Path: src/main/java/com/romraider/maps/checksum/NissanChecksum.java
// public static final String XORT = "xort";
// Path: src/main/java/com/romraider/maps/checksum/CalculateSTD.java
import static com.romraider.maps.checksum.NissanChecksum.END;
import static com.romraider.maps.checksum.NissanChecksum.START;
import static com.romraider.maps.checksum.NissanChecksum.SUMLOC;
import static com.romraider.maps.checksum.NissanChecksum.SUMT;
import static com.romraider.maps.checksum.NissanChecksum.XORLOC;
import static com.romraider.maps.checksum.NissanChecksum.XORT;
import static com.romraider.xml.RomAttributeParser.parseByteValue;
import java.util.Map;
import com.romraider.Settings;
/*
* RomRaider Open-Source Tuning, Logging and Reflashing
* Copyright (C) 2006-2019 RomRaider.com
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License along
* with this program; if not, write to the Free Software Foundation, Inc.,
* 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
*/
package com.romraider.maps.checksum;
public final class CalculateSTD implements Calculator {
public CalculateSTD() {
}
public final void calculate(
Map<String, Integer> range,
byte[] binData,
Map<String, Integer> results) {
int sumt = 0;
int xort = 0;
int dw = 0;
for (int i = range.get(START); i < range.get(END); i += 4) {
if ((i == range.get(SUMLOC)) || (i == range.get(XORLOC))) continue;
dw = (int)parseByteValue(binData, Settings.Endian.BIG, i, 4, true);
sumt += dw;
xort ^= dw;
} | results.put(SUMT, sumt); |
RomRaider/RomRaider | src/main/java/com/romraider/maps/checksum/CalculateSTD.java | // Path: src/main/java/com/romraider/maps/checksum/NissanChecksum.java
// public static final String END = "end";
//
// Path: src/main/java/com/romraider/maps/checksum/NissanChecksum.java
// public static final String START = "start";
//
// Path: src/main/java/com/romraider/maps/checksum/NissanChecksum.java
// public static final String SUMLOC = "sumloc";
//
// Path: src/main/java/com/romraider/maps/checksum/NissanChecksum.java
// public static final String SUMT = "sumt";
//
// Path: src/main/java/com/romraider/maps/checksum/NissanChecksum.java
// public static final String XORLOC = "xorloc";
//
// Path: src/main/java/com/romraider/maps/checksum/NissanChecksum.java
// public static final String XORT = "xort";
| import static com.romraider.maps.checksum.NissanChecksum.END;
import static com.romraider.maps.checksum.NissanChecksum.START;
import static com.romraider.maps.checksum.NissanChecksum.SUMLOC;
import static com.romraider.maps.checksum.NissanChecksum.SUMT;
import static com.romraider.maps.checksum.NissanChecksum.XORLOC;
import static com.romraider.maps.checksum.NissanChecksum.XORT;
import static com.romraider.xml.RomAttributeParser.parseByteValue;
import java.util.Map;
import com.romraider.Settings; | /*
* RomRaider Open-Source Tuning, Logging and Reflashing
* Copyright (C) 2006-2019 RomRaider.com
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License along
* with this program; if not, write to the Free Software Foundation, Inc.,
* 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
*/
package com.romraider.maps.checksum;
public final class CalculateSTD implements Calculator {
public CalculateSTD() {
}
public final void calculate(
Map<String, Integer> range,
byte[] binData,
Map<String, Integer> results) {
int sumt = 0;
int xort = 0;
int dw = 0;
for (int i = range.get(START); i < range.get(END); i += 4) {
if ((i == range.get(SUMLOC)) || (i == range.get(XORLOC))) continue;
dw = (int)parseByteValue(binData, Settings.Endian.BIG, i, 4, true);
sumt += dw;
xort ^= dw;
}
results.put(SUMT, sumt); | // Path: src/main/java/com/romraider/maps/checksum/NissanChecksum.java
// public static final String END = "end";
//
// Path: src/main/java/com/romraider/maps/checksum/NissanChecksum.java
// public static final String START = "start";
//
// Path: src/main/java/com/romraider/maps/checksum/NissanChecksum.java
// public static final String SUMLOC = "sumloc";
//
// Path: src/main/java/com/romraider/maps/checksum/NissanChecksum.java
// public static final String SUMT = "sumt";
//
// Path: src/main/java/com/romraider/maps/checksum/NissanChecksum.java
// public static final String XORLOC = "xorloc";
//
// Path: src/main/java/com/romraider/maps/checksum/NissanChecksum.java
// public static final String XORT = "xort";
// Path: src/main/java/com/romraider/maps/checksum/CalculateSTD.java
import static com.romraider.maps.checksum.NissanChecksum.END;
import static com.romraider.maps.checksum.NissanChecksum.START;
import static com.romraider.maps.checksum.NissanChecksum.SUMLOC;
import static com.romraider.maps.checksum.NissanChecksum.SUMT;
import static com.romraider.maps.checksum.NissanChecksum.XORLOC;
import static com.romraider.maps.checksum.NissanChecksum.XORT;
import static com.romraider.xml.RomAttributeParser.parseByteValue;
import java.util.Map;
import com.romraider.Settings;
/*
* RomRaider Open-Source Tuning, Logging and Reflashing
* Copyright (C) 2006-2019 RomRaider.com
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License along
* with this program; if not, write to the Free Software Foundation, Inc.,
* 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
*/
package com.romraider.maps.checksum;
public final class CalculateSTD implements Calculator {
public CalculateSTD() {
}
public final void calculate(
Map<String, Integer> range,
byte[] binData,
Map<String, Integer> results) {
int sumt = 0;
int xort = 0;
int dw = 0;
for (int i = range.get(START); i < range.get(END); i += 4) {
if ((i == range.get(SUMLOC)) || (i == range.get(XORLOC))) continue;
dw = (int)parseByteValue(binData, Settings.Endian.BIG, i, 4, true);
sumt += dw;
xort ^= dw;
}
results.put(SUMT, sumt); | results.put(XORT, xort); |
RomRaider/RomRaider | src/main/java/com/romraider/io/serial/connection/SerialConnectionManager.java | // Path: src/main/java/com/romraider/util/ThreadUtil.java
// public static void sleep(long millis) {
// try {
// TimeUnit.MILLISECONDS.sleep(millis);
// } catch (InterruptedException e) {
// if (LOGGER.isTraceEnabled())
// LOGGER.trace("Sleep interrupted", e);
// }
// }
//
// Path: src/main/java/com/romraider/io/connection/ConnectionManager.java
// public interface ConnectionManager {
// /**
// * Use the open method when communications to a Module requires a
// * StartCommunication sequence, such as Five Baud or Fast Init.
// * Include the StopCommunication sequence in the open so that
// * if something fails, the stop sequence is pre-loaded for use.
// * @param start - the byte sequence used to start comms
// * @param stop - the byte sequence used to stop comss
// */
// void open(byte[] start, byte[] stop);
//
// /**
// * Use this send method to send a request to a Module and return the
// * Module's reply in response. Polling state can be slow or fast as
// * provided by the PollingState parameter.
// * @param request - the bytes to send to the Module
// * @param response - a byte array sized to contain the Module's response
// * @param pollState - polling state, State_0 (slow) or State_1 (fast)
// */
// void send(byte[] request, byte[] response, PollingState pollState);
//
// /**
// * Use this send method to send bytes to a Module and return the
// * Module's reply.
// * @param bytes - the bytes to send to the Module
// * @return A byte array of the Module's response, variable sized
// */
// byte[] send(byte[] bytes);
//
// /**
// * Use this method to clear the communications line of any erroneous data.
// * It can be called before closing off communications to clear buffers
// * of stale data, or when changing polling modes.
// */
// void clearLine();
//
// /**
// * Use this method to close communications with the Module.
// */
// void close();
// }
| import com.romraider.io.connection.ConnectionManager;
import com.romraider.io.connection.ConnectionProperties;
import com.romraider.logger.ecu.comms.manager.PollingState;
import static com.romraider.io.protocol.ssm.iso9141.SSMChecksumCalculator.calculateChecksum;
import static com.romraider.util.HexUtil.asHex;
import static com.romraider.util.ParamChecker.checkNotNull;
import static com.romraider.util.ParamChecker.checkNotNullOrEmpty;
import static com.romraider.util.ThreadUtil.sleep;
import static java.lang.System.arraycopy;
import static java.lang.System.currentTimeMillis;
import static org.apache.log4j.Logger.getLogger;
import org.apache.log4j.Logger; | checkNotNull(connectionProperties, "connectionProperties");
this.connectionProperties = connectionProperties;
timeout = connectionProperties.getConnectTimeout();
readTimeout = timeout;
// Use TestSerialConnection for testing!!
connection = new SerialConnectionImpl(portName, connectionProperties);
//connection = new TestSerialConnection2(portName, connectionProperties);
}
@Override
public void open(byte[] start, byte[] stop) {
}
// Send request and wait for response with known length
@Override
public void send(byte[] request, byte[] response, PollingState pollState) {
checkNotNull(request, "request");
checkNotNull(response, "response");
checkNotNull(pollState, "pollState");
if (pollState.getCurrentState() == PollingState.State.STATE_0 &&
pollState.getLastState() == PollingState.State.STATE_1) {
clearLine();
}
if (pollState.getCurrentState() == PollingState.State.STATE_0) {
connection.readStaleData();
connection.write(request);
}
while (connection.available() < response.length) { | // Path: src/main/java/com/romraider/util/ThreadUtil.java
// public static void sleep(long millis) {
// try {
// TimeUnit.MILLISECONDS.sleep(millis);
// } catch (InterruptedException e) {
// if (LOGGER.isTraceEnabled())
// LOGGER.trace("Sleep interrupted", e);
// }
// }
//
// Path: src/main/java/com/romraider/io/connection/ConnectionManager.java
// public interface ConnectionManager {
// /**
// * Use the open method when communications to a Module requires a
// * StartCommunication sequence, such as Five Baud or Fast Init.
// * Include the StopCommunication sequence in the open so that
// * if something fails, the stop sequence is pre-loaded for use.
// * @param start - the byte sequence used to start comms
// * @param stop - the byte sequence used to stop comss
// */
// void open(byte[] start, byte[] stop);
//
// /**
// * Use this send method to send a request to a Module and return the
// * Module's reply in response. Polling state can be slow or fast as
// * provided by the PollingState parameter.
// * @param request - the bytes to send to the Module
// * @param response - a byte array sized to contain the Module's response
// * @param pollState - polling state, State_0 (slow) or State_1 (fast)
// */
// void send(byte[] request, byte[] response, PollingState pollState);
//
// /**
// * Use this send method to send bytes to a Module and return the
// * Module's reply.
// * @param bytes - the bytes to send to the Module
// * @return A byte array of the Module's response, variable sized
// */
// byte[] send(byte[] bytes);
//
// /**
// * Use this method to clear the communications line of any erroneous data.
// * It can be called before closing off communications to clear buffers
// * of stale data, or when changing polling modes.
// */
// void clearLine();
//
// /**
// * Use this method to close communications with the Module.
// */
// void close();
// }
// Path: src/main/java/com/romraider/io/serial/connection/SerialConnectionManager.java
import com.romraider.io.connection.ConnectionManager;
import com.romraider.io.connection.ConnectionProperties;
import com.romraider.logger.ecu.comms.manager.PollingState;
import static com.romraider.io.protocol.ssm.iso9141.SSMChecksumCalculator.calculateChecksum;
import static com.romraider.util.HexUtil.asHex;
import static com.romraider.util.ParamChecker.checkNotNull;
import static com.romraider.util.ParamChecker.checkNotNullOrEmpty;
import static com.romraider.util.ThreadUtil.sleep;
import static java.lang.System.arraycopy;
import static java.lang.System.currentTimeMillis;
import static org.apache.log4j.Logger.getLogger;
import org.apache.log4j.Logger;
checkNotNull(connectionProperties, "connectionProperties");
this.connectionProperties = connectionProperties;
timeout = connectionProperties.getConnectTimeout();
readTimeout = timeout;
// Use TestSerialConnection for testing!!
connection = new SerialConnectionImpl(portName, connectionProperties);
//connection = new TestSerialConnection2(portName, connectionProperties);
}
@Override
public void open(byte[] start, byte[] stop) {
}
// Send request and wait for response with known length
@Override
public void send(byte[] request, byte[] response, PollingState pollState) {
checkNotNull(request, "request");
checkNotNull(response, "response");
checkNotNull(pollState, "pollState");
if (pollState.getCurrentState() == PollingState.State.STATE_0 &&
pollState.getLastState() == PollingState.State.STATE_1) {
clearLine();
}
if (pollState.getCurrentState() == PollingState.State.STATE_0) {
connection.readStaleData();
connection.write(request);
}
while (connection.available() < response.length) { | sleep(1); |
RomRaider/RomRaider | src/main/java/com/romraider/logger/external/core/ExternalDataSourceLoaderImpl.java | // Path: src/main/java/com/romraider/logger/ecu/exception/PluginNotInstalledException.java
// public final class PluginNotInstalledException extends RuntimeException {
//
// private static final long serialVersionUID = -523838685805525387L;
//
// public PluginNotInstalledException() {
// }
//
// public PluginNotInstalledException(String string) {
// super(string);
// }
//
// public PluginNotInstalledException(String string, Throwable throwable) {
// super(string, throwable);
// }
//
// public PluginNotInstalledException(Throwable throwable) {
// super(throwable);
// }
// }
| import java.util.Properties;
import com.romraider.logger.ecu.definition.plugin.PluginFilenameFilter;
import com.romraider.logger.ecu.exception.ConfigurationException;
import com.romraider.logger.ecu.exception.PluginNotInstalledException;
import static com.romraider.util.ParamChecker.isNullOrEmpty;
import org.apache.log4j.Logger;
import java.io.File;
import java.io.FileInputStream;
import java.util.ArrayList;
import java.util.List;
import java.util.Map; | /*
* RomRaider Open-Source Tuning, Logging and Reflashing
* Copyright (C) 2006-2015 RomRaider.com
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License along
* with this program; if not, write to the Free Software Foundation, Inc.,
* 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
*/
package com.romraider.logger.external.core;
public final class ExternalDataSourceLoaderImpl implements ExternalDataSourceLoader {
private static final Logger LOGGER = Logger.getLogger(ExternalDataSourceLoaderImpl.class);
private List<ExternalDataSource> externalDataSources = new ArrayList<ExternalDataSource>();
public void loadExternalDataSources(Map<String, String> loggerPluginPorts) {
try {
File pluginsDir = new File("./plugins");
if (pluginsDir.exists() && pluginsDir.isDirectory()) {
File[] pluginPropertyFiles = pluginsDir.listFiles(new PluginFilenameFilter());
for (File pluginPropertyFile : pluginPropertyFiles) {
Properties pluginProps = new Properties();
FileInputStream inputStream = new FileInputStream(pluginPropertyFile);
try {
pluginProps.load(inputStream);
String datasourceClassName = pluginProps.getProperty("datasource.class");
if (!isNullOrEmpty(datasourceClassName)) {
try {
Class<?> dataSourceClass = getClass().getClassLoader().loadClass(datasourceClassName);
if (dataSourceClass != null && ExternalDataSource.class.isAssignableFrom(dataSourceClass)) {
ExternalDataSource dataSource = dataSource(dataSourceClass, loggerPluginPorts, pluginProps);
ExternalDataSource managedDataSource = new GenericDataSourceManager(dataSource);
externalDataSources.add(managedDataSource);
LOGGER.info("Plugin loaded: " + dataSource.getName() + " v" + dataSource.getVersion());
}
} | // Path: src/main/java/com/romraider/logger/ecu/exception/PluginNotInstalledException.java
// public final class PluginNotInstalledException extends RuntimeException {
//
// private static final long serialVersionUID = -523838685805525387L;
//
// public PluginNotInstalledException() {
// }
//
// public PluginNotInstalledException(String string) {
// super(string);
// }
//
// public PluginNotInstalledException(String string, Throwable throwable) {
// super(string, throwable);
// }
//
// public PluginNotInstalledException(Throwable throwable) {
// super(throwable);
// }
// }
// Path: src/main/java/com/romraider/logger/external/core/ExternalDataSourceLoaderImpl.java
import java.util.Properties;
import com.romraider.logger.ecu.definition.plugin.PluginFilenameFilter;
import com.romraider.logger.ecu.exception.ConfigurationException;
import com.romraider.logger.ecu.exception.PluginNotInstalledException;
import static com.romraider.util.ParamChecker.isNullOrEmpty;
import org.apache.log4j.Logger;
import java.io.File;
import java.io.FileInputStream;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
/*
* RomRaider Open-Source Tuning, Logging and Reflashing
* Copyright (C) 2006-2015 RomRaider.com
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License along
* with this program; if not, write to the Free Software Foundation, Inc.,
* 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
*/
package com.romraider.logger.external.core;
public final class ExternalDataSourceLoaderImpl implements ExternalDataSourceLoader {
private static final Logger LOGGER = Logger.getLogger(ExternalDataSourceLoaderImpl.class);
private List<ExternalDataSource> externalDataSources = new ArrayList<ExternalDataSource>();
public void loadExternalDataSources(Map<String, String> loggerPluginPorts) {
try {
File pluginsDir = new File("./plugins");
if (pluginsDir.exists() && pluginsDir.isDirectory()) {
File[] pluginPropertyFiles = pluginsDir.listFiles(new PluginFilenameFilter());
for (File pluginPropertyFile : pluginPropertyFiles) {
Properties pluginProps = new Properties();
FileInputStream inputStream = new FileInputStream(pluginPropertyFile);
try {
pluginProps.load(inputStream);
String datasourceClassName = pluginProps.getProperty("datasource.class");
if (!isNullOrEmpty(datasourceClassName)) {
try {
Class<?> dataSourceClass = getClass().getClassLoader().loadClass(datasourceClassName);
if (dataSourceClass != null && ExternalDataSource.class.isAssignableFrom(dataSourceClass)) {
ExternalDataSource dataSource = dataSource(dataSourceClass, loggerPluginPorts, pluginProps);
ExternalDataSource managedDataSource = new GenericDataSourceManager(dataSource);
externalDataSources.add(managedDataSource);
LOGGER.info("Plugin loaded: " + dataSource.getName() + " v" + dataSource.getVersion());
}
} | catch (PluginNotInstalledException e) { |
RomRaider/RomRaider | src/main/java/com/romraider/logger/ecu/comms/manager/QueryManagerImpl.java | // Path: src/main/java/com/romraider/util/ThreadUtil.java
// public static void sleep(long millis) {
// try {
// TimeUnit.MILLISECONDS.sleep(millis);
// } catch (InterruptedException e) {
// if (LOGGER.isTraceEnabled())
// LOGGER.trace("Sleep interrupted", e);
// }
// }
//
// Path: src/main/java/com/romraider/logger/ecu/comms/io/connection/LoggerConnection.java
// public interface LoggerConnection {
//
// /**
// * Use the open method when communications to a Module requires a
// * StartCommunication sequence, such as Five Baud or Fast Init.
// * @param module - the Module to open
// */
// void open(Module module);
//
// /**
// * Use this method to reset the module.
// * @param module - the Module to reset
// * @param resetCode - the reset procedure to activate
// */
// void ecuReset(Module module, int resetCode);
//
// /**
// * Use this method to get the identity the Module communicating with.
// * @param callback - callback which will identify the Module
// * @param module - the Module to identify
// */
// void ecuInit(EcuInitCallback callback, Module module);
//
// /**
// * Use this method to query the Module for the parameters included as queries.
// * @param queries - the Collection of EcuQuery items
// * @param module - the Module to query
// * @param pollState - the PollingState to use
// */
// void sendAddressReads(Collection<EcuQuery> queries, Module module, PollingState pollState);
//
// /**
// * Use this method to clear the communications line of any erroneous data.
// * It can be called before closing off communications to clear buffers
// * of stale data, or when changing polling modes.
// */
// void clearLine();
//
// /**
// * Use this method to close communications with the Module.
// */
// void close();
//
// /**
// * Use this method to write to a Module.
// * @param writeQueries - a Map of EcuQuery items to write
// * @param module - the Module to write to
// */
// void sendAddressWrites(Map<EcuQuery, byte[]> writeQueries, Module module);
// }
| import static com.romraider.logger.ecu.comms.io.connection.LoggerConnectionFactory.getConnection;
import static com.romraider.logger.ecu.definition.EcuDataType.EXTERNAL;
import static com.romraider.util.ParamChecker.checkNotNull;
import static com.romraider.util.ParamChecker.isNullOrEmpty;
import static com.romraider.util.ThreadUtil.sleep;
import static java.lang.System.currentTimeMillis;
import static java.util.Collections.synchronizedList;
import static java.util.Collections.synchronizedMap;
import java.text.MessageFormat;
import java.util.ArrayList;
import java.util.Collection;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.ResourceBundle;
import java.util.Set;
import javax.swing.SwingUtilities;
import org.apache.log4j.Logger;
import com.romraider.Settings;
import com.romraider.io.j2534.api.J2534Library;
import com.romraider.io.j2534.api.J2534LibraryLocator;
import com.romraider.logger.ecu.comms.io.connection.LoggerConnection;
import com.romraider.logger.ecu.comms.query.EcuInitCallback;
import com.romraider.logger.ecu.comms.query.EcuQuery;
import com.romraider.logger.ecu.comms.query.EcuQueryImpl;
import com.romraider.logger.ecu.comms.query.ExternalQuery;
import com.romraider.logger.ecu.comms.query.ExternalQueryImpl;
import com.romraider.logger.ecu.comms.query.Query;
import com.romraider.logger.ecu.comms.query.Response;
import com.romraider.logger.ecu.comms.query.ResponseImpl;
import com.romraider.logger.ecu.definition.EcuData;
import com.romraider.logger.ecu.definition.ExternalData;
import com.romraider.logger.ecu.definition.LoggerData;
import com.romraider.logger.ecu.definition.Module;
import com.romraider.logger.ecu.ui.MessageListener;
import com.romraider.logger.ecu.ui.StatusChangeListener;
import com.romraider.logger.ecu.ui.handler.DataUpdateHandler;
import com.romraider.logger.ecu.ui.handler.file.FileLoggerControllerSwitchMonitor;
import com.romraider.util.ResourceUtil;
import com.romraider.util.SettingsManager; | return queryManagerThread;
}
@Override
public boolean isRunning() {
return started && !stop;
}
@Override
public void run() {
started = true;
queryManagerThread = Thread.currentThread();
queryManagerThread.setName("Query Manager");
if (LOGGER.isDebugEnabled())
LOGGER.debug("QueryManager started.");
try {
stop = false;
while (!stop) {
notifyConnecting();
Module target = settings.getDestinationTarget();
if (!settings.isLogExternalsOnly() && doEcuInit(target)) {
notifyReading();
runLogger(target);
} else if (settings.isLogExternalsOnly()) {
notifyReading();
runLogger(null);
} else { | // Path: src/main/java/com/romraider/util/ThreadUtil.java
// public static void sleep(long millis) {
// try {
// TimeUnit.MILLISECONDS.sleep(millis);
// } catch (InterruptedException e) {
// if (LOGGER.isTraceEnabled())
// LOGGER.trace("Sleep interrupted", e);
// }
// }
//
// Path: src/main/java/com/romraider/logger/ecu/comms/io/connection/LoggerConnection.java
// public interface LoggerConnection {
//
// /**
// * Use the open method when communications to a Module requires a
// * StartCommunication sequence, such as Five Baud or Fast Init.
// * @param module - the Module to open
// */
// void open(Module module);
//
// /**
// * Use this method to reset the module.
// * @param module - the Module to reset
// * @param resetCode - the reset procedure to activate
// */
// void ecuReset(Module module, int resetCode);
//
// /**
// * Use this method to get the identity the Module communicating with.
// * @param callback - callback which will identify the Module
// * @param module - the Module to identify
// */
// void ecuInit(EcuInitCallback callback, Module module);
//
// /**
// * Use this method to query the Module for the parameters included as queries.
// * @param queries - the Collection of EcuQuery items
// * @param module - the Module to query
// * @param pollState - the PollingState to use
// */
// void sendAddressReads(Collection<EcuQuery> queries, Module module, PollingState pollState);
//
// /**
// * Use this method to clear the communications line of any erroneous data.
// * It can be called before closing off communications to clear buffers
// * of stale data, or when changing polling modes.
// */
// void clearLine();
//
// /**
// * Use this method to close communications with the Module.
// */
// void close();
//
// /**
// * Use this method to write to a Module.
// * @param writeQueries - a Map of EcuQuery items to write
// * @param module - the Module to write to
// */
// void sendAddressWrites(Map<EcuQuery, byte[]> writeQueries, Module module);
// }
// Path: src/main/java/com/romraider/logger/ecu/comms/manager/QueryManagerImpl.java
import static com.romraider.logger.ecu.comms.io.connection.LoggerConnectionFactory.getConnection;
import static com.romraider.logger.ecu.definition.EcuDataType.EXTERNAL;
import static com.romraider.util.ParamChecker.checkNotNull;
import static com.romraider.util.ParamChecker.isNullOrEmpty;
import static com.romraider.util.ThreadUtil.sleep;
import static java.lang.System.currentTimeMillis;
import static java.util.Collections.synchronizedList;
import static java.util.Collections.synchronizedMap;
import java.text.MessageFormat;
import java.util.ArrayList;
import java.util.Collection;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.ResourceBundle;
import java.util.Set;
import javax.swing.SwingUtilities;
import org.apache.log4j.Logger;
import com.romraider.Settings;
import com.romraider.io.j2534.api.J2534Library;
import com.romraider.io.j2534.api.J2534LibraryLocator;
import com.romraider.logger.ecu.comms.io.connection.LoggerConnection;
import com.romraider.logger.ecu.comms.query.EcuInitCallback;
import com.romraider.logger.ecu.comms.query.EcuQuery;
import com.romraider.logger.ecu.comms.query.EcuQueryImpl;
import com.romraider.logger.ecu.comms.query.ExternalQuery;
import com.romraider.logger.ecu.comms.query.ExternalQueryImpl;
import com.romraider.logger.ecu.comms.query.Query;
import com.romraider.logger.ecu.comms.query.Response;
import com.romraider.logger.ecu.comms.query.ResponseImpl;
import com.romraider.logger.ecu.definition.EcuData;
import com.romraider.logger.ecu.definition.ExternalData;
import com.romraider.logger.ecu.definition.LoggerData;
import com.romraider.logger.ecu.definition.Module;
import com.romraider.logger.ecu.ui.MessageListener;
import com.romraider.logger.ecu.ui.StatusChangeListener;
import com.romraider.logger.ecu.ui.handler.DataUpdateHandler;
import com.romraider.logger.ecu.ui.handler.file.FileLoggerControllerSwitchMonitor;
import com.romraider.util.ResourceUtil;
import com.romraider.util.SettingsManager;
return queryManagerThread;
}
@Override
public boolean isRunning() {
return started && !stop;
}
@Override
public void run() {
started = true;
queryManagerThread = Thread.currentThread();
queryManagerThread.setName("Query Manager");
if (LOGGER.isDebugEnabled())
LOGGER.debug("QueryManager started.");
try {
stop = false;
while (!stop) {
notifyConnecting();
Module target = settings.getDestinationTarget();
if (!settings.isLogExternalsOnly() && doEcuInit(target)) {
notifyReading();
runLogger(target);
} else if (settings.isLogExternalsOnly()) {
notifyReading();
runLogger(null);
} else { | sleep(1000L); |
RomRaider/RomRaider | src/main/java/com/romraider/logger/ecu/comms/manager/QueryManagerImpl.java | // Path: src/main/java/com/romraider/util/ThreadUtil.java
// public static void sleep(long millis) {
// try {
// TimeUnit.MILLISECONDS.sleep(millis);
// } catch (InterruptedException e) {
// if (LOGGER.isTraceEnabled())
// LOGGER.trace("Sleep interrupted", e);
// }
// }
//
// Path: src/main/java/com/romraider/logger/ecu/comms/io/connection/LoggerConnection.java
// public interface LoggerConnection {
//
// /**
// * Use the open method when communications to a Module requires a
// * StartCommunication sequence, such as Five Baud or Fast Init.
// * @param module - the Module to open
// */
// void open(Module module);
//
// /**
// * Use this method to reset the module.
// * @param module - the Module to reset
// * @param resetCode - the reset procedure to activate
// */
// void ecuReset(Module module, int resetCode);
//
// /**
// * Use this method to get the identity the Module communicating with.
// * @param callback - callback which will identify the Module
// * @param module - the Module to identify
// */
// void ecuInit(EcuInitCallback callback, Module module);
//
// /**
// * Use this method to query the Module for the parameters included as queries.
// * @param queries - the Collection of EcuQuery items
// * @param module - the Module to query
// * @param pollState - the PollingState to use
// */
// void sendAddressReads(Collection<EcuQuery> queries, Module module, PollingState pollState);
//
// /**
// * Use this method to clear the communications line of any erroneous data.
// * It can be called before closing off communications to clear buffers
// * of stale data, or when changing polling modes.
// */
// void clearLine();
//
// /**
// * Use this method to close communications with the Module.
// */
// void close();
//
// /**
// * Use this method to write to a Module.
// * @param writeQueries - a Map of EcuQuery items to write
// * @param module - the Module to write to
// */
// void sendAddressWrites(Map<EcuQuery, byte[]> writeQueries, Module module);
// }
| import static com.romraider.logger.ecu.comms.io.connection.LoggerConnectionFactory.getConnection;
import static com.romraider.logger.ecu.definition.EcuDataType.EXTERNAL;
import static com.romraider.util.ParamChecker.checkNotNull;
import static com.romraider.util.ParamChecker.isNullOrEmpty;
import static com.romraider.util.ThreadUtil.sleep;
import static java.lang.System.currentTimeMillis;
import static java.util.Collections.synchronizedList;
import static java.util.Collections.synchronizedMap;
import java.text.MessageFormat;
import java.util.ArrayList;
import java.util.Collection;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.ResourceBundle;
import java.util.Set;
import javax.swing.SwingUtilities;
import org.apache.log4j.Logger;
import com.romraider.Settings;
import com.romraider.io.j2534.api.J2534Library;
import com.romraider.io.j2534.api.J2534LibraryLocator;
import com.romraider.logger.ecu.comms.io.connection.LoggerConnection;
import com.romraider.logger.ecu.comms.query.EcuInitCallback;
import com.romraider.logger.ecu.comms.query.EcuQuery;
import com.romraider.logger.ecu.comms.query.EcuQueryImpl;
import com.romraider.logger.ecu.comms.query.ExternalQuery;
import com.romraider.logger.ecu.comms.query.ExternalQueryImpl;
import com.romraider.logger.ecu.comms.query.Query;
import com.romraider.logger.ecu.comms.query.Response;
import com.romraider.logger.ecu.comms.query.ResponseImpl;
import com.romraider.logger.ecu.definition.EcuData;
import com.romraider.logger.ecu.definition.ExternalData;
import com.romraider.logger.ecu.definition.LoggerData;
import com.romraider.logger.ecu.definition.Module;
import com.romraider.logger.ecu.ui.MessageListener;
import com.romraider.logger.ecu.ui.StatusChangeListener;
import com.romraider.logger.ecu.ui.handler.DataUpdateHandler;
import com.romraider.logger.ecu.ui.handler.file.FileLoggerControllerSwitchMonitor;
import com.romraider.util.ResourceUtil;
import com.romraider.util.SettingsManager; | for (J2534Library dll : libraries) {
LOGGER.info(String.format("Trying new J2534/%s connection: %s",
settings.getTransportProtocol(),
dll.getVendor()));
settings.setJ2534Device(dll.getLibrary());
if (initConnection(module, dll.getVendor())) {
return true;
}
}
}
else {
// Try previous J2534 library from settings
LOGGER.info(String.format(
"Trying previous J2534/%s connection: %s",
settings.getTransportProtocol(),
settings.getJ2534Device()));
if (initConnection(module, settings.getJ2534Device())) {
return true;
}
}
settings.setJ2534Device("");
// Finally try Serial
if (initConnection(module, settings.getLoggerPort())) {
return true;
}
return false;
}
private boolean initConnection(final Module module, final String name) { | // Path: src/main/java/com/romraider/util/ThreadUtil.java
// public static void sleep(long millis) {
// try {
// TimeUnit.MILLISECONDS.sleep(millis);
// } catch (InterruptedException e) {
// if (LOGGER.isTraceEnabled())
// LOGGER.trace("Sleep interrupted", e);
// }
// }
//
// Path: src/main/java/com/romraider/logger/ecu/comms/io/connection/LoggerConnection.java
// public interface LoggerConnection {
//
// /**
// * Use the open method when communications to a Module requires a
// * StartCommunication sequence, such as Five Baud or Fast Init.
// * @param module - the Module to open
// */
// void open(Module module);
//
// /**
// * Use this method to reset the module.
// * @param module - the Module to reset
// * @param resetCode - the reset procedure to activate
// */
// void ecuReset(Module module, int resetCode);
//
// /**
// * Use this method to get the identity the Module communicating with.
// * @param callback - callback which will identify the Module
// * @param module - the Module to identify
// */
// void ecuInit(EcuInitCallback callback, Module module);
//
// /**
// * Use this method to query the Module for the parameters included as queries.
// * @param queries - the Collection of EcuQuery items
// * @param module - the Module to query
// * @param pollState - the PollingState to use
// */
// void sendAddressReads(Collection<EcuQuery> queries, Module module, PollingState pollState);
//
// /**
// * Use this method to clear the communications line of any erroneous data.
// * It can be called before closing off communications to clear buffers
// * of stale data, or when changing polling modes.
// */
// void clearLine();
//
// /**
// * Use this method to close communications with the Module.
// */
// void close();
//
// /**
// * Use this method to write to a Module.
// * @param writeQueries - a Map of EcuQuery items to write
// * @param module - the Module to write to
// */
// void sendAddressWrites(Map<EcuQuery, byte[]> writeQueries, Module module);
// }
// Path: src/main/java/com/romraider/logger/ecu/comms/manager/QueryManagerImpl.java
import static com.romraider.logger.ecu.comms.io.connection.LoggerConnectionFactory.getConnection;
import static com.romraider.logger.ecu.definition.EcuDataType.EXTERNAL;
import static com.romraider.util.ParamChecker.checkNotNull;
import static com.romraider.util.ParamChecker.isNullOrEmpty;
import static com.romraider.util.ThreadUtil.sleep;
import static java.lang.System.currentTimeMillis;
import static java.util.Collections.synchronizedList;
import static java.util.Collections.synchronizedMap;
import java.text.MessageFormat;
import java.util.ArrayList;
import java.util.Collection;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.ResourceBundle;
import java.util.Set;
import javax.swing.SwingUtilities;
import org.apache.log4j.Logger;
import com.romraider.Settings;
import com.romraider.io.j2534.api.J2534Library;
import com.romraider.io.j2534.api.J2534LibraryLocator;
import com.romraider.logger.ecu.comms.io.connection.LoggerConnection;
import com.romraider.logger.ecu.comms.query.EcuInitCallback;
import com.romraider.logger.ecu.comms.query.EcuQuery;
import com.romraider.logger.ecu.comms.query.EcuQueryImpl;
import com.romraider.logger.ecu.comms.query.ExternalQuery;
import com.romraider.logger.ecu.comms.query.ExternalQueryImpl;
import com.romraider.logger.ecu.comms.query.Query;
import com.romraider.logger.ecu.comms.query.Response;
import com.romraider.logger.ecu.comms.query.ResponseImpl;
import com.romraider.logger.ecu.definition.EcuData;
import com.romraider.logger.ecu.definition.ExternalData;
import com.romraider.logger.ecu.definition.LoggerData;
import com.romraider.logger.ecu.definition.Module;
import com.romraider.logger.ecu.ui.MessageListener;
import com.romraider.logger.ecu.ui.StatusChangeListener;
import com.romraider.logger.ecu.ui.handler.DataUpdateHandler;
import com.romraider.logger.ecu.ui.handler.file.FileLoggerControllerSwitchMonitor;
import com.romraider.util.ResourceUtil;
import com.romraider.util.SettingsManager;
for (J2534Library dll : libraries) {
LOGGER.info(String.format("Trying new J2534/%s connection: %s",
settings.getTransportProtocol(),
dll.getVendor()));
settings.setJ2534Device(dll.getLibrary());
if (initConnection(module, dll.getVendor())) {
return true;
}
}
}
else {
// Try previous J2534 library from settings
LOGGER.info(String.format(
"Trying previous J2534/%s connection: %s",
settings.getTransportProtocol(),
settings.getJ2534Device()));
if (initConnection(module, settings.getJ2534Device())) {
return true;
}
}
settings.setJ2534Device("");
// Finally try Serial
if (initConnection(module, settings.getLoggerPort())) {
return true;
}
return false;
}
private boolean initConnection(final Module module, final String name) { | LoggerConnection connection = null; |
CST-Group/cst | src/main/java/br/unicamp/cst/motivational/Drive.java | // Path: src/main/java/br/unicamp/cst/support/ToString.java
// public class ToString {
// public static String from(Object n) {
// String s=null;
// if (n == null)
// s = "<NULL>";
// else if (n instanceof Long) {
// long i = (long) n;
// s = String.format("%d",i);
// }
// else if (n instanceof Integer) {
// int i = (int) n;
// s = String.format("%d",i);
// }
// else if (n instanceof Float) {
// float d = (float) n;
// s = String.format("%4.2f", d);
// }
// else if (n instanceof Double) {
// double d = (double) n;
// s = String.format("%4.2f", d);
// }
// else if (n instanceof Byte) {
// byte b = (byte) n;
// s = String.format("%x", b);
// }
// else if (n instanceof Short) {
// short sh = (short) n;
// s = String.format("%d", sh);
// }
// else if (n instanceof Boolean) {
// boolean b = (boolean) n;
// if (b == true) s = "true";
// else s = "false";
// }
// else if (n instanceof Date) {
// Date d = (Date) n;
// s = TimeStamp.getStringTimeStamp(d.getTime(),"dd/MM/yyyy HH:mm:ss.SSS");
// }
// else if (n instanceof String) {
// s = (String) n;
// }
// return(s);
// }
//
// public static String fromArray(Object n) {
// String s=null;
// if (n == null)
// s = "<NULL>";
// else if (n instanceof double[]) {
// double[] value = (double[]) n;
// if (value.length == 1)
// s = String.format("%4.2f",value[0]);
// else if (value.length == 2)
// s = String.format("%4.2f,%4.2f",value[0],value[1]);
// else if (value.length == 3)
// s = String.format("%4.2f,%4.2f,%4.2f",value[0],value[1],value[2]);
// else if (value.length == 4)
// s = String.format("%4.2f,%4.2f,%4.2f,%4.2f",value[0],value[1],value[2],value[3]);
// else if (value.length == 5)
// s = String.format("%4.2f,%4.2f,%4.2f,%4.2f,%4.2f",value[0],value[1],value[2],value[3],value[4]);
// else if (value.length == 6)
// s = String.format("%4.2f,%4.2f,%4.2f,%4.2f,%4.2f,%4.2f",value[0],value[1],value[2],value[3],value[4],value[5]);
// else if (value.length > 6)
// s = String.format("%4.2f,%4.2f,%4.2f,%4.2f,%4.2f,%4.2f...",value[0],value[1],value[2],value[3],value[4],value[5]);
// }
// else if (n instanceof float[]) {
// float[] value = (float[]) n;
// if (value.length == 1)
// s = String.format("%4.2f",value[0]);
// else if (value.length == 2)
// s = String.format("%4.2f,%4.2f",value[0],value[1]);
// else if (value.length == 3)
// s = String.format("%4.2f,%4.2f,%4.2f",value[0],value[1],value[2]);
// else if (value.length == 4)
// s = String.format("%4.2f,%4.2f,%4.2f,%4.2f",value[0],value[1],value[2],value[3]);
// else if (value.length == 5)
// s = String.format("%4.2f,%4.2f,%4.2f,%4.2f,%4.2f",value[0],value[1],value[2],value[3],value[4]);
// else if (value.length == 6)
// s = String.format("%4.2f,%4.2f,%4.2f,%4.2f,%4.2f,%4.2f",value[0],value[1],value[2],value[3],value[4],value[5]);
// else if (value.length > 6)
// s = String.format("%4.2f,%4.2f,%4.2f,%4.2f,%4.2f,%4.2f...",value[0],value[1],value[2],value[3],value[4],value[5]);
// }
// return(s);
// }
//
// public static String el(String name, int i) {
// String s = name +"["+i+"]";
// return(s);
// }
//
// public static String getSimpleName(String fullname) {
// String[] mc = fullname.split("\\.");
// String simplename = mc[mc.length-1];
// return (simplename);
// }
//
// }
| import br.unicamp.cst.support.ToString;
import java.io.Serializable; | public synchronized void setPriority(double priority) {
this.priority = priority;
}
public synchronized double getLevel() {
return level;
}
public synchronized void setLevel(double level) {
this.level = level;
}
public synchronized double getUrgencyThreshold() {
return urgencyThreshold;
}
public synchronized void setUrgencyThreshold(double urgencyThreshold) {
this.urgencyThreshold = urgencyThreshold;
}
public synchronized double getEmotionalDistortion() {
return emotionalDistortion;
}
public synchronized void setEmotionalDistortion(double emotionalDistortion) {
this.emotionalDistortion = emotionalDistortion;
}
@Override
public String toString(){ | // Path: src/main/java/br/unicamp/cst/support/ToString.java
// public class ToString {
// public static String from(Object n) {
// String s=null;
// if (n == null)
// s = "<NULL>";
// else if (n instanceof Long) {
// long i = (long) n;
// s = String.format("%d",i);
// }
// else if (n instanceof Integer) {
// int i = (int) n;
// s = String.format("%d",i);
// }
// else if (n instanceof Float) {
// float d = (float) n;
// s = String.format("%4.2f", d);
// }
// else if (n instanceof Double) {
// double d = (double) n;
// s = String.format("%4.2f", d);
// }
// else if (n instanceof Byte) {
// byte b = (byte) n;
// s = String.format("%x", b);
// }
// else if (n instanceof Short) {
// short sh = (short) n;
// s = String.format("%d", sh);
// }
// else if (n instanceof Boolean) {
// boolean b = (boolean) n;
// if (b == true) s = "true";
// else s = "false";
// }
// else if (n instanceof Date) {
// Date d = (Date) n;
// s = TimeStamp.getStringTimeStamp(d.getTime(),"dd/MM/yyyy HH:mm:ss.SSS");
// }
// else if (n instanceof String) {
// s = (String) n;
// }
// return(s);
// }
//
// public static String fromArray(Object n) {
// String s=null;
// if (n == null)
// s = "<NULL>";
// else if (n instanceof double[]) {
// double[] value = (double[]) n;
// if (value.length == 1)
// s = String.format("%4.2f",value[0]);
// else if (value.length == 2)
// s = String.format("%4.2f,%4.2f",value[0],value[1]);
// else if (value.length == 3)
// s = String.format("%4.2f,%4.2f,%4.2f",value[0],value[1],value[2]);
// else if (value.length == 4)
// s = String.format("%4.2f,%4.2f,%4.2f,%4.2f",value[0],value[1],value[2],value[3]);
// else if (value.length == 5)
// s = String.format("%4.2f,%4.2f,%4.2f,%4.2f,%4.2f",value[0],value[1],value[2],value[3],value[4]);
// else if (value.length == 6)
// s = String.format("%4.2f,%4.2f,%4.2f,%4.2f,%4.2f,%4.2f",value[0],value[1],value[2],value[3],value[4],value[5]);
// else if (value.length > 6)
// s = String.format("%4.2f,%4.2f,%4.2f,%4.2f,%4.2f,%4.2f...",value[0],value[1],value[2],value[3],value[4],value[5]);
// }
// else if (n instanceof float[]) {
// float[] value = (float[]) n;
// if (value.length == 1)
// s = String.format("%4.2f",value[0]);
// else if (value.length == 2)
// s = String.format("%4.2f,%4.2f",value[0],value[1]);
// else if (value.length == 3)
// s = String.format("%4.2f,%4.2f,%4.2f",value[0],value[1],value[2]);
// else if (value.length == 4)
// s = String.format("%4.2f,%4.2f,%4.2f,%4.2f",value[0],value[1],value[2],value[3]);
// else if (value.length == 5)
// s = String.format("%4.2f,%4.2f,%4.2f,%4.2f,%4.2f",value[0],value[1],value[2],value[3],value[4]);
// else if (value.length == 6)
// s = String.format("%4.2f,%4.2f,%4.2f,%4.2f,%4.2f,%4.2f",value[0],value[1],value[2],value[3],value[4],value[5]);
// else if (value.length > 6)
// s = String.format("%4.2f,%4.2f,%4.2f,%4.2f,%4.2f,%4.2f...",value[0],value[1],value[2],value[3],value[4],value[5]);
// }
// return(s);
// }
//
// public static String el(String name, int i) {
// String s = name +"["+i+"]";
// return(s);
// }
//
// public static String getSimpleName(String fullname) {
// String[] mc = fullname.split("\\.");
// String simplename = mc[mc.length-1];
// return (simplename);
// }
//
// }
// Path: src/main/java/br/unicamp/cst/motivational/Drive.java
import br.unicamp.cst.support.ToString;
import java.io.Serializable;
public synchronized void setPriority(double priority) {
this.priority = priority;
}
public synchronized double getLevel() {
return level;
}
public synchronized void setLevel(double level) {
this.level = level;
}
public synchronized double getUrgencyThreshold() {
return urgencyThreshold;
}
public synchronized void setUrgencyThreshold(double urgencyThreshold) {
this.urgencyThreshold = urgencyThreshold;
}
public synchronized double getEmotionalDistortion() {
return emotionalDistortion;
}
public synchronized void setEmotionalDistortion(double emotionalDistortion) {
this.emotionalDistortion = emotionalDistortion;
}
@Override
public String toString(){ | return(ToString.from(getActivation())); |
CST-Group/cst | src/main/java/br/unicamp/cst/representation/owrl/DynamicAffordance.java | // Path: src/main/java/br/unicamp/cst/core/entities/CSTMessages.java
// public class CSTMessages {
//
// // DRIVE MESSAGES.
// public static final String MSG_VAR_NAME_NULL = "Drive name is null.";
// public static final String MSG_VAR_RELEVANCE = "Drive relevance must be less equal than 1 and greater equal than 0.";
// public static final String MSG_VAR_PRIORITY_NULL = "Drive priority is null.";
// public static final String MSG_VAR_URGENT_ACTIVATION_RANGE = "Drive urgent activation must be less equal than 1 and greater equal than 0.";
// public static final String MSG_VAR_URGENT_ACTIVATION_THRESHOLD_RANGE = "Drive urgent activation threshold must be less equal than 1 and greater equal than 0.";
// public static final String MSG_VAR_LOWER_URGENT_ACTIVATION_THRESHOLD_RANGE = "Drive lower urgent activation threshold must be less equal than 1 and greater equal than 0.";
// public static final String MSG_VAR_HIGH_PRIORITY = "Drive high priority must be less equal than 1 and greater equal than 0.";
//
// // GOAL MESSAGES.
// public static final String MSG_VAR_EMOTIONAL_NAME_NULL = "EmotionalCodelet name is null";
// public static final String MSG_VAR_EMOTIONAL_DRIVE_VOTES = "EmotionalCodelet drive votes is null or empty.";
// public static final String MSG_VAR_EMOTIONAL_INTERVENTION_THRESHOLD = "Intervention threshold must be less equal than 1 and greater equal than 0.";
//
// // AFFORDANCE MESSAGES.
// public static final String MSG_VAR_DETECTOR_OBJECT = "Detector object is null.";
// public static final String MSG_VAR_APPLY_OBJECT = "Apply object is null.";
//
// }
| import br.unicamp.cst.core.entities.CSTMessages;
import java.util.Arrays;
import java.util.Date;
import java.util.HashMap;
import java.util.List; | /*******************************************************************************
* Copyright (c) 2012 DCA-FEEC-UNICAMP
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the GNU Lesser Public License v3
* which accompanies this distribution, and is available at
* http://www.gnu.org/licenses/lgpl.html
*
* Contributors:
* K. Raizer, A. L. O. Paraense, R. R. Gudwin - initial API and implementation
******************************************************************************/
package br.unicamp.cst.representation.owrl;
/**
* @author Suelen Mapa and Eduardo Froes.
*/
public class DynamicAffordance extends Affordance {
private String applyCode;
private String applyClassName;
private String detectorCode;
private String detectorClassName;
private Object applyObject;
private Object detectorObject;
public DynamicAffordance(String name) {
super(name, new HashMap<>(), new HashMap<>(), new HashMap<>());
}
public DynamicAffordance(String name, HashMap<String, AbstractObject> aggregateObjects, HashMap<String, AbstractObject> compositeObjects, HashMap<String, Property> modifiedProperties) {
super(name, aggregateObjects, compositeObjects, modifiedProperties);
}
public DynamicAffordance(String name, String applyClassName, String applyCode, String detectorClassName, String detectorCode, HashMap<String, AbstractObject> aggregateObjects, HashMap<String, AbstractObject> compositeObjects, HashMap<String, Property> modifiedProperties) {
super(name, aggregateObjects, compositeObjects, modifiedProperties);
setApplyCode(applyCode);
setApplyClassName(applyClassName);
setDetectorCode(detectorCode);
setDetectorClassName(detectorClassName);
setDetectorObject(CodeBuilder.generateNewInstance(CodeBuilder.compile(getDetectorClassName(), getDetectorCode())));
setApplyObject(CodeBuilder.generateNewInstance(CodeBuilder.compile(getApplyClassName(), getApplyCode())));
}
public Object detector(String methodName, Object... args) {
try {
if (getDetectorObject() == null) { | // Path: src/main/java/br/unicamp/cst/core/entities/CSTMessages.java
// public class CSTMessages {
//
// // DRIVE MESSAGES.
// public static final String MSG_VAR_NAME_NULL = "Drive name is null.";
// public static final String MSG_VAR_RELEVANCE = "Drive relevance must be less equal than 1 and greater equal than 0.";
// public static final String MSG_VAR_PRIORITY_NULL = "Drive priority is null.";
// public static final String MSG_VAR_URGENT_ACTIVATION_RANGE = "Drive urgent activation must be less equal than 1 and greater equal than 0.";
// public static final String MSG_VAR_URGENT_ACTIVATION_THRESHOLD_RANGE = "Drive urgent activation threshold must be less equal than 1 and greater equal than 0.";
// public static final String MSG_VAR_LOWER_URGENT_ACTIVATION_THRESHOLD_RANGE = "Drive lower urgent activation threshold must be less equal than 1 and greater equal than 0.";
// public static final String MSG_VAR_HIGH_PRIORITY = "Drive high priority must be less equal than 1 and greater equal than 0.";
//
// // GOAL MESSAGES.
// public static final String MSG_VAR_EMOTIONAL_NAME_NULL = "EmotionalCodelet name is null";
// public static final String MSG_VAR_EMOTIONAL_DRIVE_VOTES = "EmotionalCodelet drive votes is null or empty.";
// public static final String MSG_VAR_EMOTIONAL_INTERVENTION_THRESHOLD = "Intervention threshold must be less equal than 1 and greater equal than 0.";
//
// // AFFORDANCE MESSAGES.
// public static final String MSG_VAR_DETECTOR_OBJECT = "Detector object is null.";
// public static final String MSG_VAR_APPLY_OBJECT = "Apply object is null.";
//
// }
// Path: src/main/java/br/unicamp/cst/representation/owrl/DynamicAffordance.java
import br.unicamp.cst.core.entities.CSTMessages;
import java.util.Arrays;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
/*******************************************************************************
* Copyright (c) 2012 DCA-FEEC-UNICAMP
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the GNU Lesser Public License v3
* which accompanies this distribution, and is available at
* http://www.gnu.org/licenses/lgpl.html
*
* Contributors:
* K. Raizer, A. L. O. Paraense, R. R. Gudwin - initial API and implementation
******************************************************************************/
package br.unicamp.cst.representation.owrl;
/**
* @author Suelen Mapa and Eduardo Froes.
*/
public class DynamicAffordance extends Affordance {
private String applyCode;
private String applyClassName;
private String detectorCode;
private String detectorClassName;
private Object applyObject;
private Object detectorObject;
public DynamicAffordance(String name) {
super(name, new HashMap<>(), new HashMap<>(), new HashMap<>());
}
public DynamicAffordance(String name, HashMap<String, AbstractObject> aggregateObjects, HashMap<String, AbstractObject> compositeObjects, HashMap<String, Property> modifiedProperties) {
super(name, aggregateObjects, compositeObjects, modifiedProperties);
}
public DynamicAffordance(String name, String applyClassName, String applyCode, String detectorClassName, String detectorCode, HashMap<String, AbstractObject> aggregateObjects, HashMap<String, AbstractObject> compositeObjects, HashMap<String, Property> modifiedProperties) {
super(name, aggregateObjects, compositeObjects, modifiedProperties);
setApplyCode(applyCode);
setApplyClassName(applyClassName);
setDetectorCode(detectorCode);
setDetectorClassName(detectorClassName);
setDetectorObject(CodeBuilder.generateNewInstance(CodeBuilder.compile(getDetectorClassName(), getDetectorCode())));
setApplyObject(CodeBuilder.generateNewInstance(CodeBuilder.compile(getApplyClassName(), getApplyCode())));
}
public Object detector(String methodName, Object... args) {
try {
if (getDetectorObject() == null) { | throw new Exception(CSTMessages.MSG_VAR_DETECTOR_OBJECT); |
CST-Group/cst | src/main/java/br/unicamp/cst/behavior/asbac/ExtractedAffordance.java | // Path: src/main/java/br/unicamp/cst/motivational/Drive.java
// public class Drive implements Serializable {
//
// private static final long serialVersionUID = 1L;
//
// private String name;
// private double activation;
// private double priority;
// private double level;
// private double urgencyThreshold;
// private double emotionalDistortion = 0;
// private boolean urgencyState = false;
//
// public Drive(String name){
// setName(name);
// }
//
// public Drive(String name, double activation, double priority, double level, double urgentThreshold){
// setName(name);
// setActivation(activation);
// setPriority(priority);
// setLevel(level);
// setUrgencyThreshold(urgentThreshold);
// }
//
// public Drive(String name, double activation, double priority, double level, double urgentThreshold, double emotionalDistortion){
// setName(name);
// setActivation(activation);
// setPriority(priority);
// setLevel(level);
// setUrgencyThreshold(urgentThreshold);
// setEmotionalDistortion(emotionalDistortion);
// }
//
// public synchronized String getName() {
// return name;
// }
//
// public synchronized void setName(String name) {
// this.name = name;
// }
//
// public synchronized double getActivation() {
// return activation;
// }
//
// public synchronized void setActivation(double activation) {
// this.activation = activation;
// }
//
// public synchronized double getPriority() {
// return priority;
// }
//
// public synchronized void setPriority(double priority) {
// this.priority = priority;
// }
//
// public synchronized double getLevel() {
// return level;
// }
//
// public synchronized void setLevel(double level) {
// this.level = level;
// }
//
// public synchronized double getUrgencyThreshold() {
// return urgencyThreshold;
// }
//
// public synchronized void setUrgencyThreshold(double urgencyThreshold) {
// this.urgencyThreshold = urgencyThreshold;
// }
//
// public synchronized double getEmotionalDistortion() {
// return emotionalDistortion;
// }
//
// public synchronized void setEmotionalDistortion(double emotionalDistortion) {
// this.emotionalDistortion = emotionalDistortion;
// }
//
// @Override
// public String toString(){
// return(ToString.from(getActivation()));
// }
//
// public String toStringComplete() {
// return"Drive [name="+getName()+", activation="+getActivation()+", urgency state="+isUrgencyState()+", priority="+getPriority()+", level="+getLevel()
// +", urgency threshold="+getUrgencyThreshold()+", emotional distortion="+getEmotionalDistortion()+"]";
// }
//
// public boolean isUrgencyState() {
// return urgencyState;
// }
//
// public void setUrgencyState(boolean urgencyState) {
// this.urgencyState = urgencyState;
// }
// }
| import br.unicamp.cst.motivational.Drive;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.logging.Level;
import java.util.logging.Logger;
| /**
* ****************************************************************************
* Copyright (c) 2018 DCA-FEEC-UNICAMP
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the GNU Lesser Public License v3
* which accompanies this distribution, and is available at
* http://www.gnu.org/licenses/lgpl.html
* <p>
* Contributors:
* R. G. Polizeli and R. R. Gudwin
* ****************************************************************************
*/
package br.unicamp.cst.behavior.asbac;
/**
*
* @author rgpolizeli
*/
public class ExtractedAffordance implements Cloneable{
private String affordanceName;
private Map<String,Percept> perceptsPermutation;
| // Path: src/main/java/br/unicamp/cst/motivational/Drive.java
// public class Drive implements Serializable {
//
// private static final long serialVersionUID = 1L;
//
// private String name;
// private double activation;
// private double priority;
// private double level;
// private double urgencyThreshold;
// private double emotionalDistortion = 0;
// private boolean urgencyState = false;
//
// public Drive(String name){
// setName(name);
// }
//
// public Drive(String name, double activation, double priority, double level, double urgentThreshold){
// setName(name);
// setActivation(activation);
// setPriority(priority);
// setLevel(level);
// setUrgencyThreshold(urgentThreshold);
// }
//
// public Drive(String name, double activation, double priority, double level, double urgentThreshold, double emotionalDistortion){
// setName(name);
// setActivation(activation);
// setPriority(priority);
// setLevel(level);
// setUrgencyThreshold(urgentThreshold);
// setEmotionalDistortion(emotionalDistortion);
// }
//
// public synchronized String getName() {
// return name;
// }
//
// public synchronized void setName(String name) {
// this.name = name;
// }
//
// public synchronized double getActivation() {
// return activation;
// }
//
// public synchronized void setActivation(double activation) {
// this.activation = activation;
// }
//
// public synchronized double getPriority() {
// return priority;
// }
//
// public synchronized void setPriority(double priority) {
// this.priority = priority;
// }
//
// public synchronized double getLevel() {
// return level;
// }
//
// public synchronized void setLevel(double level) {
// this.level = level;
// }
//
// public synchronized double getUrgencyThreshold() {
// return urgencyThreshold;
// }
//
// public synchronized void setUrgencyThreshold(double urgencyThreshold) {
// this.urgencyThreshold = urgencyThreshold;
// }
//
// public synchronized double getEmotionalDistortion() {
// return emotionalDistortion;
// }
//
// public synchronized void setEmotionalDistortion(double emotionalDistortion) {
// this.emotionalDistortion = emotionalDistortion;
// }
//
// @Override
// public String toString(){
// return(ToString.from(getActivation()));
// }
//
// public String toStringComplete() {
// return"Drive [name="+getName()+", activation="+getActivation()+", urgency state="+isUrgencyState()+", priority="+getPriority()+", level="+getLevel()
// +", urgency threshold="+getUrgencyThreshold()+", emotional distortion="+getEmotionalDistortion()+"]";
// }
//
// public boolean isUrgencyState() {
// return urgencyState;
// }
//
// public void setUrgencyState(boolean urgencyState) {
// this.urgencyState = urgencyState;
// }
// }
// Path: src/main/java/br/unicamp/cst/behavior/asbac/ExtractedAffordance.java
import br.unicamp.cst.motivational.Drive;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.logging.Level;
import java.util.logging.Logger;
/**
* ****************************************************************************
* Copyright (c) 2018 DCA-FEEC-UNICAMP
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the GNU Lesser Public License v3
* which accompanies this distribution, and is available at
* http://www.gnu.org/licenses/lgpl.html
* <p>
* Contributors:
* R. G. Polizeli and R. R. Gudwin
* ****************************************************************************
*/
package br.unicamp.cst.behavior.asbac;
/**
*
* @author rgpolizeli
*/
public class ExtractedAffordance implements Cloneable{
private String affordanceName;
private Map<String,Percept> perceptsPermutation;
| private Map<Drive,List<AffordanceType>> hierachiesNodes;
|
iswangheng/DataMining-over-Sina-Weibo | src/weibo4j/Weibo.java | // Path: src/weibo4j/http/RequestToken.java
// public class RequestToken extends OAuthToken {
// private HttpClient httpClient;
// private static final long serialVersionUID = -8214365845469757952L;
//
// RequestToken(Response res, HttpClient httpClient) throws WeiboException{
// super(res);
// this.httpClient = httpClient;
// }
//
// RequestToken(String token, String tokenSecret) {
// super(token, tokenSecret);
// }
//
// public String getAuthorizationURL() {
// return httpClient.getAuthorizationURL() + "?oauth_token=" + getToken();
// }
//
// /**
// * since Weibo4J 2.0.10
// */
// public String getAuthenticationURL() {
// return httpClient.getAuthenticationRL() + "?oauth_token=" + getToken();
// }
//
// public AccessToken getAccessToken(String pin) throws WeiboException {
// return httpClient.getOAuthAccessToken(this, pin);
// }
//
// public HttpClient getHttpClient() {
// return httpClient;
// }
//
// public void setHttpClient(HttpClient httpClient) {
// this.httpClient = httpClient;
// }
//
// @Override
// public boolean equals(Object o) {
// if (this == o) return true;
// if (o == null || getClass() != o.getClass()) return false;
// if (!super.equals(o)) return false;
//
// RequestToken that = (RequestToken) o;
//
// if (httpClient != null ? !httpClient.equals(that.httpClient) : that.httpClient != null)
// return false;
//
// return true;
// }
//
// @Override
// public int hashCode() {
// int result = super.hashCode();
// result = 31 * result + (httpClient != null ? httpClient.hashCode() : 0);
// return result;
// }
// }
| import java.io.File;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Locale;
import java.util.Map;
import java.util.TimeZone;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import weibo4j.http.AccessToken;
import weibo4j.http.HttpClient;
import weibo4j.http.ImageItem;
import weibo4j.http.PostParameter;
import weibo4j.http.RequestToken;
import weibo4j.http.Response;
import weibo4j.org.json.JSONException;
import weibo4j.org.json.JSONObject;
import weibo4j.util.URLEncodeUtils; | * @see <a href="http://open.t.sina.com.cn/wiki/index.php/Statuses/reply">Statuses/reply</a>
* @throws WeiboException when Weibo service or network is unavailable
* @since Weibo4J 1.2.1
*/
public Comment reply(String sid, String cid, String comment)
throws WeiboException {
return new Comment(http.post(getBaseURL() + "statuses/reply.json",
new PostParameter[] { new PostParameter("id", sid),
new PostParameter("cid", cid),
new PostParameter("comment", comment) }, true));
}
//--------------auth method----------
/**
*
* @param consumerKey OAuth consumer key
* @param consumerSecret OAuth consumer secret
* @since Weibo4J 1.2.1
*/
public synchronized void setOAuthConsumer(String consumerKey, String consumerSecret){
this.http.setOAuthConsumer(consumerKey, consumerSecret);
}
/**
* 获取request token
* @return generated request token.
* @throws WeiboException when Weibo service or network is unavailable
* @since Weibo4J 1.2.1
* @see <a href="http://oauth.net/core/1.0/#auth_step1">OAuth Core 1.0 - 6.1. Obtaining an Unauthorized Request Token</a>
*/ | // Path: src/weibo4j/http/RequestToken.java
// public class RequestToken extends OAuthToken {
// private HttpClient httpClient;
// private static final long serialVersionUID = -8214365845469757952L;
//
// RequestToken(Response res, HttpClient httpClient) throws WeiboException{
// super(res);
// this.httpClient = httpClient;
// }
//
// RequestToken(String token, String tokenSecret) {
// super(token, tokenSecret);
// }
//
// public String getAuthorizationURL() {
// return httpClient.getAuthorizationURL() + "?oauth_token=" + getToken();
// }
//
// /**
// * since Weibo4J 2.0.10
// */
// public String getAuthenticationURL() {
// return httpClient.getAuthenticationRL() + "?oauth_token=" + getToken();
// }
//
// public AccessToken getAccessToken(String pin) throws WeiboException {
// return httpClient.getOAuthAccessToken(this, pin);
// }
//
// public HttpClient getHttpClient() {
// return httpClient;
// }
//
// public void setHttpClient(HttpClient httpClient) {
// this.httpClient = httpClient;
// }
//
// @Override
// public boolean equals(Object o) {
// if (this == o) return true;
// if (o == null || getClass() != o.getClass()) return false;
// if (!super.equals(o)) return false;
//
// RequestToken that = (RequestToken) o;
//
// if (httpClient != null ? !httpClient.equals(that.httpClient) : that.httpClient != null)
// return false;
//
// return true;
// }
//
// @Override
// public int hashCode() {
// int result = super.hashCode();
// result = 31 * result + (httpClient != null ? httpClient.hashCode() : 0);
// return result;
// }
// }
// Path: src/weibo4j/Weibo.java
import java.io.File;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Locale;
import java.util.Map;
import java.util.TimeZone;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import weibo4j.http.AccessToken;
import weibo4j.http.HttpClient;
import weibo4j.http.ImageItem;
import weibo4j.http.PostParameter;
import weibo4j.http.RequestToken;
import weibo4j.http.Response;
import weibo4j.org.json.JSONException;
import weibo4j.org.json.JSONObject;
import weibo4j.util.URLEncodeUtils;
* @see <a href="http://open.t.sina.com.cn/wiki/index.php/Statuses/reply">Statuses/reply</a>
* @throws WeiboException when Weibo service or network is unavailable
* @since Weibo4J 1.2.1
*/
public Comment reply(String sid, String cid, String comment)
throws WeiboException {
return new Comment(http.post(getBaseURL() + "statuses/reply.json",
new PostParameter[] { new PostParameter("id", sid),
new PostParameter("cid", cid),
new PostParameter("comment", comment) }, true));
}
//--------------auth method----------
/**
*
* @param consumerKey OAuth consumer key
* @param consumerSecret OAuth consumer secret
* @since Weibo4J 1.2.1
*/
public synchronized void setOAuthConsumer(String consumerKey, String consumerSecret){
this.http.setOAuthConsumer(consumerKey, consumerSecret);
}
/**
* 获取request token
* @return generated request token.
* @throws WeiboException when Weibo service or network is unavailable
* @since Weibo4J 1.2.1
* @see <a href="http://oauth.net/core/1.0/#auth_step1">OAuth Core 1.0 - 6.1. Obtaining an Unauthorized Request Token</a>
*/ | public RequestToken getOAuthRequestToken() throws WeiboException { |
iswangheng/DataMining-over-Sina-Weibo | src/swarm/GetTrendsThread.java | // Path: src/weibo4j/Trends.java
// public class Trends extends WeiboResponse implements Comparable<Trends> {
// private Date asOf;
// private Date trendAt;
// private Trend[] trends;
// private static final long serialVersionUID = -7151479143843312309L;
//
// public int compareTo(Trends that) {
// return this.trendAt.compareTo(that.trendAt);
// }
//
// /*package*/ Trends(Response res, Date asOf, Date trendAt, Trend[] trends)
// throws WeiboException {
// super(res);
// this.asOf = asOf;
// this.trendAt = trendAt;
// this.trends = trends;
// }
//
// /*package*/
// static List<Trends> constructTrendsList(Response res) throws
// WeiboException {
// JSONObject json = res.asJSONObject();
// List<Trends> trends;
// try {
// Date asOf = parseDate(json.getString("as_of"));
// JSONObject trendsJson = json.getJSONObject("trends");
// trends = new ArrayList<Trends>(trendsJson.length());
// Iterator ite = trendsJson.keys();
// while (ite.hasNext()) {
// String key = (String) ite.next();
// JSONArray array = trendsJson.getJSONArray(key);
// Trend[] trendsArray = jsonArrayToTrendArray(array);
// if (key.length() == 19) {
// // current trends
// trends.add(new Trends(res, asOf, parseDate(key
// , "yyyy-MM-dd HH:mm:ss"), trendsArray));
// } else if (key.length() == 16) {
// // daily trends
// trends.add(new Trends(res, asOf, parseDate(key
// , "yyyy-MM-dd HH:mm"), trendsArray));
// } else if (key.length() == 10) {
// // weekly trends
// trends.add(new Trends(res, asOf, parseDate(key
// , "yyyy-MM-dd"), trendsArray));
// }
// }
// Collections.sort(trends);
// return trends;
// } catch (JSONException jsone) {
// throw new WeiboException(jsone.getMessage() + ":" + res.asString(), jsone);
// }
// }
//
// /*package*/
// static Trends constructTrends(Response res) throws WeiboException {
// JSONObject json = res.asJSONObject();
// try {
// Date asOf = parseDate(json.getString("as_of"));
// JSONArray array = json.getJSONArray("trends");
// Trend[] trendsArray = jsonArrayToTrendArray(array);
// return new Trends(res, asOf, asOf, trendsArray);
// } catch (JSONException jsone) {
// throw new WeiboException(jsone.getMessage() + ":" + res.asString(), jsone);
// }
// }
//
// private static Date parseDate(String asOfStr) throws WeiboException {
// Date parsed;
// if (asOfStr.length() == 10) {
// parsed = new Date(Long.parseLong(asOfStr) * 1000);
// } else {
// parsed = WeiboResponse.parseDate(asOfStr, "EEE, d MMM yyyy HH:mm:ss z");
// }
// return parsed;
// }
//
// private static Trend[] jsonArrayToTrendArray(JSONArray array) throws JSONException {
// Trend[] trends = new Trend[array.length()];
// for (int i = 0; i < array.length(); i++) {
// JSONObject trend = array.getJSONObject(i);
// trends[i] = new Trend(trend);
// }
// return trends;
// }
//
// public Trend[] getTrends() {
// return this.trends;
// }
//
// public Date getAsOf() {
// return asOf;
// }
//
// public Date getTrendAt() {
// return trendAt;
// }
//
// @Override
// public boolean equals(Object o) {
// if (this == o) return true;
// if (!(o instanceof Trends)) return false;
//
// Trends trends1 = (Trends) o;
//
// if (asOf != null ? !asOf.equals(trends1.asOf) : trends1.asOf != null)
// return false;
// if (trendAt != null ? !trendAt.equals(trends1.trendAt) : trends1.trendAt != null)
// return false;
// if (!Arrays.equals(trends, trends1.trends)) return false;
//
// return true;
// }
//
// @Override
// public int hashCode() {
// int result = asOf != null ? asOf.hashCode() : 0;
// result = 31 * result + (trendAt != null ? trendAt.hashCode() : 0);
// result = 31 * result + (trends != null ? Arrays.hashCode(trends) : 0);
// return result;
// }
//
// @Override
// public String toString() {
// return "Trends{" +
// "asOf=" + asOf +
// ", trendAt=" + trendAt +
// ", trends=" + (trends == null ? null : Arrays.asList(trends)) +
// '}';
// }
// }
| import java.sql.Connection;
import java.sql.PreparedStatement;
import java.util.List;
import weibo4j.Paging;
import weibo4j.Trend;
import weibo4j.Trends;
import weibo4j.WeiboException;
| package swarm;
public class GetTrendsThread implements Runnable
{
int pauseTime;
public GetTrendsThread()
{
pauseTime = 1000*60*60;
}
| // Path: src/weibo4j/Trends.java
// public class Trends extends WeiboResponse implements Comparable<Trends> {
// private Date asOf;
// private Date trendAt;
// private Trend[] trends;
// private static final long serialVersionUID = -7151479143843312309L;
//
// public int compareTo(Trends that) {
// return this.trendAt.compareTo(that.trendAt);
// }
//
// /*package*/ Trends(Response res, Date asOf, Date trendAt, Trend[] trends)
// throws WeiboException {
// super(res);
// this.asOf = asOf;
// this.trendAt = trendAt;
// this.trends = trends;
// }
//
// /*package*/
// static List<Trends> constructTrendsList(Response res) throws
// WeiboException {
// JSONObject json = res.asJSONObject();
// List<Trends> trends;
// try {
// Date asOf = parseDate(json.getString("as_of"));
// JSONObject trendsJson = json.getJSONObject("trends");
// trends = new ArrayList<Trends>(trendsJson.length());
// Iterator ite = trendsJson.keys();
// while (ite.hasNext()) {
// String key = (String) ite.next();
// JSONArray array = trendsJson.getJSONArray(key);
// Trend[] trendsArray = jsonArrayToTrendArray(array);
// if (key.length() == 19) {
// // current trends
// trends.add(new Trends(res, asOf, parseDate(key
// , "yyyy-MM-dd HH:mm:ss"), trendsArray));
// } else if (key.length() == 16) {
// // daily trends
// trends.add(new Trends(res, asOf, parseDate(key
// , "yyyy-MM-dd HH:mm"), trendsArray));
// } else if (key.length() == 10) {
// // weekly trends
// trends.add(new Trends(res, asOf, parseDate(key
// , "yyyy-MM-dd"), trendsArray));
// }
// }
// Collections.sort(trends);
// return trends;
// } catch (JSONException jsone) {
// throw new WeiboException(jsone.getMessage() + ":" + res.asString(), jsone);
// }
// }
//
// /*package*/
// static Trends constructTrends(Response res) throws WeiboException {
// JSONObject json = res.asJSONObject();
// try {
// Date asOf = parseDate(json.getString("as_of"));
// JSONArray array = json.getJSONArray("trends");
// Trend[] trendsArray = jsonArrayToTrendArray(array);
// return new Trends(res, asOf, asOf, trendsArray);
// } catch (JSONException jsone) {
// throw new WeiboException(jsone.getMessage() + ":" + res.asString(), jsone);
// }
// }
//
// private static Date parseDate(String asOfStr) throws WeiboException {
// Date parsed;
// if (asOfStr.length() == 10) {
// parsed = new Date(Long.parseLong(asOfStr) * 1000);
// } else {
// parsed = WeiboResponse.parseDate(asOfStr, "EEE, d MMM yyyy HH:mm:ss z");
// }
// return parsed;
// }
//
// private static Trend[] jsonArrayToTrendArray(JSONArray array) throws JSONException {
// Trend[] trends = new Trend[array.length()];
// for (int i = 0; i < array.length(); i++) {
// JSONObject trend = array.getJSONObject(i);
// trends[i] = new Trend(trend);
// }
// return trends;
// }
//
// public Trend[] getTrends() {
// return this.trends;
// }
//
// public Date getAsOf() {
// return asOf;
// }
//
// public Date getTrendAt() {
// return trendAt;
// }
//
// @Override
// public boolean equals(Object o) {
// if (this == o) return true;
// if (!(o instanceof Trends)) return false;
//
// Trends trends1 = (Trends) o;
//
// if (asOf != null ? !asOf.equals(trends1.asOf) : trends1.asOf != null)
// return false;
// if (trendAt != null ? !trendAt.equals(trends1.trendAt) : trends1.trendAt != null)
// return false;
// if (!Arrays.equals(trends, trends1.trends)) return false;
//
// return true;
// }
//
// @Override
// public int hashCode() {
// int result = asOf != null ? asOf.hashCode() : 0;
// result = 31 * result + (trendAt != null ? trendAt.hashCode() : 0);
// result = 31 * result + (trends != null ? Arrays.hashCode(trends) : 0);
// return result;
// }
//
// @Override
// public String toString() {
// return "Trends{" +
// "asOf=" + asOf +
// ", trendAt=" + trendAt +
// ", trends=" + (trends == null ? null : Arrays.asList(trends)) +
// '}';
// }
// }
// Path: src/swarm/GetTrendsThread.java
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.util.List;
import weibo4j.Paging;
import weibo4j.Trend;
import weibo4j.Trends;
import weibo4j.WeiboException;
package swarm;
public class GetTrendsThread implements Runnable
{
int pauseTime;
public GetTrendsThread()
{
pauseTime = 1000*60*60;
}
| public static void InsertSql(Trends trends)
|
facebookarchive/swift-hive-metastore | src/main/java/org/apache/hadoop/hive/metastore/MetaStoreFS.java | // Path: src/main/java/org/apache/hadoop/hive/metastore/api/MetaException.java
// @ThriftStruct("MetaException")
// public class MetaException extends RuntimeException
// {
// private static final long serialVersionUID = 1L;
//
// @ThriftConstructor
// public MetaException(@ThriftField(value = 1, name = "message") final String message)
// {
// super(message);
// }
//
// public MetaException(final Throwable t)
// {
// super(t);
// }
//
// public MetaException(final String message, final Throwable t)
// {
// super(message, t);
// }
//
// public MetaException()
// {
// }
//
// @Override
// @ThriftField(value = 1, name = "message")
// public String getMessage()
// {
// return super.getMessage();
// }
// }
| import org.apache.hadoop.conf.Configuration;
import org.apache.hadoop.fs.FileSystem;
import org.apache.hadoop.fs.Path;
import org.apache.hadoop.hive.metastore.api.MetaException; | /*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.hadoop.hive.metastore;
/**
* Define a set of APIs that may vary in different environments
*/
public interface MetaStoreFS {
/**
* delete a directory
*
* @param f
* @param recursive
* @return true on success
* @throws MetaException
*/
public boolean deleteDir(FileSystem fs, Path f, boolean recursive, | // Path: src/main/java/org/apache/hadoop/hive/metastore/api/MetaException.java
// @ThriftStruct("MetaException")
// public class MetaException extends RuntimeException
// {
// private static final long serialVersionUID = 1L;
//
// @ThriftConstructor
// public MetaException(@ThriftField(value = 1, name = "message") final String message)
// {
// super(message);
// }
//
// public MetaException(final Throwable t)
// {
// super(t);
// }
//
// public MetaException(final String message, final Throwable t)
// {
// super(message, t);
// }
//
// public MetaException()
// {
// }
//
// @Override
// @ThriftField(value = 1, name = "message")
// public String getMessage()
// {
// return super.getMessage();
// }
// }
// Path: src/main/java/org/apache/hadoop/hive/metastore/MetaStoreFS.java
import org.apache.hadoop.conf.Configuration;
import org.apache.hadoop.fs.FileSystem;
import org.apache.hadoop.fs.Path;
import org.apache.hadoop.hive.metastore.api.MetaException;
/*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.hadoop.hive.metastore;
/**
* Define a set of APIs that may vary in different environments
*/
public interface MetaStoreFS {
/**
* delete a directory
*
* @param f
* @param recursive
* @return true on success
* @throws MetaException
*/
public boolean deleteDir(FileSystem fs, Path f, boolean recursive, | Configuration conf) throws MetaException; |
emmaguy/wear-notify-for-reddit | mobile/src/main/java/com/emmaguy/todayilearned/storage/SharedPreferencesUniqueIdentifierStorage.java | // Path: mobile/src/main/java/com/emmaguy/todayilearned/common/StringUtils.java
// public class StringUtils {
// /**
// * Returns true if the string is null or 0-length.
// *
// * @param str the string to be examined
// * @return true if str is null or zero length
// */
// public static boolean isEmpty(String str) {
// return (str == null || str.length() == 0);
// }
//
// /**
// * Returns a string containing the tokens joined by delimiters.
// *
// * @param tokens an array objects to be joined. Strings will be formed from
// * the objects by calling object.toString().
// */
// public static String join(CharSequence delimiter, Iterable tokens) {
// StringBuilder sb = new StringBuilder();
// boolean firstTime = true;
// for (Object token : tokens) {
// if (firstTime) {
// firstTime = false;
// } else {
// sb.append(delimiter);
// }
// sb.append(token);
// }
// return sb.toString();
// }
// }
| import android.content.SharedPreferences;
import android.support.annotation.NonNull;
import com.emmaguy.todayilearned.common.StringUtils;
import java.util.UUID; | package com.emmaguy.todayilearned.storage;
/**
* Stores a unique identifier in {@link SharedPreferences}
*/
public class SharedPreferencesUniqueIdentifierStorage implements UniqueIdentifierStorage {
private final SharedPreferences mSharedPreferences;
private final String mKey;
public SharedPreferencesUniqueIdentifierStorage(SharedPreferences sharedPreferences,
String key) {
mSharedPreferences = sharedPreferences;
mKey = key;
}
private String generateNewUniqueIdentifier() {
final String uniqueIdentifier = UUID.randomUUID().toString();
mSharedPreferences.edit().putString(mKey, uniqueIdentifier).apply();
return uniqueIdentifier;
}
@Override @NonNull public String getUniqueIdentifier() {
String uniqueIdentifier = getStoredIdentifier();
| // Path: mobile/src/main/java/com/emmaguy/todayilearned/common/StringUtils.java
// public class StringUtils {
// /**
// * Returns true if the string is null or 0-length.
// *
// * @param str the string to be examined
// * @return true if str is null or zero length
// */
// public static boolean isEmpty(String str) {
// return (str == null || str.length() == 0);
// }
//
// /**
// * Returns a string containing the tokens joined by delimiters.
// *
// * @param tokens an array objects to be joined. Strings will be formed from
// * the objects by calling object.toString().
// */
// public static String join(CharSequence delimiter, Iterable tokens) {
// StringBuilder sb = new StringBuilder();
// boolean firstTime = true;
// for (Object token : tokens) {
// if (firstTime) {
// firstTime = false;
// } else {
// sb.append(delimiter);
// }
// sb.append(token);
// }
// return sb.toString();
// }
// }
// Path: mobile/src/main/java/com/emmaguy/todayilearned/storage/SharedPreferencesUniqueIdentifierStorage.java
import android.content.SharedPreferences;
import android.support.annotation.NonNull;
import com.emmaguy.todayilearned.common.StringUtils;
import java.util.UUID;
package com.emmaguy.todayilearned.storage;
/**
* Stores a unique identifier in {@link SharedPreferences}
*/
public class SharedPreferencesUniqueIdentifierStorage implements UniqueIdentifierStorage {
private final SharedPreferences mSharedPreferences;
private final String mKey;
public SharedPreferencesUniqueIdentifierStorage(SharedPreferences sharedPreferences,
String key) {
mSharedPreferences = sharedPreferences;
mKey = key;
}
private String generateNewUniqueIdentifier() {
final String uniqueIdentifier = UUID.randomUUID().toString();
mSharedPreferences.edit().putString(mKey, uniqueIdentifier).apply();
return uniqueIdentifier;
}
@Override @NonNull public String getUniqueIdentifier() {
String uniqueIdentifier = getStoredIdentifier();
| if (!StringUtils.isEmpty(uniqueIdentifier)) { |
emmaguy/wear-notify-for-reddit | wear/src/main/java/com/emmaguy/todayilearned/comments/ActionReceiver.java | // Path: sharedlib/src/main/java/com/emmaguy/todayilearned/sharedlib/Constants.java
// public class Constants {
// public final static Set<String> sDefaultSelectedSubreddits = new LinkedHashSet<>(Arrays.asList(
// "todayilearned",
// "AskReddit"));
//
// public static final String WEB_URL_REDDIT = "https://www.reddit.com";
// public static final String ENDPOINT_URL_SSL_REDDIT = "https://ssl.reddit.com/";
// public static final String ENDPOINT_URL_OAUTH_REDDIT = "https://oauth.reddit.com/";
//
// public static final String AUTHORIZATION = "Authorization";
//
// public static final String GRANT_TYPE_AUTHORISATION_CODE = "authorization_code";
// public static final String GRANT_TYPE_REFRESH_TOKEN = "refresh_token";
// public static final String GRANT_TYPE_INSTALLED_CLIENT = "https://oauth.reddit.com/grants/installed_client";
//
// public static final String PATH_REDDIT_POSTS = "/redditwear";
// public static final String PATH_REFRESH = "/refresh";
// public static final String PATH_OPEN_ON_PHONE = "/openonphone";
// public static final String PATH_REPLY = "/replytopost";
// public static final String PATH_SAVE_TO_POCKET = "/send_to_pocket";
// public static final String PATH_VOTE = "/vote";
// public static final String PATH_COMMENTS = "/comments";
// public static final String PATH_NO_NEW_POSTS = "/no_new_posts";
// public static final String PATH_LOGGING = "/logging";
//
// public static final String KEY_REDDIT_POSTS = "posts";
// public static final String KEY_POST_PERMALINK = "post_permalink";
//
// public static final String PATH_POST_REPLY_RESULT_SUCCESS = "/post_reply_success";
// public static final String PATH_POST_REPLY_RESULT_FAILURE = "/post_reply_failure";
//
// public static final String PATH_KEY_MESSAGE = "post_message";
// public static final String PATH_KEY_POST_FULLNAME = "post_fullname";
// public static final String PATH_KEY_IS_DIRECT_MESSAGE = "is_direct";
// public static final String PATH_KEY_MESSAGE_SUBJECT = "msg_subject";
// public static final String PATH_KEY_MESSAGE_TO_USER = "msg_to_user";
//
// public static final String PATH_SAVE_TO_POCKET_RESULT_SUCCESS = "/save_pocket_success";
// public static final String PATH_SAVE_TO_POCKET_RESULT_FAILED = "/save_pocket_failed";
//
// public static final String PATH_VOTE_RESULT_SUCCESS = "/vote_success";
// public static final String PATH_VOTE_RESULT_FAILED = "/vote_failed";
// public static final String PATH_GET_COMMENTS_RESULT_FAILED = "/getting_comments";
//
// public static final String KEY_CONFIRMATION_MESSAGE = "confirm_message";
// public static final String KEY_PATH = "receiver_path";
// public static final String KEY_POST_VOTE_DIRECTION = "vote_direction";
// public static final String KEY_CONFIRMATION_ANIMATION = "key_confirm_animation";
// public static final String KEY_DISMISS_AFTER_ACTION = "open_on_phone_dismisses";
// public static final String KEY_NOTIFICATION_ID = "notification_id";
// public static final String KEY_ACTION_ORDER = "action_order";
// public static final String KEY_HIGHRES_IMAGE_NAME = "view_image";
//
// public static final int ACTION_ORDER_VIEW_COMMENTS = 0;
// public static final int ACTION_ORDER_REPLY = 1;
// public static final int ACTION_ORDER_UPVOTE = 2;
// public static final int ACTION_ORDER_DOWNVOTE = 3;
// public static final int ACTION_ORDER_SAVE_TO_POCKET = 4;
// public static final int ACTION_ORDER_OPEN_ON_PHONE = 5;
// public static final int ACTION_ORDER_VIEW_IMAGE = 6;
// }
| import android.app.NotificationManager;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.os.AsyncTask;
import android.os.Bundle;
import android.support.wearable.activity.ConfirmationActivity;
import com.emmaguy.todayilearned.Logger;
import com.emmaguy.todayilearned.sharedlib.Constants;
import com.google.android.gms.common.ConnectionResult;
import com.google.android.gms.common.api.GoogleApiClient;
import com.google.android.gms.common.api.ResultCallback;
import com.google.android.gms.wearable.DataApi;
import com.google.android.gms.wearable.PutDataMapRequest;
import com.google.android.gms.wearable.Wearable;
import java.util.concurrent.TimeUnit; | mGoogleApiClient = new GoogleApiClient.Builder(context).addApi(Wearable.API).build();
Logger.log("onReceive in ActionReceiver");
new ConnectTask(context, intent.getExtras()).execute();
}
private void showConfirmation(Context context, String message, int animation) {
Intent confirmationActivity = new Intent(context, ConfirmationActivity.class).setFlags(
Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_NO_ANIMATION)
.putExtra(ConfirmationActivity.EXTRA_ANIMATION_TYPE, animation)
.putExtra(ConfirmationActivity.EXTRA_MESSAGE, message);
context.startActivity(confirmationActivity);
}
private class ConnectTask extends AsyncTask<Void, Void, Void> {
private final Context mContext;
private final Bundle mBundle;
public ConnectTask(Context context, Bundle bundle) {
mContext = context;
mBundle = bundle;
}
@Override protected Void doInBackground(Void... params) {
ConnectionResult connectionResult = mGoogleApiClient.blockingConnect(30,
TimeUnit.SECONDS);
if (!connectionResult.isSuccess()) {
Logger.log("Action receiver, service failed to connect: " + connectionResult);
return null;
}
| // Path: sharedlib/src/main/java/com/emmaguy/todayilearned/sharedlib/Constants.java
// public class Constants {
// public final static Set<String> sDefaultSelectedSubreddits = new LinkedHashSet<>(Arrays.asList(
// "todayilearned",
// "AskReddit"));
//
// public static final String WEB_URL_REDDIT = "https://www.reddit.com";
// public static final String ENDPOINT_URL_SSL_REDDIT = "https://ssl.reddit.com/";
// public static final String ENDPOINT_URL_OAUTH_REDDIT = "https://oauth.reddit.com/";
//
// public static final String AUTHORIZATION = "Authorization";
//
// public static final String GRANT_TYPE_AUTHORISATION_CODE = "authorization_code";
// public static final String GRANT_TYPE_REFRESH_TOKEN = "refresh_token";
// public static final String GRANT_TYPE_INSTALLED_CLIENT = "https://oauth.reddit.com/grants/installed_client";
//
// public static final String PATH_REDDIT_POSTS = "/redditwear";
// public static final String PATH_REFRESH = "/refresh";
// public static final String PATH_OPEN_ON_PHONE = "/openonphone";
// public static final String PATH_REPLY = "/replytopost";
// public static final String PATH_SAVE_TO_POCKET = "/send_to_pocket";
// public static final String PATH_VOTE = "/vote";
// public static final String PATH_COMMENTS = "/comments";
// public static final String PATH_NO_NEW_POSTS = "/no_new_posts";
// public static final String PATH_LOGGING = "/logging";
//
// public static final String KEY_REDDIT_POSTS = "posts";
// public static final String KEY_POST_PERMALINK = "post_permalink";
//
// public static final String PATH_POST_REPLY_RESULT_SUCCESS = "/post_reply_success";
// public static final String PATH_POST_REPLY_RESULT_FAILURE = "/post_reply_failure";
//
// public static final String PATH_KEY_MESSAGE = "post_message";
// public static final String PATH_KEY_POST_FULLNAME = "post_fullname";
// public static final String PATH_KEY_IS_DIRECT_MESSAGE = "is_direct";
// public static final String PATH_KEY_MESSAGE_SUBJECT = "msg_subject";
// public static final String PATH_KEY_MESSAGE_TO_USER = "msg_to_user";
//
// public static final String PATH_SAVE_TO_POCKET_RESULT_SUCCESS = "/save_pocket_success";
// public static final String PATH_SAVE_TO_POCKET_RESULT_FAILED = "/save_pocket_failed";
//
// public static final String PATH_VOTE_RESULT_SUCCESS = "/vote_success";
// public static final String PATH_VOTE_RESULT_FAILED = "/vote_failed";
// public static final String PATH_GET_COMMENTS_RESULT_FAILED = "/getting_comments";
//
// public static final String KEY_CONFIRMATION_MESSAGE = "confirm_message";
// public static final String KEY_PATH = "receiver_path";
// public static final String KEY_POST_VOTE_DIRECTION = "vote_direction";
// public static final String KEY_CONFIRMATION_ANIMATION = "key_confirm_animation";
// public static final String KEY_DISMISS_AFTER_ACTION = "open_on_phone_dismisses";
// public static final String KEY_NOTIFICATION_ID = "notification_id";
// public static final String KEY_ACTION_ORDER = "action_order";
// public static final String KEY_HIGHRES_IMAGE_NAME = "view_image";
//
// public static final int ACTION_ORDER_VIEW_COMMENTS = 0;
// public static final int ACTION_ORDER_REPLY = 1;
// public static final int ACTION_ORDER_UPVOTE = 2;
// public static final int ACTION_ORDER_DOWNVOTE = 3;
// public static final int ACTION_ORDER_SAVE_TO_POCKET = 4;
// public static final int ACTION_ORDER_OPEN_ON_PHONE = 5;
// public static final int ACTION_ORDER_VIEW_IMAGE = 6;
// }
// Path: wear/src/main/java/com/emmaguy/todayilearned/comments/ActionReceiver.java
import android.app.NotificationManager;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.os.AsyncTask;
import android.os.Bundle;
import android.support.wearable.activity.ConfirmationActivity;
import com.emmaguy.todayilearned.Logger;
import com.emmaguy.todayilearned.sharedlib.Constants;
import com.google.android.gms.common.ConnectionResult;
import com.google.android.gms.common.api.GoogleApiClient;
import com.google.android.gms.common.api.ResultCallback;
import com.google.android.gms.wearable.DataApi;
import com.google.android.gms.wearable.PutDataMapRequest;
import com.google.android.gms.wearable.Wearable;
import java.util.concurrent.TimeUnit;
mGoogleApiClient = new GoogleApiClient.Builder(context).addApi(Wearable.API).build();
Logger.log("onReceive in ActionReceiver");
new ConnectTask(context, intent.getExtras()).execute();
}
private void showConfirmation(Context context, String message, int animation) {
Intent confirmationActivity = new Intent(context, ConfirmationActivity.class).setFlags(
Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_NO_ANIMATION)
.putExtra(ConfirmationActivity.EXTRA_ANIMATION_TYPE, animation)
.putExtra(ConfirmationActivity.EXTRA_MESSAGE, message);
context.startActivity(confirmationActivity);
}
private class ConnectTask extends AsyncTask<Void, Void, Void> {
private final Context mContext;
private final Bundle mBundle;
public ConnectTask(Context context, Bundle bundle) {
mContext = context;
mBundle = bundle;
}
@Override protected Void doInBackground(Void... params) {
ConnectionResult connectionResult = mGoogleApiClient.blockingConnect(30,
TimeUnit.SECONDS);
if (!connectionResult.isSuccess()) {
Logger.log("Action receiver, service failed to connect: " + connectionResult);
return null;
}
| final String path = getStringAndRemoveKey(Constants.KEY_PATH); |
emmaguy/wear-notify-for-reddit | wear/src/main/java/com/emmaguy/todayilearned/comments/RedditCommentCardFragment.java | // Path: sharedlib/src/main/java/com/emmaguy/todayilearned/sharedlib/Comment.java
// public class Comment {
// private final boolean mScoreHidden;
//
// private final String mPostContents;
// private final String mAuthor;
// private final String mTitle;
//
// private final int mReplyLevel;
// private final int mGilded;
// private final int mScore;
//
// private final List<Comment> mReplies;
//
// public Comment(Builder builder) {
// mScore = builder.mScore;
// mTitle = builder.mTitle;
// mGilded = builder.mGilded;
// mAuthor = builder.mAuthor;
// mReplies = builder.mReplies;
// mReplyLevel = builder.mReplyLevel;
// mPostContents = builder.mPostContents;
// mScoreHidden = builder.mIsScoreHidden;
// }
//
// public String getTitle() {
// return mTitle;
// }
//
// public String getAuthor() {
// return mAuthor;
// }
//
// public int getScore() {
// return mScore;
// }
//
// public int getGilded() {
// return mGilded;
// }
//
// public boolean isScoreHidden() {
// return mScoreHidden;
// }
//
// public String getPostContents() {
// return mPostContents;
// }
//
// public int getReplyLevel() {
// return mReplyLevel;
// }
//
// public List<Comment> getReplies() {
// return mReplies;
// }
//
// public static final class Builder {
// private boolean mIsScoreHidden;
//
// private String mPostContents;
// private String mAuthor;
// private String mTitle;
// private List<Comment> mReplies;
//
// private int mGilded;
// private int mScore;
// private int mReplyLevel;
//
// public Comment build() {
// return new Comment(this);
// }
//
// public Builder setTitle(String title) {
// mTitle = title;
// return this;
// }
//
// public Builder setAuthor(String author) {
// mAuthor = author;
// return this;
// }
//
// public Builder setComments(List<Comment> replies) {
// mReplies = replies;
// return this;
// }
//
// public Builder setPostContents(String postContents) {
// mPostContents = postContents;
// return this;
// }
//
// public Builder setGilded(int gilded) {
// mGilded = gilded;
// return this;
// }
//
// public Builder setScore(int score) {
// mScore = score;
// return this;
// }
//
// public Builder setReplyLevel(int replyLevel) {
// mReplyLevel = replyLevel;
// return this;
// }
//
// public Builder setIsScoreHidden(boolean scoreHidden) {
// mIsScoreHidden = scoreHidden;
// return this;
// }
// }
// }
| import android.os.Bundle;
import android.support.wearable.view.CardFragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;
import com.emmaguy.todayilearned.R;
import com.emmaguy.todayilearned.sharedlib.Comment; | package com.emmaguy.todayilearned.comments;
public class RedditCommentCardFragment extends CardFragment {
private static final String ARGS_KEY_SCORE_HIDDEN = "card_score_hidden";
private static final String ARGS_KEY_REPLY_LEVEL = "card_reply_level";
private static final String ARGS_KEY_GILDED = "card_gilded";
private static final String ARGS_KEY_TITLE = "card_title";
private static final String ARGS_KEY_SCORE = "card_score";
private static final String ARGS_KEY_TEXT = "card_text";
private String mTitle;
private String mText;
private boolean mIsScoreHidden;
private int mScore;
private int mGildedCount;
private int mReplyLevel;
| // Path: sharedlib/src/main/java/com/emmaguy/todayilearned/sharedlib/Comment.java
// public class Comment {
// private final boolean mScoreHidden;
//
// private final String mPostContents;
// private final String mAuthor;
// private final String mTitle;
//
// private final int mReplyLevel;
// private final int mGilded;
// private final int mScore;
//
// private final List<Comment> mReplies;
//
// public Comment(Builder builder) {
// mScore = builder.mScore;
// mTitle = builder.mTitle;
// mGilded = builder.mGilded;
// mAuthor = builder.mAuthor;
// mReplies = builder.mReplies;
// mReplyLevel = builder.mReplyLevel;
// mPostContents = builder.mPostContents;
// mScoreHidden = builder.mIsScoreHidden;
// }
//
// public String getTitle() {
// return mTitle;
// }
//
// public String getAuthor() {
// return mAuthor;
// }
//
// public int getScore() {
// return mScore;
// }
//
// public int getGilded() {
// return mGilded;
// }
//
// public boolean isScoreHidden() {
// return mScoreHidden;
// }
//
// public String getPostContents() {
// return mPostContents;
// }
//
// public int getReplyLevel() {
// return mReplyLevel;
// }
//
// public List<Comment> getReplies() {
// return mReplies;
// }
//
// public static final class Builder {
// private boolean mIsScoreHidden;
//
// private String mPostContents;
// private String mAuthor;
// private String mTitle;
// private List<Comment> mReplies;
//
// private int mGilded;
// private int mScore;
// private int mReplyLevel;
//
// public Comment build() {
// return new Comment(this);
// }
//
// public Builder setTitle(String title) {
// mTitle = title;
// return this;
// }
//
// public Builder setAuthor(String author) {
// mAuthor = author;
// return this;
// }
//
// public Builder setComments(List<Comment> replies) {
// mReplies = replies;
// return this;
// }
//
// public Builder setPostContents(String postContents) {
// mPostContents = postContents;
// return this;
// }
//
// public Builder setGilded(int gilded) {
// mGilded = gilded;
// return this;
// }
//
// public Builder setScore(int score) {
// mScore = score;
// return this;
// }
//
// public Builder setReplyLevel(int replyLevel) {
// mReplyLevel = replyLevel;
// return this;
// }
//
// public Builder setIsScoreHidden(boolean scoreHidden) {
// mIsScoreHidden = scoreHidden;
// return this;
// }
// }
// }
// Path: wear/src/main/java/com/emmaguy/todayilearned/comments/RedditCommentCardFragment.java
import android.os.Bundle;
import android.support.wearable.view.CardFragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;
import com.emmaguy.todayilearned.R;
import com.emmaguy.todayilearned.sharedlib.Comment;
package com.emmaguy.todayilearned.comments;
public class RedditCommentCardFragment extends CardFragment {
private static final String ARGS_KEY_SCORE_HIDDEN = "card_score_hidden";
private static final String ARGS_KEY_REPLY_LEVEL = "card_reply_level";
private static final String ARGS_KEY_GILDED = "card_gilded";
private static final String ARGS_KEY_TITLE = "card_title";
private static final String ARGS_KEY_SCORE = "card_score";
private static final String ARGS_KEY_TEXT = "card_text";
private String mTitle;
private String mText;
private boolean mIsScoreHidden;
private int mScore;
private int mGildedCount;
private int mReplyLevel;
| public static CardFragment create(Comment comment) { |
emmaguy/wear-notify-for-reddit | mobile/src/test/java/com/emmaguy/todayilearned/refresh/CommentsConverterTest.java | // Path: sharedlib/src/main/java/com/emmaguy/todayilearned/sharedlib/Comment.java
// public class Comment {
// private final boolean mScoreHidden;
//
// private final String mPostContents;
// private final String mAuthor;
// private final String mTitle;
//
// private final int mReplyLevel;
// private final int mGilded;
// private final int mScore;
//
// private final List<Comment> mReplies;
//
// public Comment(Builder builder) {
// mScore = builder.mScore;
// mTitle = builder.mTitle;
// mGilded = builder.mGilded;
// mAuthor = builder.mAuthor;
// mReplies = builder.mReplies;
// mReplyLevel = builder.mReplyLevel;
// mPostContents = builder.mPostContents;
// mScoreHidden = builder.mIsScoreHidden;
// }
//
// public String getTitle() {
// return mTitle;
// }
//
// public String getAuthor() {
// return mAuthor;
// }
//
// public int getScore() {
// return mScore;
// }
//
// public int getGilded() {
// return mGilded;
// }
//
// public boolean isScoreHidden() {
// return mScoreHidden;
// }
//
// public String getPostContents() {
// return mPostContents;
// }
//
// public int getReplyLevel() {
// return mReplyLevel;
// }
//
// public List<Comment> getReplies() {
// return mReplies;
// }
//
// public static final class Builder {
// private boolean mIsScoreHidden;
//
// private String mPostContents;
// private String mAuthor;
// private String mTitle;
// private List<Comment> mReplies;
//
// private int mGilded;
// private int mScore;
// private int mReplyLevel;
//
// public Comment build() {
// return new Comment(this);
// }
//
// public Builder setTitle(String title) {
// mTitle = title;
// return this;
// }
//
// public Builder setAuthor(String author) {
// mAuthor = author;
// return this;
// }
//
// public Builder setComments(List<Comment> replies) {
// mReplies = replies;
// return this;
// }
//
// public Builder setPostContents(String postContents) {
// mPostContents = postContents;
// return this;
// }
//
// public Builder setGilded(int gilded) {
// mGilded = gilded;
// return this;
// }
//
// public Builder setScore(int score) {
// mScore = score;
// return this;
// }
//
// public Builder setReplyLevel(int replyLevel) {
// mReplyLevel = replyLevel;
// return this;
// }
//
// public Builder setIsScoreHidden(boolean scoreHidden) {
// mIsScoreHidden = scoreHidden;
// return this;
// }
// }
// }
//
// Path: mobile/src/main/java/com/emmaguy/todayilearned/storage/UserStorage.java
// public interface UserStorage {
// int getNumberToRequest();
//
// void setSeenTimestamp(long timestamp);
// void clearTimestamp();
//
// long getTimestamp();
//
// String getSortType();
// String getSubreddits();
// Set<String> getSubredditCollection();
// String getRefreshInterval();
//
// boolean messagesEnabled();
// boolean downloadFullSizedImages();
// boolean openOnPhoneDismissesAfterAction();
// }
| import android.content.res.Resources;
import com.emmaguy.todayilearned.TestUtils;
import com.emmaguy.todayilearned.sharedlib.Comment;
import com.emmaguy.todayilearned.storage.UserStorage;
import com.google.gson.Gson;
import org.junit.Before;
import org.junit.Test;
import org.mockito.Mock;
import java.io.IOException;
import java.lang.reflect.ParameterizedType;
import java.lang.reflect.Type;
import java.util.List;
import retrofit.converter.ConversionException;
import retrofit.converter.GsonConverter;
import retrofit.mime.TypedInput;
import static org.hamcrest.MatcherAssert.assertThat;
import static org.hamcrest.core.IsEqual.equalTo;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.when;
import static org.mockito.MockitoAnnotations.initMocks; | package com.emmaguy.todayilearned.refresh;
public class CommentsConverterTest {
private final Gson mGson = new Gson();
private final GsonConverter mGsonConverter = new GsonConverter(mGson);
| // Path: sharedlib/src/main/java/com/emmaguy/todayilearned/sharedlib/Comment.java
// public class Comment {
// private final boolean mScoreHidden;
//
// private final String mPostContents;
// private final String mAuthor;
// private final String mTitle;
//
// private final int mReplyLevel;
// private final int mGilded;
// private final int mScore;
//
// private final List<Comment> mReplies;
//
// public Comment(Builder builder) {
// mScore = builder.mScore;
// mTitle = builder.mTitle;
// mGilded = builder.mGilded;
// mAuthor = builder.mAuthor;
// mReplies = builder.mReplies;
// mReplyLevel = builder.mReplyLevel;
// mPostContents = builder.mPostContents;
// mScoreHidden = builder.mIsScoreHidden;
// }
//
// public String getTitle() {
// return mTitle;
// }
//
// public String getAuthor() {
// return mAuthor;
// }
//
// public int getScore() {
// return mScore;
// }
//
// public int getGilded() {
// return mGilded;
// }
//
// public boolean isScoreHidden() {
// return mScoreHidden;
// }
//
// public String getPostContents() {
// return mPostContents;
// }
//
// public int getReplyLevel() {
// return mReplyLevel;
// }
//
// public List<Comment> getReplies() {
// return mReplies;
// }
//
// public static final class Builder {
// private boolean mIsScoreHidden;
//
// private String mPostContents;
// private String mAuthor;
// private String mTitle;
// private List<Comment> mReplies;
//
// private int mGilded;
// private int mScore;
// private int mReplyLevel;
//
// public Comment build() {
// return new Comment(this);
// }
//
// public Builder setTitle(String title) {
// mTitle = title;
// return this;
// }
//
// public Builder setAuthor(String author) {
// mAuthor = author;
// return this;
// }
//
// public Builder setComments(List<Comment> replies) {
// mReplies = replies;
// return this;
// }
//
// public Builder setPostContents(String postContents) {
// mPostContents = postContents;
// return this;
// }
//
// public Builder setGilded(int gilded) {
// mGilded = gilded;
// return this;
// }
//
// public Builder setScore(int score) {
// mScore = score;
// return this;
// }
//
// public Builder setReplyLevel(int replyLevel) {
// mReplyLevel = replyLevel;
// return this;
// }
//
// public Builder setIsScoreHidden(boolean scoreHidden) {
// mIsScoreHidden = scoreHidden;
// return this;
// }
// }
// }
//
// Path: mobile/src/main/java/com/emmaguy/todayilearned/storage/UserStorage.java
// public interface UserStorage {
// int getNumberToRequest();
//
// void setSeenTimestamp(long timestamp);
// void clearTimestamp();
//
// long getTimestamp();
//
// String getSortType();
// String getSubreddits();
// Set<String> getSubredditCollection();
// String getRefreshInterval();
//
// boolean messagesEnabled();
// boolean downloadFullSizedImages();
// boolean openOnPhoneDismissesAfterAction();
// }
// Path: mobile/src/test/java/com/emmaguy/todayilearned/refresh/CommentsConverterTest.java
import android.content.res.Resources;
import com.emmaguy.todayilearned.TestUtils;
import com.emmaguy.todayilearned.sharedlib.Comment;
import com.emmaguy.todayilearned.storage.UserStorage;
import com.google.gson.Gson;
import org.junit.Before;
import org.junit.Test;
import org.mockito.Mock;
import java.io.IOException;
import java.lang.reflect.ParameterizedType;
import java.lang.reflect.Type;
import java.util.List;
import retrofit.converter.ConversionException;
import retrofit.converter.GsonConverter;
import retrofit.mime.TypedInput;
import static org.hamcrest.MatcherAssert.assertThat;
import static org.hamcrest.core.IsEqual.equalTo;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.when;
import static org.mockito.MockitoAnnotations.initMocks;
package com.emmaguy.todayilearned.refresh;
public class CommentsConverterTest {
private final Gson mGson = new Gson();
private final GsonConverter mGsonConverter = new GsonConverter(mGson);
| @Mock UserStorage mUserStorage; |
emmaguy/wear-notify-for-reddit | mobile/src/test/java/com/emmaguy/todayilearned/refresh/CommentsConverterTest.java | // Path: sharedlib/src/main/java/com/emmaguy/todayilearned/sharedlib/Comment.java
// public class Comment {
// private final boolean mScoreHidden;
//
// private final String mPostContents;
// private final String mAuthor;
// private final String mTitle;
//
// private final int mReplyLevel;
// private final int mGilded;
// private final int mScore;
//
// private final List<Comment> mReplies;
//
// public Comment(Builder builder) {
// mScore = builder.mScore;
// mTitle = builder.mTitle;
// mGilded = builder.mGilded;
// mAuthor = builder.mAuthor;
// mReplies = builder.mReplies;
// mReplyLevel = builder.mReplyLevel;
// mPostContents = builder.mPostContents;
// mScoreHidden = builder.mIsScoreHidden;
// }
//
// public String getTitle() {
// return mTitle;
// }
//
// public String getAuthor() {
// return mAuthor;
// }
//
// public int getScore() {
// return mScore;
// }
//
// public int getGilded() {
// return mGilded;
// }
//
// public boolean isScoreHidden() {
// return mScoreHidden;
// }
//
// public String getPostContents() {
// return mPostContents;
// }
//
// public int getReplyLevel() {
// return mReplyLevel;
// }
//
// public List<Comment> getReplies() {
// return mReplies;
// }
//
// public static final class Builder {
// private boolean mIsScoreHidden;
//
// private String mPostContents;
// private String mAuthor;
// private String mTitle;
// private List<Comment> mReplies;
//
// private int mGilded;
// private int mScore;
// private int mReplyLevel;
//
// public Comment build() {
// return new Comment(this);
// }
//
// public Builder setTitle(String title) {
// mTitle = title;
// return this;
// }
//
// public Builder setAuthor(String author) {
// mAuthor = author;
// return this;
// }
//
// public Builder setComments(List<Comment> replies) {
// mReplies = replies;
// return this;
// }
//
// public Builder setPostContents(String postContents) {
// mPostContents = postContents;
// return this;
// }
//
// public Builder setGilded(int gilded) {
// mGilded = gilded;
// return this;
// }
//
// public Builder setScore(int score) {
// mScore = score;
// return this;
// }
//
// public Builder setReplyLevel(int replyLevel) {
// mReplyLevel = replyLevel;
// return this;
// }
//
// public Builder setIsScoreHidden(boolean scoreHidden) {
// mIsScoreHidden = scoreHidden;
// return this;
// }
// }
// }
//
// Path: mobile/src/main/java/com/emmaguy/todayilearned/storage/UserStorage.java
// public interface UserStorage {
// int getNumberToRequest();
//
// void setSeenTimestamp(long timestamp);
// void clearTimestamp();
//
// long getTimestamp();
//
// String getSortType();
// String getSubreddits();
// Set<String> getSubredditCollection();
// String getRefreshInterval();
//
// boolean messagesEnabled();
// boolean downloadFullSizedImages();
// boolean openOnPhoneDismissesAfterAction();
// }
| import android.content.res.Resources;
import com.emmaguy.todayilearned.TestUtils;
import com.emmaguy.todayilearned.sharedlib.Comment;
import com.emmaguy.todayilearned.storage.UserStorage;
import com.google.gson.Gson;
import org.junit.Before;
import org.junit.Test;
import org.mockito.Mock;
import java.io.IOException;
import java.lang.reflect.ParameterizedType;
import java.lang.reflect.Type;
import java.util.List;
import retrofit.converter.ConversionException;
import retrofit.converter.GsonConverter;
import retrofit.mime.TypedInput;
import static org.hamcrest.MatcherAssert.assertThat;
import static org.hamcrest.core.IsEqual.equalTo;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.when;
import static org.mockito.MockitoAnnotations.initMocks; | package com.emmaguy.todayilearned.refresh;
public class CommentsConverterTest {
private final Gson mGson = new Gson();
private final GsonConverter mGsonConverter = new GsonConverter(mGson);
@Mock UserStorage mUserStorage;
@Mock Resources mResources;
@Before public void before() throws Exception {
initMocks(this);
}
@Test public void parsesCommentsSuccessfully() throws Exception { | // Path: sharedlib/src/main/java/com/emmaguy/todayilearned/sharedlib/Comment.java
// public class Comment {
// private final boolean mScoreHidden;
//
// private final String mPostContents;
// private final String mAuthor;
// private final String mTitle;
//
// private final int mReplyLevel;
// private final int mGilded;
// private final int mScore;
//
// private final List<Comment> mReplies;
//
// public Comment(Builder builder) {
// mScore = builder.mScore;
// mTitle = builder.mTitle;
// mGilded = builder.mGilded;
// mAuthor = builder.mAuthor;
// mReplies = builder.mReplies;
// mReplyLevel = builder.mReplyLevel;
// mPostContents = builder.mPostContents;
// mScoreHidden = builder.mIsScoreHidden;
// }
//
// public String getTitle() {
// return mTitle;
// }
//
// public String getAuthor() {
// return mAuthor;
// }
//
// public int getScore() {
// return mScore;
// }
//
// public int getGilded() {
// return mGilded;
// }
//
// public boolean isScoreHidden() {
// return mScoreHidden;
// }
//
// public String getPostContents() {
// return mPostContents;
// }
//
// public int getReplyLevel() {
// return mReplyLevel;
// }
//
// public List<Comment> getReplies() {
// return mReplies;
// }
//
// public static final class Builder {
// private boolean mIsScoreHidden;
//
// private String mPostContents;
// private String mAuthor;
// private String mTitle;
// private List<Comment> mReplies;
//
// private int mGilded;
// private int mScore;
// private int mReplyLevel;
//
// public Comment build() {
// return new Comment(this);
// }
//
// public Builder setTitle(String title) {
// mTitle = title;
// return this;
// }
//
// public Builder setAuthor(String author) {
// mAuthor = author;
// return this;
// }
//
// public Builder setComments(List<Comment> replies) {
// mReplies = replies;
// return this;
// }
//
// public Builder setPostContents(String postContents) {
// mPostContents = postContents;
// return this;
// }
//
// public Builder setGilded(int gilded) {
// mGilded = gilded;
// return this;
// }
//
// public Builder setScore(int score) {
// mScore = score;
// return this;
// }
//
// public Builder setReplyLevel(int replyLevel) {
// mReplyLevel = replyLevel;
// return this;
// }
//
// public Builder setIsScoreHidden(boolean scoreHidden) {
// mIsScoreHidden = scoreHidden;
// return this;
// }
// }
// }
//
// Path: mobile/src/main/java/com/emmaguy/todayilearned/storage/UserStorage.java
// public interface UserStorage {
// int getNumberToRequest();
//
// void setSeenTimestamp(long timestamp);
// void clearTimestamp();
//
// long getTimestamp();
//
// String getSortType();
// String getSubreddits();
// Set<String> getSubredditCollection();
// String getRefreshInterval();
//
// boolean messagesEnabled();
// boolean downloadFullSizedImages();
// boolean openOnPhoneDismissesAfterAction();
// }
// Path: mobile/src/test/java/com/emmaguy/todayilearned/refresh/CommentsConverterTest.java
import android.content.res.Resources;
import com.emmaguy.todayilearned.TestUtils;
import com.emmaguy.todayilearned.sharedlib.Comment;
import com.emmaguy.todayilearned.storage.UserStorage;
import com.google.gson.Gson;
import org.junit.Before;
import org.junit.Test;
import org.mockito.Mock;
import java.io.IOException;
import java.lang.reflect.ParameterizedType;
import java.lang.reflect.Type;
import java.util.List;
import retrofit.converter.ConversionException;
import retrofit.converter.GsonConverter;
import retrofit.mime.TypedInput;
import static org.hamcrest.MatcherAssert.assertThat;
import static org.hamcrest.core.IsEqual.equalTo;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.when;
import static org.mockito.MockitoAnnotations.initMocks;
package com.emmaguy.todayilearned.refresh;
public class CommentsConverterTest {
private final Gson mGson = new Gson();
private final GsonConverter mGsonConverter = new GsonConverter(mGson);
@Mock UserStorage mUserStorage;
@Mock Resources mResources;
@Before public void before() throws Exception {
initMocks(this);
}
@Test public void parsesCommentsSuccessfully() throws Exception { | List<Comment> comments = convertComments("comment-default.json"); |
emmaguy/wear-notify-for-reddit | wear/src/main/java/com/emmaguy/todayilearned/DeleteCachedImageReceiver.java | // Path: sharedlib/src/main/java/com/emmaguy/todayilearned/sharedlib/Constants.java
// public class Constants {
// public final static Set<String> sDefaultSelectedSubreddits = new LinkedHashSet<>(Arrays.asList(
// "todayilearned",
// "AskReddit"));
//
// public static final String WEB_URL_REDDIT = "https://www.reddit.com";
// public static final String ENDPOINT_URL_SSL_REDDIT = "https://ssl.reddit.com/";
// public static final String ENDPOINT_URL_OAUTH_REDDIT = "https://oauth.reddit.com/";
//
// public static final String AUTHORIZATION = "Authorization";
//
// public static final String GRANT_TYPE_AUTHORISATION_CODE = "authorization_code";
// public static final String GRANT_TYPE_REFRESH_TOKEN = "refresh_token";
// public static final String GRANT_TYPE_INSTALLED_CLIENT = "https://oauth.reddit.com/grants/installed_client";
//
// public static final String PATH_REDDIT_POSTS = "/redditwear";
// public static final String PATH_REFRESH = "/refresh";
// public static final String PATH_OPEN_ON_PHONE = "/openonphone";
// public static final String PATH_REPLY = "/replytopost";
// public static final String PATH_SAVE_TO_POCKET = "/send_to_pocket";
// public static final String PATH_VOTE = "/vote";
// public static final String PATH_COMMENTS = "/comments";
// public static final String PATH_NO_NEW_POSTS = "/no_new_posts";
// public static final String PATH_LOGGING = "/logging";
//
// public static final String KEY_REDDIT_POSTS = "posts";
// public static final String KEY_POST_PERMALINK = "post_permalink";
//
// public static final String PATH_POST_REPLY_RESULT_SUCCESS = "/post_reply_success";
// public static final String PATH_POST_REPLY_RESULT_FAILURE = "/post_reply_failure";
//
// public static final String PATH_KEY_MESSAGE = "post_message";
// public static final String PATH_KEY_POST_FULLNAME = "post_fullname";
// public static final String PATH_KEY_IS_DIRECT_MESSAGE = "is_direct";
// public static final String PATH_KEY_MESSAGE_SUBJECT = "msg_subject";
// public static final String PATH_KEY_MESSAGE_TO_USER = "msg_to_user";
//
// public static final String PATH_SAVE_TO_POCKET_RESULT_SUCCESS = "/save_pocket_success";
// public static final String PATH_SAVE_TO_POCKET_RESULT_FAILED = "/save_pocket_failed";
//
// public static final String PATH_VOTE_RESULT_SUCCESS = "/vote_success";
// public static final String PATH_VOTE_RESULT_FAILED = "/vote_failed";
// public static final String PATH_GET_COMMENTS_RESULT_FAILED = "/getting_comments";
//
// public static final String KEY_CONFIRMATION_MESSAGE = "confirm_message";
// public static final String KEY_PATH = "receiver_path";
// public static final String KEY_POST_VOTE_DIRECTION = "vote_direction";
// public static final String KEY_CONFIRMATION_ANIMATION = "key_confirm_animation";
// public static final String KEY_DISMISS_AFTER_ACTION = "open_on_phone_dismisses";
// public static final String KEY_NOTIFICATION_ID = "notification_id";
// public static final String KEY_ACTION_ORDER = "action_order";
// public static final String KEY_HIGHRES_IMAGE_NAME = "view_image";
//
// public static final int ACTION_ORDER_VIEW_COMMENTS = 0;
// public static final int ACTION_ORDER_REPLY = 1;
// public static final int ACTION_ORDER_UPVOTE = 2;
// public static final int ACTION_ORDER_DOWNVOTE = 3;
// public static final int ACTION_ORDER_SAVE_TO_POCKET = 4;
// public static final int ACTION_ORDER_OPEN_ON_PHONE = 5;
// public static final int ACTION_ORDER_VIEW_IMAGE = 6;
// }
| import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import com.emmaguy.todayilearned.sharedlib.Constants;
import java.io.File; | package com.emmaguy.todayilearned;
public class DeleteCachedImageReceiver extends BroadcastReceiver {
public DeleteCachedImageReceiver() {
}
@Override public void onReceive(Context context, Intent intent) { | // Path: sharedlib/src/main/java/com/emmaguy/todayilearned/sharedlib/Constants.java
// public class Constants {
// public final static Set<String> sDefaultSelectedSubreddits = new LinkedHashSet<>(Arrays.asList(
// "todayilearned",
// "AskReddit"));
//
// public static final String WEB_URL_REDDIT = "https://www.reddit.com";
// public static final String ENDPOINT_URL_SSL_REDDIT = "https://ssl.reddit.com/";
// public static final String ENDPOINT_URL_OAUTH_REDDIT = "https://oauth.reddit.com/";
//
// public static final String AUTHORIZATION = "Authorization";
//
// public static final String GRANT_TYPE_AUTHORISATION_CODE = "authorization_code";
// public static final String GRANT_TYPE_REFRESH_TOKEN = "refresh_token";
// public static final String GRANT_TYPE_INSTALLED_CLIENT = "https://oauth.reddit.com/grants/installed_client";
//
// public static final String PATH_REDDIT_POSTS = "/redditwear";
// public static final String PATH_REFRESH = "/refresh";
// public static final String PATH_OPEN_ON_PHONE = "/openonphone";
// public static final String PATH_REPLY = "/replytopost";
// public static final String PATH_SAVE_TO_POCKET = "/send_to_pocket";
// public static final String PATH_VOTE = "/vote";
// public static final String PATH_COMMENTS = "/comments";
// public static final String PATH_NO_NEW_POSTS = "/no_new_posts";
// public static final String PATH_LOGGING = "/logging";
//
// public static final String KEY_REDDIT_POSTS = "posts";
// public static final String KEY_POST_PERMALINK = "post_permalink";
//
// public static final String PATH_POST_REPLY_RESULT_SUCCESS = "/post_reply_success";
// public static final String PATH_POST_REPLY_RESULT_FAILURE = "/post_reply_failure";
//
// public static final String PATH_KEY_MESSAGE = "post_message";
// public static final String PATH_KEY_POST_FULLNAME = "post_fullname";
// public static final String PATH_KEY_IS_DIRECT_MESSAGE = "is_direct";
// public static final String PATH_KEY_MESSAGE_SUBJECT = "msg_subject";
// public static final String PATH_KEY_MESSAGE_TO_USER = "msg_to_user";
//
// public static final String PATH_SAVE_TO_POCKET_RESULT_SUCCESS = "/save_pocket_success";
// public static final String PATH_SAVE_TO_POCKET_RESULT_FAILED = "/save_pocket_failed";
//
// public static final String PATH_VOTE_RESULT_SUCCESS = "/vote_success";
// public static final String PATH_VOTE_RESULT_FAILED = "/vote_failed";
// public static final String PATH_GET_COMMENTS_RESULT_FAILED = "/getting_comments";
//
// public static final String KEY_CONFIRMATION_MESSAGE = "confirm_message";
// public static final String KEY_PATH = "receiver_path";
// public static final String KEY_POST_VOTE_DIRECTION = "vote_direction";
// public static final String KEY_CONFIRMATION_ANIMATION = "key_confirm_animation";
// public static final String KEY_DISMISS_AFTER_ACTION = "open_on_phone_dismisses";
// public static final String KEY_NOTIFICATION_ID = "notification_id";
// public static final String KEY_ACTION_ORDER = "action_order";
// public static final String KEY_HIGHRES_IMAGE_NAME = "view_image";
//
// public static final int ACTION_ORDER_VIEW_COMMENTS = 0;
// public static final int ACTION_ORDER_REPLY = 1;
// public static final int ACTION_ORDER_UPVOTE = 2;
// public static final int ACTION_ORDER_DOWNVOTE = 3;
// public static final int ACTION_ORDER_SAVE_TO_POCKET = 4;
// public static final int ACTION_ORDER_OPEN_ON_PHONE = 5;
// public static final int ACTION_ORDER_VIEW_IMAGE = 6;
// }
// Path: wear/src/main/java/com/emmaguy/todayilearned/DeleteCachedImageReceiver.java
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import com.emmaguy.todayilearned.sharedlib.Constants;
import java.io.File;
package com.emmaguy.todayilearned;
public class DeleteCachedImageReceiver extends BroadcastReceiver {
public DeleteCachedImageReceiver() {
}
@Override public void onReceive(Context context, Intent intent) { | String cachedImageName = intent.getExtras().getString(Constants.KEY_HIGHRES_IMAGE_NAME); |
emmaguy/wear-notify-for-reddit | wear/src/main/java/com/emmaguy/todayilearned/MainActivity.java | // Path: sharedlib/src/main/java/com/emmaguy/todayilearned/sharedlib/Constants.java
// public class Constants {
// public final static Set<String> sDefaultSelectedSubreddits = new LinkedHashSet<>(Arrays.asList(
// "todayilearned",
// "AskReddit"));
//
// public static final String WEB_URL_REDDIT = "https://www.reddit.com";
// public static final String ENDPOINT_URL_SSL_REDDIT = "https://ssl.reddit.com/";
// public static final String ENDPOINT_URL_OAUTH_REDDIT = "https://oauth.reddit.com/";
//
// public static final String AUTHORIZATION = "Authorization";
//
// public static final String GRANT_TYPE_AUTHORISATION_CODE = "authorization_code";
// public static final String GRANT_TYPE_REFRESH_TOKEN = "refresh_token";
// public static final String GRANT_TYPE_INSTALLED_CLIENT = "https://oauth.reddit.com/grants/installed_client";
//
// public static final String PATH_REDDIT_POSTS = "/redditwear";
// public static final String PATH_REFRESH = "/refresh";
// public static final String PATH_OPEN_ON_PHONE = "/openonphone";
// public static final String PATH_REPLY = "/replytopost";
// public static final String PATH_SAVE_TO_POCKET = "/send_to_pocket";
// public static final String PATH_VOTE = "/vote";
// public static final String PATH_COMMENTS = "/comments";
// public static final String PATH_NO_NEW_POSTS = "/no_new_posts";
// public static final String PATH_LOGGING = "/logging";
//
// public static final String KEY_REDDIT_POSTS = "posts";
// public static final String KEY_POST_PERMALINK = "post_permalink";
//
// public static final String PATH_POST_REPLY_RESULT_SUCCESS = "/post_reply_success";
// public static final String PATH_POST_REPLY_RESULT_FAILURE = "/post_reply_failure";
//
// public static final String PATH_KEY_MESSAGE = "post_message";
// public static final String PATH_KEY_POST_FULLNAME = "post_fullname";
// public static final String PATH_KEY_IS_DIRECT_MESSAGE = "is_direct";
// public static final String PATH_KEY_MESSAGE_SUBJECT = "msg_subject";
// public static final String PATH_KEY_MESSAGE_TO_USER = "msg_to_user";
//
// public static final String PATH_SAVE_TO_POCKET_RESULT_SUCCESS = "/save_pocket_success";
// public static final String PATH_SAVE_TO_POCKET_RESULT_FAILED = "/save_pocket_failed";
//
// public static final String PATH_VOTE_RESULT_SUCCESS = "/vote_success";
// public static final String PATH_VOTE_RESULT_FAILED = "/vote_failed";
// public static final String PATH_GET_COMMENTS_RESULT_FAILED = "/getting_comments";
//
// public static final String KEY_CONFIRMATION_MESSAGE = "confirm_message";
// public static final String KEY_PATH = "receiver_path";
// public static final String KEY_POST_VOTE_DIRECTION = "vote_direction";
// public static final String KEY_CONFIRMATION_ANIMATION = "key_confirm_animation";
// public static final String KEY_DISMISS_AFTER_ACTION = "open_on_phone_dismisses";
// public static final String KEY_NOTIFICATION_ID = "notification_id";
// public static final String KEY_ACTION_ORDER = "action_order";
// public static final String KEY_HIGHRES_IMAGE_NAME = "view_image";
//
// public static final int ACTION_ORDER_VIEW_COMMENTS = 0;
// public static final int ACTION_ORDER_REPLY = 1;
// public static final int ACTION_ORDER_UPVOTE = 2;
// public static final int ACTION_ORDER_DOWNVOTE = 3;
// public static final int ACTION_ORDER_SAVE_TO_POCKET = 4;
// public static final int ACTION_ORDER_OPEN_ON_PHONE = 5;
// public static final int ACTION_ORDER_VIEW_IMAGE = 6;
// }
| import android.app.Activity;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.os.Bundle;
import android.os.Handler;
import android.widget.ViewFlipper;
import com.emmaguy.todayilearned.sharedlib.Constants;
import com.google.android.gms.common.api.GoogleApiClient;
import com.google.android.gms.common.api.ResultCallback;
import com.google.android.gms.wearable.MessageApi;
import com.google.android.gms.wearable.Wearable;
import java.util.concurrent.TimeUnit; | package com.emmaguy.todayilearned;
public class MainActivity extends Activity implements GoogleApiClient.ConnectionCallbacks {
public static final int REQUEST_NEW_POSTS_TIMEOUT = 30;
private GoogleApiClient mGoogleApiClient;
private final BroadcastReceiver mForceFinishMainActivity = new BroadcastReceiver() {
@Override public void onReceive(Context context, Intent intent) {
finish();
}
};
@Override protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
ViewFlipper flipper = (ViewFlipper) findViewById(R.id.main_flipper_benefits);
flipper.startFlipping();
registerReceiver(mForceFinishMainActivity,
new IntentFilter(getString(R.string.force_finish_main_activity)));
mGoogleApiClient = new GoogleApiClient.Builder(this).addConnectionCallbacks(this)
.addApi(Wearable.API)
.build();
mGoogleApiClient.connect();
}
@Override protected void onDestroy() {
unregisterReceiver(mForceFinishMainActivity);
super.onDestroy();
}
@Override public void onConnected(Bundle bundle) { | // Path: sharedlib/src/main/java/com/emmaguy/todayilearned/sharedlib/Constants.java
// public class Constants {
// public final static Set<String> sDefaultSelectedSubreddits = new LinkedHashSet<>(Arrays.asList(
// "todayilearned",
// "AskReddit"));
//
// public static final String WEB_URL_REDDIT = "https://www.reddit.com";
// public static final String ENDPOINT_URL_SSL_REDDIT = "https://ssl.reddit.com/";
// public static final String ENDPOINT_URL_OAUTH_REDDIT = "https://oauth.reddit.com/";
//
// public static final String AUTHORIZATION = "Authorization";
//
// public static final String GRANT_TYPE_AUTHORISATION_CODE = "authorization_code";
// public static final String GRANT_TYPE_REFRESH_TOKEN = "refresh_token";
// public static final String GRANT_TYPE_INSTALLED_CLIENT = "https://oauth.reddit.com/grants/installed_client";
//
// public static final String PATH_REDDIT_POSTS = "/redditwear";
// public static final String PATH_REFRESH = "/refresh";
// public static final String PATH_OPEN_ON_PHONE = "/openonphone";
// public static final String PATH_REPLY = "/replytopost";
// public static final String PATH_SAVE_TO_POCKET = "/send_to_pocket";
// public static final String PATH_VOTE = "/vote";
// public static final String PATH_COMMENTS = "/comments";
// public static final String PATH_NO_NEW_POSTS = "/no_new_posts";
// public static final String PATH_LOGGING = "/logging";
//
// public static final String KEY_REDDIT_POSTS = "posts";
// public static final String KEY_POST_PERMALINK = "post_permalink";
//
// public static final String PATH_POST_REPLY_RESULT_SUCCESS = "/post_reply_success";
// public static final String PATH_POST_REPLY_RESULT_FAILURE = "/post_reply_failure";
//
// public static final String PATH_KEY_MESSAGE = "post_message";
// public static final String PATH_KEY_POST_FULLNAME = "post_fullname";
// public static final String PATH_KEY_IS_DIRECT_MESSAGE = "is_direct";
// public static final String PATH_KEY_MESSAGE_SUBJECT = "msg_subject";
// public static final String PATH_KEY_MESSAGE_TO_USER = "msg_to_user";
//
// public static final String PATH_SAVE_TO_POCKET_RESULT_SUCCESS = "/save_pocket_success";
// public static final String PATH_SAVE_TO_POCKET_RESULT_FAILED = "/save_pocket_failed";
//
// public static final String PATH_VOTE_RESULT_SUCCESS = "/vote_success";
// public static final String PATH_VOTE_RESULT_FAILED = "/vote_failed";
// public static final String PATH_GET_COMMENTS_RESULT_FAILED = "/getting_comments";
//
// public static final String KEY_CONFIRMATION_MESSAGE = "confirm_message";
// public static final String KEY_PATH = "receiver_path";
// public static final String KEY_POST_VOTE_DIRECTION = "vote_direction";
// public static final String KEY_CONFIRMATION_ANIMATION = "key_confirm_animation";
// public static final String KEY_DISMISS_AFTER_ACTION = "open_on_phone_dismisses";
// public static final String KEY_NOTIFICATION_ID = "notification_id";
// public static final String KEY_ACTION_ORDER = "action_order";
// public static final String KEY_HIGHRES_IMAGE_NAME = "view_image";
//
// public static final int ACTION_ORDER_VIEW_COMMENTS = 0;
// public static final int ACTION_ORDER_REPLY = 1;
// public static final int ACTION_ORDER_UPVOTE = 2;
// public static final int ACTION_ORDER_DOWNVOTE = 3;
// public static final int ACTION_ORDER_SAVE_TO_POCKET = 4;
// public static final int ACTION_ORDER_OPEN_ON_PHONE = 5;
// public static final int ACTION_ORDER_VIEW_IMAGE = 6;
// }
// Path: wear/src/main/java/com/emmaguy/todayilearned/MainActivity.java
import android.app.Activity;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.os.Bundle;
import android.os.Handler;
import android.widget.ViewFlipper;
import com.emmaguy.todayilearned.sharedlib.Constants;
import com.google.android.gms.common.api.GoogleApiClient;
import com.google.android.gms.common.api.ResultCallback;
import com.google.android.gms.wearable.MessageApi;
import com.google.android.gms.wearable.Wearable;
import java.util.concurrent.TimeUnit;
package com.emmaguy.todayilearned;
public class MainActivity extends Activity implements GoogleApiClient.ConnectionCallbacks {
public static final int REQUEST_NEW_POSTS_TIMEOUT = 30;
private GoogleApiClient mGoogleApiClient;
private final BroadcastReceiver mForceFinishMainActivity = new BroadcastReceiver() {
@Override public void onReceive(Context context, Intent intent) {
finish();
}
};
@Override protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
ViewFlipper flipper = (ViewFlipper) findViewById(R.id.main_flipper_benefits);
flipper.startFlipping();
registerReceiver(mForceFinishMainActivity,
new IntentFilter(getString(R.string.force_finish_main_activity)));
mGoogleApiClient = new GoogleApiClient.Builder(this).addConnectionCallbacks(this)
.addApi(Wearable.API)
.build();
mGoogleApiClient.connect();
}
@Override protected void onDestroy() {
unregisterReceiver(mForceFinishMainActivity);
super.onDestroy();
}
@Override public void onConnected(Bundle bundle) { | Wearable.MessageApi.sendMessage(mGoogleApiClient, "", Constants.PATH_REFRESH, null) |
emmaguy/wear-notify-for-reddit | mobile/src/main/java/com/emmaguy/todayilearned/settings/RedditAccessTokenRequester.java | // Path: sharedlib/src/main/java/com/emmaguy/todayilearned/sharedlib/Constants.java
// public class Constants {
// public final static Set<String> sDefaultSelectedSubreddits = new LinkedHashSet<>(Arrays.asList(
// "todayilearned",
// "AskReddit"));
//
// public static final String WEB_URL_REDDIT = "https://www.reddit.com";
// public static final String ENDPOINT_URL_SSL_REDDIT = "https://ssl.reddit.com/";
// public static final String ENDPOINT_URL_OAUTH_REDDIT = "https://oauth.reddit.com/";
//
// public static final String AUTHORIZATION = "Authorization";
//
// public static final String GRANT_TYPE_AUTHORISATION_CODE = "authorization_code";
// public static final String GRANT_TYPE_REFRESH_TOKEN = "refresh_token";
// public static final String GRANT_TYPE_INSTALLED_CLIENT = "https://oauth.reddit.com/grants/installed_client";
//
// public static final String PATH_REDDIT_POSTS = "/redditwear";
// public static final String PATH_REFRESH = "/refresh";
// public static final String PATH_OPEN_ON_PHONE = "/openonphone";
// public static final String PATH_REPLY = "/replytopost";
// public static final String PATH_SAVE_TO_POCKET = "/send_to_pocket";
// public static final String PATH_VOTE = "/vote";
// public static final String PATH_COMMENTS = "/comments";
// public static final String PATH_NO_NEW_POSTS = "/no_new_posts";
// public static final String PATH_LOGGING = "/logging";
//
// public static final String KEY_REDDIT_POSTS = "posts";
// public static final String KEY_POST_PERMALINK = "post_permalink";
//
// public static final String PATH_POST_REPLY_RESULT_SUCCESS = "/post_reply_success";
// public static final String PATH_POST_REPLY_RESULT_FAILURE = "/post_reply_failure";
//
// public static final String PATH_KEY_MESSAGE = "post_message";
// public static final String PATH_KEY_POST_FULLNAME = "post_fullname";
// public static final String PATH_KEY_IS_DIRECT_MESSAGE = "is_direct";
// public static final String PATH_KEY_MESSAGE_SUBJECT = "msg_subject";
// public static final String PATH_KEY_MESSAGE_TO_USER = "msg_to_user";
//
// public static final String PATH_SAVE_TO_POCKET_RESULT_SUCCESS = "/save_pocket_success";
// public static final String PATH_SAVE_TO_POCKET_RESULT_FAILED = "/save_pocket_failed";
//
// public static final String PATH_VOTE_RESULT_SUCCESS = "/vote_success";
// public static final String PATH_VOTE_RESULT_FAILED = "/vote_failed";
// public static final String PATH_GET_COMMENTS_RESULT_FAILED = "/getting_comments";
//
// public static final String KEY_CONFIRMATION_MESSAGE = "confirm_message";
// public static final String KEY_PATH = "receiver_path";
// public static final String KEY_POST_VOTE_DIRECTION = "vote_direction";
// public static final String KEY_CONFIRMATION_ANIMATION = "key_confirm_animation";
// public static final String KEY_DISMISS_AFTER_ACTION = "open_on_phone_dismisses";
// public static final String KEY_NOTIFICATION_ID = "notification_id";
// public static final String KEY_ACTION_ORDER = "action_order";
// public static final String KEY_HIGHRES_IMAGE_NAME = "view_image";
//
// public static final int ACTION_ORDER_VIEW_COMMENTS = 0;
// public static final int ACTION_ORDER_REPLY = 1;
// public static final int ACTION_ORDER_UPVOTE = 2;
// public static final int ACTION_ORDER_DOWNVOTE = 3;
// public static final int ACTION_ORDER_SAVE_TO_POCKET = 4;
// public static final int ACTION_ORDER_OPEN_ON_PHONE = 5;
// public static final int ACTION_ORDER_VIEW_IMAGE = 6;
// }
| import android.content.Context;
import android.content.Intent;
import android.content.res.Resources;
import android.net.Uri;
import android.widget.Toast;
import com.emmaguy.todayilearned.R;
import com.emmaguy.todayilearned.sharedlib.Constants;
import com.emmaguy.todayilearned.storage.UniqueIdentifierStorage;
import javax.inject.Inject;
import javax.inject.Named; | package com.emmaguy.todayilearned.settings;
/**
* Created by emma on 14/06/15.
*/
class RedditAccessTokenRequester {
private final Context mContext;
private final Resources mResources;
private final UniqueIdentifierStorage mStateStorage;
private final BrowserIntentBuilder mBrowserIntentBuilder;
@Inject RedditAccessTokenRequester(Context context, Resources resources,
@Named("state") UniqueIdentifierStorage stateStorage,
BrowserIntentBuilder browserIntentBuilder) {
mContext = context;
mResources = resources;
mStateStorage = stateStorage;
mBrowserIntentBuilder = browserIntentBuilder;
}
public void request() {
final String redirectUrl = mResources.getString(R.string.redirect_url_scheme) + mResources.getString(
R.string.redirect_url_callback);
| // Path: sharedlib/src/main/java/com/emmaguy/todayilearned/sharedlib/Constants.java
// public class Constants {
// public final static Set<String> sDefaultSelectedSubreddits = new LinkedHashSet<>(Arrays.asList(
// "todayilearned",
// "AskReddit"));
//
// public static final String WEB_URL_REDDIT = "https://www.reddit.com";
// public static final String ENDPOINT_URL_SSL_REDDIT = "https://ssl.reddit.com/";
// public static final String ENDPOINT_URL_OAUTH_REDDIT = "https://oauth.reddit.com/";
//
// public static final String AUTHORIZATION = "Authorization";
//
// public static final String GRANT_TYPE_AUTHORISATION_CODE = "authorization_code";
// public static final String GRANT_TYPE_REFRESH_TOKEN = "refresh_token";
// public static final String GRANT_TYPE_INSTALLED_CLIENT = "https://oauth.reddit.com/grants/installed_client";
//
// public static final String PATH_REDDIT_POSTS = "/redditwear";
// public static final String PATH_REFRESH = "/refresh";
// public static final String PATH_OPEN_ON_PHONE = "/openonphone";
// public static final String PATH_REPLY = "/replytopost";
// public static final String PATH_SAVE_TO_POCKET = "/send_to_pocket";
// public static final String PATH_VOTE = "/vote";
// public static final String PATH_COMMENTS = "/comments";
// public static final String PATH_NO_NEW_POSTS = "/no_new_posts";
// public static final String PATH_LOGGING = "/logging";
//
// public static final String KEY_REDDIT_POSTS = "posts";
// public static final String KEY_POST_PERMALINK = "post_permalink";
//
// public static final String PATH_POST_REPLY_RESULT_SUCCESS = "/post_reply_success";
// public static final String PATH_POST_REPLY_RESULT_FAILURE = "/post_reply_failure";
//
// public static final String PATH_KEY_MESSAGE = "post_message";
// public static final String PATH_KEY_POST_FULLNAME = "post_fullname";
// public static final String PATH_KEY_IS_DIRECT_MESSAGE = "is_direct";
// public static final String PATH_KEY_MESSAGE_SUBJECT = "msg_subject";
// public static final String PATH_KEY_MESSAGE_TO_USER = "msg_to_user";
//
// public static final String PATH_SAVE_TO_POCKET_RESULT_SUCCESS = "/save_pocket_success";
// public static final String PATH_SAVE_TO_POCKET_RESULT_FAILED = "/save_pocket_failed";
//
// public static final String PATH_VOTE_RESULT_SUCCESS = "/vote_success";
// public static final String PATH_VOTE_RESULT_FAILED = "/vote_failed";
// public static final String PATH_GET_COMMENTS_RESULT_FAILED = "/getting_comments";
//
// public static final String KEY_CONFIRMATION_MESSAGE = "confirm_message";
// public static final String KEY_PATH = "receiver_path";
// public static final String KEY_POST_VOTE_DIRECTION = "vote_direction";
// public static final String KEY_CONFIRMATION_ANIMATION = "key_confirm_animation";
// public static final String KEY_DISMISS_AFTER_ACTION = "open_on_phone_dismisses";
// public static final String KEY_NOTIFICATION_ID = "notification_id";
// public static final String KEY_ACTION_ORDER = "action_order";
// public static final String KEY_HIGHRES_IMAGE_NAME = "view_image";
//
// public static final int ACTION_ORDER_VIEW_COMMENTS = 0;
// public static final int ACTION_ORDER_REPLY = 1;
// public static final int ACTION_ORDER_UPVOTE = 2;
// public static final int ACTION_ORDER_DOWNVOTE = 3;
// public static final int ACTION_ORDER_SAVE_TO_POCKET = 4;
// public static final int ACTION_ORDER_OPEN_ON_PHONE = 5;
// public static final int ACTION_ORDER_VIEW_IMAGE = 6;
// }
// Path: mobile/src/main/java/com/emmaguy/todayilearned/settings/RedditAccessTokenRequester.java
import android.content.Context;
import android.content.Intent;
import android.content.res.Resources;
import android.net.Uri;
import android.widget.Toast;
import com.emmaguy.todayilearned.R;
import com.emmaguy.todayilearned.sharedlib.Constants;
import com.emmaguy.todayilearned.storage.UniqueIdentifierStorage;
import javax.inject.Inject;
import javax.inject.Named;
package com.emmaguy.todayilearned.settings;
/**
* Created by emma on 14/06/15.
*/
class RedditAccessTokenRequester {
private final Context mContext;
private final Resources mResources;
private final UniqueIdentifierStorage mStateStorage;
private final BrowserIntentBuilder mBrowserIntentBuilder;
@Inject RedditAccessTokenRequester(Context context, Resources resources,
@Named("state") UniqueIdentifierStorage stateStorage,
BrowserIntentBuilder browserIntentBuilder) {
mContext = context;
mResources = resources;
mStateStorage = stateStorage;
mBrowserIntentBuilder = browserIntentBuilder;
}
public void request() {
final String redirectUrl = mResources.getString(R.string.redirect_url_scheme) + mResources.getString(
R.string.redirect_url_callback);
| final String url = Constants.WEB_URL_REDDIT + "/api/v1/authorize.compact?" + |
emmaguy/wear-notify-for-reddit | wear/src/main/java/com/emmaguy/todayilearned/comments/CommentsGridPagerAdapter.java | // Path: sharedlib/src/main/java/com/emmaguy/todayilearned/sharedlib/Comment.java
// public class Comment {
// private final boolean mScoreHidden;
//
// private final String mPostContents;
// private final String mAuthor;
// private final String mTitle;
//
// private final int mReplyLevel;
// private final int mGilded;
// private final int mScore;
//
// private final List<Comment> mReplies;
//
// public Comment(Builder builder) {
// mScore = builder.mScore;
// mTitle = builder.mTitle;
// mGilded = builder.mGilded;
// mAuthor = builder.mAuthor;
// mReplies = builder.mReplies;
// mReplyLevel = builder.mReplyLevel;
// mPostContents = builder.mPostContents;
// mScoreHidden = builder.mIsScoreHidden;
// }
//
// public String getTitle() {
// return mTitle;
// }
//
// public String getAuthor() {
// return mAuthor;
// }
//
// public int getScore() {
// return mScore;
// }
//
// public int getGilded() {
// return mGilded;
// }
//
// public boolean isScoreHidden() {
// return mScoreHidden;
// }
//
// public String getPostContents() {
// return mPostContents;
// }
//
// public int getReplyLevel() {
// return mReplyLevel;
// }
//
// public List<Comment> getReplies() {
// return mReplies;
// }
//
// public static final class Builder {
// private boolean mIsScoreHidden;
//
// private String mPostContents;
// private String mAuthor;
// private String mTitle;
// private List<Comment> mReplies;
//
// private int mGilded;
// private int mScore;
// private int mReplyLevel;
//
// public Comment build() {
// return new Comment(this);
// }
//
// public Builder setTitle(String title) {
// mTitle = title;
// return this;
// }
//
// public Builder setAuthor(String author) {
// mAuthor = author;
// return this;
// }
//
// public Builder setComments(List<Comment> replies) {
// mReplies = replies;
// return this;
// }
//
// public Builder setPostContents(String postContents) {
// mPostContents = postContents;
// return this;
// }
//
// public Builder setGilded(int gilded) {
// mGilded = gilded;
// return this;
// }
//
// public Builder setScore(int score) {
// mScore = score;
// return this;
// }
//
// public Builder setReplyLevel(int replyLevel) {
// mReplyLevel = replyLevel;
// return this;
// }
//
// public Builder setIsScoreHidden(boolean scoreHidden) {
// mIsScoreHidden = scoreHidden;
// return this;
// }
// }
// }
| import android.app.Fragment;
import android.app.FragmentManager;
import android.content.Context;
import android.graphics.Point;
import android.graphics.drawable.ColorDrawable;
import android.graphics.drawable.Drawable;
import android.graphics.drawable.TransitionDrawable;
import android.support.wearable.view.CardFragment;
import android.support.wearable.view.FragmentGridPagerAdapter;
import android.support.wearable.view.GridPagerAdapter;
import android.util.LruCache;
import com.emmaguy.todayilearned.R;
import com.emmaguy.todayilearned.sharedlib.Comment;
import java.util.ArrayList;
import java.util.List; | package com.emmaguy.todayilearned.comments;
public class CommentsGridPagerAdapter extends FragmentGridPagerAdapter {
private static final int TRANSITION_DURATION_MILLIS = 100;
private final LruCache<Point, Drawable> mPageBackgrounds;
private final Context mContext;
private final List<Row> mRows;
public CommentsGridPagerAdapter(Context context, FragmentManager fm, | // Path: sharedlib/src/main/java/com/emmaguy/todayilearned/sharedlib/Comment.java
// public class Comment {
// private final boolean mScoreHidden;
//
// private final String mPostContents;
// private final String mAuthor;
// private final String mTitle;
//
// private final int mReplyLevel;
// private final int mGilded;
// private final int mScore;
//
// private final List<Comment> mReplies;
//
// public Comment(Builder builder) {
// mScore = builder.mScore;
// mTitle = builder.mTitle;
// mGilded = builder.mGilded;
// mAuthor = builder.mAuthor;
// mReplies = builder.mReplies;
// mReplyLevel = builder.mReplyLevel;
// mPostContents = builder.mPostContents;
// mScoreHidden = builder.mIsScoreHidden;
// }
//
// public String getTitle() {
// return mTitle;
// }
//
// public String getAuthor() {
// return mAuthor;
// }
//
// public int getScore() {
// return mScore;
// }
//
// public int getGilded() {
// return mGilded;
// }
//
// public boolean isScoreHidden() {
// return mScoreHidden;
// }
//
// public String getPostContents() {
// return mPostContents;
// }
//
// public int getReplyLevel() {
// return mReplyLevel;
// }
//
// public List<Comment> getReplies() {
// return mReplies;
// }
//
// public static final class Builder {
// private boolean mIsScoreHidden;
//
// private String mPostContents;
// private String mAuthor;
// private String mTitle;
// private List<Comment> mReplies;
//
// private int mGilded;
// private int mScore;
// private int mReplyLevel;
//
// public Comment build() {
// return new Comment(this);
// }
//
// public Builder setTitle(String title) {
// mTitle = title;
// return this;
// }
//
// public Builder setAuthor(String author) {
// mAuthor = author;
// return this;
// }
//
// public Builder setComments(List<Comment> replies) {
// mReplies = replies;
// return this;
// }
//
// public Builder setPostContents(String postContents) {
// mPostContents = postContents;
// return this;
// }
//
// public Builder setGilded(int gilded) {
// mGilded = gilded;
// return this;
// }
//
// public Builder setScore(int score) {
// mScore = score;
// return this;
// }
//
// public Builder setReplyLevel(int replyLevel) {
// mReplyLevel = replyLevel;
// return this;
// }
//
// public Builder setIsScoreHidden(boolean scoreHidden) {
// mIsScoreHidden = scoreHidden;
// return this;
// }
// }
// }
// Path: wear/src/main/java/com/emmaguy/todayilearned/comments/CommentsGridPagerAdapter.java
import android.app.Fragment;
import android.app.FragmentManager;
import android.content.Context;
import android.graphics.Point;
import android.graphics.drawable.ColorDrawable;
import android.graphics.drawable.Drawable;
import android.graphics.drawable.TransitionDrawable;
import android.support.wearable.view.CardFragment;
import android.support.wearable.view.FragmentGridPagerAdapter;
import android.support.wearable.view.GridPagerAdapter;
import android.util.LruCache;
import com.emmaguy.todayilearned.R;
import com.emmaguy.todayilearned.sharedlib.Comment;
import java.util.ArrayList;
import java.util.List;
package com.emmaguy.todayilearned.comments;
public class CommentsGridPagerAdapter extends FragmentGridPagerAdapter {
private static final int TRANSITION_DURATION_MILLIS = 100;
private final LruCache<Point, Drawable> mPageBackgrounds;
private final Context mContext;
private final List<Row> mRows;
public CommentsGridPagerAdapter(Context context, FragmentManager fm, | ArrayList<Comment> comments) { |
emmaguy/wear-notify-for-reddit | wear/src/main/java/com/emmaguy/todayilearned/comments/ActionFragment.java | // Path: sharedlib/src/main/java/com/emmaguy/todayilearned/sharedlib/Comment.java
// public class Comment {
// private final boolean mScoreHidden;
//
// private final String mPostContents;
// private final String mAuthor;
// private final String mTitle;
//
// private final int mReplyLevel;
// private final int mGilded;
// private final int mScore;
//
// private final List<Comment> mReplies;
//
// public Comment(Builder builder) {
// mScore = builder.mScore;
// mTitle = builder.mTitle;
// mGilded = builder.mGilded;
// mAuthor = builder.mAuthor;
// mReplies = builder.mReplies;
// mReplyLevel = builder.mReplyLevel;
// mPostContents = builder.mPostContents;
// mScoreHidden = builder.mIsScoreHidden;
// }
//
// public String getTitle() {
// return mTitle;
// }
//
// public String getAuthor() {
// return mAuthor;
// }
//
// public int getScore() {
// return mScore;
// }
//
// public int getGilded() {
// return mGilded;
// }
//
// public boolean isScoreHidden() {
// return mScoreHidden;
// }
//
// public String getPostContents() {
// return mPostContents;
// }
//
// public int getReplyLevel() {
// return mReplyLevel;
// }
//
// public List<Comment> getReplies() {
// return mReplies;
// }
//
// public static final class Builder {
// private boolean mIsScoreHidden;
//
// private String mPostContents;
// private String mAuthor;
// private String mTitle;
// private List<Comment> mReplies;
//
// private int mGilded;
// private int mScore;
// private int mReplyLevel;
//
// public Comment build() {
// return new Comment(this);
// }
//
// public Builder setTitle(String title) {
// mTitle = title;
// return this;
// }
//
// public Builder setAuthor(String author) {
// mAuthor = author;
// return this;
// }
//
// public Builder setComments(List<Comment> replies) {
// mReplies = replies;
// return this;
// }
//
// public Builder setPostContents(String postContents) {
// mPostContents = postContents;
// return this;
// }
//
// public Builder setGilded(int gilded) {
// mGilded = gilded;
// return this;
// }
//
// public Builder setScore(int score) {
// mScore = score;
// return this;
// }
//
// public Builder setReplyLevel(int replyLevel) {
// mReplyLevel = replyLevel;
// return this;
// }
//
// public Builder setIsScoreHidden(boolean scoreHidden) {
// mIsScoreHidden = scoreHidden;
// return this;
// }
// }
// }
| import android.app.Activity;
import android.app.Fragment;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import com.emmaguy.todayilearned.R;
import com.emmaguy.todayilearned.sharedlib.Comment;
import com.google.gson.Gson;
import java.util.List; | package com.emmaguy.todayilearned.comments;
public class ActionFragment extends Fragment implements View.OnClickListener {
private static final String ARGS_KEY_REPLIES = "key_replies";
private OnActionListener mListener;
private String mReplies;
| // Path: sharedlib/src/main/java/com/emmaguy/todayilearned/sharedlib/Comment.java
// public class Comment {
// private final boolean mScoreHidden;
//
// private final String mPostContents;
// private final String mAuthor;
// private final String mTitle;
//
// private final int mReplyLevel;
// private final int mGilded;
// private final int mScore;
//
// private final List<Comment> mReplies;
//
// public Comment(Builder builder) {
// mScore = builder.mScore;
// mTitle = builder.mTitle;
// mGilded = builder.mGilded;
// mAuthor = builder.mAuthor;
// mReplies = builder.mReplies;
// mReplyLevel = builder.mReplyLevel;
// mPostContents = builder.mPostContents;
// mScoreHidden = builder.mIsScoreHidden;
// }
//
// public String getTitle() {
// return mTitle;
// }
//
// public String getAuthor() {
// return mAuthor;
// }
//
// public int getScore() {
// return mScore;
// }
//
// public int getGilded() {
// return mGilded;
// }
//
// public boolean isScoreHidden() {
// return mScoreHidden;
// }
//
// public String getPostContents() {
// return mPostContents;
// }
//
// public int getReplyLevel() {
// return mReplyLevel;
// }
//
// public List<Comment> getReplies() {
// return mReplies;
// }
//
// public static final class Builder {
// private boolean mIsScoreHidden;
//
// private String mPostContents;
// private String mAuthor;
// private String mTitle;
// private List<Comment> mReplies;
//
// private int mGilded;
// private int mScore;
// private int mReplyLevel;
//
// public Comment build() {
// return new Comment(this);
// }
//
// public Builder setTitle(String title) {
// mTitle = title;
// return this;
// }
//
// public Builder setAuthor(String author) {
// mAuthor = author;
// return this;
// }
//
// public Builder setComments(List<Comment> replies) {
// mReplies = replies;
// return this;
// }
//
// public Builder setPostContents(String postContents) {
// mPostContents = postContents;
// return this;
// }
//
// public Builder setGilded(int gilded) {
// mGilded = gilded;
// return this;
// }
//
// public Builder setScore(int score) {
// mScore = score;
// return this;
// }
//
// public Builder setReplyLevel(int replyLevel) {
// mReplyLevel = replyLevel;
// return this;
// }
//
// public Builder setIsScoreHidden(boolean scoreHidden) {
// mIsScoreHidden = scoreHidden;
// return this;
// }
// }
// }
// Path: wear/src/main/java/com/emmaguy/todayilearned/comments/ActionFragment.java
import android.app.Activity;
import android.app.Fragment;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import com.emmaguy.todayilearned.R;
import com.emmaguy.todayilearned.sharedlib.Comment;
import com.google.gson.Gson;
import java.util.List;
package com.emmaguy.todayilearned.comments;
public class ActionFragment extends Fragment implements View.OnClickListener {
private static final String ARGS_KEY_REPLIES = "key_replies";
private OnActionListener mListener;
private String mReplies;
| public static Fragment create(List<Comment> replies) { |
emmaguy/wear-notify-for-reddit | mobile/src/main/java/com/emmaguy/todayilearned/settings/SubredditPreference.java | // Path: sharedlib/src/main/java/com/emmaguy/todayilearned/sharedlib/Constants.java
// public class Constants {
// public final static Set<String> sDefaultSelectedSubreddits = new LinkedHashSet<>(Arrays.asList(
// "todayilearned",
// "AskReddit"));
//
// public static final String WEB_URL_REDDIT = "https://www.reddit.com";
// public static final String ENDPOINT_URL_SSL_REDDIT = "https://ssl.reddit.com/";
// public static final String ENDPOINT_URL_OAUTH_REDDIT = "https://oauth.reddit.com/";
//
// public static final String AUTHORIZATION = "Authorization";
//
// public static final String GRANT_TYPE_AUTHORISATION_CODE = "authorization_code";
// public static final String GRANT_TYPE_REFRESH_TOKEN = "refresh_token";
// public static final String GRANT_TYPE_INSTALLED_CLIENT = "https://oauth.reddit.com/grants/installed_client";
//
// public static final String PATH_REDDIT_POSTS = "/redditwear";
// public static final String PATH_REFRESH = "/refresh";
// public static final String PATH_OPEN_ON_PHONE = "/openonphone";
// public static final String PATH_REPLY = "/replytopost";
// public static final String PATH_SAVE_TO_POCKET = "/send_to_pocket";
// public static final String PATH_VOTE = "/vote";
// public static final String PATH_COMMENTS = "/comments";
// public static final String PATH_NO_NEW_POSTS = "/no_new_posts";
// public static final String PATH_LOGGING = "/logging";
//
// public static final String KEY_REDDIT_POSTS = "posts";
// public static final String KEY_POST_PERMALINK = "post_permalink";
//
// public static final String PATH_POST_REPLY_RESULT_SUCCESS = "/post_reply_success";
// public static final String PATH_POST_REPLY_RESULT_FAILURE = "/post_reply_failure";
//
// public static final String PATH_KEY_MESSAGE = "post_message";
// public static final String PATH_KEY_POST_FULLNAME = "post_fullname";
// public static final String PATH_KEY_IS_DIRECT_MESSAGE = "is_direct";
// public static final String PATH_KEY_MESSAGE_SUBJECT = "msg_subject";
// public static final String PATH_KEY_MESSAGE_TO_USER = "msg_to_user";
//
// public static final String PATH_SAVE_TO_POCKET_RESULT_SUCCESS = "/save_pocket_success";
// public static final String PATH_SAVE_TO_POCKET_RESULT_FAILED = "/save_pocket_failed";
//
// public static final String PATH_VOTE_RESULT_SUCCESS = "/vote_success";
// public static final String PATH_VOTE_RESULT_FAILED = "/vote_failed";
// public static final String PATH_GET_COMMENTS_RESULT_FAILED = "/getting_comments";
//
// public static final String KEY_CONFIRMATION_MESSAGE = "confirm_message";
// public static final String KEY_PATH = "receiver_path";
// public static final String KEY_POST_VOTE_DIRECTION = "vote_direction";
// public static final String KEY_CONFIRMATION_ANIMATION = "key_confirm_animation";
// public static final String KEY_DISMISS_AFTER_ACTION = "open_on_phone_dismisses";
// public static final String KEY_NOTIFICATION_ID = "notification_id";
// public static final String KEY_ACTION_ORDER = "action_order";
// public static final String KEY_HIGHRES_IMAGE_NAME = "view_image";
//
// public static final int ACTION_ORDER_VIEW_COMMENTS = 0;
// public static final int ACTION_ORDER_REPLY = 1;
// public static final int ACTION_ORDER_UPVOTE = 2;
// public static final int ACTION_ORDER_DOWNVOTE = 3;
// public static final int ACTION_ORDER_SAVE_TO_POCKET = 4;
// public static final int ACTION_ORDER_OPEN_ON_PHONE = 5;
// public static final int ACTION_ORDER_VIEW_IMAGE = 6;
// }
| import android.annotation.SuppressLint;
import android.app.AlertDialog;
import android.content.Context;
import android.preference.Preference;
import android.util.AttributeSet;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.EditText;
import com.emmaguy.todayilearned.R;
import com.emmaguy.todayilearned.sharedlib.Constants;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.HashSet;
import java.util.List;
import java.util.Set; | public SubredditPreference(Context context) {
super(context, null);
}
public SubredditPreference(Context context, AttributeSet attrs) {
super(context, attrs);
}
@Override protected void onClick() {
super.onClick();
showSelectSubredditsDialog();
}
public String getSelectedSubredditsKey() {
return getContext().getString(R.string.prefs_key_selected_subreddits);
}
public List<String> getAllSubreddits() {
Set<String> subreddits = getSharedPreferences().getStringSet(getKey(), DefaultSubreddits);
ArrayList<String> sortedSubreddits = new ArrayList(subreddits);
Collections.sort(sortedSubreddits);
return sortedSubreddits;
}
public List<String> getAllSelectedSubreddits() {
final String key = getSelectedSubredditsKey();
Set<String> subreddits = getSharedPreferences().getStringSet(key, | // Path: sharedlib/src/main/java/com/emmaguy/todayilearned/sharedlib/Constants.java
// public class Constants {
// public final static Set<String> sDefaultSelectedSubreddits = new LinkedHashSet<>(Arrays.asList(
// "todayilearned",
// "AskReddit"));
//
// public static final String WEB_URL_REDDIT = "https://www.reddit.com";
// public static final String ENDPOINT_URL_SSL_REDDIT = "https://ssl.reddit.com/";
// public static final String ENDPOINT_URL_OAUTH_REDDIT = "https://oauth.reddit.com/";
//
// public static final String AUTHORIZATION = "Authorization";
//
// public static final String GRANT_TYPE_AUTHORISATION_CODE = "authorization_code";
// public static final String GRANT_TYPE_REFRESH_TOKEN = "refresh_token";
// public static final String GRANT_TYPE_INSTALLED_CLIENT = "https://oauth.reddit.com/grants/installed_client";
//
// public static final String PATH_REDDIT_POSTS = "/redditwear";
// public static final String PATH_REFRESH = "/refresh";
// public static final String PATH_OPEN_ON_PHONE = "/openonphone";
// public static final String PATH_REPLY = "/replytopost";
// public static final String PATH_SAVE_TO_POCKET = "/send_to_pocket";
// public static final String PATH_VOTE = "/vote";
// public static final String PATH_COMMENTS = "/comments";
// public static final String PATH_NO_NEW_POSTS = "/no_new_posts";
// public static final String PATH_LOGGING = "/logging";
//
// public static final String KEY_REDDIT_POSTS = "posts";
// public static final String KEY_POST_PERMALINK = "post_permalink";
//
// public static final String PATH_POST_REPLY_RESULT_SUCCESS = "/post_reply_success";
// public static final String PATH_POST_REPLY_RESULT_FAILURE = "/post_reply_failure";
//
// public static final String PATH_KEY_MESSAGE = "post_message";
// public static final String PATH_KEY_POST_FULLNAME = "post_fullname";
// public static final String PATH_KEY_IS_DIRECT_MESSAGE = "is_direct";
// public static final String PATH_KEY_MESSAGE_SUBJECT = "msg_subject";
// public static final String PATH_KEY_MESSAGE_TO_USER = "msg_to_user";
//
// public static final String PATH_SAVE_TO_POCKET_RESULT_SUCCESS = "/save_pocket_success";
// public static final String PATH_SAVE_TO_POCKET_RESULT_FAILED = "/save_pocket_failed";
//
// public static final String PATH_VOTE_RESULT_SUCCESS = "/vote_success";
// public static final String PATH_VOTE_RESULT_FAILED = "/vote_failed";
// public static final String PATH_GET_COMMENTS_RESULT_FAILED = "/getting_comments";
//
// public static final String KEY_CONFIRMATION_MESSAGE = "confirm_message";
// public static final String KEY_PATH = "receiver_path";
// public static final String KEY_POST_VOTE_DIRECTION = "vote_direction";
// public static final String KEY_CONFIRMATION_ANIMATION = "key_confirm_animation";
// public static final String KEY_DISMISS_AFTER_ACTION = "open_on_phone_dismisses";
// public static final String KEY_NOTIFICATION_ID = "notification_id";
// public static final String KEY_ACTION_ORDER = "action_order";
// public static final String KEY_HIGHRES_IMAGE_NAME = "view_image";
//
// public static final int ACTION_ORDER_VIEW_COMMENTS = 0;
// public static final int ACTION_ORDER_REPLY = 1;
// public static final int ACTION_ORDER_UPVOTE = 2;
// public static final int ACTION_ORDER_DOWNVOTE = 3;
// public static final int ACTION_ORDER_SAVE_TO_POCKET = 4;
// public static final int ACTION_ORDER_OPEN_ON_PHONE = 5;
// public static final int ACTION_ORDER_VIEW_IMAGE = 6;
// }
// Path: mobile/src/main/java/com/emmaguy/todayilearned/settings/SubredditPreference.java
import android.annotation.SuppressLint;
import android.app.AlertDialog;
import android.content.Context;
import android.preference.Preference;
import android.util.AttributeSet;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.EditText;
import com.emmaguy.todayilearned.R;
import com.emmaguy.todayilearned.sharedlib.Constants;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
public SubredditPreference(Context context) {
super(context, null);
}
public SubredditPreference(Context context, AttributeSet attrs) {
super(context, attrs);
}
@Override protected void onClick() {
super.onClick();
showSelectSubredditsDialog();
}
public String getSelectedSubredditsKey() {
return getContext().getString(R.string.prefs_key_selected_subreddits);
}
public List<String> getAllSubreddits() {
Set<String> subreddits = getSharedPreferences().getStringSet(getKey(), DefaultSubreddits);
ArrayList<String> sortedSubreddits = new ArrayList(subreddits);
Collections.sort(sortedSubreddits);
return sortedSubreddits;
}
public List<String> getAllSelectedSubreddits() {
final String key = getSelectedSubredditsKey();
Set<String> subreddits = getSharedPreferences().getStringSet(key, | Constants.sDefaultSelectedSubreddits); |
emmaguy/wear-notify-for-reddit | mobile/src/main/java/com/emmaguy/todayilearned/refresh/TokenRefreshInterceptor.java | // Path: sharedlib/src/main/java/com/emmaguy/todayilearned/sharedlib/Constants.java
// public class Constants {
// public final static Set<String> sDefaultSelectedSubreddits = new LinkedHashSet<>(Arrays.asList(
// "todayilearned",
// "AskReddit"));
//
// public static final String WEB_URL_REDDIT = "https://www.reddit.com";
// public static final String ENDPOINT_URL_SSL_REDDIT = "https://ssl.reddit.com/";
// public static final String ENDPOINT_URL_OAUTH_REDDIT = "https://oauth.reddit.com/";
//
// public static final String AUTHORIZATION = "Authorization";
//
// public static final String GRANT_TYPE_AUTHORISATION_CODE = "authorization_code";
// public static final String GRANT_TYPE_REFRESH_TOKEN = "refresh_token";
// public static final String GRANT_TYPE_INSTALLED_CLIENT = "https://oauth.reddit.com/grants/installed_client";
//
// public static final String PATH_REDDIT_POSTS = "/redditwear";
// public static final String PATH_REFRESH = "/refresh";
// public static final String PATH_OPEN_ON_PHONE = "/openonphone";
// public static final String PATH_REPLY = "/replytopost";
// public static final String PATH_SAVE_TO_POCKET = "/send_to_pocket";
// public static final String PATH_VOTE = "/vote";
// public static final String PATH_COMMENTS = "/comments";
// public static final String PATH_NO_NEW_POSTS = "/no_new_posts";
// public static final String PATH_LOGGING = "/logging";
//
// public static final String KEY_REDDIT_POSTS = "posts";
// public static final String KEY_POST_PERMALINK = "post_permalink";
//
// public static final String PATH_POST_REPLY_RESULT_SUCCESS = "/post_reply_success";
// public static final String PATH_POST_REPLY_RESULT_FAILURE = "/post_reply_failure";
//
// public static final String PATH_KEY_MESSAGE = "post_message";
// public static final String PATH_KEY_POST_FULLNAME = "post_fullname";
// public static final String PATH_KEY_IS_DIRECT_MESSAGE = "is_direct";
// public static final String PATH_KEY_MESSAGE_SUBJECT = "msg_subject";
// public static final String PATH_KEY_MESSAGE_TO_USER = "msg_to_user";
//
// public static final String PATH_SAVE_TO_POCKET_RESULT_SUCCESS = "/save_pocket_success";
// public static final String PATH_SAVE_TO_POCKET_RESULT_FAILED = "/save_pocket_failed";
//
// public static final String PATH_VOTE_RESULT_SUCCESS = "/vote_success";
// public static final String PATH_VOTE_RESULT_FAILED = "/vote_failed";
// public static final String PATH_GET_COMMENTS_RESULT_FAILED = "/getting_comments";
//
// public static final String KEY_CONFIRMATION_MESSAGE = "confirm_message";
// public static final String KEY_PATH = "receiver_path";
// public static final String KEY_POST_VOTE_DIRECTION = "vote_direction";
// public static final String KEY_CONFIRMATION_ANIMATION = "key_confirm_animation";
// public static final String KEY_DISMISS_AFTER_ACTION = "open_on_phone_dismisses";
// public static final String KEY_NOTIFICATION_ID = "notification_id";
// public static final String KEY_ACTION_ORDER = "action_order";
// public static final String KEY_HIGHRES_IMAGE_NAME = "view_image";
//
// public static final int ACTION_ORDER_VIEW_COMMENTS = 0;
// public static final int ACTION_ORDER_REPLY = 1;
// public static final int ACTION_ORDER_UPVOTE = 2;
// public static final int ACTION_ORDER_DOWNVOTE = 3;
// public static final int ACTION_ORDER_SAVE_TO_POCKET = 4;
// public static final int ACTION_ORDER_OPEN_ON_PHONE = 5;
// public static final int ACTION_ORDER_VIEW_IMAGE = 6;
// }
| import android.support.annotation.NonNull;
import com.emmaguy.todayilearned.sharedlib.Constants;
import com.emmaguy.todayilearned.storage.TokenStorage;
import com.squareup.okhttp.Interceptor;
import com.squareup.okhttp.Request;
import com.squareup.okhttp.Response;
import java.io.IOException;
import java.net.HttpURLConnection;
import java.util.UUID;
import retrofit.RetrofitError; | package com.emmaguy.todayilearned.refresh;
/**
* Refresh a token - transparently to rest of the code. Will block a request whilst doing the token refresh,
* then continue with the original request once we have a valid token again.
* <p>
* Created by emma on 14/06/15.
*/
public class TokenRefreshInterceptor implements Interceptor {
private static final String BEARER_FORMAT = "bearer %s";
private final TokenStorage mTokenStorage;
private final RedditAuthenticationService mAuthenticationService;
public TokenRefreshInterceptor(TokenStorage tokenStorage,
RedditAuthenticationService authenticationService) {
mTokenStorage = tokenStorage;
mAuthenticationService = authenticationService;
}
@Override public Response intercept(Chain chain) throws IOException {
Request request = chain.request();
Response response;
if (request.url().toString().contains("access_token")) {
// if we're trying to get the access token, carry on
response = chain.proceed(request);
} else if (mTokenStorage.hasNoToken()) {
// User hasn't logged in, request an app only token
response = requestAppOnlyTokenAndProceed(chain, request);
} else if (mTokenStorage.hasTokenExpired()) {
// Token's expired, renew it first
response = renewTokenAndProceed(chain, request);
} else {
response = makeRequest(chain, request);
}
return response;
}
// synchronized so we only renew one request at a time
@NonNull private synchronized Response requestAppOnlyTokenAndProceed(Chain chain,
Request originalRequest) throws
IOException {
try { | // Path: sharedlib/src/main/java/com/emmaguy/todayilearned/sharedlib/Constants.java
// public class Constants {
// public final static Set<String> sDefaultSelectedSubreddits = new LinkedHashSet<>(Arrays.asList(
// "todayilearned",
// "AskReddit"));
//
// public static final String WEB_URL_REDDIT = "https://www.reddit.com";
// public static final String ENDPOINT_URL_SSL_REDDIT = "https://ssl.reddit.com/";
// public static final String ENDPOINT_URL_OAUTH_REDDIT = "https://oauth.reddit.com/";
//
// public static final String AUTHORIZATION = "Authorization";
//
// public static final String GRANT_TYPE_AUTHORISATION_CODE = "authorization_code";
// public static final String GRANT_TYPE_REFRESH_TOKEN = "refresh_token";
// public static final String GRANT_TYPE_INSTALLED_CLIENT = "https://oauth.reddit.com/grants/installed_client";
//
// public static final String PATH_REDDIT_POSTS = "/redditwear";
// public static final String PATH_REFRESH = "/refresh";
// public static final String PATH_OPEN_ON_PHONE = "/openonphone";
// public static final String PATH_REPLY = "/replytopost";
// public static final String PATH_SAVE_TO_POCKET = "/send_to_pocket";
// public static final String PATH_VOTE = "/vote";
// public static final String PATH_COMMENTS = "/comments";
// public static final String PATH_NO_NEW_POSTS = "/no_new_posts";
// public static final String PATH_LOGGING = "/logging";
//
// public static final String KEY_REDDIT_POSTS = "posts";
// public static final String KEY_POST_PERMALINK = "post_permalink";
//
// public static final String PATH_POST_REPLY_RESULT_SUCCESS = "/post_reply_success";
// public static final String PATH_POST_REPLY_RESULT_FAILURE = "/post_reply_failure";
//
// public static final String PATH_KEY_MESSAGE = "post_message";
// public static final String PATH_KEY_POST_FULLNAME = "post_fullname";
// public static final String PATH_KEY_IS_DIRECT_MESSAGE = "is_direct";
// public static final String PATH_KEY_MESSAGE_SUBJECT = "msg_subject";
// public static final String PATH_KEY_MESSAGE_TO_USER = "msg_to_user";
//
// public static final String PATH_SAVE_TO_POCKET_RESULT_SUCCESS = "/save_pocket_success";
// public static final String PATH_SAVE_TO_POCKET_RESULT_FAILED = "/save_pocket_failed";
//
// public static final String PATH_VOTE_RESULT_SUCCESS = "/vote_success";
// public static final String PATH_VOTE_RESULT_FAILED = "/vote_failed";
// public static final String PATH_GET_COMMENTS_RESULT_FAILED = "/getting_comments";
//
// public static final String KEY_CONFIRMATION_MESSAGE = "confirm_message";
// public static final String KEY_PATH = "receiver_path";
// public static final String KEY_POST_VOTE_DIRECTION = "vote_direction";
// public static final String KEY_CONFIRMATION_ANIMATION = "key_confirm_animation";
// public static final String KEY_DISMISS_AFTER_ACTION = "open_on_phone_dismisses";
// public static final String KEY_NOTIFICATION_ID = "notification_id";
// public static final String KEY_ACTION_ORDER = "action_order";
// public static final String KEY_HIGHRES_IMAGE_NAME = "view_image";
//
// public static final int ACTION_ORDER_VIEW_COMMENTS = 0;
// public static final int ACTION_ORDER_REPLY = 1;
// public static final int ACTION_ORDER_UPVOTE = 2;
// public static final int ACTION_ORDER_DOWNVOTE = 3;
// public static final int ACTION_ORDER_SAVE_TO_POCKET = 4;
// public static final int ACTION_ORDER_OPEN_ON_PHONE = 5;
// public static final int ACTION_ORDER_VIEW_IMAGE = 6;
// }
// Path: mobile/src/main/java/com/emmaguy/todayilearned/refresh/TokenRefreshInterceptor.java
import android.support.annotation.NonNull;
import com.emmaguy.todayilearned.sharedlib.Constants;
import com.emmaguy.todayilearned.storage.TokenStorage;
import com.squareup.okhttp.Interceptor;
import com.squareup.okhttp.Request;
import com.squareup.okhttp.Response;
import java.io.IOException;
import java.net.HttpURLConnection;
import java.util.UUID;
import retrofit.RetrofitError;
package com.emmaguy.todayilearned.refresh;
/**
* Refresh a token - transparently to rest of the code. Will block a request whilst doing the token refresh,
* then continue with the original request once we have a valid token again.
* <p>
* Created by emma on 14/06/15.
*/
public class TokenRefreshInterceptor implements Interceptor {
private static final String BEARER_FORMAT = "bearer %s";
private final TokenStorage mTokenStorage;
private final RedditAuthenticationService mAuthenticationService;
public TokenRefreshInterceptor(TokenStorage tokenStorage,
RedditAuthenticationService authenticationService) {
mTokenStorage = tokenStorage;
mAuthenticationService = authenticationService;
}
@Override public Response intercept(Chain chain) throws IOException {
Request request = chain.request();
Response response;
if (request.url().toString().contains("access_token")) {
// if we're trying to get the access token, carry on
response = chain.proceed(request);
} else if (mTokenStorage.hasNoToken()) {
// User hasn't logged in, request an app only token
response = requestAppOnlyTokenAndProceed(chain, request);
} else if (mTokenStorage.hasTokenExpired()) {
// Token's expired, renew it first
response = renewTokenAndProceed(chain, request);
} else {
response = makeRequest(chain, request);
}
return response;
}
// synchronized so we only renew one request at a time
@NonNull private synchronized Response requestAppOnlyTokenAndProceed(Chain chain,
Request originalRequest) throws
IOException {
try { | Token token = mAuthenticationService.appOnlyToken(Constants.GRANT_TYPE_INSTALLED_CLIENT, |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.