Marker.remove() is not working in Google map? - javascript

In my application I have two set of marker when I click a marker another marker should be removed.But marker.remove() is not working, have checked whether the marker!=null then am removing the marker but the marker is not removed please help me.
public class MapFragment extends Fragment implements LocationListener
{
private static final String LOG_TAG = "ExampleApp";
private MapView mMapView;
private GoogleMap mMap;
private Bundle mBundle;
private static final String SERVICE_URL = "http://203.187.247.199/primevts/vtsservice.svc/data";
JSONObject json = null;
JSONObject jsonobject = null;
JSONObject jsonobject1 =null;
JSONObject jsonobject2 =null;
JSONObject ja = null;
JSONArray jsonarray = null;
JSONArray jsonarray1 = null;
JSONArray jsonarray2 = null;
ProgressDialog mProgressDialog;
ArrayList<HashMap<String, String>> arraylist1;
ArrayList<HashMap<String, String>> arraylist11;
ArrayList<HashMap<String, String>> arraylist12;
ArrayList<HashMap<String, String>> arraylist;
List<Marker> markerList = new ArrayList<Marker>();
private Timer timer;
static String LONG = "Long";
static String LAT = "Lat";
ArrayList<String> ct;
public double latt = 0;
public double lng = 0;
public ArrayList<Integer> dLat;
private AlarmManager alarmMgr;
private PendingIntent alarmIntent;
private Handler handler;
public Marker marker;
Marker stop;
String RegistrationNo="";
LatLng destination,source,destination2,center;
Polyline polylin;
String ime1,destname,routeid;
GMapV2GetRouteDirection md;
private HashMap<String, Marker> mMarkers = new HashMap<>();
int value=1;
// LatLngBounds values ;
double latitude, longitude,destlat,destlong,sourcelat,sourcelong,destlat2,destlong2;
String ime,reg,regi;
Geocoder geocoder;
List<Address> addresses;
CircleOptions circleOptions;
Circle circle;
// LatLng val;
float[] distance = new float[2];
static HashMap<String, String> datas;
static HashMap<String, String> map;
String[] latlngvalues;
// LocationManager locman;
Context context;
View rootView;
ImageView imageView1;
TextView Address;
public MapFragment() {
}
#Override
public View onCreateView(final LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
rootView = inflater.inflate(R.layout.fragment_layout_one, container, false);
MapsInitializer.initialize(getActivity());
mMapView = (MapView)rootView.findViewById(R.id.mapView);
Address=(TextView)rootView.findViewById(R.id.adressText);
//imageView1=(ImageView) rootView.findViewById(R.id.imageView1);
mMapView.onCreate(mBundle);
MapsInitializer.initialize(getActivity());
if (android.os.Build.VERSION.SDK_INT > 9) {
StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder()
.permitAll().build();
StrictMode.setThreadPolicy(policy);
}
new DownloadJSON().execute();
setUpMapIfNeeded(rootView);
new DestinationJSON().execute();
mMap.setInfoWindowAdapter(new InfoWindowAdapter() {
#Override
public View getInfoContents(Marker marker) {
// TODO Auto-generated method stub
return null;
}
#Override
public View getInfoWindow(Marker marker) {
// TODO Auto-generated method stub
View v = getActivity().getLayoutInflater().inflate(R.layout.info_window_layout, null);
TextView markerLabel = (TextView)v.findViewById(R.id.ime);
TextView destiname=(TextView)v.findViewById(R.id.destname);
TextView route=(TextView)v.findViewById(R.id.routeid);
markerLabel.setText(regi);
destiname.setText(destname);
route.setText(routeid);
Log.e("imeid", ""+ime1);
return v;
}
});
/* handler = new Handler();
handler.postDelayed(new Runnable() {
#Override
public void run() {
// TODO Auto-generated method stub
new DownloadJSON().execute();
setUpMapIfNeeded(rootView);
Toast.makeText(getActivity(), "Data Updated!!!! ", Toast.LENGTH_SHORT).show();
Log.e("Data in Log", "");
}
}, 1000);
*/
final Handler handler = new Handler();
timer = new Timer();
TimerTask doAsynchronousTask = new TimerTask() {
#Override
public void run() {
handler.post(new Runnable() {
public void run() {
//mMap.clear();
//Toast.makeText(getActivity(), "Data Updated!!!! ", Toast.LENGTH_SHORT).show();
new DownloadJSON().execute();
setUpMapIfNeeded(rootView);
}
});
}
};
timer.schedule(doAsynchronousTask, 20000, 20000);
/*LocationManager locman = (LocationManager)getActivity().getSystemService(Context.LOCATION_SERVICE);
//locman.requestLocationUpdates(minTime, minDistance, criteria, intent);
locman.requestLocationUpdates(LocationManager.GPS_PROVIDER, 1000, 10, this);*/
return rootView;
}
private void setUpMapIfNeeded(View inflatedView) {
if (mMap == null) {
mMap = ((MapView) inflatedView.findViewById(R.id.mapView)).getMap();
mMap.setMyLocationEnabled(true);
Location myLocation = mMap.getMyLocation();
if (mMap != null) {
//mMap.clear();
mMap.setOnCameraChangeListener(new OnCameraChangeListener() {
#Override
public void onCameraChange(final CameraPosition arg0) {
mMap.setOnMapLoadedCallback(new GoogleMap.OnMapLoadedCallback() {
#Override
public void onMapLoaded() {
LatLng latLng= mMap.getCameraPosition().target;
double lat = latLng.latitude;
double lng = latLng.longitude;
Log.e("lati",""+lat);
Log.e("longi",""+lng);
Log.d("TAG", latLng.toString());
//mMap.clear();
if(circle!=null){
circle.remove();
//mMap.clear();
}
circleOptions = new CircleOptions();
circleOptions.center(latLng);
//circleOptions.fillColor(Color.TRANSPARENT);
circleOptions.radius(10000);
circleOptions.strokeColor(Color.TRANSPARENT);
circle = mMap.addCircle(circleOptions);
Log.e("",""+circle);
center = mMap.getCameraPosition().target;
new GetLocationAsync(center.latitude, center.longitude).execute();
/* geocoder = new Geocoder(getActivity(), Locale.getDefault());
try {
addresses = geocoder.getFromLocation(lat, lng, 1);
String address = addresses.get(0).getAddressLine(0); // If any additional address line present than only, check with max available address lines by getMaxAddressLineIndex()
Log.e("address",""+address);
String city = addresses.get(0).getLocality();
Log.e("city",""+city);
String state = addresses.get(0).getAdminArea();
Log.e("state",""+state);
String country = addresses.get(0).getCountryName();
Log.e("contry",""+country);
String postalCode = addresses.get(0).getPostalCode();
Log.e("postalcode",""+postalCode);
String knownName = addresses.get(0).getFeatureName();
Log.e("knownName",""+knownName);
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} // Here 1 represent max location result to returned, by documents it recommended 1 to 5
//Toast.makeText(this, latLng.toString(), Toast.LENGTH_LONG).show();
}*/
}
});
}
});
mMap.setOnMarkerClickListener(new OnMarkerClickListener() {
#Override
public boolean onMarkerClick(Marker arg0) {
// TODO Auto-generated method stub
if(stop!=null){
stop.remove();
}
arg0.showInfoWindow();
regi=arg0.getTitle().toString();
Log.e("aaa", ""+regi);
JSONPost jsonpost= new JSONPost();
ja=jsonpost.datewise(regi);
Log.e("Home_details..", "" + ja);
// new DownloadJSON2().execute();
try
{
arraylist11 = new ArrayList<HashMap<String, String>>();
arraylist12 = new ArrayList<HashMap<String, String>>();
jsonarray = ja.getJSONArray("Routeinbus");
for (int i = 0; i <jsonarray.length(); i++) {
HashMap<String, String> map = new HashMap<String, String>();
json = jsonarray.getJSONObject(i);
Log.e("G>>>>>>>>>>>", "" + json);
// Retrive JSON Objects
// map.put("flatID", jsonobject.getString("flatID"));
map.put("FromLat", json.getString("FromLat"));
map.put("FromLong", json.getString("FromLong"));
sourcelat = json.getDouble("FromLat");
sourcelong=json.getDouble("FromLong");
source=new LatLng(sourcelat, sourcelong);
map.put("Fromaddress", json.getString("Fromaddress"));
map.put("ToLat", json.getString("ToLat"));
map.put("ToLong", json.getString("ToLong"));
routeid=json.getString("RouteID");
destname=json.getString("Toaddress");
destlat2=json.getDouble("ToLat");
destlong2=json.getDouble("ToLong");
destination2=new LatLng(destlat2, destlong2);
jsonarray1 = json.getJSONArray("Routes");
Log.d("Hbbbbbbbbbbbbbbb", "" + jsonarray1);
for (int j = 0; j <jsonarray1.length(); j++) {
jsonobject1 = jsonarray1.getJSONObject(j);
jsonarray2=jsonobject1.getJSONArray("stages");
Log.d("jsonarray2", "" + jsonarray2);
for(int k=0;k<jsonarray2.length();k++)
{
jsonobject2 =jsonarray2.getJSONObject(k);
HashMap<String, String> map1 = new HashMap<String, String>();
map1.put("Lat",jsonobject2.getString("Lat"));
Log.d("Hbbbbbbbbbbbbbbb", "" + jsonobject2.getString("Lat"));
map1.put("Long",jsonobject2.getString("Long"));
map1.put("StopName", jsonobject2.getString("StopName"));
Log.d("Hbbbbbbbbbbbbbbb", "" + jsonobject2.getString("Long"));
// map1.put("LiveLongitude",jsonobject1.getString("LiveLongitude"));
// Log.d("Hbbbbbbbbbbbbbbb", "" + jsonobject1.getString("LiveLongitude"));
arraylist12.add(map1);
Log.e("arraylist12", ""+arraylist12);
//marker=mMap.addMarker(new MarkerOptions().position(destination2).icon(BitmapDescriptorFactory .fromResource(R.drawable.bustour)));
for (int m = 0; m < arraylist12.size(); m++)
{
final LatLng stopposition = new LatLng(Double .parseDouble(arraylist12.get(m).get("Lat")),Double.parseDouble(arraylist12.get(m).get("Long")));
Log.e("position", ""+stopposition);
String stopname = arraylist12.get(m).get("StopName");
Log.e("markcheck",""+stopname);
final MarkerOptions options = new MarkerOptions().position(stopposition);
//mMap.addMarker(options);
stop=mMap.addMarker(options.icon(BitmapDescriptorFactory .fromResource(R.drawable.bustour)).title(stopname));
}
}
}
arraylist11.add(map);
Log.e("arraylist11",""+arraylist11);
}
}catch (Exception e) {
String result = "Error";
}
return false;
}
});

Related

Gridview ,open new activity on item click

Clicking on the items here is supposed to go to the specific activity, but as I have given the if else statement, instead of going to the specific activity, the homework-2 activity goes as soon as the apps run. And after pressing back three times the main activity comes again. When I press on specific item on menu, supposed to go to the next activity, but nothing happens.
public class MainActivity extends AppCompatActivity {
GridView grid_view;
ArrayList <HashMap<String,String>>arrayList = new ArrayList<>();
HashMap<String,String>hashMap = new HashMap<>();
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
grid_view = findViewById(R.id.grid_view);
creatTable ();
myAdapter myAdapter = new myAdapter();
grid_view.setAdapter(myAdapter);
}
private class myAdapter extends BaseAdapter {
#Override
public int getCount() {
return arrayList.size();
}
#Override
public Object getItem(int position) {
return null;
}
#Override
public long getItemId(int position) {
return 0;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
LayoutInflater layoutInflater = (LayoutInflater) getSystemService(Context.LAYOUT_INFLATER_SERVICE);
View myView = layoutInflater.inflate(R.layout.item_lay,parent,false);
TextView item_cat = myView.findViewById(R.id.item_cat);
TextView item_title = myView.findViewById(R.id.item_title);
HashMap<String,String>hashMap = arrayList.get(position);
Random rnd = new Random();
int color = Color.argb(255, rnd.nextInt(256), rnd.nextInt(256), rnd.nextInt(256));
item_cat.setBackgroundColor(color);
Random rnd1 = new Random();
int color1 = Color.argb(255, rnd1.nextInt(256), rnd1.nextInt(256), rnd1.nextInt(256));
item_title.setBackgroundColor(color1);
String cat = hashMap.get("CAt");
String title = hashMap.get("Title");
item_cat.setText(cat);
item_title.setText(title);
if (cat.contains("HomeWork_207")){
startActivity(new Intent(MainActivity.this,HomeWork_One.class));
}else if (cat.contains("HomeWork_214.1")){
startActivity(new Intent(MainActivity.this,HomeWork_Two.class));
}
return myView;
}
}
private void creatTable() {
hashMap = new HashMap<>();
hashMap.put("CAt","HomeWork_207");
hashMap.put("Title","bmi cal");
arrayList.add(hashMap);
hashMap = new HashMap<>();
hashMap.put("CAt","HomeWork_214.1");
hashMap.put("Title","Divisible");
arrayList.add(hashMap);
hashMap = new HashMap<>();
hashMap.put("CAt","HomeWork 214.2");
hashMap.put("Title","Leap year");
arrayList.add(hashMap);
hashMap = new HashMap<>();
hashMap.put("CAt","HomeWork 214.3");
hashMap.put("Title","Week");
arrayList.add(hashMap);
hashMap = new HashMap<>();
hashMap.put("CAt","HomeWork 214.4");
hashMap.put("Title","Exam Grade");
arrayList.add(hashMap);
hashMap = new HashMap<>();
hashMap.put("CAt","HomeWork 214.5");
hashMap.put("Title","Bill");
arrayList.add(hashMap);
hashMap = new HashMap<>();
hashMap.put("CAt","HomeWork 232.1");
hashMap.put("Title","নামতা");
arrayList.add(hashMap);
hashMap = new HashMap<>();
hashMap.put("CAt","HomeWork 232.2");
hashMap.put("Title","E.No & sum");
arrayList.add(hashMap);
hashMap = new HashMap<>();
hashMap.put("CAt","HomeWork 232.3");
hashMap.put("Title","E.No & sum");
arrayList.add(hashMap);
hashMap = new HashMap<>();
hashMap.put("CAt","HomeWork 232.3");
hashMap.put("Title","N.terms");
arrayList.add(hashMap);
}
}
I am trying this , way but problem is not solved yet.

distance and duration between two point selected from google autocomplete using latitude and longitude in androidstudio

I am trying to get the distance between the points and because the places has no routes names it won't work.
This is the code that I am using
private void getPrice(String mLocation, String mDestination) {
String requestUrl= null;
try {
requestUrl = "https://maps.googleapis.com/maps/api/directions/json?"
+ "mode=driving&"
+"transit_routing_preference=less_driving&"
+ "origin="+mLocation+"&"
+"destination="+mDestination+"&"
+"key="+getResources().getString(R.string.google_browser_key);
Log.e("LINK",requestUrl);
mService.getPath(requestUrl).enqueue(new Callback<String>() {
#Override public void onResponse(Call<String> call, Response<String> response) {
try {
JSONObject jsonObject = new JSONObject(response.body().toString());
JSONArray routes = jsonObject.getJSONArray("routes");
JSONObject object = routes.getJSONObject(0);
JSONArray legs = object.getJSONArray("legs");
JSONObject legsObject = legs.getJSONObject(0);
JSONObject distance = legsObject.getJSONObject("distance");
String distance_text = distance.getString("text");
Double distance_value = Double.parseDouble(distance_text.replaceAll("[^0-9\\\\.]+",""));
JSONObject time = legsObject.getJSONObject("duration");
String time_text = time.getString("text");
Integer time_value = Integer.parseInt(time_text.replaceAll("\\D+",""));
String final_calculate = String.format("%s + %s = $%.2f",distance_text,time_text,
Common.getPrice(distance_value,time_value));
txtCalculate.setText(final_calculate);
} catch (JSONException e) {
e.printStackTrace();
}
}
#Override
public void onFailure(Call<String> call, Throwable t) {
Log.e("ERROR",t.getMessage());
}
});
}
catch (Exception ex) {
ex.printStackTrace();
}
}

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;
}
}

