Java Program TextFile Issue - javascript

I have a program where a text file is read in and then each word in the file is outputted, followed by the # of times it is repeated throughout the file.

Use the following code.
import java.io.*;
class FileRead {
public static void main(String args[]) {
try {
// Open the file that is the first
// command line parameter
FileInputStream fstream = new FileInputStream("C:\\Users\\Desktop\\formate.txt");
// Get the object of DataInputStream
DataInputStream in = new DataInputStream(fstream);
BufferedReader br = new BufferedReader(new InputStreamReader(in));
String strLine;
//Read File Line By Line
while ((strLine = br.readLine()) != null) {
// Print the content on the console
System.out.println(strLine);
}
//Close the input stream
in.close();
} catch (Exception e) {//Catch exception if any
System.err.println("Error: " + e.getMessage());
}
}
}

Try this code:
public static void main(String[] args) throws Throwable
{
File inputFile = new File("input.txt");
File outputFile = new File("output.txt");
Scanner scanner = new Scanner(inputFile);
HashMap<String, Integer> count = new HashMap<String, Integer>();
while (scanner.hasNext())
{
String word = scanner.next();
if (count.containsKey(word))
{
count.put(word, count.get(word) + 1);
}
else
{
count.put(word, 1);
}
}
scanner.close();
BufferedWriter writer = new BufferedWriter(new FileWriter(outputFile));
for (Entry<String, Integer> entry : count.entrySet())
{
writer.write("#" + entry.getKey() + " " + entry.getValue()+"\r\n");
}
writer.close();
}

This also, it is a lot simpler if You can't use HashMap or BufferedReader:
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.util.LinkedList;
import java.util.Scanner;
public class WordCounter
{
public static void main(String[] args) throws Throwable
{
File inputFile = new File("input.txt");
File outputFile = new File("output.txt");
Scanner scanner = new Scanner(inputFile);
LinkedList<Word> words = new LinkedList<Word>();
while (scanner.hasNext())
{
String word = scanner.next();
addWord(words, word);
}
scanner.close();
WriteToFile(outputFile, words);
}
private static void WriteToFile(File outputFile, LinkedList<Word> words) throws IOException
{
BufferedWriter writer = new BufferedWriter(new FileWriter(outputFile));
for (Word word : words)
{
writer.write("#" + word.getWord() + " " + word.getCount() + "\r\n");
}
writer.close();
}
private static void addWord(LinkedList<Word> words, String word)
{
for (Word aWord : words)
{
if (aWord.getWord().equals(word))
{
aWord.incrementCount();
return;
}
}
words.add(new Word(word, 1));
}
}
class Word
{
private String word;
private int count;
public Word(String word, int count)
{
this.word = word;
this.count = count;
}
public String getWord()
{
return word;
}
public void setWord(String word)
{
this.word = word;
}
public int getCount()
{
return count;
}
public void setCount(int count)
{
this.count = count;
}
public void incrementCount()
{
count++;
}
#Override
public String toString()
{
return "Word: " + word + " Count: " + count;
}
}

Related

api layer, exchangerate // IOException : Server returned HTTP response code: 403 for URL

