Java tutorial
package com.app.server.util; /*Copyright 2013 - 2015, Arun_Soundararajan (arun_srajan_2007@yahoo.com).and/or its affiliates. All files in this repository or distribution are licensed under the Apache License, Version 2.0 (the "License"); you may not use any files in this repository or distribution 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.*/ import java.io.DataInputStream; import java.io.DataOutputStream; import java.io.File; import java.io.FileInputStream; import java.io.FileNotFoundException; import java.io.FileOutputStream; import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; import java.net.InetAddress; import java.nio.file.Files; import java.nio.file.Paths; import java.util.LinkedList; import java.util.List; import java.util.Vector; import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors; import java.util.concurrent.ScheduledExecutorService; import java.util.concurrent.TimeUnit; import javax.management.MBeanServer; import javax.management.ObjectName; import org.apache.commons.io.FilenameUtils; import org.apache.log4j.Logger; import org.jgroups.JChannel; import org.jgroups.Message; import org.jgroups.ReceiverAdapter; import org.jgroups.View; import org.jgroups.Message.Flag; import org.jgroups.protocols.UDP; import org.jgroups.protocols.pbcast.NAKACK; import org.jgroups.stack.ProtocolStack; import org.jgroups.util.Util; import com.app.server.ServerConfig; import static java.nio.file.StandardCopyOption.*; public class FarmWarFileTransfer extends ReceiverAdapter implements FarmWarFileTransferMBean { JChannel channel; FileOutputStream fout; final List<String> state = new LinkedList<String>(); String transfer = "Transfer:"; String transferEnd = "TransferEnd:"; String address; ObjectName objName; Vector serviceList; ServerConfig serverConfig; MBeanServer mbeanServer; ScheduledExecutorService exec; String isdeployer; Logger log = Logger.getLogger(FarmWarFileTransfer.class); public void init(Vector serviceList, ServerConfig serverConfig, MBeanServer mbeanServer) { this.serviceList = serviceList; this.serverConfig = serverConfig; this.mbeanServer = mbeanServer; } public void viewAccepted(View new_view) { log.info("** view: " + new_view); } public void receive(Message msg) { //String line=msg.getSrc() + ": " + msg.getObject(); //log.info(msg.getSrc().toString()+" "+address); //if(!msg.getSrc().toString().equals(address)){ byte[] buffer = msg.getBuffer(); String str = new String(buffer); if (str.startsWith(transfer)) { fout = null; try { fout = new FileOutputStream( serverConfig.getDeploydirectory() + "/" + str.substring(transfer.length())); } catch (Exception e) { log.error("Error in creating file " + (serverConfig.getDeploydirectory() + "/" + str.substring(transfer.length())), e); // TODO Auto-generated catch block //e.printStackTrace(); } } else if (str.startsWith(transferEnd)) { try { log.info("file closed"); fout.close(); //Files.move(Paths.get(farmwarDir, str.substring(transferEnd.length())),Paths.get(deployDir, str.substring(transferEnd.length())),REPLACE_EXISTING); } catch (Exception e) { log.error("Error in closing file " + (serverConfig.getDeploydirectory() + "/" + str.substring(transfer.length())), e); //e.printStackTrace(); } } else { try { //log.info("writing buffer"+buffer.length+" "+msg.getObject()); fout.write(buffer); } catch (Exception e) { log.error("Error in writing content to the file " + (serverConfig.getDeploydirectory() + "/" + str.substring(transfer.length())), e); // TODO Auto-generated catch block //e.printStackTrace(); } } //} /*log.info(line); synchronized(state) { state.add(line); }*/ } public void getState(OutputStream output) throws Exception { synchronized (state) { Util.objectToStream(state, new DataOutputStream(output)); } } public void setState(InputStream input) throws Exception { List<String> list = (List<String>) Util.objectFromStream(new DataInputStream(input)); synchronized (state) { state.clear(); state.addAll(list); } //log.info("received state (" + list.size() + " messages in chat history):"); for (String str : list) { log.info(str); } } public void sendFilesToClusterServer(File file) { try { if (file.isFile() && file.exists()) { int len; byte[] bt = new byte[1048576]; Message msg = new Message(); msg.setFlag(Flag.RSVP); msg.setBuffer(("Transfer:" + file.getName()).getBytes()); channel.send(msg); FileInputStream str = new FileInputStream(file.getAbsolutePath()); int count = 0; while ((len = str.read(bt)) > 0) { msg = new Message(); msg.setFlag(Flag.RSVP); //msg.setObject(""+count++); msg.setBuffer(bt, 0, len); channel.send(msg); } msg = new Message(); msg.setBuffer(("TransferEnd:" + file.getName()).getBytes()); msg.setFlag(Flag.RSVP); channel.send(msg); str.close(); log.info(file.getName() + " transferred"); } } catch (Exception ex) { log.info("File could not be transferred " + file.getName(), ex); } } public void start() { try { channel = new JChannel(); channel.setReceiver(this); /*ProtocolStack stack=new ProtocolStack(); // 2 channel.setProtocolStack(stack); stack.addProtocol(new UDP().setValue("bind_addr", InetAddress.getByName("0.0.0.0"))); //stack.addProtocol(new NAKACK()); stack.init();*/ channel.connect(serverConfig.getClustergroup()); address = channel.getAddress().toString(); channel.getState(null, 10000); // channel.close(); } catch (Exception ex) { log.info("Could not able to create jgroups Channel for the cluster group " + serverConfig.getClustergroup(), ex); } exec = Executors.newSingleThreadScheduledExecutor(); FarmWarDirWatcher task = new FarmWarDirWatcher(serverConfig.getFarmWarDir(), this); exec.scheduleAtFixedRate(task, 0, 1000, TimeUnit.MILLISECONDS); serviceList.add(objName.getCanonicalName()); } public void setObjectName(ObjectName objName) { this.objName = objName; } public ObjectName getObjectName() { return this.objName; } public String getDeployer() { return this.isdeployer; } public void setDeployer(String isdeployer) { this.isdeployer = isdeployer; } public void stop() { exec.shutdown(); serviceList.remove(objName.getCanonicalName()); log.info("stopped"); } public void destroy() { log.info("destroyed"); } }