file download angularjs and servlets

I have an image stored in a database table, with primary key for a particular number. That image below the database to a folder of the java project by means of a servlet.
So far, so good.
My problem is that I need to download that image to the user and I can not do it.
My steps are as follows:
JSP:
$scope.downloadFile = function(){
var tkAct = $scope.ticketActual.tknum;
var param = {
nroTk: tkAct
};
var res = $http.post($scope.testHost +"/downloadAttachment",JSON.stringify(param));
});
res.error(function(data, status, headers, config) {
alert("failure message: " + JSON.stringify({data: data}));
});
}
SERVLET:
#WebServlet("/downloadAttachment")
public class downloadAttachment extends HttpServlet {
// size of byte buffer to send file
private static final int BUFFER_SIZE = 4096;
private final int BYTES_DOWNLOAD=1024;
public static final String FILE_SEPARATOR = System.getProperty("file.separator");
#Override
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
doPost(request, response);
}
#Override
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
HttpSession sess = request.getSession();
Controller ctrl = Controller.get();
ServletContext sc = getServletContext();
//int nroTicket=-1;
//nroTicket = 104;
System.out.println(request.getParameter("NroTk"));
System.out.println(request.getAttribute("NroTk"));
JSONObject joParam = getParametrosJo(request);
Long lNroTk = (Long) joParam.get("nroTk");
int nroTicket = lNroTk.intValue();
Vector<String> vNamesFile = ctrl.getFile(nroTicket,sc.getRealPath("/downloads"));
if(vNamesFile.size()==1){
String archivo = vNamesFile.get(0);
File downloadFile = new File(archivo);
String nombreFile = getNombreFileEnvio(nroTicket,downloadFile.getName());
// if you want to use a relative path to context root:
String relativePath = getServletContext().getRealPath("/downloads/");
System.out.println("relativePath = " + relativePath);
// obtains ServletContext
ServletContext context = getServletContext();
String mimeType = context.getMimeType(nombreFile);
if (mimeType == null) {
mimeType = "application/octet-stream";
}
response.setContentType(mimeType);
response.setHeader("Content-Disposition","attachment;filename="+nombreFile);
System.out.println("Obteniendo el Stream...");
System.out.println("nombre del file es: "+nombreFile);
InputStream is = sc.getResourceAsStream("/downloads/" + downloadFile.getName());
int read=0;
byte[] bytes = new byte[BYTES_DOWNLOAD];
ServletOutputStream out;
out = response.getOutputStream();
FileInputStream fin = new FileInputStream(relativePath+downloadFile.getName());
BufferedInputStream bin = new BufferedInputStream(fin);
BufferedOutputStream bout = new BufferedOutputStream(out);
int ch =0; ;
while((ch=bin.read())!=-1)
{
bout.write(ch);
}
bin.close();
fin.close();
bout.close();
out.close();
}else{
byte[] zip = zipFiles(getServletContext().getRealPath("/downloads/"),vNamesFile, 95);
ServletOutputStream sos = response.getOutputStream();
response.setContentType("application/zip");
response.setHeader("Content-Disposition", "attachment; filename=AdjuntosTicket95" + ".ZIP");
sos.write(zip);
sos.flush();
}
}
private JSONObject getParametrosJo(HttpServletRequest request) throws IOException{
StringBuilder buffer = new StringBuilder();
BufferedReader joParam = request.getReader();
String texto="";
String str = null;
while ((str = joParam.readLine()) != null) {
buffer.append(str);
//texto+=str;
}
texto = buffer.toString();
System.out.println(texto);
if(!texto.equalsIgnoreCase("")){
JSONObject obj = JSONObject.parse(texto);
return obj;
}else{
return null;
}
}
private byte[] zipFiles(String path, Vector<String> vNamesFile, int nroTk) throws IOException {
ByteArrayOutputStream baos = new ByteArrayOutputStream();
ZipOutputStream zos = new ZipOutputStream(baos);
byte bytes[] = new byte[2048];
for (String fileName : vNamesFile) {
FileInputStream fis = new FileInputStream(fileName);
BufferedInputStream bis = new BufferedInputStream(fis);
zos.putNextEntry(new ZipEntry(getNombreFileEnvio(nroTk,fileName)));
int bytesRead;
while ((bytesRead = bis.read(bytes)) != -1) {
zos.write(bytes, 0, bytesRead);
}
zos.closeEntry();
bis.close();
fis.close();
}
zos.flush();
baos.flush();
zos.close();
baos.close();
return baos.toByteArray();
}
private String getNombreFileEnvio(int nroTk, String nombreEnFS){
String[] aNombreFile = nombreEnFS.split("%");
String nombreFile = aNombreFile[1];
return nombreFile;
}
}
How do I recover that image from the database to the folder / downloads / and deliver it to the user?
Thank you

Java Program TextFile Issue

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;
}
}

Categories

Resources