id
stringlengths
36
36
text
stringlengths
1
1.25M
350584d0-a9b9-4bfa-9d08-3fe4a36ea11c
private static void printUsage() { System.out .println( "USAGE: $ java GeneBankCreateBtree <0 (no cache) | 1 (cache)> <degree> <gbk.file>\n" + " <sequence_length> [<cache_size>] [<debug_level>]\n\n" + "-<0 (no cache) | 1 (cache)> -- specifies if program should use cache;\n" + " if cache value is 1, <cache_value> has to be specified.\n" + "-<degree> -- degree used for BTree. Enter 0 for optimial degree usage.\n" + "-<gbk.file> -- any gene bank file( *.gbk) containing input DNA sequences.\n" + "-<sequence_length> -- integer value between 1 and 31 (inclusive)\n" + "-[<cache-size>] -- integer between 100 and 500 (inclusive)\n" + " only needed if 1 is entered for cache\n" + "-[<debug_level>] -- [optional] 0 (default) or 1.\n"); System.exit(1); }
598d24e1-942d-4431-a650-4ae7c91a9963
public static void main(String[] args) { SequenceTest t = new SequenceTest(); if (args.length == 0) { t.runTests(10000); } else { t.runTests(Integer.parseInt(args[0])); } }
f20e73b6-c60f-484a-8294-4f04258fa147
private void runTests(int tests) { failMessages = new ArrayList<String>(); @SuppressWarnings("unused") Sequence sequence = null; success = 0; failure = 0; total = 0; try { total++; sequence = new Sequence(""); System.err.println("\nNo error thrown for empty sequence!"); failure++; } catch (SequenceException e) { System.out.println("Passed empty sequence test"); success++; } try { total++; sequence = new Sequence("AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA"); System.err.println("\nNo error thrown for length 32 sequence!"); failure++; } catch (SequenceException e) { System.out.println("Passed long sequence test"); success++; } try { total++; sequence = new Sequence("GATCB"); System.err.println("\nNo error thrown for illegal character!"); failure++; } catch (SequenceException e) { System.out.println("Passed illegal character test"); success++; } sequence = null; System.out.println("Running test battery..."); String[] base = { "A", "T", "G", "C" }; Random rand = new Random(1337); for (int i = 1; i < 32; i++) { String[] seq1 = new String[i]; String[] seq2 = new String[i]; for (int j = 0; j < tests; j++) { for (int ind = 0; ind < i; ind++) { seq1[ind] = base[rand.nextInt(4)]; } String str1 = ""; for (String s : seq1) { str1 = str1 + s; } for (int ind = 0; ind < i; ind++) { seq2[ind] = base[rand.nextInt(4)]; } String str2 = ""; for (String s : seq2) { str2 = str2 + s; } test(str1); test(str2); test(str1, str2); test(str2, str1); test(str1, str1); test(str2, str2); } } System.out.println("Total: " + total); System.out.println("Success: " + success); System.out.println("Failure: " + failure); for (String m : failMessages) { System.out.println(m); } }
f4c330c3-9eda-4f74-b076-bfb0eaab1958
private void test(String str) { total++; try { Sequence seq = new Sequence(str); if (seq.toString().equals(str)) { // System.out.println("Passed: " + str); success++; } else { String message = "\nFAILED: " + str + " Returned: " + seq.toString(); System.err.println(message); failMessages.add(message); failure++; } } catch (SequenceException e) { String message = "\nFAILED: " + str + "-- ERROR: " + e.getMessage(); System.err.println(message); failMessages.add(message); failure++; } }
dcac189b-057f-46f3-af1d-7132fd286711
private void test(String str1, String str2) { total++; try { Sequence seq1 = new Sequence(str1); Sequence seq2 = new Sequence(str2); if (!(seq1.toString().equals(str1)) || !(seq2.toString().equals(str2))) { String message = "\nFAILED: " + str1 + " Returned: " + seq1.toString(); System.err.println(message); failMessages.add(message); failure++; return; } if (!(seq1.compareTo(seq2) == str1.compareTo(str2))) { String message = "\nFAILED: " + str1 + " compareTo " + str2 + " Returned: " + seq1.compareTo(seq2) + " Expected: " + str1.compareTo(str2); System.err.println(message); failMessages.add(message); failure++; return; } else { success++; } } catch (SequenceException e) { String message = "\nFAILED: " + str1 + " and " + str2 + "-- ERROR: " + e.getMessage(); System.err.println(message); failMessages.add(message); failure++; } }
d060e2f5-ad3d-4449-ad0e-57834c05db9d
public static void main(String[] args) { // TODO Auto-generated method stub int cacheOption = 0; String btreeFileName; String queryFileName; int cacheSize = 0; int debugLevel = 0; try { if (args.length < 4 || args.length > 6) { System.out.println("Incorrect command line usage. 4 or 5 argments required.\n"); printUsage(); } cacheOption = Integer.parseInt(args[1]); btreeFileName = args[2]; queryFileName = args[3]; if (cacheOption != 0 && cacheOption != 1) { System.out.println("Cache options must be either 0 or 1.\n"); printUsage(); } if (cacheOption == 1) { if (args.length == 4) { System.out.println("Must enter a cache size when cache option is 1.\n"); printUsage(); } else { cacheSize = Integer.parseInt(args[4]); if ( cacheSize < 100 || cacheSize > 500 ) { System.out.println("Cache size must be an integer between 100 and 500 (inclusive)\n"); printUsage(); } if (args.length == 6) { debugLevel = Integer.parseInt(args[5]); } } } else { if (args.length == 5) { debugLevel = Integer.parseInt(args[4]); } else if (args.length == 6) { System.out.println("Too many arguments for when cache option is 0.\n"); printUsage(); } } if (debugLevel != 0 && debugLevel != 1) { System.out.println("Debug option must be either 0 or 1.\n"); printUsage(); } // System.out.println(cacheOption); // System.out.println(btreeFileName); // System.out.println(queryFileName); // System.out.println(cacheSize); // System.out.println(debugLevel); } catch (NumberFormatException e) { System.out.println("\nNumberFormatException:"); System.out.println("\n\tCache option, cache size, and debug level must be integer values.\n"); printUsage(); } }
75058730-884b-4944-9ddd-7a7f0cff076a
private static void printUsage() { System.out .println( "USAGE: $ java GeneBankSearch < 0 (no cache) | 1 (cache) > < b-tree_file > < query_file >\n" + " [< cache_size >] [< debug_level >]\n\n" + "-< 0 (no cache) | 1 (cache) > -- specifies if program should use cache;\n" + " if cache value is 1, <cache_value> has to be specified.\n" + "-< b-tree_file > -- file created by GeneBankCreateBTree program.\n" + "-< query_file > -- file containing all DNA strings to be searched for.\n" + "-[< cache-size >] -- integer between 100 and 500 (inclusive)\n" + " only needed if 1 is entered for cache\n" + "-[< debug_level >] -- [optional] 0 (default) or 1.\n"); // don't think debug level is needed for this program. System.exit(1); }
98f50c05-ee68-481f-b43a-df7cdad8529c
public static void main(String[] args) { SequenceReaderTest t = new SequenceReaderTest(); t.runTests(); }
10a36f36-8d5d-4ab8-9cdd-f72d58a7273a
private void runTests() { total = 0; success = 0; failure = 0; reader = new SequenceReader(); populateArrays(); // testFromBinaryStringExplicit(); // testToBinaryStringExplicit(); testToAndFromByteArray(); printResults(); }
120eacc8-8572-4464-98db-1f29fa609125
private void printResults() { System.out.println("Total: " + total); System.out.println("Success: " + success); System.out.println("Failure: " + failure); }
85d725e3-5b48-45ad-9fe1-4e540c04aafd
private void populateArrays() { length = new String[32]; for (int i = 0; i < 32; i++) { String l = Integer.toBinaryString(i); while (l.length() < 8) { l = "0" + l; } length[i] = l; } code = new String[4]; code[A] = "00"; code[C] = "01"; code[G] = "10"; code[T] = "11"; }
53b75ebe-8b51-478f-867d-b44ca6aaf7fe
private void testToAndFromByteArray() { total++; try { String source = "GATTACA"; Sequence sequence = new Sequence(source); byte[] bytes = reader.toByteArray(sequence); Sequence result = reader.fromByteArray(bytes); if (sequence.compareTo(result) == 0) { System.out .println("testToAndFromByteArray - Success! Expected: " + sequence + " Result: " + result); success++; } else { failure++; System.out .println("testToAndFromByteArray - FAILED!\n\t Expected: " + sequence + "\n\t Result: " + result + "\nIntermediate byte array: "); for (byte b : bytes){ String out = Integer.toBinaryString(b); // while (out.length() < 8) { // out = code[A] + out; // } System.out.println("\t"+out+" "+b); } } } catch (Exception e) { failure++; e.printStackTrace(); } }
ea5a13b4-16ab-4cf0-8dee-9ac30f4c1419
public Sequence(String seq) throws SequenceException { if (seq.length() > 31){ throw new SequenceException("Sequence Length > 31: "+seq); } if (seq.length() == 0){ throw new SequenceException("Empty Sequence: "+seq); } this.len = (byte) seq.length(); encode(seq); }
a44e54fb-2ae1-4d5b-8d55-3192650bfa4c
public Sequence(long code, byte len){ this.code = code; this.len = len; }
5466826c-0ab6-44f3-8a53-fdf7534b4c96
private void encode(String seq) throws SequenceException{ for (char c : seq.toUpperCase().toCharArray()){ code = code<<2; if (c == 'A'){ code = code ^ 0; } else if (c == 'C'){ code = code ^ 1; } else if (c == 'G'){ code = code ^ 2; } else if (c == 'T'){ code = code ^ 3; } else { throw new SequenceException("Illegal Sequence Character: "+c+" Sequence: "+seq); } } }
c4bc7a75-54c4-464a-a81b-900f5246df0e
private String decode(){ long decode = this.code; long mask = 3; String seq = ""; for (int i = 1; i <= len; i++){ if ((decode & mask) == 0){ seq = "A"+seq; decode = decode>>2; } else if ((decode & mask) == 3){ seq = "T"+seq; decode = decode>>2; } else if ((decode & mask) == 1){ seq = "C"+seq; decode = decode>>2; } else if ((decode & mask) == 2){ seq = "G"+seq; decode = decode>>2; } } return seq; }
53a41c80-61a8-4114-94d3-340a24ce2007
public long getLong(){ return code; }
3f9bc7c1-82bb-4dda-a444-4727c2a3e9e2
public byte getLength(){ return len; }
eabb1cb0-e855-4e9c-b4aa-7d08267d2b18
public String toString(){ return decode(); }
99e40e04-8bab-4194-8abc-ada78df78fc0
@Override public int compareTo(Sequence o) { return this.toString().compareTo(o.toString()); }
9f31b30a-2314-4a6c-8492-d543fafca410
public BinaryReaderException(String message) { super(message); }
7714ac7d-3180-4111-ad84-89a2fcf6c86d
public Chat() throws RemoteException{ this.clientes = new ArrayList<ClienteInterface>(); this.mensagensPublicas = new ArrayList<String>(); }
33f5758e-6570-4379-b015-e0aa66e76cee
public String registrarCliente(String cli) throws RemoteException{ ClienteInterface c; try { c = (ClienteInterface) Naming.lookup(cli); if(!clientes.isEmpty()){ for(ClienteInterface cliente : clientes){ if(cliente.getNome().equals(cli)){ return "Cliente ja registrado"; } } } this.clientes.add(c); for(ClienteInterface cl : clientes){ cl.setClientesLogados(this.getClientesCadastrados()); } } catch (Exception e) { System.out.println("Erro: :( " + e.getMessage()); } return "Cliente Registrado com sucesso"; }
50a5abd6-c2d4-42ec-a06e-72155d093ef6
@Override public void enviarMensagemPrivada(String remetente, String destino, String mensagem) throws RemoteException{ if(!this.clientes.isEmpty()){ for(ClienteInterface c : clientes){ if(c.getNome().equals(destino)){ c.receberMensagem(remetente + ": " + mensagem); } } } }
7a1200f5-126d-4925-aad3-b8bb2e6d7851
@Override public void enviarMensagemPublica(String remetente, String mensagem) throws RemoteException{ if(!this.clientes.isEmpty()){ for(ClienteInterface c : clientes) c.receberMensagem(remetente + ": " + mensagem); } }
5084fdd4-c497-4985-9094-c43bbcc75da2
public List<String> getMensagensPublicas() throws RemoteException{ return this.mensagensPublicas; }
76e66e5e-fea1-4509-ba7c-b0859fe869d4
public List<String> getClientesCadastrados() throws RemoteException{ List<String> nomes = new ArrayList<String>(); for(ClienteInterface c : clientes){ nomes.add(c.getNome()); } return nomes; }
7b31e9eb-2102-46ba-af51-0d9a891304a2
public ServidorChat() { initComponents(); }
a16fbcbf-205c-41e0-bfdc-33d54cb76e06
@SuppressWarnings("unchecked") // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents private void initComponents() { jLabel1 = new javax.swing.JLabel(); jLabel2 = new javax.swing.JLabel(); txtIp = new javax.swing.JTextField(); jLabel3 = new javax.swing.JLabel(); txtPorta = new javax.swing.JTextField(); btnIniciar = new javax.swing.JButton(); lblStatus = new javax.swing.JLabel(); setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE); jLabel1.setText("Servidor - IFPB Chat"); jLabel2.setText("IP:"); jLabel3.setText("Porta:"); btnIniciar.setText("Iniciar Servidor"); btnIniciar.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { btnIniciarActionPerformed(evt); } }); lblStatus.setHorizontalAlignment(javax.swing.SwingConstants.CENTER); javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane()); getContentPane().setLayout(layout); layout.setHorizontalGroup( layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(layout.createSequentialGroup() .addGap(137, 137, 137) .addComponent(jLabel1) .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)) .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup() .addGap(33, 33, 33) .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING) .addComponent(jLabel2) .addComponent(jLabel3)) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE) .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addComponent(txtIp, javax.swing.GroupLayout.Alignment.TRAILING, javax.swing.GroupLayout.PREFERRED_SIZE, 250, javax.swing.GroupLayout.PREFERRED_SIZE) .addComponent(txtPorta, javax.swing.GroupLayout.Alignment.TRAILING, javax.swing.GroupLayout.PREFERRED_SIZE, 250, javax.swing.GroupLayout.PREFERRED_SIZE)) .addGap(47, 47, 47)) .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup() .addContainerGap(21, Short.MAX_VALUE) .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup() .addComponent(lblStatus) .addGap(136, 136, 136)) .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup() .addComponent(btnIniciar, javax.swing.GroupLayout.PREFERRED_SIZE, 363, javax.swing.GroupLayout.PREFERRED_SIZE) .addGap(16, 16, 16)))) ); layout.setVerticalGroup( layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(layout.createSequentialGroup() .addContainerGap() .addComponent(jLabel1) .addGap(28, 28, 28) .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE) .addComponent(jLabel2) .addComponent(txtIp, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED) .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE) .addComponent(jLabel3) .addComponent(txtPorta, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, 58, Short.MAX_VALUE) .addComponent(btnIniciar, javax.swing.GroupLayout.PREFERRED_SIZE, 66, javax.swing.GroupLayout.PREFERRED_SIZE) .addGap(18, 18, 18) .addComponent(lblStatus) .addGap(40, 40, 40)) ); pack(); }// </editor-fold>//GEN-END:initComponents
019a9dc0-b70e-45c1-af05-f11193a5a5ac
public void actionPerformed(java.awt.event.ActionEvent evt) { btnIniciarActionPerformed(evt); }
37cb4eb8-d87b-483e-a72b-3314f7f4fcd1
private void btnIniciarActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnIniciarActionPerformed try { LocateRegistry.createRegistry(1099); String ip = txtIp.getText().equals("") ? "localhost" : txtIp.getText(); String porta = txtPorta.getText().equals("") ? "1099" : txtIp.getText(); String url = "rmi://" + ip + ":" + porta + "/Chat"; System.out.println(url); Naming.rebind(url, new Chat()); JOptionPane.showMessageDialog(null, "Servidor Iniciado"); lblStatus.setText("Servidor funcionando..."); btnIniciar.setEnabled(false); } catch (Exception e) { JOptionPane.showMessageDialog(null, "Erro"); } }//GEN-LAST:event_btnIniciarActionPerformed
98a3bfc7-95d2-4216-ae8f-f1ac2e360e22
public static void main(String args[]) { /* Set the Nimbus look and feel */ //<editor-fold defaultstate="collapsed" desc=" Look and feel setting code (optional) "> /* If Nimbus (introduced in Java SE 6) is not available, stay with the default look and feel. * For details see http://download.oracle.com/javase/tutorial/uiswing/lookandfeel/plaf.html */ try { for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) { if ("Nimbus".equals(info.getName())) { javax.swing.UIManager.setLookAndFeel(info.getClassName()); break; } } } catch (ClassNotFoundException ex) { java.util.logging.Logger.getLogger(ServidorChat.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); } catch (InstantiationException ex) { java.util.logging.Logger.getLogger(ServidorChat.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); } catch (IllegalAccessException ex) { java.util.logging.Logger.getLogger(ServidorChat.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); } catch (javax.swing.UnsupportedLookAndFeelException ex) { java.util.logging.Logger.getLogger(ServidorChat.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); } //</editor-fold> /* Create and display the form */ java.awt.EventQueue.invokeLater(new Runnable() { public void run() { new ServidorChat().setVisible(true); } }); }
f84ee92e-a4dc-467e-bb4f-76c4a908796f
public void run() { new ServidorChat().setVisible(true); }
01042ef5-0916-473c-bb8a-5dadd01cb796
public String registrarCliente(String cli) throws RemoteException;
b305232c-24f0-46b3-a038-4f70467a0a76
public void enviarMensagemPrivada(String remetente, String destino, String mensagem) throws RemoteException;
e94002c7-5beb-4000-b32a-8bff67def6e3
public void enviarMensagemPublica(String remetente, String mensagem) throws RemoteException;
b1329b2d-89b0-40d0-808e-7a8bd7428af4
public List<String> getMensagensPublicas() throws RemoteException;
0f74db6e-c3cd-4009-91ba-2c8532956df7
public List<String> getClientesCadastrados() throws RemoteException;
15f41e0b-3f64-4858-858d-dfa91a2e9906
public String getNome() throws RemoteException;
ee6d2cf4-1fdb-4ede-abe4-84f44518289e
public void setNome(String nome) throws RemoteException;
5d14a253-3b88-4fb6-8fe6-5ce9e08a0d90
public List<String> getMensagensPrivadas() throws RemoteException;
b1e21a6f-0fb2-4bf9-b5c3-158c85aa0181
public void setClientesLogados(List<String> nomes) throws RemoteException;
41eb11fa-5561-4341-b585-1bdf8eb41826
public void setDelegate(InterfaceController delegate) throws RemoteException;
c21f6875-854e-4237-8dbd-1023501a68ac
public void receberMensagem(String msg) throws RemoteException;
1281842f-13cf-48e7-8be8-6fef3206f34b
@Override public void atualizarContatos(List<String> nomes) throws RemoteException{ System.out.println("ENTROU"); this.listUsuarios.setListData(nomes.toArray()); }
e4b326b2-ea6f-41af-bea4-7eb9cd35ee0f
@Override public void atualizarMensagens(String mensagem) throws RemoteException { this.txtAreaMensagens.append(mensagem + "\n"); }
541c13bc-0cec-4fd1-af32-6960249b68dc
public TelaPrincipal() { initComponents(); }
5e3a85a1-3ec9-4c2d-8f4d-fc8d27ae8261
@SuppressWarnings("unchecked") // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents private void initComponents() { jScrollPane1 = new javax.swing.JScrollPane(); txtAreaMensagens = new javax.swing.JTextArea(); jScrollPane2 = new javax.swing.JScrollPane(); listUsuarios = new javax.swing.JList(); lblMensagem = new javax.swing.JLabel(); txtMensagem = new javax.swing.JTextField(); btnEnviar = new javax.swing.JButton(); lblNome = new javax.swing.JLabel(); txtNome = new javax.swing.JTextField(); btnLogar = new javax.swing.JButton(); lblServidor = new javax.swing.JLabel(); lblPorta = new javax.swing.JLabel(); txtServidor = new javax.swing.JTextField(); txtPorta = new javax.swing.JTextField(); jLabel1 = new javax.swing.JLabel(); jLabel2 = new javax.swing.JLabel(); setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE); txtAreaMensagens.setColumns(20); txtAreaMensagens.setRows(5); jScrollPane1.setViewportView(txtAreaMensagens); listUsuarios.setModel(new javax.swing.AbstractListModel() { String[] strings = { "aguardando login" }; public int getSize() { return strings.length; } public Object getElementAt(int i) { return strings[i]; } }); jScrollPane2.setViewportView(listUsuarios); lblMensagem.setText("Mensagem:"); txtMensagem.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { txtMensagemActionPerformed(evt); } }); btnEnviar.setText("enviar"); btnEnviar.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { btnEnviarActionPerformed(evt); } }); lblNome.setText("Digite seu nome:"); txtNome.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { txtNomeActionPerformed(evt); } }); btnLogar.setText("Logar"); btnLogar.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { logarHandler(evt); } }); lblServidor.setText("Servidor:"); lblPorta.setText("Porta:"); jLabel1.setText("Mensagens"); jLabel2.setText("Usuarios"); javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane()); getContentPane().setLayout(layout); layout.setHorizontalGroup( layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(layout.createSequentialGroup() .addContainerGap() .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(layout.createSequentialGroup() .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup() .addComponent(lblMensagem) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addComponent(txtMensagem, javax.swing.GroupLayout.PREFERRED_SIZE, 245, javax.swing.GroupLayout.PREFERRED_SIZE)) .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup() .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING) .addComponent(lblServidor) .addComponent(lblNome) .addComponent(lblPorta)) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED) .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false) .addComponent(txtNome, javax.swing.GroupLayout.DEFAULT_SIZE, 209, Short.MAX_VALUE) .addComponent(txtServidor) .addComponent(txtPorta)))) .addComponent(jScrollPane1, javax.swing.GroupLayout.Alignment.TRAILING, javax.swing.GroupLayout.PREFERRED_SIZE, 328, javax.swing.GroupLayout.PREFERRED_SIZE)) .addGap(18, 18, 18) .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addComponent(jScrollPane2) .addComponent(btnLogar, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE) .addComponent(btnEnviar, javax.swing.GroupLayout.DEFAULT_SIZE, 125, Short.MAX_VALUE))) .addGroup(layout.createSequentialGroup() .addComponent(jLabel1) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE) .addComponent(jLabel2) .addGap(43, 43, 43))) .addContainerGap()) ); layout.setVerticalGroup( layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(layout.createSequentialGroup() .addContainerGap() .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING) .addGroup(layout.createSequentialGroup() .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE) .addComponent(lblNome) .addComponent(txtNome, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED) .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE) .addComponent(lblServidor) .addComponent(txtServidor, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)) .addGap(8, 8, 8) .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE) .addComponent(lblPorta) .addComponent(txtPorta, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))) .addComponent(btnLogar, javax.swing.GroupLayout.PREFERRED_SIZE, 115, javax.swing.GroupLayout.PREFERRED_SIZE)) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, 19, Short.MAX_VALUE) .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE) .addComponent(jLabel1) .addComponent(jLabel2)) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false) .addComponent(jScrollPane1) .addComponent(jScrollPane2, javax.swing.GroupLayout.DEFAULT_SIZE, 168, Short.MAX_VALUE)) .addGap(20, 20, 20) .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE) .addComponent(lblMensagem) .addComponent(txtMensagem, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE) .addComponent(btnEnviar, javax.swing.GroupLayout.PREFERRED_SIZE, 65, javax.swing.GroupLayout.PREFERRED_SIZE)) .addGap(51, 51, 51)) ); pack(); }// </editor-fold>//GEN-END:initComponents
48f13187-7748-4b8d-a8c5-a53433f42cae
public int getSize() { return strings.length; }
ae0afcf2-0316-4821-959c-d827481fe18b
public Object getElementAt(int i) { return strings[i]; }
60a9e9e5-847f-4872-a9bf-a66bc5607389
public void actionPerformed(java.awt.event.ActionEvent evt) { txtMensagemActionPerformed(evt); }
48141041-ff5d-46ab-9859-9cd6a1920f1f
public void actionPerformed(java.awt.event.ActionEvent evt) { btnEnviarActionPerformed(evt); }
588d9ad9-a5f9-4c96-aa2e-788d5f37d536
public void actionPerformed(java.awt.event.ActionEvent evt) { txtNomeActionPerformed(evt); }
e2b3e515-6484-41b3-ad67-5b32b72854d2
public void actionPerformed(java.awt.event.ActionEvent evt) { logarHandler(evt); }
6cea8d8d-c594-4922-a049-fffbb826e4ce
private void logarHandler(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_logarHandler String nome = txtNome.getText(); String servidor = txtServidor.getText().equals("") ? "localhost" : txtServidor.getText(); int porta = txtPorta.getText().equals("") ? 1099 : Integer.parseInt(txtPorta.getText()); try { String url = "rmi://" + servidor + ":" + porta + "/" + "Chat"; System.out.println(url); chat = (ChatInterface) Naming.lookup(url); try { //cliente = (ClienteInterface) Naming.lookup(nome); } catch (Exception e) { System.out.println("Erro:" + e.getMessage()); JOptionPane.showMessageDialog(null, "Cliente já cadastrado, escolha outro nome"); return; } cliente = new Cliente(nome); cliente.setDelegate(this); Naming.bind(cliente.getNome(), cliente); this.chat.registrarCliente(cliente.getNome()); JOptionPane.showMessageDialog(null, "Cliente Cadastrado"); btnLogar.setEnabled(false); txtNome.setEnabled(false); txtServidor.setEnabled(false); txtPorta.setEnabled(false); } catch (Exception e) { System.out.println("Erro: " + e.getMessage()); System.out.println("Objeto Chat nao encontrado"); JOptionPane.showMessageDialog(null, "Chat OffLine"); } }//GEN-LAST:event_logarHandler
e2577d46-4f2d-406a-a0f9-f3aa8dd3864a
private void txtNomeActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_txtNomeActionPerformed // TODO add your handling code here: }//GEN-LAST:event_txtNomeActionPerformed
c4b26b30-ac9b-4249-bb97-61d116ada538
private void btnEnviarActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnEnviarActionPerformed //txtAreaMensagens.append(txtMensagem.getText() + "\n"); try { this.chat.enviarMensagemPublica(cliente.getNome(), txtMensagem.getText()); } catch (Exception e) { JOptionPane.showMessageDialog(null, "Mensagem nao enviada"); } txtMensagem.setText(""); }//GEN-LAST:event_btnEnviarActionPerformed
bf363eee-e7fc-49de-9ebc-ad7c4b79f16b
private void txtMensagemActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_txtMensagemActionPerformed this.btnEnviarActionPerformed(evt); }//GEN-LAST:event_txtMensagemActionPerformed
ec0019a9-fc64-475c-89b7-791ff782998f
public static void main(String args[]) { /* Set the Nimbus look and feel */ //<editor-fold defaultstate="collapsed" desc=" Look and feel setting code (optional) "> /* If Nimbus (introduced in Java SE 6) is not available, stay with the default look and feel. * For details see http://download.oracle.com/javase/tutorial/uiswing/lookandfeel/plaf.html */ try { for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) { if ("Nimbus".equals(info.getName())) { javax.swing.UIManager.setLookAndFeel(info.getClassName()); break; } } } catch (ClassNotFoundException ex) { java.util.logging.Logger.getLogger(TelaPrincipal.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); } catch (InstantiationException ex) { java.util.logging.Logger.getLogger(TelaPrincipal.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); } catch (IllegalAccessException ex) { java.util.logging.Logger.getLogger(TelaPrincipal.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); } catch (javax.swing.UnsupportedLookAndFeelException ex) { java.util.logging.Logger.getLogger(TelaPrincipal.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); } //</editor-fold> /* Create and display the form */ java.awt.EventQueue.invokeLater(new Runnable() { public void run() { new TelaPrincipal().setVisible(true); } }); }
a497bca6-5ee6-4123-8561-866c625e5deb
public void run() { new TelaPrincipal().setVisible(true); }
9ec463ad-5247-4f0d-9f3f-eeae30daa948
public void atualizarContatos(List<String> nomes) throws RemoteException;
dfccc985-97ca-400b-92f7-bb633944d002
public void atualizarMensagens(String mensagem) throws RemoteException;
72735bd6-b266-4ccb-b1da-53353ba611e2
public Cliente(String nome) throws RemoteException{ this.nome = nome; this.mensagensPrivadas = new ArrayList<String>(); }
8fa3d2ac-9f81-4a29-9ccf-962b0b0744a9
public String getNome() throws RemoteException{ return nome; }
d2b8d446-dab5-4460-838d-75d0c94d026c
public void setNome(String nome) throws RemoteException{ this.nome = nome; }
f6598902-1915-4703-b2a1-a9e04e9ba5cf
public List<String> getMensagensPrivadas() throws RemoteException{ return mensagensPrivadas; }
12113ce8-6338-4101-829a-a5462f1cc65c
public void setMensagensPrivadas(List<String> mensagensPrivadas) throws RemoteException{ this.mensagensPrivadas = mensagensPrivadas; }
9c8ffcf2-41d8-45df-a127-3c8db94af25e
public void receberMensagem(String msg) throws RemoteException{ this.delegate.atualizarMensagens(msg); }
7ead0afb-4fa1-41ee-9e81-77d8392d0816
public void setClientesLogados(List<String> nomes) throws RemoteException{ this.clientesLogados = nomes; this.delegate.atualizarContatos(nomes); }
7e6720fc-14e0-46e2-a242-2a09b14ca6c1
public void setDelegate(InterfaceController delegate) throws RemoteException{ this.delegate = delegate; }
3bd90d3b-98ae-4cc8-838c-aa44137eafe0
public static void main(String[] args) { System.out.println("Projeto funcionando"); new TelaPrincipal().setVisible(true); }
aa54f6df-9c9b-4fcb-9baa-434c7fa4e2f8
private final static byte[] getAlphabet( int options ) { if ((options & URL_SAFE) == URL_SAFE) { return _URL_SAFE_ALPHABET; } else if ((options & ORDERED) == ORDERED) { return _ORDERED_ALPHABET; } else { return _STANDARD_ALPHABET; } } // end getAlphabet
1fd1df7c-5c56-43b9-875f-cd00f57b9752
private final static byte[] getDecodabet( int options ) { if( (options & URL_SAFE) == URL_SAFE) { return _URL_SAFE_DECODABET; } else if ((options & ORDERED) == ORDERED) { return _ORDERED_DECODABET; } else { return _STANDARD_DECODABET; } } // end getAlphabet
2d49c0fc-ca29-486d-87a9-41f736fce45c
private Base64(){}
9b7436e1-ed85-444d-aca8-4ce0d5129514
private static byte[] encode3to4( byte[] b4, byte[] threeBytes, int numSigBytes, int options ) { encode3to4( threeBytes, 0, numSigBytes, b4, 0, options ); return b4; } // end encode3to4
3c79d372-6b7f-4471-8a7a-8a45c6d394dd
private static byte[] encode3to4( byte[] source, int srcOffset, int numSigBytes, byte[] destination, int destOffset, int options ) { byte[] ALPHABET = getAlphabet( options ); // 1 2 3 // 01234567890123456789012345678901 Bit position // --------000000001111111122222222 Array position from threeBytes // --------| || || || | Six bit groups to index ALPHABET // >>18 >>12 >> 6 >> 0 Right shift necessary // 0x3f 0x3f 0x3f Additional AND // Create buffer with zero-padding if there are only one or two // significant bytes passed in the array. // We have to shift left 24 in order to flush out the 1's that appear // when Java treats a value as negative that is cast from a byte to an int. int inBuff = ( numSigBytes > 0 ? ((source[ srcOffset ] << 24) >>> 8) : 0 ) | ( numSigBytes > 1 ? ((source[ srcOffset + 1 ] << 24) >>> 16) : 0 ) | ( numSigBytes > 2 ? ((source[ srcOffset + 2 ] << 24) >>> 24) : 0 ); switch( numSigBytes ) { case 3: destination[ destOffset ] = ALPHABET[ (inBuff >>> 18) ]; destination[ destOffset + 1 ] = ALPHABET[ (inBuff >>> 12) & 0x3f ]; destination[ destOffset + 2 ] = ALPHABET[ (inBuff >>> 6) & 0x3f ]; destination[ destOffset + 3 ] = ALPHABET[ (inBuff ) & 0x3f ]; return destination; case 2: destination[ destOffset ] = ALPHABET[ (inBuff >>> 18) ]; destination[ destOffset + 1 ] = ALPHABET[ (inBuff >>> 12) & 0x3f ]; destination[ destOffset + 2 ] = ALPHABET[ (inBuff >>> 6) & 0x3f ]; destination[ destOffset + 3 ] = EQUALS_SIGN; return destination; case 1: destination[ destOffset ] = ALPHABET[ (inBuff >>> 18) ]; destination[ destOffset + 1 ] = ALPHABET[ (inBuff >>> 12) & 0x3f ]; destination[ destOffset + 2 ] = EQUALS_SIGN; destination[ destOffset + 3 ] = EQUALS_SIGN; return destination; default: return destination; } // end switch } // end encode3to4
d8bb0bbd-87c9-4195-bca3-8d34bf78106e
public static void encode( java.nio.ByteBuffer raw, java.nio.ByteBuffer encoded ){ byte[] raw3 = new byte[3]; byte[] enc4 = new byte[4]; while( raw.hasRemaining() ){ int rem = Math.min(3,raw.remaining()); raw.get(raw3,0,rem); Base64.encode3to4(enc4, raw3, rem, Base64.NO_OPTIONS ); encoded.put(enc4); } // end input remaining }
302c6ec4-d6d4-4a63-9afa-bc2bd7dcb6a0
public static void encode( java.nio.ByteBuffer raw, java.nio.CharBuffer encoded ){ byte[] raw3 = new byte[3]; byte[] enc4 = new byte[4]; while( raw.hasRemaining() ){ int rem = Math.min(3,raw.remaining()); raw.get(raw3,0,rem); Base64.encode3to4(enc4, raw3, rem, Base64.NO_OPTIONS ); for( int i = 0; i < 4; i++ ){ encoded.put( (char)(enc4[i] & 0xFF) ); } } // end input remaining }
e05e7fd9-52f3-42e7-8237-fb2d4f762794
public static String encodeObject( java.io.Serializable serializableObject ) throws java.io.IOException { return encodeObject( serializableObject, NO_OPTIONS ); } // end encodeObject
0abfb4e8-2ff7-4809-a1a5-fa4b7cc26b19
public static String encodeObject( java.io.Serializable serializableObject, int options ) throws java.io.IOException { if( serializableObject == null ){ throw new NullPointerException( "Cannot serialize a null object." ); } // end if: null // Streams java.io.ByteArrayOutputStream baos = null; java.io.OutputStream b64os = null; java.util.zip.GZIPOutputStream gzos = null; java.io.ObjectOutputStream oos = null; try { // ObjectOutputStream -> (GZIP) -> Base64 -> ByteArrayOutputStream baos = new java.io.ByteArrayOutputStream(); b64os = new Base64.OutputStream( baos, ENCODE | options ); if( (options & GZIP) != 0 ){ // Gzip gzos = new java.util.zip.GZIPOutputStream(b64os); oos = new java.io.ObjectOutputStream( gzos ); } else { // Not gzipped oos = new java.io.ObjectOutputStream( b64os ); } oos.writeObject( serializableObject ); } // end try catch( java.io.IOException e ) { // Catch it and then throw it immediately so that // the finally{} block is called for cleanup. throw e; } // end catch finally { try{ oos.close(); } catch( Exception e ){} try{ gzos.close(); } catch( Exception e ){} try{ b64os.close(); } catch( Exception e ){} try{ baos.close(); } catch( Exception e ){} } // end finally // Return value according to relevant encoding. try { return new String( baos.toByteArray(), PREFERRED_ENCODING ); } // end try catch (java.io.UnsupportedEncodingException uue){ // Fall back to some Java default return new String( baos.toByteArray() ); } // end catch } // end encode
986b1fe6-9bc7-4429-987b-01fe081402a6
public static String encodeBytes( byte[] source ) { // Since we're not going to have the GZIP encoding turned on, // we're not going to have an java.io.IOException thrown, so // we should not force the user to have to catch it. String encoded = null; try { encoded = encodeBytes(source, 0, source.length, NO_OPTIONS); } catch (java.io.IOException ex) { assert false : ex.getMessage(); } // end catch assert encoded != null; return encoded; } // end encodeBytes
679bc390-d52f-4201-bdc5-3e1048847b67
public static String encodeBytes( byte[] source, int options ) throws java.io.IOException { return encodeBytes( source, 0, source.length, options ); } // end encodeBytes
eab4de88-c685-4e1c-b584-d66c5677df4d
public static String encodeBytes( byte[] source, int off, int len ) { // Since we're not going to have the GZIP encoding turned on, // we're not going to have an java.io.IOException thrown, so // we should not force the user to have to catch it. String encoded = null; try { encoded = encodeBytes( source, off, len, NO_OPTIONS ); } catch (java.io.IOException ex) { assert false : ex.getMessage(); } // end catch assert encoded != null; return encoded; } // end encodeBytes
740fe741-4580-4239-a95f-dff0f4fe71bc
public static String encodeBytes( byte[] source, int off, int len, int options ) throws java.io.IOException { byte[] encoded = encodeBytesToBytes( source, off, len, options ); // Return value according to relevant encoding. try { return new String( encoded, PREFERRED_ENCODING ); } // end try catch (java.io.UnsupportedEncodingException uue) { return new String( encoded ); } // end catch } // end encodeBytes
6494a98b-e19d-462d-aa69-8e0b9394e0ee
public static byte[] encodeBytesToBytes( byte[] source ) { byte[] encoded = null; try { encoded = encodeBytesToBytes( source, 0, source.length, Base64.NO_OPTIONS ); } catch( java.io.IOException ex ) { assert false : "IOExceptions only come from GZipping, which is turned off: " + ex.getMessage(); } return encoded; }
1018e4ce-61aa-4433-9f3c-3e2f86dee5ce
public static byte[] encodeBytesToBytes( byte[] source, int off, int len, int options ) throws java.io.IOException { if( source == null ){ throw new NullPointerException( "Cannot serialize a null array." ); } // end if: null if( off < 0 ){ throw new IllegalArgumentException( "Cannot have negative offset: " + off ); } // end if: off < 0 if( len < 0 ){ throw new IllegalArgumentException( "Cannot have length offset: " + len ); } // end if: len < 0 if( off + len > source.length ){ throw new IllegalArgumentException( String.format( "Cannot have offset of %d and length of %d with array of length %d", off,len,source.length)); } // end if: off < 0 // Compress? if( (options & GZIP) != 0 ) { java.io.ByteArrayOutputStream baos = null; java.util.zip.GZIPOutputStream gzos = null; Base64.OutputStream b64os = null; try { // GZip -> Base64 -> ByteArray baos = new java.io.ByteArrayOutputStream(); b64os = new Base64.OutputStream( baos, ENCODE | options ); gzos = new java.util.zip.GZIPOutputStream( b64os ); gzos.write( source, off, len ); gzos.close(); } // end try catch( java.io.IOException e ) { // Catch it and then throw it immediately so that // the finally{} block is called for cleanup. throw e; } // end catch finally { try{ gzos.close(); } catch( Exception e ){} try{ b64os.close(); } catch( Exception e ){} try{ baos.close(); } catch( Exception e ){} } // end finally return baos.toByteArray(); } // end if: compress // Else, don't compress. Better not to use streams at all then. else { boolean breakLines = (options & DO_BREAK_LINES) != 0; //int len43 = len * 4 / 3; //byte[] outBuff = new byte[ ( len43 ) // Main 4:3 // + ( (len % 3) > 0 ? 4 : 0 ) // Account for padding // + (breakLines ? ( len43 / MAX_LINE_LENGTH ) : 0) ]; // New lines // Try to determine more precisely how big the array needs to be. // If we get it right, we don't have to do an array copy, and // we save a bunch of memory. int encLen = ( len / 3 ) * 4 + ( len % 3 > 0 ? 4 : 0 ); // Bytes needed for actual encoding if( breakLines ){ encLen += encLen / MAX_LINE_LENGTH; // Plus extra newline characters } byte[] outBuff = new byte[ encLen ]; int d = 0; int e = 0; int len2 = len - 2; int lineLength = 0; for( ; d < len2; d+=3, e+=4 ) { encode3to4( source, d+off, 3, outBuff, e, options ); lineLength += 4; if( breakLines && lineLength >= MAX_LINE_LENGTH ) { outBuff[e+4] = NEW_LINE; e++; lineLength = 0; } // end if: end of line } // en dfor: each piece of array if( d < len ) { encode3to4( source, d+off, len - d, outBuff, e, options ); e += 4; } // end if: some padding needed // Only resize array if we didn't guess it right. if( e <= outBuff.length - 1 ){ // If breaking lines and the last byte falls right at // the line length (76 bytes per line), there will be // one extra byte, and the array will need to be resized. // Not too bad of an estimate on array size, I'd say. byte[] finalOut = new byte[e]; System.arraycopy(outBuff,0, finalOut,0,e); //System.err.println("Having to resize array from " + outBuff.length + " to " + e ); return finalOut; } else { //System.err.println("No need to resize array."); return outBuff; } } // end else: don't compress } // end encodeBytesToBytes
b3becfa7-c299-40ef-99f3-617d1753f6b1
private static int decode4to3( byte[] source, int srcOffset, byte[] destination, int destOffset, int options ) { // Lots of error checking and exception throwing if( source == null ){ throw new NullPointerException( "Source array was null." ); } // end if if( destination == null ){ throw new NullPointerException( "Destination array was null." ); } // end if if( srcOffset < 0 || srcOffset + 3 >= source.length ){ throw new IllegalArgumentException( String.format( "Source array with length %d cannot have offset of %d and still process four bytes.", source.length, srcOffset ) ); } // end if if( destOffset < 0 || destOffset +2 >= destination.length ){ throw new IllegalArgumentException( String.format( "Destination array with length %d cannot have offset of %d and still store three bytes.", destination.length, destOffset ) ); } // end if byte[] DECODABET = getDecodabet( options ); // Example: Dk== if( source[ srcOffset + 2] == EQUALS_SIGN ) { // Two ways to do the same thing. Don't know which way I like best. //int outBuff = ( ( DECODABET[ source[ srcOffset ] ] << 24 ) >>> 6 ) // | ( ( DECODABET[ source[ srcOffset + 1] ] << 24 ) >>> 12 ); int outBuff = ( ( DECODABET[ source[ srcOffset ] ] & 0xFF ) << 18 ) | ( ( DECODABET[ source[ srcOffset + 1] ] & 0xFF ) << 12 ); destination[ destOffset ] = (byte)( outBuff >>> 16 ); return 1; } // Example: DkL= else if( source[ srcOffset + 3 ] == EQUALS_SIGN ) { // Two ways to do the same thing. Don't know which way I like best. //int outBuff = ( ( DECODABET[ source[ srcOffset ] ] << 24 ) >>> 6 ) // | ( ( DECODABET[ source[ srcOffset + 1 ] ] << 24 ) >>> 12 ) // | ( ( DECODABET[ source[ srcOffset + 2 ] ] << 24 ) >>> 18 ); int outBuff = ( ( DECODABET[ source[ srcOffset ] ] & 0xFF ) << 18 ) | ( ( DECODABET[ source[ srcOffset + 1 ] ] & 0xFF ) << 12 ) | ( ( DECODABET[ source[ srcOffset + 2 ] ] & 0xFF ) << 6 ); destination[ destOffset ] = (byte)( outBuff >>> 16 ); destination[ destOffset + 1 ] = (byte)( outBuff >>> 8 ); return 2; } // Example: DkLE else { // Two ways to do the same thing. Don't know which way I like best. //int outBuff = ( ( DECODABET[ source[ srcOffset ] ] << 24 ) >>> 6 ) // | ( ( DECODABET[ source[ srcOffset + 1 ] ] << 24 ) >>> 12 ) // | ( ( DECODABET[ source[ srcOffset + 2 ] ] << 24 ) >>> 18 ) // | ( ( DECODABET[ source[ srcOffset + 3 ] ] << 24 ) >>> 24 ); int outBuff = ( ( DECODABET[ source[ srcOffset ] ] & 0xFF ) << 18 ) | ( ( DECODABET[ source[ srcOffset + 1 ] ] & 0xFF ) << 12 ) | ( ( DECODABET[ source[ srcOffset + 2 ] ] & 0xFF ) << 6) | ( ( DECODABET[ source[ srcOffset + 3 ] ] & 0xFF ) ); destination[ destOffset ] = (byte)( outBuff >> 16 ); destination[ destOffset + 1 ] = (byte)( outBuff >> 8 ); destination[ destOffset + 2 ] = (byte)( outBuff ); return 3; } } // end decodeToBytes
5dda9cc4-dfb4-4953-acf7-bc5e253f498b
public static byte[] decode( byte[] source ) throws java.io.IOException { byte[] decoded = null; // try { decoded = decode( source, 0, source.length, Base64.NO_OPTIONS ); // } catch( java.io.IOException ex ) { // assert false : "IOExceptions only come from GZipping, which is turned off: " + ex.getMessage(); // } return decoded; }
e0ffdd30-5573-4e39-9306-f033ac8dc334
public static byte[] decode( byte[] source, int off, int len, int options ) throws java.io.IOException { // Lots of error checking and exception throwing if( source == null ){ throw new NullPointerException( "Cannot decode null source array." ); } // end if if( off < 0 || off + len > source.length ){ throw new IllegalArgumentException( String.format( "Source array with length %d cannot have offset of %d and process %d bytes.", source.length, off, len ) ); } // end if if( len == 0 ){ return new byte[0]; }else if( len < 4 ){ throw new IllegalArgumentException( "Base64-encoded string must have at least four characters, but length specified was " + len ); } // end if byte[] DECODABET = getDecodabet( options ); int len34 = len * 3 / 4; // Estimate on array size byte[] outBuff = new byte[ len34 ]; // Upper limit on size of output int outBuffPosn = 0; // Keep track of where we're writing byte[] b4 = new byte[4]; // Four byte buffer from source, eliminating white space int b4Posn = 0; // Keep track of four byte input buffer int i = 0; // Source array counter byte sbiDecode = 0; // Special value from DECODABET for( i = off; i < off+len; i++ ) { // Loop through source sbiDecode = DECODABET[ source[i]&0xFF ]; // White space, Equals sign, or legit Base64 character // Note the values such as -5 and -9 in the // DECODABETs at the top of the file. if( sbiDecode >= WHITE_SPACE_ENC ) { if( sbiDecode >= EQUALS_SIGN_ENC ) { b4[ b4Posn++ ] = source[i]; // Save non-whitespace if( b4Posn > 3 ) { // Time to decode? outBuffPosn += decode4to3( b4, 0, outBuff, outBuffPosn, options ); b4Posn = 0; // If that was the equals sign, break out of 'for' loop if( source[i] == EQUALS_SIGN ) { break; } // end if: equals sign } // end if: quartet built } // end if: equals sign or better } // end if: white space, equals sign or better else { // There's a bad input character in the Base64 stream. throw new java.io.IOException( String.format( "Bad Base64 input character decimal %d in array position %d", ((int)source[i])&0xFF, i ) ); } // end else: } // each input character byte[] out = new byte[ outBuffPosn ]; System.arraycopy( outBuff, 0, out, 0, outBuffPosn ); return out; } // end decode
8638e0bf-7f78-499b-8091-924358fd149e
public static byte[] decode( String s ) throws java.io.IOException { return decode( s, NO_OPTIONS ); }
15b4bf7c-a583-4652-96ee-bc611b74b40b
public static byte[] decode( String s, int options ) throws java.io.IOException { if( s == null ){ throw new NullPointerException( "Input string was null." ); } // end if byte[] bytes; try { bytes = s.getBytes( PREFERRED_ENCODING ); } // end try catch( java.io.UnsupportedEncodingException uee ) { bytes = s.getBytes(); } // end catch //</change> // Decode bytes = decode( bytes, 0, bytes.length, options ); // Check to see if it's gzip-compressed // GZIP Magic Two-Byte Number: 0x8b1f (35615) boolean dontGunzip = (options & DONT_GUNZIP) != 0; if( (bytes != null) && (bytes.length >= 4) && (!dontGunzip) ) { int head = ((int)bytes[0] & 0xff) | ((bytes[1] << 8) & 0xff00); if( java.util.zip.GZIPInputStream.GZIP_MAGIC == head ) { java.io.ByteArrayInputStream bais = null; java.util.zip.GZIPInputStream gzis = null; java.io.ByteArrayOutputStream baos = null; byte[] buffer = new byte[2048]; int length = 0; try { baos = new java.io.ByteArrayOutputStream(); bais = new java.io.ByteArrayInputStream( bytes ); gzis = new java.util.zip.GZIPInputStream( bais ); while( ( length = gzis.read( buffer ) ) >= 0 ) { baos.write(buffer,0,length); } // end while: reading input // No error? Get new bytes. bytes = baos.toByteArray(); } // end try catch( java.io.IOException e ) { e.printStackTrace(); // Just return originally-decoded bytes } // end catch finally { try{ baos.close(); } catch( Exception e ){} try{ gzis.close(); } catch( Exception e ){} try{ bais.close(); } catch( Exception e ){} } // end finally } // end if: gzipped } // end if: bytes.length >= 2 return bytes; } // end decode
352016b6-bf0e-4e96-b0bb-b40e63c58682
public static Object decodeToObject( String encodedObject ) throws java.io.IOException, java.lang.ClassNotFoundException { return decodeToObject(encodedObject,NO_OPTIONS,null); }
214d4973-0729-42bb-85f6-cfda08033405
public static Object decodeToObject( String encodedObject, int options, final ClassLoader loader ) throws java.io.IOException, java.lang.ClassNotFoundException { // Decode and gunzip if necessary byte[] objBytes = decode( encodedObject, options ); java.io.ByteArrayInputStream bais = null; java.io.ObjectInputStream ois = null; Object obj = null; try { bais = new java.io.ByteArrayInputStream( objBytes ); // If no custom class loader is provided, use Java's builtin OIS. if( loader == null ){ ois = new java.io.ObjectInputStream( bais ); } // end if: no loader provided // Else make a customized object input stream that uses // the provided class loader. else { ois = new java.io.ObjectInputStream(bais){ @Override public Class<?> resolveClass(java.io.ObjectStreamClass streamClass) throws java.io.IOException, ClassNotFoundException { Class c = Class.forName(streamClass.getName(), false, loader); if( c == null ){ return super.resolveClass(streamClass); } else { return c; // Class loader knows of this class. } // end else: not null } // end resolveClass }; // end ois } // end else: no custom class loader obj = ois.readObject(); } // end try catch( java.io.IOException e ) { throw e; // Catch and throw in order to execute finally{} } // end catch catch( java.lang.ClassNotFoundException e ) { throw e; // Catch and throw in order to execute finally{} } // end catch finally { try{ bais.close(); } catch( Exception e ){} try{ ois.close(); } catch( Exception e ){} } // end finally return obj; } // end decodeObject
e0e2ae02-1028-46d7-8202-48dd8b81bc6b
@Override public Class<?> resolveClass(java.io.ObjectStreamClass streamClass) throws java.io.IOException, ClassNotFoundException { Class c = Class.forName(streamClass.getName(), false, loader); if( c == null ){ return super.resolveClass(streamClass); } else { return c; // Class loader knows of this class. } // end else: not null } // end resolveClass
9f9884a6-262f-4f8f-8894-28c35ce2c06c
public static void encodeToFile( byte[] dataToEncode, String filename ) throws java.io.IOException { if( dataToEncode == null ){ throw new NullPointerException( "Data to encode was null." ); } // end iff Base64.OutputStream bos = null; try { bos = new Base64.OutputStream( new java.io.FileOutputStream( filename ), Base64.ENCODE ); bos.write( dataToEncode ); } // end try catch( java.io.IOException e ) { throw e; // Catch and throw to execute finally{} block } // end catch: java.io.IOException finally { try{ bos.close(); } catch( Exception e ){} } // end finally } // end encodeToFile
2a851db9-552c-4736-b436-b39a4a5bff46
public static void decodeToFile( String dataToDecode, String filename ) throws java.io.IOException { Base64.OutputStream bos = null; try{ bos = new Base64.OutputStream( new java.io.FileOutputStream( filename ), Base64.DECODE ); bos.write( dataToDecode.getBytes( PREFERRED_ENCODING ) ); } // end try catch( java.io.IOException e ) { throw e; // Catch and throw to execute finally{} block } // end catch: java.io.IOException finally { try{ bos.close(); } catch( Exception e ){} } // end finally } // end decodeToFile
3eb3392c-efd4-466c-9f8a-6984919ead37
public static byte[] decodeFromFile( String filename ) throws java.io.IOException { byte[] decodedData = null; Base64.InputStream bis = null; try { // Set up some useful variables java.io.File file = new java.io.File( filename ); byte[] buffer = null; int length = 0; int numBytes = 0; // Check for size of file if( file.length() > Integer.MAX_VALUE ) { throw new java.io.IOException( "File is too big for this convenience method (" + file.length() + " bytes)." ); } // end if: file too big for int index buffer = new byte[ (int)file.length() ]; // Open a stream bis = new Base64.InputStream( new java.io.BufferedInputStream( new java.io.FileInputStream( file ) ), Base64.DECODE ); // Read until done while( ( numBytes = bis.read( buffer, length, 4096 ) ) >= 0 ) { length += numBytes; } // end while // Save in a variable to return decodedData = new byte[ length ]; System.arraycopy( buffer, 0, decodedData, 0, length ); } // end try catch( java.io.IOException e ) { throw e; // Catch and release to execute finally{} } // end catch: java.io.IOException finally { try{ bis.close(); } catch( Exception e) {} } // end finally return decodedData; } // end decodeFromFile
6ee30524-8c12-4785-97a1-2fc057cef3e8
public static String encodeFromFile( String filename ) throws java.io.IOException { String encodedData = null; Base64.InputStream bis = null; try { // Set up some useful variables java.io.File file = new java.io.File( filename ); byte[] buffer = new byte[ Math.max((int)(file.length() * 1.4+1),40) ]; // Need max() for math on small files (v2.2.1); Need +1 for a few corner cases (v2.3.5) int length = 0; int numBytes = 0; // Open a stream bis = new Base64.InputStream( new java.io.BufferedInputStream( new java.io.FileInputStream( file ) ), Base64.ENCODE ); // Read until done while( ( numBytes = bis.read( buffer, length, 4096 ) ) >= 0 ) { length += numBytes; } // end while // Save in a variable to return encodedData = new String( buffer, 0, length, Base64.PREFERRED_ENCODING ); } // end try catch( java.io.IOException e ) { throw e; // Catch and release to execute finally{} } // end catch: java.io.IOException finally { try{ bis.close(); } catch( Exception e) {} } // end finally return encodedData; } // end encodeFromFile
d7a5cefb-c013-4053-ad7c-cc0be3cd3c61
public static void encodeFileToFile( String infile, String outfile ) throws java.io.IOException { String encoded = Base64.encodeFromFile( infile ); java.io.OutputStream out = null; try{ out = new java.io.BufferedOutputStream( new java.io.FileOutputStream( outfile ) ); out.write( encoded.getBytes("US-ASCII") ); // Strict, 7-bit output. } // end try catch( java.io.IOException e ) { throw e; // Catch and release to execute finally{} } // end catch finally { try { out.close(); } catch( Exception ex ){} } // end finally } // end encodeFileToFile
cc1e4445-927b-4e4b-b4cf-f0991d0c9a28
public static void decodeFileToFile( String infile, String outfile ) throws java.io.IOException { byte[] decoded = Base64.decodeFromFile( infile ); java.io.OutputStream out = null; try{ out = new java.io.BufferedOutputStream( new java.io.FileOutputStream( outfile ) ); out.write( decoded ); } // end try catch( java.io.IOException e ) { throw e; // Catch and release to execute finally{} } // end catch finally { try { out.close(); } catch( Exception ex ){} } // end finally } // end decodeFileToFile