PASTEBIN
| #1 paste tool since 2002
create new paste
tools
api
archive
real-time
faq
PASTEBIN
create new paste
trending pastes
sign up
login
my settings
my profile
Public Pastes
What is the correc...
5 sec ago
premium accounts free
22 sec ago
About stdout/stder...
11 sec ago
Untitled
20 sec ago
Can I have multipl...
17 sec ago
Untitled
17 sec ago
Untitled
C | 18 sec ago
Untitled
22 sec ago
New Paste
package makhin.mykola.minor.utils.routerreset; import java.awt.BorderLayout; import java.awt.GridLayout; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import java.io.IOException; import java.net.InetAddress; import java.net.Socket; import java.net.UnknownHostException; import java.security.SecureRandom; import java.text.SimpleDateFormat; import java.util.Date; import javax.net.ssl.SSLContext; import javax.net.ssl.SSLSocketFactory; import javax.net.ssl.TrustManager; import javax.swing.JButton; import javax.swing.JComboBox; import javax.swing.JComponent; import javax.swing.JFrame; import javax.swing.JLabel; import javax.swing.JOptionPane; import javax.swing.JPanel; import javax.swing.JPasswordField; import javax.swing.JScrollPane; import javax.swing.JTextArea; import javax.swing.JTextField; import javax.swing.SwingUtilities; import javax.swing.border.EmptyBorder; import org.apache.commons.httpclient.ConnectTimeoutException; import org.apache.commons.httpclient.Credentials; import org.apache.commons.httpclient.HttpClient; import org.apache.commons.httpclient.MultiThreadedHttpConnectionManager; import org.apache.commons.httpclient.URI; import org.apache.commons.httpclient.UsernamePasswordCredentials; import org.apache.commons.httpclient.auth.AuthScope; import org.apache.commons.httpclient.methods.GetMethod; import org.apache.commons.httpclient.methods.PostMethod; import org.apache.commons.httpclient.params.HttpConnectionParams; import org.apache.commons.httpclient.protocol.Protocol; import org.apache.commons.httpclient.protocol.ProtocolSocketFactory; /** * @author Mykola Makhin * @version 0.2 */ public class RouterResetUtil extends JComponent { private static final long serialVersionUID = -6196217426008036402L; public static final int WAIT_TIME = 30000; public static void main(String[] args) { JFrame frame = new JFrame("Router resetter"); frame.getContentPane().setLayout(new BorderLayout()); frame.getContentPane().add(new RouterResetUtil(), BorderLayout.CENTER); frame.pack(); frame.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE); frame.setVisible(true); } public RouterResetUtil() { initGui(); initNet(); } protected void error(final Throwable t) { t.printStackTrace(); SwingUtilities.invokeLater(new Runnable() { public void run() { JOptionPane.showMessageDialog(RouterResetUtil.this, "Error "+t.getClass().getName()+" occured: "+t.getMessage(), "Error", JOptionPane.ERROR_MESSAGE); } }); } protected SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy.MM.dd HH:mm:ss S"); protected void log(String message) { System.out.println("["+dateFormat.format(new Date())+"]: "+message); } // ## GUI start // TODO: move to separate GUI class protected JPanel pnlRouterParams = new JPanel(); protected JTextField tfRouterHost = new JTextField("192.168.1.1"); protected JTextField tfRouterLogin = new JTextField("admin"); protected JPasswordField tfRouterPass = new JPasswordField("admin"); protected JComboBox cbProtocol = new JComboBox(); protected JPanel pnlStatusLog = new JPanel(); protected JTextField tfStatus = new JTextField(); protected JTextArea taLog = new JTextArea(); protected JButton btnSave = new JButton("Save"); protected JButton btnTest = new JButton("Test"); protected ButtonsHandler buttonsHandler = new ButtonsHandler(); protected static final String ACT_SAVE = "ACT_SAVE"; protected static final String ACT_TEST = "ACT_TEST"; public void initGui() { // Init components cbProtocol.addItem("HTTP"); cbProtocol.addItem("HTTPS"); btnSave.addActionListener(buttonsHandler); btnSave.setActionCommand(ACT_SAVE); btnTest.addActionListener(buttonsHandler); btnTest.setActionCommand(ACT_TEST); tfStatus.setEditable(false); taLog.setEditable(false); // Init config panel pnlRouterParams.setLayout(new GridLayout(5,2)); pnlRouterParams.add(new JLabel("Router host")); pnlRouterParams.add(tfRouterHost); pnlRouterParams.add(new JLabel("Protocol")); pnlRouterParams.add(cbProtocol); pnlRouterParams.add(new JLabel("Login")); pnlRouterParams.add(tfRouterLogin); pnlRouterParams.add(new JLabel("Password")); pnlRouterParams.add(tfRouterPass); pnlRouterParams.add(btnTest); pnlRouterParams.add(btnSave); // Init status/log panel pnlStatusLog.setLayout(new BorderLayout()); pnlStatusLog.add(tfStatus, BorderLayout.NORTH); pnlStatusLog.add(new JScrollPane(taLog), BorderLayout.CENTER); this.setLayout(new BorderLayout()); this.add(pnlRouterParams, BorderLayout.CENTER); this.setBorder(new EmptyBorder(10,10,10,10)); } // ## Handler start protected class ButtonsHandler implements ActionListener { public void actionPerformed(ActionEvent actEvent) { String actionCommand = actEvent.getActionCommand(); String routerHost = tfRouterHost.getText(); boolean useHttps = cbProtocol.getSelectedItem().toString().toLowerCase().equals("https"); String routerLogin = tfRouterLogin.getText(); String routerPass = new String(tfRouterPass.getPassword()); if(ACT_SAVE.equals(actionCommand)) { RouterResetUtil.this.configureNet(routerHost, useHttps, routerLogin, routerPass); if(RouterResetUtil.this.testRouterLogin()) RouterResetUtil.this.doSaveParams(); else JOptionPane.showMessageDialog(RouterResetUtil.this, "Connection error", "Error", JOptionPane.ERROR_MESSAGE); } else if(ACT_TEST.equals(actionCommand)) { RouterResetUtil.this.configureNet(routerHost, useHttps, routerLogin, routerPass); if(RouterResetUtil.this.testRouterLogin()) JOptionPane.showMessageDialog(RouterResetUtil.this, "Router connection OK", "Message", JOptionPane.INFORMATION_MESSAGE); else JOptionPane.showMessageDialog(RouterResetUtil.this, "Connection error", "Error", JOptionPane.ERROR_MESSAGE); } } } Thread monitorThread = null; protected void doSaveParams() { this.removeAll(); this.add(pnlStatusLog, BorderLayout.CENTER); this.invalidate(); this.revalidate(); if(monitorThread!=null) { try { monitorThread.interrupt(); doStartMonitor(); } catch (Throwable t) { error(t); } } else { doStartMonitor(); } } protected void doStartMonitor() { monitorThread = new Thread(new MonitorResetter()); monitorThread.setDaemon(true); monitorThread.start(); this.setStatus("Monitoring started"); this.logInfoMsg("Monitoring started"); } // ## Handler end protected void setStatus(final String status) { SwingUtilities.invokeLater(new Runnable() { public void run() { tfStatus.setText("["+dateFormat.format(new Date())+"]: "+status); } }); } protected void logInfoMsg(final String message) { SwingUtilities.invokeLater(new Runnable() { public void run() { taLog.append("["+dateFormat.format(new Date())+"]: "+message+"\n"); } }); } // ## GUI end // ## Netz start protected void initSsl() { try { SSLContext context = SSLContext.getInstance("TLS"); context.init(null, new TrustManager[] {new AllowAllTrustManager()}, new SecureRandom()); /* javax.net.ssl.HttpsURLConnection.setDefaultSSLSocketFactory(context.getSocketFactory()); context = SSLContext.getInstance("SSL"); context.init(null, new TrustManager[] {new AllowAllTrustManager()}, new SecureRandom()); javax.net.ssl.HttpsURLConnection.setDefaultSSLSocketFactory(context.getSocketFactory()); */ Protocol myhttps = new Protocol("https", new ProtocolSocketFactory() { SSLSocketFactory socketFactory; public ProtocolSocketFactory setSocketFactory(SSLSocketFactory socketFactory) { this.socketFactory = socketFactory; return this; } public Socket createSocket(String host, int port) throws IOException, UnknownHostException { return socketFactory.createSocket(host, port); } public Socket createSocket(String host, int port, InetAddress localAddress, int localPort) throws IOException, UnknownHostException { return socketFactory.createSocket(host, port, localAddress, localPort); } public Socket createSocket(String host, int port, InetAddress localAddress, int localPort, HttpConnectionParams params) throws IOException, UnknownHostException, ConnectTimeoutException { return socketFactory.createSocket(host, port, localAddress, localPort); } }.setSocketFactory(context.getSocketFactory()), 443); Protocol.registerProtocol("https", myhttps); }catch(Throwable t) { t.printStackTrace(); } } protected HttpClient httpClient; protected GetMethod getGoogle = new GetMethod("http://www.google.com"); protected GetMethod getRouterStartPage = new GetMethod(); protected PostMethod postRouterDHCPRenew = new PostMethod(); protected void initHttpClient() { MultiThreadedHttpConnectionManager connectionManager = new MultiThreadedHttpConnectionManager(); httpClient = new HttpClient(connectionManager); httpClient.getParams().setConnectionManagerTimeout(12000L); httpClient.getParams().setSoTimeout(12000); postRouterDHCPRenew.addParameter("submit_type", "renew"); postRouterDHCPRenew.addParameter("submit_button", "Status_Router"); postRouterDHCPRenew.addParameter("change_action", "gozila_cgi"); postRouterDHCPRenew.addParameter("dhcp_renew", "DHCP Renew"); } protected void initNet() { initSsl(); initHttpClient(); } protected void configureNet(String routerHost, boolean useHttps, String login, String pass) { Credentials credentials = new UsernamePasswordCredentials(login, pass); httpClient.getState().clearCredentials(); httpClient.getState().setCredentials(new AuthScope(routerHost, AuthScope.ANY_PORT), credentials); //httpClient.getState().setCredentials(AuthScope.ANY, credentials); try { getRouterStartPage.setURI(new URI((useHttps? "https://" : "http://") + routerHost+"/index.asp", true)); postRouterDHCPRenew.setURI(new URI((useHttps? "https://" : "http://") + routerHost+"/apply.cgi", true)); } catch (Exception e) { error(e); } } protected boolean testRouterLogin() { boolean result = false; try { log("Trying Router login"); int rspCode = httpClient.executeMethod(getRouterStartPage); System.out.println(getRouterStartPage.getURI()); if(rspCode>=200 && rspCode<300) { result = true; log("Router login seems successfull. Code: "+rspCode); } else { log("Router login seems not OK. Code: "+rspCode+".\nResponse:\n"+getRouterStartPage.getResponseBodyAsString()); } } catch (Throwable t) { error(t); log("!! Error loggin in to Router - "+t.getClass().getName()+": "+t.getMessage()); } finally { getRouterStartPage.releaseConnection(); } return result; } protected boolean testInetConnection() { boolean connected = false; try { log("Testing Inet connection"); int responseCode = httpClient.executeMethod(getGoogle); byte[] responseBytes = getGoogle.getResponseBody(); String responseText = new String(responseBytes, getGoogle.getResponseCharSet()); if(responseCode<200 || responseCode>=300 || responseText.indexOf("<title>Google</title>")<0) { if(responseCode<200 || responseCode>=300) { log("Wrong response code from google.com"); } else { log("Suspicious response text from google.com"); } log("Response code: "+responseCode+"\nResponse text:"+responseText); } connected = true; log("Inet connection OK"); } catch(UnknownHostException unknownHostException) { connected = false; // Superficial. Well, whatever... unknownHostException.printStackTrace(); log("Unknown host exception for www.google.com - obvious DNS failure"); log(unknownHostException.getClass().getName()+": "+unknownHostException.getMessage()); } catch(Throwable err) { err.printStackTrace(); log("Error on testing Inet connection: "+err.getMessage()); log(err.getClass().getName()+": "+err.getMessage()); } finally { getGoogle.releaseConnection(); } return connected; } private boolean resetInternetConnection() { boolean done = false; try { log("Resetting Inet connection"); if(!testRouterLogin()) log("Warning - router login error!"); int responseCode = httpClient.executeMethod(postRouterDHCPRenew); byte[] responseBytes = postRouterDHCPRenew.getResponseBody(); String responseText = new String(responseBytes, postRouterDHCPRenew.getResponseCharSet()); if(responseCode<200 || responseCode>=300 || responseText.indexOf(">0.0.0.0<")>=0) { if(responseCode<200 || responseCode>=300) { log("Wrong response code from Router"); } else { log("Zero IPs in response text from Router"); } log("Router response code: "+responseCode+"\nRouter response text:"+responseText); log("Resetting Inet connection unsuccessfull"); } else { done = true; log("Resetting Inet connection seems successfull"); } } catch (Throwable err) { err.printStackTrace(); log("Error on resetting Inet connection: "+err.getMessage()); log(err.getClass().getName()+": "+err.getMessage()); } finally { postRouterDHCPRenew.releaseConnection(); } return done; } // ## Netz end protected enum TheCode { GREEN, YELLOW, RED}; protected class MonitorResetter implements Runnable { protected TheCode code = TheCode.GREEN; public void run() { while(true) { if(!RouterResetUtil.this.testInetConnection()) { log("!! Internet connection failure suspected"); setStatus("YELLOW: Connection failure suspected"); if(code.equals(TheCode.GREEN)) { code = TheCode.YELLOW; log("!! Code YELLOW"); } else if(code.equals(TheCode.YELLOW)) { code = TheCode.RED; log("!! Code RED"); log("!! Internet connection failure detected"); setStatus("RED: Connection failure detected!"); logInfoMsg("Connection failure detected"); } if(code.equals(TheCode.RED)) { log("!! Resetting Inet connection"); if(resetInternetConnection()) { code = TheCode.YELLOW; log("!! Connection reset\nCode YELLOW"); setStatus("YELLOW: Connection reset"); logInfoMsg("Connection reset attempt"); } else { log("!! Failed to reset connection\nCode RED"); setStatus("RED: Failed to reset connection!!!"); logInfoMsg("Failed to reset connection!"); } } } else { if(!code.equals(TheCode.GREEN)) { if(code.equals(TheCode.RED)) { code = TheCode.YELLOW; log("!! Internet connection seems OK now by itself\nCode YELLOW"); setStatus("YELLOW: Connection seems OK by itself"); } else { code = TheCode.GREEN; log("!! Internet connection is OK\nCode GREEN"); setStatus("GREEN: Connection is now OK"); logInfoMsg("Connection is now OK"); } } else { log("Connection Ok"); setStatus("GREEN: Connection is OK"); } } try { if(code.equals(TheCode.GREEN)) Thread.sleep(WAIT_TIME); else Thread.sleep(WAIT_TIME/4); } catch (InterruptedException e) { log("!! We've been interrupted"); log("InterruptedException"); break; } catch (Exception e) { log("!! Thread insomnia"); log(e.getClass().getName()+": "+e.getMessage()); break; } } } } public static class AllowAllTrustManager implements javax.net.ssl.TrustManager, javax.net.ssl.X509TrustManager { public java.security.cert.X509Certificate[] getAcceptedIssuers() { return null; } public boolean isServerTrusted(java.security.cert.X509Certificate[] certs) { return true; } public boolean isClientTrusted(java.security.cert.X509Certificate[] certs) { return true; } public void checkServerTrusted(java.security.cert.X509Certificate[] certs, String authType) throws java.security.cert.CertificateException { return; } public void checkClientTrusted(java.security.cert.X509Certificate[] certs, String authType) throws java.security.cert.CertificateException { return; } } }
Optional Paste Settings
Syntax Highlighting:
None
Bash
C
C#
C++
CSS
HTML
HTML 5
Java
JavaScript
Lua
None
Perl
PHP
Python
Rails
-------------
4CS
6502 ACME Cross Assembler
6502 Kick Assembler
6502 TASM/64TASS
ABAP
ActionScript
ActionScript 3
Ada
ALGOL 68
Apache Log
AppleScript
APT Sources
ASM (NASM)
ASP
autoconf
Autohotkey
AutoIt
Avisynth
Awk
BASCOM AVR
Bash
Basic4GL
BibTeX
Blitz Basic
BNF
BOO
BrainFuck
C
C for Macs
C Intermediate Language
C#
C++
C++ (with QT extensions)
C: Loadrunner
CAD DCL
CAD Lisp
CFDG
ChaiScript
Clojure
Clone C
Clone C++
CMake
COBOL
CoffeeScript
ColdFusion
CSS
Cuesheet
D
DCS
Delphi
Delphi Prism (Oxygene)
Diff
DIV
DOS
DOT
E
ECMAScript
Eiffel
Email
EPC
Erlang
F#
Falcon
FO Language
Formula One
Fortran
FreeBasic
FreeSWITCH
GAMBAS
Game Maker
GDB
Genero
Genie
GetText
Go
Groovy
GwBasic
Haskell
HicEst
HQ9 Plus
HTML
HTML 5
Icon
IDL
INI file
Inno Script
INTERCAL
IO
J
Java
Java 5
JavaScript
jQuery
KiXtart
Latex
Liberty BASIC
Linden Scripting
Lisp
LLVM
Loco Basic
Logtalk
LOL Code
Lotus Formulas
Lotus Script
LScript
Lua
M68000 Assembler
MagikSF
Make
MapBasic
MatLab
mIRC
MIX Assembler
Modula 2
Modula 3
Motorola 68000 HiSoft Dev
MPASM
MXML
MySQL
newLISP
None
NullSoft Installer
Oberon 2
Objeck Programming Langua
Objective C
OCalm Brief
OCaml
OpenBSD PACKET FILTER
OpenGL Shading
Openoffice BASIC
Oracle 11
Oracle 8
Oz
Pascal
PAWN
PCRE
Per
Perl
Perl 6
PHP
PHP Brief
Pic 16
Pike
Pixel Bender
PL/SQL
PostgreSQL
POV-Ray
Power Shell
PowerBuilder
ProFTPd
Progress
Prolog
Properties
ProvideX
PureBasic
PyCon
Python
q/kdb+
QBasic
R
Rails
REBOL
REG
Robots
RPM Spec
Ruby
Ruby Gnuplot
SAS
Scala
Scheme
Scilab
SdlBasic
Smalltalk
Smarty
SQL
SystemVerilog
T-SQL
TCL
Tera Term
thinBasic
TypoScript
Unicon
UnrealScript
Vala
VB.NET
VeriLog
VHDL
VIM
Visual Pro Log
VisualBasic
VisualFoxPro
WhiteSpace
WHOIS
Winbatch
XBasic
XML
Xorg Config
XPP
YAML
Z80 Assembler
ZXBasic
Paste Expiration:
Never
10 Minutes
1 Hour
1 Day
1 Month
Paste Exposure:
Public
Unlisted
Private (members only)
Paste Name / Title:
Hello
Guest
Sign Up
or
Login
You are currently not logged in, this means you can not edit or delete anything you paste.
Sign Up
or
Login