control.java
public class control {
public static void main(String[] args) {
boolean success = true;
String timestamp = "1659072666";
String base = "USD";
String date = "2022-07-29";
double GBP = 0.82011;
double JPY = 133.000499;
double EUR = 0.979105;
excJSON vwJson = new excJSON();
exc vw = vwJson.getexc(success, timestamp, base, date, GBP, JPY, EUR);
excDAO vwDao = new excDAO();
vwDao.intertexc(1, vw);
}
}
exc.java
public class exc {
String base;
String date;
String timestamp;
public String getbase() {
return base;
}
public void setbase(String base) {
this.base = base;
}
public String getdate() {
return date;
}
public void setdate(String date) {
this.date = date;
}
public String gettimestamp() {
return timestamp;
}
public void settimestamp(String timestamp) {
this.timestamp = timestamp;
}
}
excDAO.java
import java.sql.Statement;
import java.sql.Connection;
//import java.sql.Driver;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
//import java.util.Enumeration;
public class excDAO {
static final String JDBC_DRIVER = "com.mysql.jdbc.Driver";
static final String DB_URL = "jdbc:mysql://localhost:3306/test?useSSL=false";
static final String USERNAME = "root"; // DB ID
static final String PASSWORD = "************"; // DB Password
private Connection conn = null;
private Statement stmt = null;
private ResultSet rs = null;
public void intertVillageWeather(int id, exc v) {
String query = "INSERT INTO exchangerate"
+ " VALUE(" + id +",'"+v.gettimestamp() + "','" + v.getbase() + "','" + v.getdate() + "');";
System.out.print("Your Database in : ");
try {
Class.forName(JDBC_DRIVER);
conn = DriverManager.getConnection(DB_URL,USERNAME,PASSWORD);
if (conn != null){System.out.println("good");}
else{System.out.println("bad");}
System.out.println(query);
stmt = conn.createStatement();
stmt.executeUpdate(query);
stmt.close();
conn.close();
} catch (ClassNotFoundException e) {
System.out.println("Class Not Found Exection");
} catch (SQLException e) {
System.out.println("SQL Exception : " + e.getMessage());
}
}
public void intertexc(int i, exc vw) {
}
}
excJSON.java
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.MalformedURLException;
import java.net.URL;
import org.json.simple.JSONObject;
import org.json.simple.parser.JSONParser;
import org.json.simple.parser.ParseException;
final static String apiKey = "tUxsDwwjT72GgMLoJRprXlqc34wmOzX4";
public exc getexc(boolean success, String timestamp, String base, String date, double GBP, double JPY, double EUR) {
String urlStr = "https://api.apilayer.com/exchangerates_data/latest?symbols=GBP%2CJPY%2CEUR&base=USD"
+ "&apiKey=" + apiKey + "&success=" + success + "&timestamp=" + timestamp
+ "&base="+ base + "&date=" + date + "&GBP=" + GBP + "&JPY=" + JPY + "&EUR=" + EUR + "&_type=json";
exc vl = new exc(); // 결과 데이터를 저장할 객체를 만듭니다.
try {
URL url = new URL(urlStr);
BufferedReader bf = new BufferedReader(new InputStreamReader(url.openStream()));
String line = "";
String result="";
while((line=bf.readLine())!=null){
result=result.concat(line);
}
//System.out.println(result);
JSONParser jsonParser = new JSONParser();
JSONObject jsonObj = (JSONObject) jsonParser.parse(result);
JSONObject parse_response = (JSONObject) jsonObj.get("response");
JSONObject obj;
String category;
vl.timestamp = timestamp;
vl.base = base;
vl.date = date;
for(int i = 0; i < parse_response.size(); i++) {
obj = (JSONObject) parse_response.get(i);
category = (String)obj.get("category");
switch(category) {
case "timestamp":
vl.timestamp = (obj.get("fcstValue")).toString();
break;
case "base":
vl.base = (obj.get("fcstValue")).toString();
break;
case "date":
vl.date = (obj.get("fcstValue")).toString();
break;
}
}
} catch (MalformedURLException e) {
System.out.println("MalformedURLException : " + e.getMessage());
} catch (IOException e) {
System.out.println("IOException : " + e.getMessage());
} catch (ParseException e) {
System.out.println("ParseException : " + e.getMessage());
}
return vl;
}
}
*Help me please. I think error in excJSON.java. I want make exchangerate program.
I want fix error.
error code : IOException : Server returned HTTP response code: 403 for URL: https://api.apilayer.com/exchangerates_data/latest?symbols=GBP%2CJPY%2CEUR&base=USD&apiKey=tUxsDwwjT72GgMLoJRprXlqc34wmOzX4&success=true&timestamp=1659072666&base=USD&date=2022-07-29&GBP=0.82011&JPY=133.000499&EUR=0.979105&_type=json
I assess "https://api.apilayer.com/exchangerates_data/latest?symbols=GBP%2CJPY%2CEUR&base=USD&apiKey=tUxsDwwjT72GgMLoJRprXlqc34wmOzX4&success=true&timestamp=1659072666&base=USD&date=2022-07-29&GBP=0.82011&JPY=133.000499&EUR=0.979105&_type=json"
but http say {"message":"No API key found in request"}
but i surely receive apikey and api.*

javascript function can't find the element

