private void onOK() { try { InputStream in = new FileInputStream(inputFile); if (outputFile == null) { outputFile = new File(inputFile.getAbsolutePath() + "_"); } OutputStream out = new FileOutputStream(outputFile); ANSIUnicodeConverter converter = new ANSIUnicodeConverter(); converter.setDirection(ANSIUnicodeConverter.ANSI2UNICODE); StringBuffer output = new StringBuffer(); final int BUFFER_SIZE = 1024 * 1024; // 1M byte[] buffer = new byte[BUFFER_SIZE]; int currentPosition = 0; while (in.available() != 0) { int currentBufferSize = BUFFER_SIZE; if (in.available() < BUFFER_SIZE) { currentBufferSize = in.available(); } in.read(buffer, currentPosition, currentBufferSize); currentBufferSize = currentBufferSize + currentBufferSize; converter.setInput(new String(buffer)); out.write(converter.convert().getBytes()); } in.close(); out.close(); } catch (Exception e) { e .printStackTrace(); // To change body of catch statement use File | Settings | File // Templates. } }
public final void writeASCII(String s) throws IOException { if (Thread.currentThread().isInterrupted()) throw new InterruptedIOException(); OutputStream os = getOutputStream(); synchronized (os) { if (Defines.DEBUG && CAT.isDebugEnabled()) CAT.debug("C: " + s); os.write(s.getBytes("ASCII")); os.write((byte) 13); os.write((byte) 10); os.flush(); } }
/** * UTF byte count is appended to the asciiPrefix, then UTF bytes are appended to the result; the * final result is sent. */ public final void writeMSG(String asciiPrefix, String msgBody) throws IOException { if (Thread.currentThread().isInterrupted()) throw new InterruptedIOException(); OutputStream os = getOutputStream(); synchronized (os) { byte[] utfBytes = msgBody.getBytes("UTF-8"); asciiPrefix = asciiPrefix + ' ' + utfBytes.length; if (Defines.DEBUG && CAT.isDebugEnabled()) CAT.debug("C: " + asciiPrefix + "\r\n" + msgBody); os.write(asciiPrefix.getBytes("ASCII")); os.write((byte) 13); os.write((byte) 10); os.write(utfBytes); os.flush(); } }
/** * ** Writes the specified byte array to the specified socket's output stream ** @param socket The * socket which's output stream to write to ** @param b The byte array to write to the socket * output stream ** @throws IOException if an error occurs */ protected static void socketWriteBytes(Socket socket, byte b[]) throws IOException { if ((socket != null) && (b != null)) { OutputStream output = socket.getOutputStream(); output.write(b); output.flush(); } }
public void run() { int count = -1; byte[] buffer = new byte[DefaultPhonePCMBlockSize]; try { pickup.acquire(); // wait until call gets picked up if (isrunning) { stopPlaying(); // stop parents player thread activate(); do { blocker.acquire(); // wait until call becomes active; if (isrunning) { try { // give player time to finish and phone output some time to send new Semaphore(0, true).tryAcquire(500, TimeUnit.MILLISECONDS); } catch (InterruptedException ie) { } microphone.flush(); while (isrunning && active) { count = microphone.read(buffer, 0, DefaultPhonePCMBlockSize); if (count == -1) { break; } pout.write(buffer, 0, count); // pipe out microphone input } } } while (isrunning && (count >= 0)); // finish when microphone stream was closed } } catch (InterruptedException ie) { } catch (Exception e) { System.out.println( "9\b" + getClass().getName() + ".run\n\tCould not create answer thread." + e); } }
// Put the text that the user typed into the pipe, so that // interested console clients can read the stuff from the in stream. private void acceptLine(String aLine) { try { fromConsoleStream.write(aLine.getBytes()); fromConsoleStream.flush(); } catch (IOException e) { e.printStackTrace(); } }
/** * ** Writes <code>length</code> bytes from the specified byte array ** starting at <code>offset * </code> to the specified socket's output stream. ** @param socket The socket which's output * stream to write to ** @param b The byte array to write to the socket output stream ** @param * offset The start offset in the data to begin writing at ** @param length The length of the * data. Normally <code>b.length</code> ** @throws IOException if an error occurs */ protected static void socketWriteBytes(Socket socket, byte b[], int offset, int length) throws IOException { if ((socket != null) && (b != null)) { int bofs = offset; int blen = (length >= 0) ? length : b.length; OutputStream output = socket.getOutputStream(); output.write(b, bofs, blen); output.flush(); } }
/** * Sends a single command the robot. Could be anything. * * @param line command to send. * @return true means the command is sent. false means it was not. */ public void SendLineToRobot(String line) { if (!portConfirmed) return; line += eol; Log("<font color='white'>" + line + "</font>"); try { out.write(line.getBytes()); } catch (IOException e) { } }
/** * Copy data from an input stream to an output stream. * * @param in Input stream. * @param out Output stream. * @throws IOException */ public static void copy(InputStream in, OutputStream out) throws IOException { // Do not allow other threads to read from the // input or write to the output while copying is // taking place synchronized (in) { synchronized (out) { byte[] buffer = new byte[1024]; while (true) { int bytesRead = in.read(buffer); if (bytesRead == -1) break; out.write(buffer, 0, bytesRead); } } } }
/** * Upload files to pre-configured url. * * @param uploadLocation the location we are uploading to. * @param fileName the filename we use for the resulting filename we upload. * @param params the optional parameter names. * @param values the optional parameter values. */ static void uploadLogs(String uploadLocation, String fileName, String[] params, String[] values) { try { File tempDir = LoggingUtilsActivator.getFileAccessService().getTemporaryDirectory(); File newDest = new File(tempDir, fileName); File optionalFile = null; // if we have some description params // save them to file and add it to archive if (params != null) { optionalFile = new File( LoggingUtilsActivator.getFileAccessService().getTemporaryDirectory(), "description.txt"); OutputStream out = new FileOutputStream(optionalFile); for (int i = 0; i < params.length; i++) { out.write((params[i] + " : " + values[i] + "\r\n").getBytes("UTF-8")); } out.flush(); out.close(); } newDest = LogsCollector.collectLogs(newDest, optionalFile); // don't leave any unneeded information if (optionalFile != null) optionalFile.delete(); if (uploadLocation == null) return; if (HttpUtils.postFile(uploadLocation, "logs", newDest) != null) { NotificationService notificationService = LoggingUtilsActivator.getNotificationService(); if (notificationService != null) { ResourceManagementService resources = LoggingUtilsActivator.getResourceService(); String bodyMsgKey = "plugin.loggingutils.ARCHIVE_MESSAGE_OK"; notificationService.fireNotification( LOGFILES_ARCHIVED, resources.getI18NString("plugin.loggingutils.ARCHIVE_BUTTON"), resources.getI18NString(bodyMsgKey, new String[] {uploadLocation}), null); } } } catch (Throwable e) { logger.error("Cannot upload file", e); } }
private static void copyfile(String srFile, String dtFile) { try { File f1 = new File(srFile); File f2 = new File(dtFile); InputStream in = new FileInputStream(f1); // For Overwrite the file. OutputStream out = new FileOutputStream(f2); byte[] buf = new byte[1024]; int len; while ((len = in.read(buf)) > 0) { out.write(buf, 0, len); } in.close(); out.close(); EIError.debugMsg("File copied " + srFile + " " + dtFile, EIError.ErrorLevel.Notice); } catch (Exception e) { EIError.debugMsg( "Couldn't copy file" + srFile + " " + dtFile + " " + e.getMessage(), EIError.ErrorLevel.Error); } }
@Override public void run() { try { // Create data input and output streams DataInputStream inputFromClient = new DataInputStream(socket.getInputStream()); DataOutputStream outputToClient = new DataOutputStream(socket.getOutputStream()); // Set up a byte buffer to capture the file from the client byte[] buffer = new byte[BUFFER_SIZE]; OutputStream outputStream = null; String fileName = ""; boolean createFile = true; int bytesReceived = 0; long totalBytesReceived = 0; long fileSize = 0; // Continuously serve the client while (true) { bytesReceived = inputFromClient.read(buffer); if (bytesReceived > 0) { // Get the file transmission header from the initial client packet String transmitHeader = new String(buffer, 0, bytesReceived); // transmitHeader = transmitHeader.substring(0, bytesReceived).trim().; String[] header = transmitHeader.split(HEADER_DEL); fileSize = Long.parseLong(header[0]); fileName = header[1]; // Send receipt acknowledgment back to the client. Just send back the number of bytes // received. outputToClient.writeInt(bytesReceived); // Reinitialize buffer values buffer = new byte[BUFFER_SIZE]; bytesReceived = 0; } // Wait for client to send bytes while ((bytesReceived = inputFromClient.read(buffer)) != -1) { if (inputFromClient.available() > 0) { if (createFile) { // Get a unique name for the file to be received fileName = textFolder.getText() + fileName; // getUniqueFileName(); outputStream = createFile(fileName); createFile = false; textArea.append("Receiving file from client.\n"); } // Write bytes to file outputStream.write(buffer, 0, bytesReceived); } else { // We get here if no more data is available, but some bytes were already // received // If bytes were received and the file wasn't already created, // it means that the file was smaller than our buffer size. // Create the file... if (bytesReceived > 0 && createFile) { // Get a unique name for the file to be received fileName = textFolder.getText() + fileName; // getUniqueFileName(); outputStream = createFile(fileName); createFile = false; textArea.append("Receiving file from client.\n"); } if (outputStream != null) { if (bytesReceived > 0) { // Write remaining bytes to file, if any outputStream.write(buffer, 0, bytesReceived); } outputStream.flush(); outputStream.close(); textArea.append("Received file successfully. Saved as " + fileName + "\n"); // Return success to client. outputToClient.writeInt(0); } // Reset creation flag createFile = true; break; } // Reinitialize buffer values buffer = new byte[BUFFER_SIZE]; bytesReceived = 0; } } } catch (IOException e) { System.err.println(e); } }
@Override public void run() { try { // Create a packet for sending data DatagramPacket sendPacket = new DatagramPacket(buffer, buffer.length); OutputStream outputStream = null; String fileName = ""; boolean createFile = true; int bytesReceived = 0; long totalBytesReceived = 0; long fileSize = 0; socket.receive(receivePacket); // Display the client number textArea.append("Starting thread for UDP client " + clientNo + " at " + new Date() + '\n'); textArea.append( "The client host name is " + receivePacket.getAddress().getHostName() + " and port number is " + receivePacket.getPort() + '\n'); // Continuously serve the client while (true) { bytesReceived = receivePacket.getLength(); if (bytesReceived > 0) { // Get the file transmission header from the initial client packet String transmitHeader = new String(receivePacket.getData(), 0, bytesReceived); // transmitHeader = transmitHeader.substring(0, bytesReceived).trim().; String[] header = transmitHeader.split(HEADER_DEL); fileSize = Long.parseLong(header[0]); fileName = header[1]; // Send receipt acknowledgment back to the client. Just send back the number of bytes // received. setSendPacketAddress(sendPacket, receivePacket); sendPacket.setData(String.valueOf(bytesReceived).getBytes()); socket.send(sendPacket); } while (totalBytesReceived < fileSize) { // Wait for client to send bytes // socket.setSendBufferSize(BUFFER_SIZE); socket.receive(receivePacket); bytesReceived = receivePacket.getLength(); if (totalBytesReceived == 0) { if (createFile) { // Get a unique name for the file to be received // fileName = getUniqueFileName(); fileName = textFolder.getText() + fileName; outputStream = createFile(fileName); createFile = false; textArea.append("Receiving file from client.\n"); } // Write bytes to file outputStream.write(receivePacket.getData(), 0, bytesReceived); } else { if (outputStream != null) { // Write bytes to file, if any outputStream.write(receivePacket.getData(), 0, bytesReceived); } } // Increment total bytes received totalBytesReceived += bytesReceived; // Tell the client to send more data. Just send back the number of bytes received. sendPacket.setData(String.valueOf(bytesReceived).getBytes()); socket.send(sendPacket); // buffer = new byte[BUFFER_SIZE]; Arrays.fill(buffer, (byte) 0); receivePacket = new DatagramPacket(buffer, buffer.length); } outputStream.flush(); outputStream.close(); textArea.append("Received file successfully. Saved as " + fileName + "\n"); // Tell the client transmission is complete. Just send back the total number of bytes // received. sendPacket.setData(String.valueOf(totalBytesReceived).getBytes()); socket.send(sendPacket); // Reset creation flag createFile = true; totalBytesReceived = 0; // Wait for client to send another file socket.receive(receivePacket); } } catch (IOException e) { System.err.println(e); } }
public void actionPerformed(ActionEvent e) { if (e.getSource() == ld.st) // 0.로딩화면에서 Enter버튼 클릭 { System.out.println("할리갈리 온라인 안쪽으로 접근중..."); card.show(getContentPane(), "LOG"); } else if (e.getSource() == login.bt1) // 1.팝업창으로 회원가입창 띄우기 { mID.setBounds(470, 310, 340, 420); mID.setVisible(true); } else if (e.getSource() == login.bt2) // 2.로그인버튼 누르기 { ld.clip.stop(); wr.clip.play(); id = login.tf.getText().trim(); // ID입력안했을때 if (id.length() < 1) { JOptionPane.showMessageDialog(this, "ID를 입력하세요"); login.tf.requestFocus(); return; } String pass = new String(login.pf.getPassword()); // PWD입력안했을때 if (pass.length() < 1) { JOptionPane.showMessageDialog(this, "Password를 입력하세요"); login.pf.requestFocus(); return; } connection(); // 모두 정확히 처리했으면, connection()메소드로 이동!! try { out.write( (Function.LOGIN + "|" + id + "|" // 로그인버튼 눌러서 server에게 요청 + pass + "\n") .getBytes()); } catch (Exception ex) { } } else if (e.getSource() == wr.tf || e.getSource() == wr.b1) // 3.waitroom에서 채팅입력할 때 { String data = wr.tf.getText(); // 입력한 값 가져오기 if (data.length() < 1) return; try { out.write((Function.WAITCHAT1 + "|" + data + "\n").getBytes()); // 채팅전송을 server에게 요청 } catch (Exception ex) { } wr.tf.setText(""); } else if (e.getSource() == gw.tf || e.getSource() == gw.b1) // 4.gameWindow에서 채팅입력할 때 { String data = gw.tf.getText(); // 입력한 값 가져오기 if (data.length() < 1) return; try { out.write((Function.ROOMCHAT + "|" + data + "\n").getBytes()); // 채팅전송을 server에게 } catch (Exception ex) { } gw.tf.setText(""); } else if (e.getSource() == wr.b2) // 5.방만들기창 { mr.tf.setText(""); // 방만들기 초기화 mr.pf.setText(""); mr.rb1.setSelected(true); mr.setBounds(500, 300, 260, 290); mr.setVisible(true); } else if (e.getSource() == wr.b3) // 6.방들어가기 버튼처리 ///////////////////////////////// { wr.clip.stop(); gw.clip.play(); System.out.println("방유저리스트수: " + gw.model1.getRowCount()); for (int i = 0; i < gw.model1.getRowCount(); i++) { System.out.println("방유저리스트삭제"); gw.model1.removeRow(i); // 추가 } // gw.model1.removeRow(0); //추가 if (rowNum >= 0) { try { gw.ta.setText(""); out.write((Function.JOINROOM + "|" + rowNum + "\n").getBytes()); } catch (Exception e2) { } } } else if (e.getSource() == mr.b1) // 6.방만들기창에서 확인 눌렀을때////////////////////////////// { wr.clip.stop(); gw.clip.play(); gw.clip.loop(); String subject = mr.tf.getText().trim(); // 방이름 입력 안했을때 if (subject.length() < 1) { JOptionPane.showMessageDialog(this, "방이름을 입력하세요"); mr.tf.requestFocus(); return; } if (mr.rb2.isSelected()) { // 비공개 버튼 눌렀을 때 String pw = new String(mr.pf.getPassword()); if (pw.length() < 1) { JOptionPane.showMessageDialog(this, "비밀번호를 입력하세요"); mr.pf.requestFocus(); return; } } mr.dispose(); /*System.out.println("방유저리스트수: "+gw.model1.getRowCount()); for(int i=0;i<gw.model1.getRowCount();i++) { System.out.println("방유저리스트삭제"); gw.model1.removeRow(i); //추가 }*/ try { String roomType = ""; // 1.공개or비공개 저장 if (mr.rb1.isSelected()) { roomType = mr.rb1.getText(); } // 공개 else if (mr.rb2.isSelected()) { roomType = mr.rb2.getText(); } // 비공개 String roomName = mr.tf.getText(); // 2.방이름 String capaNum = mr.box.getSelectedItem().toString(); // 3.최대인원수 out.write( (Function.MAKEROOM + "|" + roomType + "|" + roomName + "|" + capaNum + "\n") .getBytes()); // 공개여부,방이름,최대인원 넘겨줌 } catch (Exception ex) { } } else if (e.getSource() == wr.b8) // 도움말 버튼처리 { help.setVisible(true); repaint(); } else if (e.getSource() == wr.b9) // 게임종료 버튼처리 { /*서버로 종료 메시지 전송후 프로그램 종료*/ try { out.write((Function.CLIENTEXIT + "|\n").getBytes()); } catch (Exception e2) { } try { s.close(); // 소켓해제 } catch (IOException e1) { e1.printStackTrace(); } System.exit(0); } else if (e.getSource() == mID.b1) // 가입완료버튼 { String name = mID.tf1.getText().trim(); String id = mID.tf2.getText().trim(); String pass1 = new String(mID.pf1.getPassword()); String pass2 = new String(mID.pf2.getPassword()); if (name.length() < 1) { JOptionPane.showMessageDialog(this, "이름을 입력하세요"); mID.tf1.requestFocus(); return; } else if (id.length() < 1) { JOptionPane.showMessageDialog(this, "ID를 입력하세요"); mID.tf2.requestFocus(); return; } else if (mID.ck == false) { JOptionPane.showMessageDialog(this, "ID 중복체크 하시오"); mID.tf2.requestFocus(); return; } else if (pass1.length() < 1) { JOptionPane.showMessageDialog(this, "비밀번호를 입력하세요"); mID.pf1.requestFocus(); return; } else if (pass2.length() < 1) { JOptionPane.showMessageDialog(this, "비밀번호 확인을 입력하세요"); mID.pf2.requestFocus(); return; } else if (!(pass1.equals(pass2))) { JOptionPane.showMessageDialog(this, "비밀번호가 동일하지 않습니다"); mID.pf1.requestFocus(); return; } try { out.write((Function.SUCCESSJOIN + "|" + name + "|" + id + "|" + pass1 + "\n").getBytes()); } catch (IOException e1) { // TODO Auto-generated catch block e1.printStackTrace(); } JOptionPane.showMessageDialog(this, "회원가입완료"); mID.dispose(); } else if (e.getSource() == mID.b2) { mID.tf1.setText(""); mID.tf2.setText(""); mID.pf1.setText(""); mID.pf2.setText(""); mID.dispose(); } else if (e.getSource() == mID.b3) // ID중복체크 { String id = mID.tf2.getText().trim(); if (id.length() < 1) { JOptionPane.showMessageDialog(this, "ID를 입력하세요"); mID.tf2.requestFocus(); return; } if (mID.num == 0) // 한번도 소켓을 연결하지 않았다면 { System.out.println("연결시도"); connection(); mID.num++; } System.out.println("ID중복체크"); try { System.out.println(id); out.write((Function.IDCHECK + "|" + id + "\n").getBytes()); // ID중복체크를 server에게 요청 } catch (Exception ex) { } } else if (e.getSource() == gw.b4) { // GameWindow에서 준비버튼 눌렀을 때 gw.clip.stop(); gw.clip3.play(); try { out.write((Function.ROOMREADY + "|" + "\n").getBytes()); } catch (IOException e1) { e1.printStackTrace(); } } else if (e.getSource() == gw.b5) { // GameWindow에서 시작버튼 눌렀을 때 try { out.write((Function.ROOMSTART + "|" + "\n").getBytes()); gw.b5.setEnabled(false); } catch (IOException e1) { e1.printStackTrace(); } } else if (e.getSource() == gw.b6) // GameWindow에서 나가기 눌렀을 때 { gw.clip.stop(); gw.clip2.play(); wr.clip.play(); System.out.println("방나가기 버튼 Click"); System.out.println("방유저리스트수: " + gw.model1.getRowCount()); // int tmp=gw.model1.getRowCount(); /*for(int i=0;i<gw.model1.getRowCount();i++) { gw.model1.removeRow(i); //추가 }*/ // gw.model1. wr.ta.setText(""); // 수정 gw.b4.setEnabled(true); try { out.write((Function.EXITROOM + "|" + "\n").getBytes()); } catch (Exception ex) { } } else if (e.getSource() == gw.cardOpen) // 카드뒤집기 눌렀을 때!!! { gw.clip4.play(); // 카드 넘기는 소리 gw.cardOpen.setBorderPainted(false); gw.cardOpen.setContentAreaFilled(false); gw.cardOpen.setEnabled(false); try { out.write((Function.CARDOPEN + "|" + id + "\n").getBytes()); } catch (IOException e1) { e1.printStackTrace(); } } else if (e.getSource() == gw.bell) // 종치기 버튼 { gw.clip1.play(); // 종치는소리 try { out.write((Function.BELL + "|" + id + "\n").getBytes()); } catch (IOException e1) { e1.printStackTrace(); } } }
/** Unpacks a resource to a temp. file */ public static File unpackInstaller(String resourceName) { // Array to hold all results (this code is slightly more // generally that it needs to be) File[] results = new File[1]; URL[] urls = new URL[1]; // Determine size of download ClassLoader cl = Main.class.getClassLoader(); urls[0] = cl.getResource(Config.getInstallerResource()); if (urls[0] == null) { Config.trace("Could not find resource: " + Config.getInstallerResource()); return null; } int totalSize = 0; int totalRead = 0; for (int i = 0; i < urls.length; i++) { if (urls[i] != null) { try { URLConnection connection = urls[i].openConnection(); totalSize += connection.getContentLength(); } catch (IOException ioe) { Config.trace("Got exception: " + ioe); return null; } } } // Unpack each file for (int i = 0; i < urls.length; i++) { if (urls[i] != null) { // Create temp. file to store unpacked file in InputStream in = null; OutputStream out = null; try { // Use extension from URL (important for dll files) String extension = new File(urls[i].getFile()).getName(); int lastdotidx = (extension != null) ? extension.lastIndexOf('.') : -1; if (lastdotidx == -1) { extension = ".dat"; } else { extension = extension.substring(lastdotidx); } // Create output stream results[i] = File.createTempFile("jre", extension); results[i].deleteOnExit(); out = new FileOutputStream(results[i]); // Create inputstream URLConnection connection = urls[i].openConnection(); in = connection.getInputStream(); int read = 0; byte[] buf = new byte[BUFFER_SIZE]; while ((read = in.read(buf)) != -1) { out.write(buf, 0, read); // Notify delegate totalRead += read; if (totalRead > totalSize && totalSize != 0) totalSize = totalRead; // Update UI if (totalSize != 0) { int percent = (100 * totalRead) / totalSize; setStepText(STEP_UNPACK, Config.getWindowStepProgress(STEP_UNPACK, percent)); } } } catch (IOException ie) { Config.trace("Got exception while downloading resource: " + ie); for (int j = 0; j < results.length; j++) { if (results[j] != null) results[j].delete(); } return null; } finally { try { if (in != null) in.close(); if (out != null) out.close(); } catch (IOException io) { /* ignore */ } } } } setStepText(STEP_UNPACK, Config.getWindowStep(STEP_UNPACK)); return results[0]; }