I need to call some file uploader JavaScript from code behind. The JavaScript is basically customizing the style of the file uploader control. However, the JavaScript function can't find the element. I get this from the inspector:
*o = {element: null,
action: "/Web/UploadHandler.axd?UploadID=55f3930c-6aa9-4201…ccfdfae6c6&ObjectID=145649&RelationshipTypeID=223",
sizeLimit: 209715
when it should look like this:
o = {element: div#uploadContent, action: "/Web/UploadHandler.axd?UploadID=c1829b40-7869-4f19…411e7a542c&ObjectID=151808&RelationshipTypeID=223", sizeLimit: 20971520, acceptTypes: "image/*", onSubmit: ƒ, …}
qq.extend
This is the code:
div = new HtmlGenericControl("div") { ID = ("dlWrapper") };
Literal litScript = new Literal();
litScript.Mode = LiteralMode.PassThrough;
div.Controls.Add(litScript);
var imageUploader = (ImageUpload)CreateImageUploader(ActiveObject, p, litScript);
div.Controls.Add(imageUploader);
controls.Add(div);
private static Control CreateImageUploader(ObjectInstance objectInstance, PropertyType propertyType, Literal litScript)
{
ImageUpload imageUpload = new ImageUpload (objectInstance, litScript) { ID = ControlFactory.GetControlId(ControlFactory.IMAGE_PREFIX, ControlFactory.PROPERTY_TYPE_PREFIX, objectInstance.Id, propertyType.Id), Width = Unit.Pixel(80), Height = Unit.Pixel(30) };
PropertyInstanceValue piv = objectInstance.GetPropertyInstanceValue(propertyType.Id);
return imageUpload;
}
public class ImageUpload : FileUpload
{
public ObjectInstance ActiveObject {get; set; }
public Literal litScript { get; set; }
private string uploadID;
private string accept = "image/*";
public string UploadID
{
get
{
if (string.IsNullOrEmpty(uploadID))
{
uploadID = GetUploadID();
}
return uploadID;
}
set { uploadID = value; }
}
public ImageUpload(ObjectInstance activeObject, Literal literal)
{
ActiveObject = activeObject;
litScript = literal;
}
public string GetUploadID()
{
string uploadID;
if (HttpContext.Current.Session[EDM.Common.Definitions.SessionKey.UPLOAD_ID] != null)
{
uploadID = (string)HttpContext.Current.Session[EDM.Common.Definitions.SessionKey.UPLOAD_ID];
HttpContext.Current.Cache.Remove("cacheFlashSessionID_" + uploadID);
HttpContext.Current.Cache.Remove("cacheFlashAuth_" + uploadID);
}
uploadID = Guid.NewGuid().ToString();
HttpContext.Current.Session[EDM.Common.Definitions.SessionKey.UPLOAD_ID] = uploadID;
HttpContext.Current.Cache.Insert("cacheFlashSessionID_" + uploadID, HttpContext.Current.Session.SessionID, null, DateTime.Now.AddMinutes(20), Cache.NoSlidingExpiration, CacheItemPriority.NotRemovable, null);
if (HttpContext.Current.Request.Cookies[FormsAuthentication.FormsCookieName] != null)
{
// ReSharper disable PossibleNullReferenceException
HttpContext.Current.Cache.Insert("cacheFlashAuth_" + uploadID, HttpContext.Current.Request.Cookies[FormsAuthentication.FormsCookieName].Value, null, DateTime.Now.AddMinutes(20), Cache.NoSlidingExpiration, CacheItemPriority.NotRemovable, null);
// ReSharper restore PossibleNullReferenceException
}
return uploadID;
}
protected override void OnLoad(EventArgs e)
{
Literal litScript = new Literal();
ScriptManager scriptManager = ScriptManager.GetCurrent(Page);
StringBuilder sb = new StringBuilder();
sb.Append("<div id=\"uploadContent\"></div>");
litScript.Text = sb.ToString();
sb.Remove(0, sb.Length);
sb.Append("<script type=\"text/javascript\">");
int maxBytes = ProcessUnity.Common.Utility.GetMaxRequestLength() * 1024;
sb.Append("var uploader = new qq.FileUploader({ element: document.getElementById('uploadContent'), action: '" + Context.Request.ApplicationPath + "/UploadHandler.axd?UploadID=" + UploadID + "&ObjectID=" + ActiveObject.Id + "&RelationshipTypeID=" + EDM.Common.Definitions.RelationshipTypeId.IMAGE_FILE + "', sizeLimit: " + maxBytes + ", acceptTypes:'" + accept + "', onSubmit: uploadStart, onComplete: uploadComplete, onError: uploadError, multiple: false });");
sb.Append("</script>");
if (scriptManager != null)
{
ScriptManager.RegisterClientScriptBlock(this, typeof(ImageUpload), Guid.NewGuid().ToString(), sb.ToString(), false);
}
else
{
Page.ClientScript.RegisterClientScriptBlock(typeof(Page), Guid.NewGuid().ToString(), sb.ToString());
}
base.OnLoad(e);
}
private object GetScriptManager()
{
foreach (DictionaryEntry entry in Page.Items)
{
if (entry.Key.ToString().IndexOf("System.Web.UI.ScriptManager") >= 0)
{
return entry.Value;
}
}
return null;
}
}
It looks like you're expecting litScript here:
Literal litScript = new Literal();
litScript.Mode = LiteralMode.PassThrough;
div.Controls.Add(litScript);
To be modified by the OnLoad event:
protected override void OnLoad(EventArgs e)
{
Literal litScript = new Literal();
// ...
StringBuilder sb = new StringBuilder();
sb.Append("<div id=\"uploadContent\"></div>");
litScript.Text = sb.ToString();
// ...
base.OnLoad(e);
}
But your OnLoad is constructing its own local Literal. Just because it has the same litScript name as the outer Literal doesn't mean that the two are related. In short, nothing is writing that div to the page.

Java Server, html client, unable to send messages to server

i got a little problem with my project. I have a Server written in Java and some clients written in html/js. Connecting works somehow, but as soon as i want to send a message from the client to the server it returns an error: "Uncaught InvalidStateError: Failed to execute 'send' on 'WebSocket': Still in CONNECTING state"
Hopefully some of you awesome guys can look over my code and help me :)
Server Code:
Server.java
public class Server {
static ArrayList<Clients> clientsArrayList = new ArrayList<>();
private static int clientCount = 1;
private static int port;
private static ServerSocket ss;
private Socket socket;
private Clients clienthandler;
static boolean isRunning = true;
public Server(int port) throws IOException {
this.port = port;
setSs(new ServerSocket(port));
}
public void run() throws IOException {
while (isRunning) {
log("Listening on " + port + "...");
socket = getSs().accept();
log("Receiving client... " + socket);
BufferedReader in = new BufferedReader(new InputStreamReader(socket.getInputStream()));
PrintWriter out = new PrintWriter(socket.getOutputStream());
String s;
while ((s = in.readLine()) != null) {
log(s);
if (s.isEmpty()) {
break;
}
}
log("Creating a new handler for this client...");
clienthandler = new Clients(socket, "Client " + clientCount, in, out);
Thread t = new Thread(clienthandler);
clientsArrayList.add(clienthandler);
log("Added to client list");
t.start();
clientCount++;
GUI.texttoclientlog();
}
}
public static ServerSocket getSs() {
return ss;
}
public static void setSs(ServerSocket ss) {
Server.ss = ss;
}
public void log(String logtext) {
System.out.println(logtext);
GUI.texttolog(logtext);
}
}
Clients.java
public class Clients implements Runnable {
private String name;
final BufferedReader in;
final PrintWriter out;
Socket socket;
boolean isloggedin;
public Clients(Socket socket, String name, BufferedReader in, PrintWriter out) {
this.out = out;
this.in = in;
this.name = name;
this.socket = socket;
this.isloggedin = true;
}
#Override
public void run() {
String received;
while (true) {
try {
// receive the string
received = in.readLine();
System.out.println(received);
GUI.messagehandler(this.getName() + ": " + received);
if (received.equals("logout")) {
this.isloggedin = false;
this.socket.close();
break;
}
this.in.close();
this.out.close();
this.out.flush();
this.out.flush();
} catch (IOException e) {
e.printStackTrace();
}
}
}
public String getName() {
return name;
}
}
And the JS client code:
<script>
var connection;
connection = new WebSocket("ws://localhost:6788/");
console.log("connection established");
connection.onmessage = function (e) { console.log(e.data); };
connection.onopen = () => conn.send("Connection established");
connection.onerror = function (error) {
console.log("WebSocket Error" + error);
};
function Send() {
if (connection.readyState === 1) {
connection.send("test");
}
console.log("error sending");
}
</script>
The WebSocket session is established via a handshake.
Post the handshake is complete and the connection is upgraded, the server and client can send messages. Here is a sample WebSocket server in Java.
Update the clients run method to
public void run() {
int len = 0;
byte[] b = new byte[80];
while(true){
try {
len = in.read(b);
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
if(len!=-1){
byte rLength = 0;
int rMaskIndex = 2;
int rDataStart = 0;
//b[0] is always text in my case so no need to check;
byte data = b[1];
byte op = (byte) 127;
rLength = (byte) (data & op);
if(rLength==(byte)126) rMaskIndex=4;
if(rLength==(byte)127) rMaskIndex=10;
byte[] masks = new byte[4];
int j=0;
int i=0;
for(i=rMaskIndex;i<(rMaskIndex+4);i++){
masks[j] = b[i];
j++;
}
rDataStart = rMaskIndex + 4;
int messLen = len - rDataStart;
byte[] message = new byte[messLen];
for(i=rDataStart, j=0; i<len; i++, j++){
message[j] = (byte) (b[i] ^ masks[j % 4]);
}
System.out.println(new String(message));
b = new byte[80];
}
}
}
based on this SO answer
In my opinion you can leverage the Spring WebSocket support, rather than writing your own. I had created one which also uses ProtoBuf or you can look at the Spring WebSocket getting started guide here
Thats the updated code. it receives the bytes from the html clients. but i have no clue how to decode them :)
Server.java
public class Server {
static ArrayList<Clients> clientsArrayList = new ArrayList<>();
private static int clientCount = 1;
private static int port;
private static ServerSocket ss;
private Socket socket;
private Clients clienthandler;
static boolean isRunning = true;
private InputStream in;
private OutputStream out;
public Server(int port) throws IOException {
Server.port = port;
setSs(new ServerSocket(port));
}
public void run() throws IOException, NoSuchAlgorithmException {
while (isRunning) {
log("Listening on " + port + "...");
socket = getSs().accept();
log("Receiving client... " + socket);
in = socket.getInputStream();
out = socket.getOutputStream();
#SuppressWarnings("resource")
String data = new Scanner(in, "UTF-8").useDelimiter("\\r\\n\\r\\n").next();
Matcher get = Pattern.compile("^GET").matcher(data);
if (get.find()) {
Matcher match = Pattern.compile("Sec-WebSocket-Key: (.*)").matcher(data);
match.find();
byte[] response = ("HTTP/1.1 101 Switching Protocols\r\n" + "Connection: Upgrade\r\n"
+ "Upgrade: websocket\r\n" + "Sec-WebSocket-Accept: "
+ DatatypeConverter.printBase64Binary(MessageDigest.getInstance("SHA-1")
.digest((match.group(1) + "258EAFA5-E914-47DA-95CA-C5AB0DC85B11").getBytes("UTF-8")))
+ "\r\n\r\n").getBytes("UTF-8");
out.write(response, 0, response.length);
log("Creating a new handler for this client...");
clienthandler = new Clients(socket, "Client " + clientCount, in, out);
Thread t = new Thread(clienthandler);
clientsArrayList.add(clienthandler);
log("Added to client list");
t.start();
clientCount++;
GUI.texttoclientlog();
} else {
log("Handshake failed");
}
}
}
public static ServerSocket getSs() {
return ss;
}
public static void setSs(ServerSocket ss) {
Server.ss = ss;
}
public void log(String logtext) {
System.out.println(logtext);
GUI.texttolog(logtext);
}
}
Clients.java
public class Clients implements Runnable {
private String name;
final InputStream in;
final OutputStream out;
Socket socket;
boolean isloggedin;
public Clients(Socket socket, String name, InputStream in, OutputStream out) {
this.out = out;
this.in = in;
this.name = name;
this.socket = socket;
this.isloggedin = true;
}
#Override
public void run() {
int received;
while (true) {
try {
received = in.read();
//how to decode??
System.out.println(received);
GUI.messagehandler(this.getName() + ": " + received);
} catch (IOException e) {
e.printStackTrace();
}
}
}
public String getName() {
return name;
}
}

Changing the program

uploading imageI am trying to make a program using http to upload a picture directly to the server from glass but i am not able to do it the code I have can only upload one picture that is already there but not the picture i have taken in the glass can someone please verify the code and tell me how to change it in such a way that i can upload the pictures i have taken directly
logcat:
06-10 15:07:43.813: D/GCM(718): GcmService start Intent { act=com.google.android.checkin.CHECKIN_COMPLETE flg=0x10 cmp=com.google.android.gms/.gcm.GcmService (has extras) } com.google.android.checkin.CHECKIN_COMPLETE
06-10 15:07:43.844: I/GlassUserEventService[42357a28](1071): Performance stats: [object: com.google.common.logging.GlassExtensionsNano$GlassUserEventPerformanceStats { batteryChargeWhenFullUah_: 604000 totalKernelMs_: 8848030 totalBytesSent_: 1218965 bitField0_: 16383 boardTemperatureMilliCentigrade_: 40970 frequencyScalingGovernor_: 0 availableMemoryKb_: 989140 isLowMemory_: false networkType_: 1 qpassedFractional_: 46921 qpassedInteger_: 17182 reportedSoc_: 99 batteryTemperatureMilliCentigrade_: 26800 batteryStateOfChargeUah_: 595000 totalMemoryKb_: 1475504 unknownFieldData: null cachedSize: -1}]
06-10 15:07:53.836: I/NativeAppVoiceMenuHelper(865): Installed packages changed; invalidating trigger cache
06-10 15:07:53.836: V/FormattingLoggers(865): TimingData [count=780, sinceCreation=14174171ms, spentLogging=272ms].
06-10 15:07:53.836: W/Searchables(498): No global search activity found
06-10 15:07:53.852: I/InputReader(498): Reconfiguring input devices. changes=0x00000010
06-10 15:07:53.860: V/GmsNetworkLocationProvi(1181): DISABLE
06-10 15:07:53.860: D/PackageBroadcastService(816): Received broadcast action=android.intent.action.PACKAGE_CHANGED and uri=com.google.android.gms
06-10 15:07:53.906: E/GCoreFlp(1181): Bound FusedProviderService with LocationManager
06-10 15:07:53.906: V/GmsNetworkLocationProvi(1181): ENABLE
06-10 15:07:53.914: V/GmsNetworkLocationProvi(1181): onSetRequest: ProviderRequestUnbundled, reportLocation is true and interval is 86400000
06-10 15:07:53.914: V/GmsNetworkLocationProvi(1181): SET-REQUEST
06-10 15:07:53.914: V/GmsNetworkLocationProvi(1181): in Handler: ProviderRequestUnbundled, reportLocation is true and interval is 86400000
06-10 15:07:56.149: W/BluetoothAdapter(773): getBluetoothService() called with no BluetoothManagerCallback
06-10 15:07:56.149: D/BluetoothSocket(773): connect(), SocketState: INIT, mPfd: {ParcelFileDescriptor: FileDescriptor[97]}
package com.morkout.nbsocial;
import java.io.BufferedInputStream;
import java.io.DataOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.OutputStreamWriter;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.ArrayList;
import java.util.List;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.util.EntityUtils;
import android.app.Activity;
import android.content.Intent;
import android.content.res.AssetManager;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.Environment;
import android.util.Log;
import android.widget.TextView;
public class HTTPRequestActivity extends Activity {
public final static String TAG = "HTTPRequestActivity";
TextView mTvInfo;
String mWhat;
HttpURLConnection mUrlConnection;
String mResult;
protected void onResume () {
super.onResume();
}
protected void onPause () {
super.onPause();
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
mTvInfo = (TextView) findViewById(R.id.info);
Intent intent = getIntent();
mWhat = intent.getStringExtra("WHAT");
Log.i(TAG, "WHAT="+mWhat);
mTvInfo.setText("Making HTTP "+ mWhat + " request...");
new HTTPRequest().execute();
}
// Async task class to make HTTP Get, Post and upload
private class HTTPRequest extends AsyncTask<Void, Void, Void> {
#Override
protected void onPreExecute() {
super.onPreExecute();
}
#Override
protected Void doInBackground(Void... arg0) {
try {
if (mWhat.equalsIgnoreCase("GET")) {
Log.w(TAG, "GET");
// get json via YouTube API
URL url = new URL("http://Google.com");
mUrlConnection = (HttpURLConnection) url.openConnection();
InputStream in = new BufferedInputStream(mUrlConnection.getInputStream());
int ch;
StringBuffer b = new StringBuffer();
while ((ch = in.read()) != -1) {
b.append((char) ch);
}
mResult = new String(b);
in.close();
}
else if (mWhat.equalsIgnoreCase("POST")) {
URL url = new URL("http://morkout.com/glass/posttest.php");
mUrlConnection = (HttpURLConnection) url.openConnection();
mUrlConnection.setRequestMethod("POST");
String urlParameters = "email=kandyala.komal-chowdary#stud.th-deg.de&name=komal chowdary&pwd=1234567&vcode=2014";
OutputStreamWriter writer = new OutputStreamWriter(mUrlConnection.getOutputStream());
writer.write(urlParameters);
writer.flush();
InputStream in = new BufferedInputStream(mUrlConnection.getInputStream());
int ch;
StringBuffer b = new StringBuffer();
while ((ch = in.read()) != -1) {
b.append((char) ch);
}
mResult = new String(b);
in.close();
writer.close();
}
else if (mWhat.equalsIgnoreCase("UPLOAD")) {
int serverResponseCode = 0;
File sourceFile = new File(copyAsset("marchmadness.png"));
DataOutputStream dos = null;
String lineEnd = "\r\n";
String twoHyphens = "--";
String boundary = "*****";
int bytesRead, bytesAvailable, bufferSize;
byte[] buffer;
int maxBufferSize = 1 * 1024 * 1024;
if (!sourceFile.isFile()) {
Log.e("uploadFile", "Source File not exist :" +sourceFile.getAbsolutePath());
}
else
{
FileInputStream fileInputStream = new FileInputStream(sourceFile);
URL url = new URL("http://www.morkout.com/glass/upload.php");
mUrlConnection = (HttpURLConnection) url.openConnection();
mUrlConnection.setRequestMethod("POST");
mUrlConnection.setRequestProperty("Content-Type", "multipart/form-data;boundary=" + boundary);
mUrlConnection.setRequestProperty("Filedata", sourceFile.getName());
dos = new DataOutputStream(mUrlConnection.getOutputStream());
dos.writeBytes(twoHyphens + boundary + lineEnd);
dos.writeBytes("Content-Disposition: form-data; name=Filedata;filename="+ sourceFile.getName() + lineEnd);
dos.writeBytes(lineEnd);
// create a buffer of maximum size
bytesAvailable = fileInputStream.available();
bufferSize = Math.min(bytesAvailable, maxBufferSize);
buffer = new byte[bufferSize];
// read file and write it into form...
bytesRead = fileInputStream.read(buffer, 0, bufferSize);
while (bytesRead > 0) {
dos.write(buffer, 0, bufferSize);
bytesAvailable = fileInputStream.available();
bufferSize = Math.min(bytesAvailable, maxBufferSize);
bytesRead = fileInputStream.read(buffer, 0, bufferSize);
}
// send multipart form data necesssary after file data...
dos.writeBytes(lineEnd);
dos.writeBytes(twoHyphens + boundary + twoHyphens + lineEnd);
// Responses from the server (code and message)
serverResponseCode = mUrlConnection.getResponseCode();
String serverResponseMessage = mUrlConnection.getResponseMessage();
Log.i("uploadFile", "HTTP Response is : "
+ serverResponseMessage + ": " + serverResponseCode);
if(serverResponseCode == 200) {
Log.v(TAG, "File Upload Completed.");
InputStream is = mUrlConnection.getInputStream();
int ch;
StringBuffer b = new StringBuffer();
while ((ch = is.read()) != -1) {
b.append((char) ch);
}
final String uploadedFilename = b.toString();
Log.v(TAG, "uploaded file at http://www.morkout.com/glass/uploads/" + uploadedFilename);
mResult = "uploaded file at http://www.morkout.com/glass/uploads/" + uploadedFilename;
is.close();
}
fileInputStream.close();
dos.close();
}
}
} catch (Exception e) {
Log.e(TAG, e.getMessage());
}
finally {
if (mUrlConnection != null)
mUrlConnection.disconnect();
}
return null;
}
String copyAsset(String filename) {
final String PATH = Environment.getExternalStorageDirectory().toString() + "/nbsocial/";
File dir = new File(PATH);
if (!dir.exists()) {
if (!dir.mkdirs()) {
Log.v(TAG, "ERROR: Creation of directory " + PATH + " on sdcard failed");
return null;
} else {
Log.v(TAG, "Created directory " + PATH + " on sdcard");
}
}
if (!(new File( PATH + filename).exists())) {
Log.v(TAG, "copying file " + filename);
try {
AssetManager assetManager = getAssets();
InputStream in = assetManager.open(filename);
OutputStream out = new FileOutputStream(PATH + filename);
// Transfer bytes from in to out
byte[] buf = new byte[1024];
int len;
while ((len = in.read(buf)) > 0) {
out.write(buf, 0, len);
}
in.close();
out.close();
} catch (IOException e) {
Log.e(TAG, "Was unable to copy " + filename + e.toString());
return null;
}
}
return PATH + filename;
}
#Override
protected void onPostExecute(Void result) {
super.onPostExecute(result);
Log.w(TAG, "onPostExecute");
mTvInfo.setText(mResult);
}
}
}

Mustache/handlebars templating: figure out context data structure from template html

In mustache/handlerbars or any templating system in js,
are there any tools to gather all the variables that a template refers to?
for example, given input
templateHTML:
<div class="{{divclass}}">
{#item}}
<h1>{{title}}</h1>
<span>{{text}}</span>
{{/item}}
</div>
would return
{
divclass: "",
item: {
title: "",
text: ""
}
}
when used like MyTemplateTool.getTemplateData(templateHTML)
I tried googling around and checking out handlebars docs but could not find anything suitable
I believe it's just .. See the related docs on paths. Example:
{{#srcs}}
<script src="{{.}}"></script>
{{/srcs}}
I had the same in mind and I thought it was worth while writing something so here you go:
import java.io.IOException;
import java.nio.charset.Charset;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.util.LinkedHashMap;
import java.util.Map;
import java.util.TreeMap;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class MustacheSchemaBuilder
{
static String javaIdentifierRegExp = "[a-zA-Z_$0-9]+";
static String tab = " ";
static Format format = Format.java;
enum Format {
json,
java,
;
}
enum TagType {
variable("\\{\\{\\s*" + javaIdentifierRegExp + "\\s*\\}\\}"),
escapedVariable("\\{\\{\\{\\s*" + javaIdentifierRegExp + "\\s*\\}\\}\\}"),
sectionStart("\\{\\{#\\s*" + javaIdentifierRegExp + "\\s*\\}\\}"),
invertedSectionStart("\\{\\{\\^\\s*" + javaIdentifierRegExp + "\\s*\\}\\}"),
sectionEnd("\\{\\{/\\s*" + javaIdentifierRegExp + "\\s*\\}\\}"),
//partial("\\{\\{>\\s*" + javaIdentifierRegExp + "\\s*\\}\\}"),
// no support for set delimiters or partials
;
Pattern pat;
private TagType(String aRegExp) {
pat = Pattern.compile(aRegExp);
}
public Pattern getPattern() { return pat; };
}
class Tag{
public TagType type;
public String identifier;
Tag(TagType aType, String aIdentifier) { type = aType; identifier = aIdentifier;}
public String toString() { return type.name() + " : " + identifier; }
#Override
public boolean equals(Object aOther) {
if(!(aOther instanceof Tag)) return false;
Tag ot = (Tag) aOther;
return ot.type.equals(this.type) && ot.identifier.equals(this.identifier);
}
#Override
public int hashCode() {return identifier.hashCode();}
}
class Node {
public Section parent;
public Tag tag;
Node(Section aParent, Tag aTag){parent = aParent; tag = aTag; if(parent != null) parent.children.put(tag, this);}
#Override
public int hashCode() {return tag.hashCode();}
public int depth() {
int depth = 0;
Node currentNode = this;
while(currentNode.parent != null) {
depth++;
currentNode = currentNode.parent;
}
return depth;
}
#Override
public String toString() {
StringBuilder sb = new StringBuilder();
for(int i = 0; i < this.depth(); i++) sb.append(tab);
switch(format) {
case java:
sb.append("public Object ").append(tag.identifier).append(";\n");
break;
case json:
default:
sb.append(tag.identifier).append(": {},\n");
}
return sb.toString();
}
}
class Section extends Node{
public Map<Tag, Node> children = new LinkedHashMap();
Section(Section aParent, Tag aTag) { super(aParent, aTag); };
#Override
public String toString() {
StringBuilder sb = new StringBuilder();
for(int i = 0; i < this.depth(); i++) sb.append(tab);
switch(format) {
case java:
sb.append("public Object ").append(tag.identifier).append(" = new Object() {\n");
for(Node child : this.children.values()) sb.append(child);
for(int i = 0; i < this.depth(); i++) sb.append(tab);
sb.append("};\n");
break;
case json:
default:
sb.append(tag.identifier).append(": {\n");
for(Node child : this.children.values()) sb.append(child);
for(int i = 0; i < this.depth(); i++) sb.append(tab);
sb.append("},\n");
}
return sb.toString();
}
}
class MustacheSchemaBuildException extends Exception {
private static final long serialVersionUID = 1L;
MustacheSchemaBuildException(String aMessage) {super(aMessage);}
}
Section rootSection;
public MustacheSchemaBuilder(String aContents) throws Exception
{
TreeMap<Integer, Tag> tagMap = new TreeMap();
for(TagType type : TagType.values()) {
populateMap(tagMap, type, aContents);
}
System.out.println(tagMap);
rootSection = new Section(null, new Tag(TagType.sectionStart, "$root$"));
Section currentSection = rootSection;
for(Tag tag : tagMap.values()) {
if(currentSection.tag.type == TagType.invertedSectionStart) {
if(tag.type == TagType.sectionEnd) {
if(!tag.identifier.equals(currentSection.tag.identifier))
throw new MustacheSchemaBuildException("The end tag: " + tag.identifier + " doesn't match the expected start tag: " + currentSection.tag.identifier + "\n\n" + rootSection);
currentSection = currentSection.parent;
}
continue;
}
switch(tag.type)
{
case variable:
if(!currentSection.children.containsKey(tag))
new Node(currentSection, tag);
break;
case sectionStart:
Tag invertedSectionStartTag = new Tag(TagType.invertedSectionStart, tag.identifier);
if(!(currentSection.children.containsKey(tag) || currentSection.children.containsKey(invertedSectionStartTag)))
new Section(currentSection, tag);
currentSection = (Section)currentSection.children.get(tag);
break;
case invertedSectionStart:
Tag sectionStartTag = new Tag(TagType.sectionStart, tag.identifier);
if(!(currentSection.children.containsKey(tag) || currentSection.children.containsKey(sectionStartTag)))
new Section(currentSection, tag);
currentSection = (Section)currentSection.children.get(sectionStartTag);
break;
case sectionEnd:
if(!tag.identifier.equals(currentSection.tag.identifier))
throw new MustacheSchemaBuildException("The end tag: " + tag.identifier + " doesn't match the expected start tag: " + currentSection.tag.identifier + "\n\n" + rootSection);
currentSection = currentSection.parent;
break;
default:
}
}
}
public void build() {
System.out.println(rootSection);
}
public static void main(String[] args) throws Exception
{
String contents;
try {
contents = readFile(args[0], Charset.defaultCharset());
}catch(Exception e)
{
System.out.println("Unable to open file!");
throw e;
}
MustacheSchemaBuilder builder = new MustacheSchemaBuilder(contents);
builder.build();
}
void populateMap(Map<Integer, Tag> map, TagType aType, String aContents) {
Matcher m = aType.getPattern().matcher(aContents);
while(m.find()) {
int start = m.start() + 3;
if(aType == TagType.variable) start = m.start() + 2;
map.put(m.start(), new Tag(aType, aContents.substring(start, m.end() - 2).trim()));
}
}
static String readFile(String path, Charset encoding) throws IOException
{
byte[] encoded = Files.readAllBytes(Paths.get(path));
return new String(encoded, encoding);
}
}
Give the template file path at the command line - you need java 7 or higher to open the file, or you can just rewrite the readFile - method. You can produce a json or java 'schema' by changing the format at the top of the class. The 'schema' gets written to stdout, you can copy it from there and paste it into where you need it. Hope this helps. Ah! This doesn't support partials or set delimiters, but if you get round to writing support ping it to me as I might want it :)

Categories

Resources