code stringlengths 3 1.18M | language stringclasses 1 value |
|---|---|
/*------------------------------------------------------------------------------
** Ident: Innovation en Inspiration > Google Android
** Author: rene
** Copyright: (c) Jan 22, 2009 Sogeti Nederland B.V. All Rights Reserved.
**------------------------------------------------------------------------------
** Sogeti Nederland B.V. | No part of this file may be reproduced
** Distributed Software Engineering | or transmitted in any form or by any
** Lange Dreef 17 | means, electronic or mechanical, for the
** 4131 NJ Vianen | purpose, without the express written
** The Netherlands | permission of the copyright holder.
*------------------------------------------------------------------------------
*
* This file is part of OpenGPSTracker.
*
* OpenGPSTracker is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* OpenGPSTracker is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with OpenGPSTracker. If not, see <http://www.gnu.org/licenses/>.
*
*/
package nl.sogeti.android.gpstracker.tests.utils;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.util.ArrayList;
import java.util.Calendar;
import org.xmlpull.v1.XmlPullParser;
import org.xmlpull.v1.XmlPullParserException;
import android.content.Context;
import android.content.res.XmlResourceParser;
import android.util.Log;
/**
* Feeder of GPS-location information
*
* @version $Id$
* @author Maarten van Berkel (maarten.van.berkel@sogeti.nl / +0586)
*/
public class MockGPSLoggerDriver implements Runnable
{
private static final String TAG = "MockGPSLoggerDriver";
private boolean running = true;
private int mTimeout;
private Context mContext;
private TelnetPositionSender sender;
private ArrayList<SimplePosition> positions;
private int mRouteResource;
/**
* Constructor: create a new MockGPSLoggerDriver.
*
* @param context context of the test package
* @param route resource identifier for the xml route
* @param timeout time to idle between waypoints in miliseconds
*/
public MockGPSLoggerDriver(Context context, int route, int timeout)
{
this();
this.mTimeout = timeout;
this.mRouteResource = route;// R.xml.denhaagdenbosch;
this.mContext = context;
}
public MockGPSLoggerDriver()
{
this.sender = new TelnetPositionSender();
}
public int getPositions()
{
return this.positions.size();
}
private void prepareRun( int xmlResource )
{
this.positions = new ArrayList<SimplePosition>();
XmlResourceParser xmlParser = this.mContext.getResources().getXml( xmlResource );
doUglyXMLParsing( this.positions, xmlParser );
xmlParser.close();
}
public void run()
{
prepareRun( this.mRouteResource );
while( this.running && ( this.positions.size() > 0 ) )
{
SimplePosition position = this.positions.remove( 0 );
//String nmeaCommand = createGPGGALocationCommand(position.getLongitude(), position.getLatitude(), 0);
String nmeaCommand = createGPRMCLocationCommand( position.lng, position.lat, 0, 0 );
String checksum = calulateChecksum( nmeaCommand );
this.sender.sendCommand( "geo nmea $" + nmeaCommand + "*" + checksum + "\r\n" );
try
{
Thread.sleep( this.mTimeout );
}
catch( InterruptedException e )
{
Log.w( TAG, "Interrupted" );
}
}
}
public static String calulateChecksum( String nmeaCommand )
{
byte[] chars = null;
try
{
chars = nmeaCommand.getBytes( "ASCII" );
}
catch( UnsupportedEncodingException e )
{
e.printStackTrace();
}
byte xor = 0;
for( int i = 0; i < chars.length; i++ )
{
xor ^= chars[i];
}
return Integer.toHexString( (int) xor ).toUpperCase();
}
public void stop()
{
this.running = false;
}
private void doUglyXMLParsing( ArrayList<SimplePosition> positions, XmlResourceParser xmlParser )
{
int eventType;
try
{
eventType = xmlParser.getEventType();
SimplePosition lastPosition = null;
boolean speed = false;
while( eventType != XmlPullParser.END_DOCUMENT )
{
if( eventType == XmlPullParser.START_TAG )
{
if( xmlParser.getName().equals( "trkpt" ) || xmlParser.getName().equals( "rtept" ) || xmlParser.getName().equals( "wpt" ) )
{
lastPosition = new SimplePosition( xmlParser.getAttributeFloatValue( 0, 12.3456F ), xmlParser.getAttributeFloatValue( 1, 12.3456F ) );
positions.add( lastPosition );
}
if( xmlParser.getName().equals( "speed" ) )
{
speed = true;
}
}
else if( eventType == XmlPullParser.END_TAG )
{
if( xmlParser.getName().equals( "speed" ) )
{
speed = false;
}
}
else if( eventType == XmlPullParser.TEXT )
{
if( lastPosition != null && speed )
{
lastPosition.speed = Float.parseFloat( xmlParser.getText() );
}
}
eventType = xmlParser.next();
}
}
catch( XmlPullParserException e )
{ /* ignore */
}
catch( IOException e )
{/* ignore */
}
}
/**
* Create a NMEA GPRMC sentence
*
* @param longitude
* @param latitude
* @param elevation
* @param speed in mps
* @return
*/
public static String createGPRMCLocationCommand( double longitude, double latitude, double elevation, double speed )
{
speed *= 0.51; // from m/s to knots
final String COMMAND_GPS = "GPRMC," + "%1$02d" + // hh c.get(Calendar.HOUR_OF_DAY)
"%2$02d" + // mm c.get(Calendar.MINUTE)
"%3$02d." + // ss. c.get(Calendar.SECOND)
"%4$03d,A," + // ss, c.get(Calendar.MILLISECOND)
"%5$03d" + // llll latDegree
"%6$09.6f," + // latMinute
"%7$c," + // latDirection (N or S)
"%8$03d" + // longDegree
"%9$09.6f," + // longMinutett
"%10$c," + // longDirection (E or W)
"%14$.2f," + // Speed over ground in knot
"0," + // Track made good in degrees True
"%11$02d" + // dd
"%12$02d" + // mm
"%13$02d," + // yy
"0," + // Magnetic variation degrees (Easterly var. subtracts from true course)
"E," + // East/West
"mode"; // Just as workaround....
Calendar c = Calendar.getInstance();
double absLong = Math.abs( longitude );
int longDegree = (int) Math.floor( absLong );
char longDirection = 'E';
if( longitude < 0 )
{
longDirection = 'W';
}
double longMinute = ( absLong - Math.floor( absLong ) ) * 60;
double absLat = Math.abs( latitude );
int latDegree = (int) Math.floor( absLat );
char latDirection = 'N';
if( latitude < 0 )
{
latDirection = 'S';
}
double latMinute = ( absLat - Math.floor( absLat ) ) * 60;
String command = String.format( COMMAND_GPS, c.get( Calendar.HOUR_OF_DAY ), c.get( Calendar.MINUTE ), c.get( Calendar.SECOND ), c.get( Calendar.MILLISECOND ), latDegree, latMinute,
latDirection, longDegree, longMinute, longDirection, c.get( Calendar.DAY_OF_MONTH ), c.get( Calendar.MONTH ), c.get( Calendar.YEAR ) - 2000 , speed);
return command;
}
public static String createGPGGALocationCommand( double longitude, double latitude, double elevation )
{
final String COMMAND_GPS = "GPGGA," + // $--GGA,
"%1$02d" + // hh c.get(Calendar.HOUR_OF_DAY)
"%2$02d" + // mm c.get(Calendar.MINUTE)
"%3$02d." + // ss. c.get(Calendar.SECOND)
"%4$03d," + // sss, c.get(Calendar.MILLISECOND)
"%5$03d" + // llll latDegree
"%6$09.6f," + // latMinute
"%7$c," + // latDirection
"%8$03d" + // longDegree
"%9$09.6f," + // longMinutett
"%10$c," + // longDirection
"1,05,02.1,00545.5,M,-26.0,M,,";
Calendar c = Calendar.getInstance();
double absLong = Math.abs( longitude );
int longDegree = (int) Math.floor( absLong );
char longDirection = 'E';
if( longitude < 0 )
{
longDirection = 'W';
}
double longMinute = ( absLong - Math.floor( absLong ) ) * 60;
double absLat = Math.abs( latitude );
int latDegree = (int) Math.floor( absLat );
char latDirection = 'N';
if( latitude < 0 )
{
latDirection = 'S';
}
double latMinute = ( absLat - Math.floor( absLat ) ) * 60;
String command = String.format( COMMAND_GPS, c.get( Calendar.HOUR_OF_DAY ), c.get( Calendar.MINUTE ), c.get( Calendar.SECOND ), c.get( Calendar.MILLISECOND ), latDegree, latMinute,
latDirection, longDegree, longMinute, longDirection );
return command;
}
class SimplePosition
{
public float speed;
public double lat, lng;
public SimplePosition(float latitude, float longtitude)
{
this.lat = latitude;
this.lng = longtitude;
}
}
public void sendSMS( String string )
{
this.sender.sendCommand( "sms send 31886606607 " + string + "\r\n" );
}
} | Java |
/*------------------------------------------------------------------------------
** Ident: Innovation en Inspiration > Google Android
** Author: rene
** Copyright: (c) Jan 22, 2009 Sogeti Nederland B.V. All Rights Reserved.
**------------------------------------------------------------------------------
** Sogeti Nederland B.V. | No part of this file may be reproduced
** Distributed Software Engineering | or transmitted in any form or by any
** Lange Dreef 17 | means, electronic or mechanical, for the
** 4131 NJ Vianen | purpose, without the express written
** The Netherlands | permission of the copyright holder.
*------------------------------------------------------------------------------
*
* This file is part of OpenGPSTracker.
*
* OpenGPSTracker is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* OpenGPSTracker is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with OpenGPSTracker. If not, see <http://www.gnu.org/licenses/>.
*
*/
package nl.sogeti.android.gpstracker.tests;
import junit.framework.TestSuite;
import nl.sogeti.android.gpstracker.tests.actions.ExportGPXTest;
import nl.sogeti.android.gpstracker.tests.db.GPStrackingProviderTest;
import nl.sogeti.android.gpstracker.tests.demo.OpenGPSTrackerDemo;
import nl.sogeti.android.gpstracker.tests.gpsmock.MockGPSLoggerServiceTest;
import nl.sogeti.android.gpstracker.tests.logger.GPSLoggerServiceTest;
import nl.sogeti.android.gpstracker.tests.perf.MapStressTest;
import nl.sogeti.android.gpstracker.tests.userinterface.LoggerMapTest;
import android.test.InstrumentationTestRunner;
import android.test.InstrumentationTestSuite;
/**
* Perform unit tests Run on the adb shell:
*
* <pre>
* am instrument -w nl.sogeti.android.gpstracker.tests/.GPStrackingInstrumentation
* </pre>
*
* @version $Id$
* @author rene (c) Jan 22, 2009, Sogeti B.V.
*/
public class GPStrackingInstrumentation extends InstrumentationTestRunner
{
/**
* (non-Javadoc)
* @see android.test.InstrumentationTestRunner#getAllTests()
*/
@Override
public TestSuite getAllTests()
{
TestSuite suite = new InstrumentationTestSuite( this );
suite.setName( "GPS Tracking Testsuite" );
suite.addTestSuite( GPStrackingProviderTest.class );
suite.addTestSuite( MockGPSLoggerServiceTest.class );
suite.addTestSuite( GPSLoggerServiceTest.class );
suite.addTestSuite( ExportGPXTest.class );
suite.addTestSuite( LoggerMapTest.class );
// suite.addTestSuite( OpenGPSTrackerDemo.class ); // The demo recorded for youtube
// suite.addTestSuite( MapStressTest.class ); // The stress test of the map viewer
return suite;
}
/**
* (non-Javadoc)
* @see android.test.InstrumentationTestRunner#getLoader()
*/
@Override
public ClassLoader getLoader()
{
return GPStrackingInstrumentation.class.getClassLoader();
}
}
| Java |
/*------------------------------------------------------------------------------
** Ident: Innovation en Inspiration > Google Android
** Author: rene
** Copyright: (c) Jan 22, 2009 Sogeti Nederland B.V. All Rights Reserved.
**------------------------------------------------------------------------------
** Sogeti Nederland B.V. | No part of this file may be reproduced
** Distributed Software Engineering | or transmitted in any form or by any
** Lange Dreef 17 | means, electronic or mechanical, for the
** 4131 NJ Vianen | purpose, without the express written
** The Netherlands | permission of the copyright holder.
*------------------------------------------------------------------------------
*
* This file is part of OpenGPSTracker.
*
* OpenGPSTracker is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* OpenGPSTracker is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with OpenGPSTracker. If not, see <http://www.gnu.org/licenses/>.
*
*/
package nl.sogeti.android.gpstracker.tests.demo;
import nl.sogeti.android.gpstracker.logger.GPSLoggerServiceManager;
import nl.sogeti.android.gpstracker.tests.utils.MockGPSLoggerDriver;
import nl.sogeti.android.gpstracker.viewer.map.GoogleLoggerMap;
import nl.sogeti.android.gpstracker.viewer.map.LoggerMap;
import android.test.ActivityInstrumentationTestCase2;
import android.test.suitebuilder.annotation.LargeTest;
import android.test.suitebuilder.annotation.SmallTest;
import com.google.android.maps.GeoPoint;
import com.google.android.maps.MapView;
/**
* @version $Id$
* @author rene (c) Jan 22, 2009, Sogeti B.V.
*/
public class OpenGPSTrackerDemo extends ActivityInstrumentationTestCase2<GoogleLoggerMap>
{
private static final int ZOOM_LEVEL = 16;
private static final Class<GoogleLoggerMap> CLASS = GoogleLoggerMap.class;
private static final String PACKAGE = "nl.sogeti.android.gpstracker";
private GoogleLoggerMap mLoggermap;
private GPSLoggerServiceManager mLoggerServiceManager;
private MapView mMapView;
private MockGPSLoggerDriver mSender;
public OpenGPSTrackerDemo()
{
super( PACKAGE, CLASS );
}
@Override
protected void setUp() throws Exception
{
super.setUp();
this.mLoggermap = getActivity();
this.mMapView = (MapView) this.mLoggermap.findViewById( nl.sogeti.android.gpstracker.R.id.myMapView );
this.mSender = new MockGPSLoggerDriver();
}
protected void tearDown() throws Exception
{
this.mLoggerServiceManager.shutdown( getActivity() );
super.tearDown();
}
/**
* Start tracking and allow it to go on for 30 seconds
*
* @throws InterruptedException
*/
@LargeTest
public void testTracking() throws InterruptedException
{
a_introSingelUtrecht30Seconds();
c_startRoute10Seconds();
d_showDrawMethods30seconds();
e_statistics10Seconds();
f_showPrecision30seconds();
g_stopTracking10Seconds();
h_shareTrack30Seconds();
i_finish10Seconds();
}
@SmallTest
public void a_introSingelUtrecht30Seconds() throws InterruptedException
{
this.mMapView.getController().setZoom( ZOOM_LEVEL);
Thread.sleep( 1 * 1000 );
// Browse the Utrecht map
sendMessage( "Selecting a previous recorded track" );
Thread.sleep( 1 * 1000 );
this.sendKeys( "MENU DPAD_RIGHT" );
Thread.sleep( 2 * 1000 );
this.sendKeys( "L" );
Thread.sleep( 2 * 1000 );
sendMessage( "The walk around the \"singel\" in Utrecht" );
this.sendKeys( "DPAD_CENTER" );
Thread.sleep( 2 * 1000 );
Thread.sleep( 2 * 1000 );
sendMessage( "Scrolling about" );
this.mMapView.getController().animateTo( new GeoPoint( 52095829, 5118599 ) );
Thread.sleep( 2 * 1000 );
this.mMapView.getController().animateTo( new GeoPoint( 52096778, 5125090 ) );
Thread.sleep( 2 * 1000 );
this.mMapView.getController().animateTo( new GeoPoint( 52085117, 5128255 ) );
Thread.sleep( 2 * 1000 );
this.mMapView.getController().animateTo( new GeoPoint( 52081517, 5121646 ) );
Thread.sleep( 2 * 1000 );
this.mMapView.getController().animateTo( new GeoPoint( 52093535, 5116711 ) );
Thread.sleep( 2 * 1000 );
this.sendKeys( "G G" );
Thread.sleep( 5 * 1000 );
}
@SmallTest
public void c_startRoute10Seconds() throws InterruptedException
{
sendMessage( "Lets start a new route" );
Thread.sleep( 1 * 1000 );
this.sendKeys( "MENU DPAD_RIGHT DPAD_LEFT" );
Thread.sleep( 2 * 1000 );
this.sendKeys( "T" );//Toggle start/stop tracker
Thread.sleep( 1 * 1000 );
this.mMapView.getController().setZoom( ZOOM_LEVEL);
this.sendKeys( "D E M O SPACE R O U T E ENTER" );
Thread.sleep( 5 * 1000 );
sendMessage( "The GPS logger is already running as a background service" );
Thread.sleep( 5 * 1000 );
this.sendKeys( "ENTER" );
this.sendKeys( "T T T T" );
Thread.sleep( 30 * 1000 );
this.sendKeys( "G G" );
}
@SmallTest
public void d_showDrawMethods30seconds() throws InterruptedException
{
sendMessage( "Track drawing color has different options" );
this.mMapView.getController().setZoom( ZOOM_LEVEL );
this.sendKeys( "MENU DPAD_RIGHT DPAD_RIGHT DPAD_RIGHT" );
Thread.sleep( 2 * 1000 );
this.sendKeys( "S" );
Thread.sleep( 3 * 1000 );
this.sendKeys( "DPAD_CENTER" );
Thread.sleep( 1 * 1000 );
this.sendKeys( "DPAD_UP DPAD_UP DPAD_UP DPAD_UP" );
Thread.sleep( 2 * 1000 );
this.sendKeys( "DPAD_CENTER" );
Thread.sleep( 1 * 1000 );
this.sendKeys( "BACK" );
sendMessage( "Plain green" );
Thread.sleep( 15 * 1000 );
this.sendKeys( "MENU DPAD_RIGHT DPAD_RIGHT DPAD_RIGHT" );
Thread.sleep( 2 * 1000 );
this.sendKeys( "S" );
Thread.sleep( 3 * 1000 );
this.sendKeys( "MENU" );
Thread.sleep( 1 * 1000 );
this.sendKeys( "DPAD_CENTER" );
Thread.sleep( 1 * 1000 );
this.sendKeys( "DPAD_UP DPAD_UP DPAD_UP DPAD_UP" );
Thread.sleep( 2 * 1000 );
this.sendKeys( "DPAD_DOWN" );
Thread.sleep( 2 * 1000 );
this.sendKeys( "DPAD_DOWN" );
Thread.sleep( 2 * 1000 );
this.sendKeys( "DPAD_DOWN" );
Thread.sleep( 2 * 1000 );
this.sendKeys( "DPAD_DOWN DPAD_DOWN" );
Thread.sleep( 2 * 1000 );
this.sendKeys( "DPAD_UP");
Thread.sleep( 2 * 1000 );
this.sendKeys( "DPAD_CENTER" );
Thread.sleep( 2 * 1000 );
this.sendKeys( "BACK" );
sendMessage( "Average speeds drawn" );
Thread.sleep( 15 * 1000 );
}
@SmallTest
public void e_statistics10Seconds() throws InterruptedException
{
// Show of the statistics screen
sendMessage( "Lets look at some statistics" );
this.sendKeys( "MENU DPAD_RIGHT DPAD_RIGHT" );
Thread.sleep( 2 * 1000 );
this.sendKeys( "E" );
Thread.sleep( 2 * 1000 );
sendMessage( "Shows the basics on time, speed and distance" );
Thread.sleep( 10 * 1000 );
this.sendKeys( "BACK" );
}
@SmallTest
public void f_showPrecision30seconds() throws InterruptedException
{
this.mMapView.getController().setZoom( ZOOM_LEVEL );
sendMessage( "There are options on the precision of tracking" );
this.sendKeys( "MENU DPAD_RIGHT DPAD_RIGHT DPAD_RIGHT" );
Thread.sleep( 2 * 1000 );
this.sendKeys( "S" );
Thread.sleep( 3 * 1000 );
this.sendKeys( "DPAD_DOWN DPAD_DOWN" );
Thread.sleep( 1 * 1000 );
this.sendKeys( "DPAD_CENTER" );
Thread.sleep( 1 * 1000 );
this.sendKeys( "DPAD_UP DPAD_UP" );
Thread.sleep( 2 * 1000 );
this.sendKeys( "DPAD_DOWN DPAD_DOWN" );
Thread.sleep( 2 * 1000 );
this.sendKeys( "DPAD_UP" );
Thread.sleep( 1 * 1000 );
this.sendKeys( "DPAD_CENTER" );
Thread.sleep( 1 * 1000 );
this.sendKeys( "BACK" );
sendMessage( "Course will drain the battery the least" );
Thread.sleep( 5 * 1000 );
sendMessage( "Fine will store the best track" );
Thread.sleep( 10 * 1000 );
}
@SmallTest
public void g_stopTracking10Seconds() throws InterruptedException
{
this.mMapView.getController().setZoom( ZOOM_LEVEL );
Thread.sleep( 5 * 1000 );
// Stop tracking
sendMessage( "Stopping tracking" );
this.sendKeys( "MENU DPAD_RIGHT DPAD_LEFT" );
Thread.sleep( 2 * 1000 );
this.sendKeys( "T" );
Thread.sleep( 2 * 1000 );
sendMessage( "Is the track stored?" );
Thread.sleep( 1 * 1000 );
this.sendKeys( "MENU DPAD_RIGHT" );
Thread.sleep( 2 * 1000 );
this.sendKeys( "L" );
this.sendKeys( "DPAD_DOWN DPAD_DOWN" );
Thread.sleep( 2 * 1000 );
this.sendKeys( "DPAD_CENTER" );
Thread.sleep( 2 * 1000 );
}
private void h_shareTrack30Seconds()
{
// TODO Auto-generated method stub
}
@SmallTest
public void i_finish10Seconds() throws InterruptedException
{
this.mMapView.getController().setZoom( ZOOM_LEVEL );
this.sendKeys( "G G" );
Thread.sleep( 1 * 1000 );
this.sendKeys( "G G" );
Thread.sleep( 1 * 1000 );
this.sendKeys( "G G" );
sendMessage( "Thank you for watching this demo." );
Thread.sleep( 10 * 1000 );
Thread.sleep( 5 * 1000 );
}
private void sendMessage( String string )
{
this.mSender.sendSMS( string );
}
}
| Java |
/*
* Copyright (C) 2010 Just Objects B.V.
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package org.opentraces.metatracker.xml;
import org.w3c.dom.*;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;
import java.io.InputStream;
import java.io.PrintWriter;
import java.io.StringWriter;
/**
* Utility methods for working with a DOM tree.
* $Id: DOMUtil.java,v 1.18 2004/09/10 14:20:50 just Exp $
*
* @author $Author: just $ - Just van den Broecke - Just Objects B.V. ©
*/
public class DOMUtil
{
/**
* Clears all childnodes in document
*/
public static void clearDocument(Document document)
{
NodeList nodeList = document.getChildNodes();
if (nodeList == null)
{
return;
}
int len = nodeList.getLength();
for (int i = 0; i < len; i++)
{
document.removeChild(nodeList.item(i));
}
}
/**
* Create empty document TO BE DEBUGGED!.
*/
public static Document createDocument()
{
DocumentBuilder documentBuilder = null;
// System.setProperty("javax.xml.parsers.DocumentBuilderFactory", "org.apache.xerces.jaxp.DocumentBuilderFactoryImpl");
try
{
documentBuilder = DocumentBuilderFactory.newInstance().newDocumentBuilder();
} catch (ParserConfigurationException pce)
{
warn("ParserConfigurationException: " + pce);
return null;
}
return documentBuilder.newDocument();
}
/**
* Copies all attributes from one element to another in the official way.
*/
public static void copyAttributes(Element elementFrom, Element elementTo)
{
NamedNodeMap nodeList = elementFrom.getAttributes();
if (nodeList == null)
{
// No attributes to copy: just return
return;
}
Attr attrFrom = null;
Attr attrTo = null;
// Needed as factory to create attrs
Document documentTo = elementTo.getOwnerDocument();
int len = nodeList.getLength();
// Copy each attr by making/setting a new one and
// adding to the target element.
for (int i = 0; i < len; i++)
{
attrFrom = (Attr) nodeList.item(i);
// Create an set value
attrTo = documentTo.createAttribute(attrFrom.getName());
attrTo.setValue(attrFrom.getValue());
// Set in target element
elementTo.setAttributeNode(attrTo);
}
}
public static Element getFirstElementByTagName(Document document, String tag)
{
// Get all elements matching the tagname
NodeList nodeList = document.getElementsByTagName(tag);
if (nodeList == null)
{
p("no list of elements with tag=" + tag);
return null;
}
// Get the first if any.
Element element = (Element) nodeList.item(0);
if (element == null)
{
p("no element for tag=" + tag);
return null;
}
return element;
}
public static Element getElementById(Document document, String id)
{
return getElementById(document.getDocumentElement(), id);
}
public static Element getElementById(Element element, String id)
{
return getElementById(element.getChildNodes(), id);
}
/**
* Get Element that has attribute id="xyz".
*/
public static Element getElementById(NodeList nodeList, String id)
{
// Note we should really use the Query here !!
Element element = null;
int len = nodeList.getLength();
for (int i = 0; i < len; i++)
{
Node node = (Node) nodeList.item(i);
if (node.getNodeType() == Node.ELEMENT_NODE)
{
element = (Element) node;
if (((Element) node).getAttribute("id").equals(id))
{
// found it !
break;
}
}
}
// returns found element or null
return element;
}
public static Document parse(InputStream anInputStream)
{
Document document;
DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
try
{
DocumentBuilder builder = factory.newDocumentBuilder();
document = builder.parse(anInputStream);
} catch (Exception e)
{
throw new RuntimeException(e);
}
return document;
}
/**
* Prints an XML DOM.
*/
public static void printAsXML(Document document, PrintWriter printWriter)
{
new TreeWalker(new XMLPrintVisitor(printWriter)).traverse(document);
}
/**
* Prints an XML DOM.
*/
public static String dom2String(Document document)
{
StringWriter sw = new StringWriter();
DOMUtil.printAsXML(document, new PrintWriter(sw));
return sw.toString();
}
/**
* Replaces an element in document.
*/
public static void replaceElement(Element newElement, Element oldElement)
{
// Must be 1
Node parent = oldElement.getParentNode();
if (parent == null)
{
warn("replaceElement: no parent of oldElement found");
return;
}
// Create a copy owned by the document
ElementCopyVisitor ecv = new ElementCopyVisitor(oldElement.getOwnerDocument(), newElement);
Element newElementCopy = ecv.getCopy();
// Replace the old element with the new copy
parent.replaceChild(newElementCopy, oldElement);
}
/**
* Write Document structure to XML file.
*/
static public void document2File(Document document, String fileName)
{
new TreeWalker(new XMLPrintVisitor(fileName)).traverse(document);
}
public static void warn(String s)
{
p("DOMUtil: WARNING " + s);
}
public static void p(String s)
{
// System.out.println("DOMUtil: "+s);
}
}
/*
* $Log: DOMUtil.java,v $
* Revision 1.18 2004/09/10 14:20:50 just
* expandIncludes() tab to 2 spaces
*
* Revision 1.17 2004/09/10 12:48:11 just
* ok
*
* Revision 1.16 2003/01/06 00:23:49 just
* moved devenv to linux
*
* Revision 1.15 2002/11/14 20:25:20 just
* reformat of code only
*
* Revision 1.14 2002/06/18 10:30:02 just
* no rel change
*
* Revision 1.13 2001/08/01 15:20:23 kstroke
* fix for expand includes (added rootDir)
*
* Revision 1.12 2001/02/17 14:28:16 just
* added comments and changed interface for expandIds()
*
* Revision 1.11 2000/12/09 14:35:35 just
* added parse() method with optional DTD validation
*
* Revision 1.10 2000/09/21 22:37:20 just
* removed print statements
*
* Revision 1.9 2000/08/28 00:07:46 just
* changes for introduction of EntityResolverImpl
*
* Revision 1.8 2000/08/24 10:11:12 just
* added XML file verfication
*
* Revision 1.7 2000/08/10 19:26:58 just
* changes for comments only
*
*
*/
| Java |
/*
* Copyright (C) 2010 Just Objects B.V.
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package org.opentraces.metatracker.xml;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.Text;
/**
* Makes deep copy of an Element for another Document.
* $Id: ElementCopyVisitor.java,v 1.4 2003/01/06 00:23:49 just Exp $
*
* @author $Author: just $ - Just van den Broecke - Just Objects B.V. ©
*/
public class ElementCopyVisitor extends DefaultVisitor
{
Document ownerDocument;
Element elementOrig;
Element elementCopy;
Element elementPointer;
int level = 0;
public ElementCopyVisitor(Document theOwnerDocument, Element theElement)
{
ownerDocument = theOwnerDocument;
elementOrig = theElement;
}
public Element getCopy()
{
new TreeWalker(this).traverse(elementOrig);
return elementCopy;
}
public void visitDocumentPre(Document document)
{
p("visitDocumentPre: level=" + level);
}
public void visitDocumentPost(Document document)
{
p("visitDocumentPost: level=" + level);
}
public void visitElementPre(Element element)
{
p("visitElementPre: " + element.getTagName() + " level=" + level);
// Create the copy; must use target document as factory
Element newElement = ownerDocument.createElement(element.getTagName());
// If first time we need to create the copy
if (elementCopy == null)
{
elementCopy = newElement;
} else
{
elementPointer.appendChild(newElement);
}
// Always point to the last created and appended element
elementPointer = newElement;
level++;
}
public void visitElementPost(Element element)
{
p("visitElementPost: " + element.getTagName() + " level=" + level);
DOMUtil.copyAttributes(element, elementPointer);
level--;
if (level == 0) return;
// Always transfer attributes if any
if (level > 0)
{
elementPointer = (Element) elementPointer.getParentNode();
}
}
public void visitText(Text element)
{
// Create the copy; must use target document as factory
Text newText = ownerDocument.createTextNode(element.getData());
// If first time we need to create the copy
if (elementPointer == null)
{
p("ERROR no element copy");
return;
} else
{
elementPointer.appendChild(newText);
}
}
private void p(String s)
{
//System.out.println("ElementCopyVisitor: "+s);
}
}
/*
* $Log: ElementCopyVisitor.java,v $
* Revision 1.4 2003/01/06 00:23:49 just
* moved devenv to linux
*
* Revision 1.3 2002/11/14 20:25:20 just
* reformat of code only
*
* Revision 1.2 2000/08/10 19:26:58 just
* changes for comments only
*
*
*/
| Java |
/*
* Copyright (C) 2010 Just Objects B.V.
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package org.opentraces.metatracker.xml;
import org.w3c.dom.*;
import java.io.FileWriter;
import java.io.IOException;
import java.io.Writer;
/**
* XMLPrintVisitor implements the Visitor interface in the visitor design pattern for the
* purpose of printing in HTML-like format the various DOM-Nodes.
* <p>In HTML-like printing, only the following Nodes are printed:
* <DL>
* <DT>Document</DT>
* <DD>Only the doctype provided on this constructor is written (i.e. no XML declaration, <!DOCTYPE>, or internal DTD).</DD>
* <DT>Element</DT>
* <DD>All element names are uppercased.</DD>
* <DD>Empty elements are written as <code><BR></code> instead of <code><BR/></code>.</DD>
* <DT>Attr</DT>
* <DD>All attribute names are lowercased.</DD>
* <DT>Text</DT>
* </DL>
* <p/>
* <p>The following sample code uses the XMLPrintVisitor on a hierarchy of nodes:
* <pre>
* <p/>
* PrintWriter printWriter = new PrintWriter();
* Visitor htmlPrintVisitor = new XMLPrintVisitor(printWriter);
* TreeWalker treeWalker = new TreeWalker(htmlPrintVisitor);
* treeWalker.traverse(document);
* printWriter.close();
* <p/>
* </pre>
* <p/>
* <P>By default, this doesn't print non-specified attributes.</P>
*
* @author $Author: just $ - Just van den Broecke - Just Objects B.V. ©
* @version $Id: XMLPrintVisitor.java,v 1.8 2003/01/06 00:23:49 just Exp $
* @see Visitor
* @see TreeWalker
*/
public class XMLPrintVisitor implements Visitor
{
protected Writer writer = null;
protected int level = 0;
protected String doctype = null;
/**
* Constructor for customized encoding and doctype.
*
* @param writer The character output stream to use.
* @param encoding Java character encoding in use by <VAR>writer</VAR>.
* @param doctype String to be printed at the top of the document.
*/
public XMLPrintVisitor(Writer writer, String encoding, String doctype)
{
this.writer = writer;
this.doctype = doctype;
// this.isPrintNonSpecifiedAttributes = false;
}
/**
* Constructor for customized encoding.
*
* @param writer The character output stream to use.
* @param encoding Java character encoding in use by <VAR>writer</VAR>.
*/
public XMLPrintVisitor(Writer writer, String encoding)
{
this(writer, encoding, null);
}
/**
* Constructor for default encoding.
*
* @param writer The character output stream to use.
*/
public XMLPrintVisitor(Writer writer)
{
this(writer, null, null);
}
/**
* Constructor for default encoding.
*
* @param fileName the filepath to write to
*/
public XMLPrintVisitor(String fileName)
{
try
{
writer = new FileWriter(fileName);
} catch (IOException ioe)
{
}
}
/**
* Writes the <var>doctype</var> from the constructor (if any).
*
* @param document Node print as HTML.
*/
public void visitDocumentPre(Document document)
{
}
/**
* Flush the writer.
*
* @param document Node to print as HTML.
*/
public void visitDocumentPost(Document document)
{
write("\n");
flush();
}
/**
* Creates a formatted string representation of the start of the specified <var>element</var> Node
* and its associated attributes, and directs it to the print writer.
*
* @param element Node to print as XML.
*/
public void visitElementPre(Element element)
{
this.level++;
write("<" + element.getTagName());
NamedNodeMap attributes = element.getAttributes();
for (int i = 0; i < attributes.getLength(); i++)
{
Attr attr = (Attr) attributes.item(i);
visitAttributePre(attr);
}
write(">\n");
}
/**
* Creates a formatted string representation of the end of the specified <var>element</var> Node,
* and directs it to the print writer.
*
* @param element Node to print as XML.
*/
public void visitElementPost(Element element)
{
String tagName = element.getTagName();
// if (element.hasChildNodes()) {
write("</" + tagName + ">\n");
// }
level--;
}
/**
* Creates a formatted string representation of the specified <var>attribute</var> Node
* and its associated attributes, and directs it to the print writer.
* <p>Note that TXAttribute Nodes are not parsed into the document object hierarchy by the
* XML4J parser; attributes exist as part of a Element Node.
*
* @param attr attr to print.
*/
public void visitAttributePre(Attr attr)
{
write(" " + attr.getName() + "=\"" + attr.getValue() + "\"");
}
/**
* Creates a formatted string representation of the specified <var>text</var> Node,
* and directs it to the print writer. CDATASections are respected.
*
* @param text Node to print with format.
*/
public void visitText(Text text)
{
if (this.level > 0)
{
write(text.getData());
}
}
private void write(String s)
{
try
{
writer.write(s);
} catch (IOException e)
{
}
}
private void flush()
{
try
{
writer.flush();
} catch (IOException e)
{
}
}
}
| Java |
/*
* Copyright (C) 2010 Just Objects B.V.
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package org.opentraces.metatracker.xml;
/**
* This class does a pre-order walk of a DOM tree or Node, calling an ElementVisitor
* interface as it goes.
* <p>The numbered nodes in the trees below indicate the order of traversal given
* the specified <code>startNode</code> of "1".
* <pre>
*
* 1 x x
* / \ / \ / \
* 2 6 1 x x x
* /|\ \ /|\ \ /|\ \
* 3 4 5 7 2 3 4 x x 1 x x
*
* </pre>
* $Id: TreeWalker.java,v 1.5 2003/01/06 00:23:49 just Exp $
*
* @author $Author: just $ - Just van den Broecke - Just Objects B.V. ©
*/
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.Node;
import org.w3c.dom.Text;
public class TreeWalker
{
private Visitor visitor;
private Node topNode;
/**
* Constructor.
*
* @param
*/
public TreeWalker(Visitor theVisitor)
{
visitor = theVisitor;
}
/**
* Disabled default constructor.
*/
private TreeWalker()
{
}
/**
* Perform a pre-order traversal non-recursive style.
*/
public void traverse(Node node)
{
// Remember the top node
if (topNode == null)
{
topNode = node;
}
while (node != null)
{
visitPre(node);
Node nextNode = node.getFirstChild();
while (nextNode == null)
{
visitPost(node);
// We are ready after post-visiting the topnode
if (node == topNode)
{
return;
}
try
{
nextNode = node.getNextSibling();
}
catch (IndexOutOfBoundsException e)
{
nextNode = null;
}
if (nextNode == null)
{
node = node.getParentNode();
if (node == null)
{
nextNode = node;
break;
}
}
}
node = nextNode;
}
}
protected void visitPre(Node node)
{
switch (node.getNodeType())
{
case Node.DOCUMENT_NODE:
visitor.visitDocumentPre((Document) node);
break;
case Node.ELEMENT_NODE:
visitor.visitElementPre((Element) node);
break;
case Node.TEXT_NODE:
visitor.visitText((Text) node);
break;
// Not yet
case Node.ENTITY_REFERENCE_NODE:
System.out.println("ENTITY_REFERENCE_NODE");
default:
break;
}
}
protected void visitPost(Node node)
{
switch (node.getNodeType())
{
case Node.DOCUMENT_NODE:
visitor.visitDocumentPost((Document) node);
break;
case Node.ELEMENT_NODE:
visitor.visitElementPost((Element) node);
break;
case Node.TEXT_NODE:
break;
default:
break;
}
}
}
/*
* $Log: TreeWalker.java,v $
* Revision 1.5 2003/01/06 00:23:49 just
* moved devenv to linux
*
* Revision 1.4 2002/11/14 20:25:20 just
* reformat of code only
*
* Revision 1.3 2000/08/10 19:26:58 just
* changes for comments only
*
*
*/
| Java |
/*
* Copyright (C) 2010 Just Objects B.V.
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package org.opentraces.metatracker.xml;
/**
* This interface specifies the callbacks from the TreeWalker.
* $Id: Visitor.java,v 1.4 2003/01/06 00:23:49 just Exp $
*
* @author $Author: just $ - Just van den Broecke - Just Objects B.V. ©
*/
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.Text;
/**
* Callback methods from the TreeWalker.
*/
public interface Visitor
{
public void visitDocumentPre(Document document);
public void visitDocumentPost(Document document);
public void visitElementPre(Element element);
public void visitElementPost(Element element);
public void visitText(Text element);
}
/*
* $Log: Visitor.java,v $
* Revision 1.4 2003/01/06 00:23:49 just
* moved devenv to linux
*
* Revision 1.3 2002/11/14 20:25:20 just
* reformat of code only
*
* Revision 1.2 2000/08/10 19:26:58 just
* changes for comments only
*
*
*/
| Java |
/*
* Copyright (C) 2010 Just Objects B.V.
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package org.opentraces.metatracker.xml;
/**
* Implements a Visitor that does nothin'
* $Id: DefaultVisitor.java,v 1.4 2003/01/06 00:23:49 just Exp $
*
* @author $Author: just $ - Just van den Broecke - Just Objects B.V. ©
*/
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.Text;
public class DefaultVisitor implements Visitor
{
public void visitDocumentPre(Document document)
{
}
public void visitDocumentPost(Document document)
{
}
public void visitElementPre(Element element)
{
}
public void visitElementPost(Element element)
{
}
public void visitText(Text element)
{
}
}
/*
* $Log: DefaultVisitor.java,v $
* Revision 1.4 2003/01/06 00:23:49 just
* moved devenv to linux
*
* Revision 1.3 2002/11/14 20:25:20 just
* reformat of code only
*
* Revision 1.2 2000/08/10 19:26:58 just
* changes for comments only
*
*
*/
| Java |
/*
* Copyright (C) 2010 Just Objects B.V.
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package org.opentraces.metatracker.logger;
import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.content.ServiceConnection;
import android.net.Uri;
import android.os.IBinder;
import android.os.RemoteException;
import android.util.Log;
import nl.sogeti.android.gpstracker.logger.IGPSLoggerServiceRemote;
import org.opentraces.metatracker.Constants;
/**
* Class to interact with the service that tracks and logs the locations
*
* @author rene (c) Jan 18, 2009, Sogeti B.V. adapted by Just van den Broecke
* @version $Id: GPSLoggerServiceManager.java 455 2010-03-14 08:16:44Z rcgroot $
*/
public class GPSLoggerServiceManager
{
private static final String TAG = "MT.GPSLoggerServiceManager";
private static final String REMOTE_EXCEPTION = "REMOTE_EXCEPTION";
private Context mCtx;
private IGPSLoggerServiceRemote mGPSLoggerRemote;
private final Object mStartLock = new Object();
private boolean mStarted = false;
/**
* Class for interacting with the main interface of the service.
*/
private ServiceConnection mServiceConnection = null;
public GPSLoggerServiceManager(Context ctx)
{
this.mCtx = ctx;
}
public boolean isStarted()
{
synchronized (mStartLock)
{
return mStarted;
}
}
public int getLoggingState()
{
synchronized (mStartLock)
{
int logging = Constants.UNKNOWN;
try
{
if (this.mGPSLoggerRemote != null)
{
logging = this.mGPSLoggerRemote.loggingState();
Log.d(TAG, "mGPSLoggerRemote tells state to be " + logging);
} else
{
Log.w(TAG, "Remote interface to logging service not found. Started: " + mStarted);
}
}
catch (RemoteException e)
{
Log.e(TAG, "Could stat GPSLoggerService.", e);
}
return logging;
}
}
public boolean isMediaPrepared()
{
synchronized (mStartLock)
{
boolean prepared = false;
try
{
if (this.mGPSLoggerRemote != null)
{
prepared = this.mGPSLoggerRemote.isMediaPrepared();
} else
{
Log.w(TAG, "Remote interface to logging service not found. Started: " + mStarted);
}
}
catch (RemoteException e)
{
Log.e(TAG, "Could stat GPSLoggerService.", e);
}
return prepared;
}
}
public long startGPSLogging(String name)
{
synchronized (mStartLock)
{
if (mStarted)
{
try
{
if (this.mGPSLoggerRemote != null)
{
return this.mGPSLoggerRemote.startLogging();
}
}
catch (RemoteException e)
{
Log.e(TAG, "Could not start GPSLoggerService.", e);
}
}
return -1;
}
}
public void pauseGPSLogging()
{
synchronized (mStartLock)
{
if (mStarted)
{
try
{
if (this.mGPSLoggerRemote != null)
{
this.mGPSLoggerRemote.pauseLogging();
}
}
catch (RemoteException e)
{
Log.e(TAG, "Could not start GPSLoggerService.", e);
}
}
}
}
public long resumeGPSLogging()
{
synchronized (mStartLock)
{
if (mStarted)
{
try
{
if (this.mGPSLoggerRemote != null)
{
return this.mGPSLoggerRemote.resumeLogging();
}
}
catch (RemoteException e)
{
Log.e(TAG, "Could not start GPSLoggerService.", e);
}
}
return -1;
}
}
public void stopGPSLogging()
{
synchronized (mStartLock)
{
if (mStarted)
{
try
{
if (this.mGPSLoggerRemote != null)
{
this.mGPSLoggerRemote.stopLogging();
}
}
catch (RemoteException e)
{
Log.e(GPSLoggerServiceManager.REMOTE_EXCEPTION, "Could not stop GPSLoggerService.", e);
}
} else
{
Log.e(TAG, "No GPSLoggerRemote service connected to this manager");
}
}
}
public void storeMediaUri(Uri mediaUri)
{
synchronized (mStartLock)
{
if (mStarted)
{
try
{
if (this.mGPSLoggerRemote != null)
{
this.mGPSLoggerRemote.storeMediaUri(mediaUri);
}
}
catch (RemoteException e)
{
Log.e(GPSLoggerServiceManager.REMOTE_EXCEPTION, "Could not send media to GPSLoggerService.", e);
}
} else
{
Log.e(TAG, "No GPSLoggerRemote service connected to this manager");
}
}
}
/**
* Means by which an Activity lifecycle aware object hints about binding and unbinding
*/
public void startup(final ServiceConnection observer)
{
Log.d(TAG, "connectToGPSLoggerService()");
if (!mStarted)
{
this.mServiceConnection = new ServiceConnection()
{
public void onServiceConnected(ComponentName className, IBinder service)
{
synchronized (mStartLock)
{
Log.d(TAG, "onServiceConnected()");
GPSLoggerServiceManager.this.mGPSLoggerRemote = IGPSLoggerServiceRemote.Stub.asInterface(service);
mStarted = true;
if (observer != null)
{
observer.onServiceConnected(className, service);
}
}
}
public void onServiceDisconnected(ComponentName className)
{
synchronized (mStartLock)
{
Log.e(TAG, "onServiceDisconnected()");
GPSLoggerServiceManager.this.mGPSLoggerRemote = null;
mStarted = false;
if (observer != null)
{
observer.onServiceDisconnected(className);
}
}
}
};
this.mCtx.bindService(new Intent(Constants.SERVICE_GPS_LOGGING), this.mServiceConnection, Context.BIND_AUTO_CREATE);
} else
{
Log.w(TAG, "Attempting to connect whilst connected");
}
}
/**
* Means by which an Activity lifecycle aware object hints about binding and unbinding
*/
public void shutdown()
{
Log.d(TAG, "disconnectFromGPSLoggerService()");
try
{
this.mCtx.unbindService(this.mServiceConnection);
}
catch (IllegalArgumentException e)
{
Log.e(TAG, "Failed to unbind a service, prehaps the service disapeared?", e);
}
}
} | Java |
/*
* Copyright (C) 2010 Just Objects B.V.
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package org.opentraces.metatracker.net;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
/**
* Constants and utilities for the KW protocol.
*
* @author $Author: $
* @version $Id: Protocol.java,v 1.2 2005/07/22 22:25:20 just Exp $
*/
public class Protocol
{
/**
* AMUSE Protocol version.
*/
public static final String PROTOCOL_VERSION = "4.0";
/**
* Postfixes
*/
public static final String POSTFIX_REQ = "-req";
public static final String POSTFIX_RSP = "-rsp";
public static final String POSTFIX_NRSP = "-nrsp";
public static final String POSTFIX_IND = "-ind";
/**
* Service id's
*/
public static final String SERVICE_SESSION_CREATE = "ses-create";
public static final String SERVICE_LOGIN = "ses-login";
public static final String SERVICE_LOGOUT = "ses-logout";
public static final String SERVICE_SESSION_PING = "ses-ping";
public static final String SERVICE_QUERY_STORE = "query-store";
public static final String SERVICE_MAP_AVAIL = "map-avail";
public static final String SERVICE_MULTI_REQ = "multi-req";
/**
* Common Attributes *
*/
public static final String ATTR_DEVID = "devid";
public static final String ATTR_USER = "user";
public static final String ATTR_AGENT = "agent";
public static final String ATTR_AGENTKEY = "agentkey";
public static final String ATTR_SECTIONS = "sections";
public static final String ATTR_ID = "id";
public static final String ATTR_CMD = "cmd";
public static final String ATTR_ERROR = "error";
public static final String ATTR_ERRORID = "errorId"; // yes id must be Id !!
public static final String ATTR_PASSWORD = "password";
public static final String ATTR_PROTOCOLVERSION = "protocolversion";
public static final String ATTR_STOPONERROR = "stoponerror";
public static final String ATTR_T = "t";
public static final String ATTR_TIME = "time";
public static final String ATTR_DETAILS = "details";
public static final String ATTR_NAME = "name";
/**
* Error ids returned in -nrsp as attribute ATTR_ERRORID
*/
public final static int
// 4000-4999 are "user-correctable" errors (user sends wrong input)
// 5000-5999 are server failures
ERR4004_ILLEGAL_COMMAND_FOR_STATE = 4003,
ERR4004_INVALID_ATTR_VALUE = 4004,
ERR4007_AGENT_LEASE_EXPIRED = 4007,
//_Portal/Application_error_codes_(4100-4199)
ERR4100_INVALID_USERNAME = 4100,
ERR4101_INVALID_PASSWORD = 4101,
ERR4102_MAX_LOGIN_ATTEMPTS_EXCEEDED = 4102,
//_General_Server_Error_Codes
ERR5000_INTERNAL_SERVER_ERROR = 5000;
/**
* Create login protocol request.
*/
public static Element createLoginRequest(String aName, String aPassword)
{
Element request = createRequest(SERVICE_LOGIN);
request.setAttribute(ATTR_NAME, aName);
request.setAttribute(ATTR_PASSWORD, aPassword);
request.setAttribute(ATTR_PROTOCOLVERSION, PROTOCOL_VERSION);
return request;
}
/**
* Create create-session protocol request.
*/
public static Element createSessionCreateRequest()
{
return createRequest(SERVICE_SESSION_CREATE);
}
/**
* Create a positive response element.
*/
public static Element createRequest(String aService)
{
Element element = null;
try
{
DocumentBuilderFactory dFact = DocumentBuilderFactory.newInstance();
DocumentBuilder build = dFact.newDocumentBuilder();
Document doc = build.newDocument();
element = doc.createElement(aService + POSTFIX_REQ);
doc.appendChild(element);
} catch (Throwable t)
{
}
return element;
}
/**
* Return service name for a message tag.
*
* @param aMessageTag
* @return
*/
public static String getServiceName(String aMessageTag)
{
try
{
return aMessageTag.substring(0, aMessageTag.lastIndexOf('-'));
}
catch (Throwable t)
{
throw new IllegalArgumentException("getServiceName: invalid tag: " + aMessageTag);
}
}
/**
* Is message a (negative) response..
*
* @param message
* @return
*/
public static boolean isResponse(Element message)
{
String tag = message.getTagName();
return tag.endsWith(POSTFIX_RSP) || tag.endsWith(POSTFIX_NRSP);
}
/**
* Is message a positive response..
*
* @param message
* @return
*/
public static boolean isPositiveResponse(Element message)
{
return message.getTagName().endsWith(POSTFIX_RSP);
}
/**
* Is message a negative response..
*
* @param message
* @return
*/
public static boolean isNegativeResponse(Element message)
{
return message.getTagName().endsWith(POSTFIX_NRSP);
}
public static boolean isPositiveServiceResponse(Element message, String service)
{
return isPositiveResponse(message) && service.equals(getServiceName(message.getTagName()));
}
public static boolean isNegativeServiceResponse(Element message, String service)
{
return isNegativeResponse(message) && service.equals(getServiceName(message.getTagName()));
}
public static boolean isService(Element message, String service)
{
return service.equals(getServiceName(message.getTagName()));
}
protected Protocol()
{
}
}
| Java |
/*
* Copyright (C) 2010 Just Objects B.V.
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package org.opentraces.metatracker.net;
import android.util.Log;
import org.apache.http.HttpResponse;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.StringEntity;
import org.apache.http.entity.mime.MultipartEntity;
import org.apache.http.entity.mime.content.FileBody;
import org.apache.http.entity.mime.content.StringBody;
import org.apache.http.impl.client.DefaultHttpClient;
import org.opentraces.metatracker.xml.DOMUtil;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.NodeList;
import java.io.File;
import java.util.ArrayList;
import java.util.List;
/**
* Basic OpenTraces client using XML over HTTP.
* <p/>
* Use this class within Android HTTP clients.
*
* @author $Author: Just van den Broecke$
* @version $Revision: 3043 $ $Id: HTTPClient.java 3043 2009-01-17 16:25:21Z just $
* @see
*/
public class OpenTracesClient extends Protocol
{
private static final String LOG_TAG = "MT.OpenTracesClient";
/**
* Default KW session timeout (minutes).
*/
public static final int DEFAULT_TIMEOUT_MINS = 5;
/**
* Full KW protocol URL.
*/
private String protocolURL;
/**
* Debug flag for verbose output.
*/
private boolean debug;
/**
* Key gotten on login ack
*/
private String agentKey;
/**
* Keyworx session timeout (minutes).
*/
private int timeout;
/**
* Saved login request for session restore on timeout.
*/
private Element loginRequest;
/**
* Constructor with full protocol URL e.g. http://www.bla.com/proto.srv.
*/
public OpenTracesClient(String aProtocolURL)
{
this(aProtocolURL, DEFAULT_TIMEOUT_MINS);
}
/**
* Constructor with protocol URL and timeout.
*/
public OpenTracesClient(String aProtocolURL, int aTimeout)
{
protocolURL = aProtocolURL;
if (!protocolURL.endsWith("/proto.srv")) {
protocolURL += "/proto.srv";
}
timeout = aTimeout;
}
/**
* Create session.
*/
synchronized public Element createSession() throws ClientException
{
agentKey = null;
// Create XML request
Element request = createRequest(SERVICE_SESSION_CREATE);
// Execute request
Element response = doRequest(request);
handleResponse(request, response);
throwOnNrsp(response);
// Returns positive response
return response;
}
public String getAgentKey()
{
return agentKey;
}
public boolean hasSession()
{
return agentKey != null;
}
public boolean isLoggedIn()
{
return hasSession() && loginRequest != null;
}
/**
* Login on portal.
*/
synchronized public Element login(String aName, String aPassword) throws ClientException
{
// Create XML request
Element request = createLoginRequest(aName, aPassword);
// Execute request
Element response = doRequest(request);
// Filter session-related attrs
handleResponse(request, response);
throwOnNrsp(response);
// Returns positive response
return response;
}
/**
* Keep alive service.
*/
synchronized public Element ping() throws ClientException
{
return service(createRequest(SERVICE_SESSION_PING));
}
/**
* perform TWorx service request.
*/
synchronized public Element service(Element request) throws ClientException
{
throwOnInvalidSession();
// Execute request
Element response = doRequest(request);
// Check for session timeout
response = redoRequestOnSessionTimeout(request, response);
// Throw exception on negative response
throwOnNrsp(response);
// Positive response: return wrapped handler response
return response;
}
/**
* perform TWorx multi-service request.
*/
synchronized public List<Element> service(List<Element> requests, boolean stopOnError) throws ClientException
{
// We don't need a valid session as one of the requests
// may be a login or create-session request.
// Create multi-req request with individual requests as children
Element request = createRequest(SERVICE_MULTI_REQ);
request.setAttribute(ATTR_STOPONERROR, stopOnError + "");
for (Element req : requests)
{
request.appendChild(req);
}
// Execute request
Element response = doRequest(request);
// Check for session timeout
response = redoRequestOnSessionTimeout(request, response);
// Throw exception on negative response
throwOnNrsp(response);
// Filter child responses for session-based responses
NodeList responseList = response.getChildNodes();
List<Element> responses = new ArrayList(responseList.getLength());
for (int i = 0; i < responseList.getLength(); i++)
{
handleResponse(requests.get(i), (Element) responseList.item(i));
responses.add((Element) responseList.item(i));
}
// Positive multi-req response: return child responses
return responses;
}
/**
* Logout from portal.
*/
synchronized public Element logout() throws ClientException
{
throwOnInvalidSession();
// Create XML request
Element request = createRequest(SERVICE_LOGOUT);
// Execute request
Element response = doRequest(request);
handleResponse(request, response);
// Throw exception or return positive response
// throwOnNrsp(response);
return response;
}
/*
http://brainflush.wordpress.com/2008/10/17/talking-to-web-servers-via-http-in-android-10/
*/
public void uploadFile(String fileName)
{
try
{
DefaultHttpClient httpclient = new DefaultHttpClient();
File f = new File(fileName);
HttpPost httpost = new HttpPost("http://local.geotracing.com/tland/media.srv");
MultipartEntity entity = new MultipartEntity();
entity.addPart("myIdentifier", new StringBody("somevalue"));
entity.addPart("myFile", new FileBody(f));
httpost.setEntity(entity);
HttpResponse response;
response = httpclient.execute(httpost);
Log.d(LOG_TAG, "Upload result: " + response.getStatusLine());
if (entity != null)
{
entity.consumeContent();
}
httpclient.getConnectionManager().shutdown();
} catch (Throwable ex)
{
Log.d(LOG_TAG, "Upload failed: " + ex.getMessage() + " Stacktrace: " + ex.getStackTrace());
}
}
public void setDebug(boolean b)
{
debug = b;
}
/**
* Filter responses for session-related requests.
*/
private void handleResponse(Element request, Element response) throws ClientException
{
if (isNegativeResponse(response))
{
return;
}
String service = Protocol.getServiceName(request.getTagName());
if (service.equals(SERVICE_LOGIN))
{
// Save for later session restore
loginRequest = request;
// Save session key
agentKey = response.getAttribute(ATTR_AGENTKEY);
// if (response.hasAttribute(ATTR_TIME)) {
// DateTimeUtils.setTime(response.getLongAttr(ATTR_TIME));
// }
} else if (service.equals(SERVICE_SESSION_CREATE))
{
// Save session key
agentKey = response.getAttribute(ATTR_AGENTKEY);
} else if (service.equals(SERVICE_LOGOUT))
{
loginRequest = null;
agentKey = null;
}
}
/**
* Throw exception on negative protocol response.
*/
private void throwOnNrsp(Element anElement) throws ClientException
{
if (isNegativeResponse(anElement))
{
String details = "no details";
if (anElement.hasAttribute(ATTR_DETAILS))
{
details = anElement.getAttribute(ATTR_DETAILS);
}
throw new ClientException(Integer.parseInt(anElement.getAttribute(ATTR_ERRORID)),
anElement.getAttribute(ATTR_ERROR), details);
}
}
/**
* Throw exception when not logged in.
*/
private void throwOnInvalidSession() throws ClientException
{
if (agentKey == null)
{
throw new ClientException("Invalid tworx session");
}
}
/**
* .
*/
private Element redoRequestOnSessionTimeout(Element request, Element response) throws ClientException
{
// Check for session timeout
if (isNegativeResponse(response) && Integer.parseInt(response.getAttribute(ATTR_ERRORID)) == Protocol.ERR4007_AGENT_LEASE_EXPIRED)
{
p("Reestablishing session...");
// Reset session
agentKey = null;
// Do login if already logged in
if (loginRequest != null)
{
response = doRequest(loginRequest);
throwOnNrsp(response);
} else
{
response = createSession();
throwOnNrsp(response);
}
// Save session key
agentKey = response.getAttribute(ATTR_AGENTKEY);
// Re-issue service request and return new response
return doRequest(request);
}
// No session timeout so same response
return response;
}
/**
* Do XML over HTTP request and retun response.
*/
private Element doRequest(Element anElement) throws ClientException
{
// Create URL to use
String url = protocolURL;
if (agentKey != null)
{
url = url + "?agentkey=" + agentKey;
} else
{
// Must be login
url = url + "?timeout=" + timeout;
}
p("doRequest: " + url + " req=" + anElement.getTagName());
// Perform request/response
HttpClient httpclient = new DefaultHttpClient();
HttpPost httpPost = new HttpPost(url);
Element replyElement = null;
try
{
// Make sure the server knows what kind of a response we will accept
httpPost.addHeader("Accept", "text/xml");
// Also be sure to tell the server what kind of content we are sending
httpPost.addHeader("Content-Type", "application/xml");
String xmlString = DOMUtil.dom2String(anElement.getOwnerDocument());
StringEntity entity = new StringEntity(xmlString, "UTF-8");
entity.setContentType("application/xml");
httpPost.setEntity(entity);
// Execute HTTP Post Request
HttpResponse response = httpclient.execute(httpPost);
// Parse response
Document replyDoc = DOMUtil.parse(response.getEntity().getContent());
replyElement = replyDoc.getDocumentElement();
p("doRequest: rsp=" + replyElement.getTagName());
}
catch (Throwable t)
{
throw new ClientException("Error in doRequest: " + t);
}
finally
{
}
return replyElement;
}
/**
* Util: print.
*/
private void p(String s)
{
if (debug)
{
Log.d(LOG_TAG, s);
}
}
/**
* Util: warn.
*/
private void warn(String s)
{
warn(s, null);
}
/**
* Util: warn with exception.
*/
private void warn(String s, Throwable t)
{
Log.e(LOG_TAG, s + " ex=" + t, t);
}
}
| Java |
/*
* Copyright (C) 2010 Just Objects B.V.
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package org.opentraces.metatracker.net;
/**
* Generic exception wrapper. $Id: ClientException.java,v 1.2 2005/07/22 22:25:20 just Exp $
*
* @author $Author: Just van den Broecke$
* @version $Revision: $
*/
public class ClientException extends Exception
{
private int errorId;
String error;
protected ClientException()
{
}
public ClientException(String aMessage, Throwable t)
{
super(aMessage + "\n embedded exception=" + t.toString());
}
public ClientException(String aMessage)
{
super(aMessage);
}
public ClientException(int anErrorId, String anError, String someDetails)
{
super(someDetails);
errorId = anErrorId;
error = anError;
}
public ClientException(Throwable t)
{
this("ClientException: ", t);
}
public String toString()
{
return "ClientException: " + getMessage();
}
}
| Java |
/*
* Copyright (C) 2010 Just Objects B.V.
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package org.opentraces.metatracker;
import android.net.Uri;
/**
* Various application wide constants
*
* @author Just van den Broecke
* @version $Id:$
*/
public class Constants
{
/**
* The authority of the track data provider
*/
public static final String AUTHORITY = "nl.sogeti.android.gpstracker";
/**
* The content:// style URL for the track data provider
*/
public static final Uri CONTENT_URI = Uri.parse("content://" + AUTHORITY);
/**
* Logging states, slightly adapted from GPSService states
*/
public static final int DOWN = 0;
public static final int LOGGING = 1;
public static final int PAUSED = 2;
public static final int STOPPED = 3;
public static final int UNKNOWN = 4;
public static String[] LOGGING_STATES = {"down", "logging", "paused", "stopped", "unknown"};
public static final String DISABLEBLANKING = "disableblanking";
public static final String PREF_ENABLE_SOUND = "pref_enablesound";
public static final String PREF_SERVER_URL = "pref_server_url";
public static final String PREF_SERVER_USER = "pref_server_user";
public static final String PREF_SERVER_PASSWORD = "pref_server_password";
public static final String SERVICE_GPS_LOGGING = "nl.sogeti.android.gpstracker.intent.action.GPSLoggerService";
public static final String EXTERNAL_DIR = "/OpenGPSTracker/";
public static final Uri NAME_URI = Uri.parse("content://" + AUTHORITY + ".string");
/**
* Activity Action: Pick a file through the file manager, or let user
* specify a custom file name.
* Data is the current file name or file name suggestion.
* Returns a new file name as file URI in data.
* <p/>
* <p>Constant Value: "org.openintents.action.PICK_FILE"</p>
*/
public static final String ACTION_PICK_FILE = "org.openintents.action.PICK_FILE";
public static final int REQUEST_CODE_PICK_FILE_OR_DIRECTORY = 1;
/**
* Activity Action: Show an about dialog to display
* information about the application.
* <p/>
* The application information is retrieved from the
* application's manifest. In order to send the package
* you have to launch this activity through
* startActivityForResult().
* <p/>
* Alternatively, you can specify the package name
* manually through the extra EXTRA_PACKAGE.
* <p/>
* All data can be replaced using optional intent extras.
* <p/>
* <p>
* Constant Value: "org.openintents.action.SHOW_ABOUT_DIALOG"
* </p>
*/
public static final String OI_ACTION_SHOW_ABOUT_DIALOG =
"org.openintents.action.SHOW_ABOUT_DIALOG";
/**
* Definitions for tracks.
*
*/
public static final class Tracks implements android.provider.BaseColumns
{
/**
* The name of this table
*/
static final String TABLE = "tracks";
/**
* The end time
*/
public static final String NAME = "name";
public static final String CREATION_TIME = "creationtime";
/**
* The MIME type of a CONTENT_URI subdirectory of a single track.
*/
public static final String CONTENT_ITEM_TYPE = "vnd.android.cursor.item/vnd.nl.sogeti.android.track";
/**
* The content:// style URL for this provider
*/
public static final Uri CONTENT_URI = Uri.parse("content://" + AUTHORITY + "/" + TABLE);
}
/**
* Definitions for segments.
*/
public static final class Segments implements android.provider.BaseColumns
{
/**
* The name of this table
*/
static final String TABLE = "segments";
/**
* The track _id to which this segment belongs
*/
public static final String TRACK = "track";
static final String TRACK_TYPE = "INTEGER NOT NULL";
static final String _ID_TYPE = "INTEGER PRIMARY KEY AUTOINCREMENT";
/**
* The MIME type of a CONTENT_URI subdirectory of a single segment.
*/
public static final String CONTENT_ITEM_TYPE = "vnd.android.cursor.item/vnd.nl.sogeti.android.segment";
/**
* The MIME type of CONTENT_URI providing a directory of segments.
*/
public static final String CONTENT_TYPE = "vnd.android.cursor.dir/vnd.nl.sogeti.android.segment";
public static final Uri CONTENT_URI = Uri.parse("content://" + AUTHORITY + "/" + TABLE);
}
/**
* Definitions for media URI's.
*
*/
public static final class Media implements android.provider.BaseColumns
{
/**
* The track _id to which this segment belongs
*/
public static final String TRACK = "track";
public static final String SEGMENT = "segment";
public static final String WAYPOINT = "waypoint";
public static final String URI = "uri";
/**
* The name of this table
*/
public static final String TABLE = "media";
public static final Uri CONTENT_URI = Uri.parse("content://" + AUTHORITY + "/" + TABLE);
}
/**
* Definitions for waypoints.
*
*/
public static final class Waypoints implements android.provider.BaseColumns
{
/**
* The name of this table
*/
public static final String TABLE = "waypoints";
/**
* The latitude
*/
public static final String LATITUDE = "latitude";
/**
* The longitude
*/
public static final String LONGITUDE = "longitude";
/**
* The recorded time
*/
public static final String TIME = "time";
/**
* The speed in meters per second
*/
public static final String SPEED = "speed";
/**
* The segment _id to which this segment belongs
*/
public static final String SEGMENT = "tracksegment";
/**
* The accuracy of the fix
*/
public static final String ACCURACY = "accuracy";
/**
* The altitude
*/
public static final String ALTITUDE = "altitude";
/**
* the bearing of the fix
*/
public static final String BEARING = "bearing";
public static final Uri CONTENT_URI = Uri.parse("content://" + AUTHORITY + "/" + TABLE);
}
}
| Java |
/*
* Copyright (C) 2010 Just Objects B.V.
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package org.opentraces.metatracker.activity;
import android.content.SharedPreferences;
import android.location.Location;
import org.opentraces.metatracker.Constants;
public class TrackingState
{
public int loggingState;
public boolean newRoadRating;
public int roadRating;
public float distance;
public Track track = new Track();
public Segment segment = new Segment();
public Waypoint waypoint = new Waypoint();
private SharedPreferences sharedPreferences;
public TrackingState(SharedPreferences sharedPreferences) {
this.sharedPreferences = sharedPreferences;
reset();
}
public void load()
{
distance = sharedPreferences.getFloat("distance", 0.0f);
track.load();
waypoint.load();
}
public void save()
{
sharedPreferences.edit().putFloat("distance", distance).commit();
track.save();
waypoint.save();
}
public void reset()
{
loggingState = Constants.DOWN;
distance = 0.0f;
waypoint.reset();
track.reset();
}
public class Track
{
public int id = -1;
public String name = "NO TRACK";
public long creationTime;
public void load()
{
id = sharedPreferences.getInt("track.id", -1);
name = sharedPreferences.getString("track.name", "NO TRACK");
}
public void save()
{
SharedPreferences.Editor editor = sharedPreferences.edit();
editor.putInt("track.id", id);
editor.putString("track.name", name);
editor.commit();
}
public void reset()
{
name = "NO TRACK";
id = -1;
}
}
public static class Segment
{
public int id = -1;
}
public class Waypoint
{
public int id = -1;
public Location location;
public float speed;
public float accuracy;
public int count;
public void load()
{
id = sharedPreferences.getInt("waypoint.id", -1);
count = sharedPreferences.getInt("waypoint.count", 0);
}
public void save()
{
SharedPreferences.Editor editor = sharedPreferences.edit();
editor.putInt("waypoint.id", id);
editor.putInt("waypoint.count", count);
editor.commit();
}
public void reset()
{
count = 0;
id = -1;
location = null;
}
}
}
| Java |
/*
* Copyright (C) 2010 Just Objects B.V.
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package org.opentraces.metatracker.activity;
import org.opentraces.metatracker.R;
import android.os.Bundle;
import android.preference.PreferenceActivity;
/**
* Dialog for setting preferences.
*
* @author Just van den Broecke
*/
public class SettingsActivity extends PreferenceActivity
{
@Override
protected void onCreate( Bundle savedInstanceState )
{
super.onCreate( savedInstanceState );
addPreferencesFromResource( R.layout.settings );
}
}
| Java |
/*
* Copyright (C) 2010 Just Objects B.V.
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package org.opentraces.metatracker.activity;
import android.app.Activity;
import android.app.AlertDialog;
import android.app.AlertDialog.Builder;
import android.app.Dialog;
import android.content.ActivityNotFoundException;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.SharedPreferences;
import android.net.Uri;
import android.os.Bundle;
import android.os.Environment;
import android.preference.PreferenceManager;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;
import org.opentraces.metatracker.Constants;
import org.opentraces.metatracker.R;
import org.opentraces.metatracker.net.OpenTracesClient;
public class UploadTrackActivity extends Activity
{
protected static final int DIALOG_FILENAME = 11;
protected static final int PROGRESS_STEPS = 10;
private static final int DIALOG_INSTALL_FILEMANAGER = 34;
private static final String TAG = "MT.UploadTrack";
private String filePath;
private TextView fileNameView;
private SharedPreferences sharedPreferences;
private final DialogInterface.OnClickListener mFileManagerDownloadDialogListener = new DialogInterface.OnClickListener()
{
public void onClick(DialogInterface dialog, int which)
{
Uri oiDownload = Uri.parse("market://details?id=org.openintents.filemanager");
Intent oiFileManagerDownloadIntent = new Intent(Intent.ACTION_VIEW, oiDownload);
try
{
startActivity(oiFileManagerDownloadIntent);
}
catch (ActivityNotFoundException e)
{
oiDownload = Uri.parse("http://openintents.googlecode.com/files/FileManager-1.1.3.apk");
oiFileManagerDownloadIntent = new Intent(Intent.ACTION_VIEW, oiDownload);
startActivity(oiFileManagerDownloadIntent);
}
}
};
@Override
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
sharedPreferences = PreferenceManager.getDefaultSharedPreferences(this);
setContentView(R.layout.uploaddialog);
fileNameView = (TextView) findViewById(R.id.filename);
filePath = null;
pickFile();
Button okay = (Button) findViewById(R.id.okayupload_button);
okay.setOnClickListener(new View.OnClickListener()
{
public void onClick(View v)
{
if (filePath == null) {
return;
}
uploadFile(filePath);
}
});
}
/*
* (non-Javadoc)
* @see android.app.Activity#onCreateDialog(int)
*/
@Override
protected Dialog onCreateDialog(int id)
{
Dialog dialog = null;
Builder builder = null;
switch (id)
{
case DIALOG_INSTALL_FILEMANAGER:
builder = new AlertDialog.Builder(this);
builder
.setTitle(R.string.dialog_nofilemanager)
.setMessage(R.string.dialog_nofilemanager_message)
.setIcon(android.R.drawable.ic_dialog_alert)
.setPositiveButton(R.string.btn_install, mFileManagerDownloadDialogListener)
.setNegativeButton(R.string.btn_cancel, null);
dialog = builder.create();
break;
default:
dialog = super.onCreateDialog(id);
break;
}
return dialog;
}
@Override
protected void onActivityResult(int requestCode, int resultCode, Intent intent)
{
super.onActivityResult(requestCode, resultCode, intent);
// Bundle extras = intent.getExtras();
switch (requestCode)
{
case Constants.REQUEST_CODE_PICK_FILE_OR_DIRECTORY:
if (resultCode == RESULT_OK && intent != null)
{
// obtain the filename
filePath = intent.getDataString();
if (filePath != null)
{
// Get rid of URI prefix:
if (filePath.startsWith("file://"))
{
filePath = filePath.substring(7);
}
fileNameView.setText(filePath);
}
}
break;
}
}
/*
http://edwards.sdsu.edu/labsite/index.php/josh/179-android-nuts-and-bolts-vii
http://code.google.com/p/openintents/source/browse/trunk/samples/TestFileManager/src/org/openintents/samples/TestFileManager/TestFileManager.java
*/
private void pickFile()
{
Intent intent = new Intent(Constants.ACTION_PICK_FILE);
intent.setData(Uri.parse("file://" + Environment.getExternalStorageDirectory() + Constants.EXTERNAL_DIR));
try
{
startActivityForResult(intent, Constants.REQUEST_CODE_PICK_FILE_OR_DIRECTORY);
} catch (ActivityNotFoundException e)
{
// No compatible file manager was found: install openintents filemanager.
showDialog(DIALOG_INSTALL_FILEMANAGER);
}
}
/*
http://edwards.sdsu.edu/labsite/index.php/josh/179-android-nuts-and-bolts-vii
http://code.google.com/p/openintents/source/browse/trunk/samples/TestFileManager/src/org/openintents/samples/TestFileManager/TestFileManager.java
*/
private void uploadFile(String aFilePath)
{
Intent intent = new Intent(Constants.ACTION_PICK_FILE);
intent.setData(Uri.parse("file://" + Environment.getExternalStorageDirectory() + Constants.EXTERNAL_DIR));
try
{
;
OpenTracesClient openTracesClient = new OpenTracesClient(sharedPreferences.getString(Constants.PREF_SERVER_URL, "http://geotracing.com/tland"));
openTracesClient.createSession();
openTracesClient.login(sharedPreferences.getString(Constants.PREF_SERVER_USER, "no_user"), sharedPreferences.getString(Constants.PREF_SERVER_PASSWORD, "no_passwd"));
openTracesClient.uploadFile(aFilePath);
openTracesClient.logout();
} catch (Throwable e)
{
Log.e(TAG, "Error uploading file : ", e);
}
}
}
| Java |
/*
* Copyright (C) 2010 Just Objects B.V.
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package org.opentraces.metatracker.activity;
import android.app.*;
import android.content.*;
import android.database.ContentObserver;
import android.database.Cursor;
import android.location.Location;
import android.media.MediaPlayer;
import android.net.Uri;
import android.os.Bundle;
import android.os.Handler;
import android.os.IBinder;
import android.preference.PreferenceManager;
import android.util.Log;
import android.view.ContextMenu;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;
import org.opentraces.metatracker.*;
import org.opentraces.metatracker.logger.GPSLoggerServiceManager;
import java.text.DecimalFormat;
public class MainActivity extends Activity
{
// MENU'S
private static final int MENU_SETTINGS = 1;
private static final int MENU_TRACKING = 2;
private static final int MENU_UPLOAD = 3;
private static final int MENU_HELP = 4;
private static final int MENU_ABOUT = 5;
private static final int DIALOG_INSTALL_OPENGPSTRACKER = 1;
private static final int DIALOG_INSTALL_ABOUT = 2;
private static DecimalFormat REAL_FORMATTER1 = new DecimalFormat("0.#");
private static DecimalFormat REAL_FORMATTER2 = new DecimalFormat("0.##");
private static final String TAG = "MetaTracker.Main";
private TextView waypointCountView, timeView, distanceView, speedView, roadRatingView, accuracyView;
private GPSLoggerServiceManager loggerServiceManager;
private TrackingState trackingState;
private MediaPlayer mediaPlayer;
// private PowerManager.WakeLock wakeLock = null;
private static final int COLOR_WHITE = 0xFFFFFFFF;
private static final int[] ROAD_RATING_COLORS = {0xFF808080, 0xFFCC0099, 0xFFEE0000, 0xFFFF6600, 0xFFFFCC00, 0xFF33CC33};
private SharedPreferences sharedPreferences;
private Button[] roadRatingButtons = new Button[6];
/**
* Called when the activity is first created.
*/
@Override
public void onCreate(Bundle savedInstanceState)
{
Log.d(TAG, "onCreate()");
super.onCreate(savedInstanceState);
sharedPreferences = PreferenceManager.getDefaultSharedPreferences(this);
sharedPreferences.registerOnSharedPreferenceChangeListener(sharedPreferenceChangeListener);
trackingState = new TrackingState(sharedPreferences);
trackingState.load();
setContentView(R.layout.main);
getLastTrackingState();
getApplicationContext().getContentResolver().registerContentObserver(Constants.Tracks.CONTENT_URI, true, trackingObserver);
// mUnits = new UnitsI18n(this, mUnitsChangeListener);
speedView = (TextView) findViewById(R.id.currentSpeed);
timeView = (TextView) findViewById(R.id.currentTime);
distanceView = (TextView) findViewById(R.id.totalDist);
waypointCountView = (TextView) findViewById(R.id.waypointCount);
accuracyView = (TextView) findViewById(R.id.currentAccuracy);
roadRatingView = (TextView) findViewById(R.id.currentRoadRating);
// Capture our button from layout
roadRatingButtons[0] = (Button) findViewById(R.id.road_qual_none);
roadRatingButtons[1] = (Button) findViewById(R.id.road_qual_nogo);
roadRatingButtons[2] = (Button) findViewById(R.id.road_qual_bad);
roadRatingButtons[3] = (Button) findViewById(R.id.road_qual_poor);
roadRatingButtons[4] = (Button) findViewById(R.id.road_qual_good);
roadRatingButtons[5] = (Button) findViewById(R.id.road_qual_best);
for (Button button : roadRatingButtons)
{
button.setOnClickListener(roadRatingButtonListener);
}
bindGPSLoggingService();
}
/**
* Called when the activity is started.
*/
@Override
public void onStart()
{
Log.d(TAG, "onStart()");
super.onStart();
}
/**
* Called when the activity is started.
*/
@Override
public void onRestart()
{
Log.d(TAG, "onRestart()");
super.onRestart();
}
/**
* Called when the activity is resumed.
*/
@Override
public void onResume()
{
Log.d(TAG, "onResume()");
getLastTrackingState();
// updateBlankingBehavior();
drawScreen();
super.onResume();
}
/**
* Called when the activity is paused.
*/
@Override
public void onPause()
{
trackingState.save();
/* if (this.wakeLock != null && this.wakeLock.isHeld())
{
this.wakeLock.release();
Log.w(TAG, "onPause(): Released lock to keep screen on!");
} */
Log.d(TAG, "onPause()");
super.onPause();
}
@Override
protected void onDestroy()
{
Log.d(TAG, "onDestroy()");
trackingState.save();
/* if (wakeLock != null && wakeLock.isHeld())
{
wakeLock.release();
Log.w(TAG, "onDestroy(): Released lock to keep screen on!");
} */
getApplicationContext().getContentResolver().unregisterContentObserver(trackingObserver);
sharedPreferences.unregisterOnSharedPreferenceChangeListener(this.sharedPreferenceChangeListener);
unbindGPSLoggingService();
super.onDestroy();
}
@Override
public boolean onCreateOptionsMenu(Menu menu)
{
boolean result = super.onCreateOptionsMenu(menu);
menu.add(ContextMenu.NONE, MENU_TRACKING, ContextMenu.NONE, R.string.menu_tracking).setIcon(R.drawable.ic_menu_movie).setAlphabeticShortcut('T');
menu.add(ContextMenu.NONE, MENU_UPLOAD, ContextMenu.NONE, R.string.menu_upload).setIcon(R.drawable.ic_menu_upload).setAlphabeticShortcut('I');
menu.add(ContextMenu.NONE, MENU_SETTINGS, ContextMenu.NONE, R.string.menu_settings).setIcon(R.drawable.ic_menu_preferences).setAlphabeticShortcut('C');
menu.add(ContextMenu.NONE, MENU_HELP, ContextMenu.NONE, R.string.menu_help).setIcon(R.drawable.ic_menu_help).setAlphabeticShortcut('I');
menu.add(ContextMenu.NONE, MENU_ABOUT, ContextMenu.NONE, R.string.menu_about).setIcon(R.drawable.ic_menu_info_details).setAlphabeticShortcut('A');
return result;
}
@Override
public boolean onOptionsItemSelected(MenuItem item)
{
switch (item.getItemId())
{
case MENU_TRACKING:
startOpenGPSTrackerActivity();
break;
case MENU_UPLOAD:
startActivityForClass("org.opentraces.metatracker", "org.opentraces.metatracker.activity.UploadTrackActivity");
break;
case MENU_SETTINGS:
startActivity(new Intent(this, SettingsActivity.class));
break;
case MENU_ABOUT:
try
{
startActivityForResult(new Intent(Constants.OI_ACTION_SHOW_ABOUT_DIALOG), MENU_ABOUT);
}
catch (ActivityNotFoundException e)
{
showDialog(DIALOG_INSTALL_ABOUT);
}
break;
default:
showAlert(R.string.menu_message_unsupported);
break;
}
return true;
}
/*
* (non-Javadoc)
* @see android.app.Activity#onCreateDialog(int)
*/
@Override
protected Dialog onCreateDialog(int id)
{
Dialog dialog = null;
AlertDialog.Builder builder = null;
switch (id)
{
case DIALOG_INSTALL_OPENGPSTRACKER:
builder = new AlertDialog.Builder(this);
builder
.setTitle(R.string.dialog_noopengpstracker)
.setMessage(R.string.dialog_noopengpstracker_message)
.setIcon(android.R.drawable.ic_dialog_alert)
.setPositiveButton(R.string.btn_install, mOpenGPSTrackerDownloadDialogListener)
.setNegativeButton(R.string.btn_cancel, null);
dialog = builder.create();
break;
case DIALOG_INSTALL_ABOUT:
builder = new AlertDialog.Builder(this);
builder
.setTitle(R.string.dialog_nooiabout)
.setMessage(R.string.dialog_nooiabout_message)
.setIcon(android.R.drawable.ic_dialog_alert)
.setPositiveButton(R.string.btn_install, mOiAboutDialogListener)
.setNegativeButton(R.string.btn_cancel, null);
dialog = builder.create();
return dialog;
default:
dialog = super.onCreateDialog(id);
break;
}
return dialog;
}
private void drawTitleBar(String s)
{
this.setTitle(s);
}
/**
* Called on any update to Tracks table.
*/
private void onTrackingUpdate()
{
getLastTrackingState();
if (trackingState.waypoint.count == 1)
{
sendRoadRating();
}
drawScreen();
}
/**
* Called on any update to Tracks table.
*/
private synchronized void playPingSound()
{
if (!sharedPreferences.getBoolean(Constants.PREF_ENABLE_SOUND, false)) {
return;
}
try
{
if (mediaPlayer == null)
{
mediaPlayer = MediaPlayer.create(this, R.raw.ping_short);
} else
{
mediaPlayer.stop();
mediaPlayer.prepare();
}
mediaPlayer.start();
} catch (Throwable t)
{
Log.e(TAG, "Error playing sound", t);
}
}
/**
* Retrieve the last point of the current track
*/
private void getLastWaypoint()
{
Cursor waypoint = null;
try
{
ContentResolver resolver = this.getContentResolver();
waypoint = resolver.query(Uri.withAppendedPath(Constants.Tracks.CONTENT_URI, trackingState.track.id + "/" + Constants.Waypoints.TABLE),
new String[]{"max(" + Constants.Waypoints.TABLE + "." + Constants.Waypoints._ID + ")", Constants.Waypoints.LONGITUDE, Constants.Waypoints.LATITUDE, Constants.Waypoints.SPEED, Constants.Waypoints.ACCURACY, Constants.Waypoints.SEGMENT
}, null, null, null);
if (waypoint != null && waypoint.moveToLast())
{
// New point: increase pointcount
int waypointId = waypoint.getInt(0);
if (waypointId > 0 && trackingState.waypoint.id != waypointId)
{
trackingState.waypoint.count++;
trackingState.waypoint.id = waypoint.getInt(0);
// Increase total distance
Location newLocation = new Location(this.getClass().getName());
newLocation.setLongitude(waypoint.getDouble(1));
newLocation.setLatitude(waypoint.getDouble(2));
if (trackingState.waypoint.location != null)
{
float delta = trackingState.waypoint.location.distanceTo(newLocation);
// Log.d(TAG, "trackingState.distance=" + trackingState.distance + " delta=" + delta + " ll=" + waypoint.getDouble(1) + ", " +waypoint.getDouble(2));
trackingState.distance += delta;
}
trackingState.waypoint.location = newLocation;
trackingState.waypoint.speed = waypoint.getFloat(3);
trackingState.waypoint.accuracy = waypoint.getFloat(4);
trackingState.segment.id = waypoint.getInt(5);
playPingSound();
}
}
}
finally
{
if (waypoint != null)
{
waypoint.close();
}
}
}
private void getLastTrack()
{
Cursor cursor = null;
try
{
ContentResolver resolver = this.getApplicationContext().getContentResolver();
cursor = resolver.query(Constants.Tracks.CONTENT_URI, new String[]{"max(" + Constants.Tracks._ID + ")", Constants.Tracks.NAME, Constants.Tracks.CREATION_TIME}, null, null, null);
if (cursor != null && cursor.moveToLast())
{
int trackId = cursor.getInt(0);
// Check if new track created
if (trackId != trackingState.track.id)
{
trackingState.reset();
trackingState.save();
}
trackingState.track.id = trackId;
trackingState.track.name = cursor.getString(1);
trackingState.track.creationTime = cursor.getLong(2);
}
}
finally
{
if (cursor != null)
{
cursor.close();
}
}
}
private void getLastTrackingState()
{
getLastTrack();
getLoggingState();
getLastWaypoint();
}
private void sendRoadRating()
{
if (trackingState.roadRating > 0 && trackingState.newRoadRating && loggerServiceManager != null)
{
Uri media = Uri.withAppendedPath(Constants.NAME_URI, Uri.encode(trackingState.roadRating + ""));
loggerServiceManager.storeMediaUri(media);
trackingState.newRoadRating = false;
}
}
private void startOpenGPSTrackerActivity()
{
try
{
startActivityForClass("nl.sogeti.android.gpstracker", "nl.sogeti.android.gpstracker.viewer.LoggerMap");
}
catch (ActivityNotFoundException e)
{
Log.i(TAG, "Cannot find activity for open-gpstracker");
// No compatible file manager was found: install openintents filemanager.
showDialog(DIALOG_INSTALL_OPENGPSTRACKER);
}
sendRoadRating();
}
private void startActivityForClass(String aPackageName, String aClassName) throws ActivityNotFoundException
{
Intent intent = new Intent();
intent.setClassName(aPackageName, aClassName);
startActivity(intent);
}
private void bindGPSLoggingService()
{
unbindGPSLoggingService();
ServiceConnection serviceConnection = new ServiceConnection()
{
public void onServiceConnected(ComponentName className, IBinder service)
{
getLoggingState();
drawTitleBar();
}
public void onServiceDisconnected(ComponentName className)
{
trackingState.loggingState = Constants.DOWN;
}
};
loggerServiceManager = new GPSLoggerServiceManager(this);
loggerServiceManager.startup(serviceConnection);
}
private void unbindGPSLoggingService()
{
if (loggerServiceManager == null)
{
return;
}
try
{
loggerServiceManager.shutdown();
} finally
{
loggerServiceManager = null;
trackingState.loggingState = Constants.DOWN;
}
}
private void getLoggingState()
{
// Get state from logger if bound
trackingState.loggingState = loggerServiceManager == null ? Constants.DOWN : loggerServiceManager.getLoggingState();
// protect for values outside array bounds (set to unknown)
if (trackingState.loggingState < 0 || trackingState.loggingState > Constants.LOGGING_STATES.length - 1)
{
trackingState.loggingState = Constants.UNKNOWN;
}
}
private String getLoggingStateStr()
{
return Constants.LOGGING_STATES[trackingState.loggingState];
}
private void drawTitleBar()
{
drawTitleBar("MT : " + trackingState.track.name + " : " + getLoggingStateStr());
}
private void drawScreen()
{
drawTitleBar();
drawTripStats();
drawRoadRating();
}
/**
* Retrieves the numbers of the measured speed and altitude
* from the most recent waypoint and
* updates UI components with this latest bit of information.
*/
private void drawTripStats()
{
try
{
waypointCountView.setText(trackingState.waypoint.count + "");
long secsDelta = 0L;
long hours = 0L;
long mins = 0L;
long secs = 0L;
if (trackingState.track.creationTime != 0)
{
secsDelta = (System.currentTimeMillis() - trackingState.track.creationTime) / 1000;
hours = secsDelta / 3600L;
mins = (secsDelta % 3600L) / 60L;
secs = ((secsDelta % 3600L) % 60);
}
timeView.setText(formatTimeNum(hours) + ":" + formatTimeNum(mins) + ":" + formatTimeNum(secs));
speedView.setText(REAL_FORMATTER1.format(3.6f * trackingState.waypoint.speed));
accuracyView.setText(REAL_FORMATTER1.format(trackingState.waypoint.accuracy));
distanceView.setText(REAL_FORMATTER2.format(trackingState.distance / 1000f));
}
finally
{
}
}
private String formatTimeNum(long n)
{
return n < 10 ? ("0" + n) : (n + "");
}
private void drawRoadRating()
{
for (int i = 0; i < roadRatingButtons.length; i++)
{
roadRatingButtons[i].setBackgroundColor(COLOR_WHITE);
}
if (trackingState.roadRating >= 0)
{
roadRatingButtons[trackingState.roadRating].setBackgroundColor(ROAD_RATING_COLORS[trackingState.roadRating]);
}
String roadRatingStr = trackingState.roadRating + "";
roadRatingView.setText(roadRatingStr);
}
private void showAlert(int aMessage)
{
new AlertDialog.Builder(this)
.setMessage(aMessage)
.setPositiveButton("Ok", null)
.show();
}
private void updateBlankingBehavior()
{
boolean disableblanking = sharedPreferences.getBoolean(Constants.DISABLEBLANKING, false);
if (disableblanking)
{
/* if (wakeLock == null)
{
PowerManager pm = (PowerManager) this.getSystemService(Context.POWER_SERVICE);
wakeLock = pm.newWakeLock(PowerManager.SCREEN_DIM_WAKE_LOCK, TAG);
}
wakeLock.acquire();
Log.w(TAG, "Acquired lock to keep screen on!"); */
}
}
private final DialogInterface.OnClickListener mOiAboutDialogListener = new DialogInterface.OnClickListener()
{
public void onClick(DialogInterface dialog, int which)
{
Uri oiDownload = Uri.parse("market://details?id=org.openintents.about");
Intent oiAboutIntent = new Intent(Intent.ACTION_VIEW, oiDownload);
try
{
startActivity(oiAboutIntent);
}
catch (ActivityNotFoundException e)
{
oiDownload = Uri.parse("http://openintents.googlecode.com/files/AboutApp-1.0.0.apk");
oiAboutIntent = new Intent(Intent.ACTION_VIEW, oiDownload);
startActivity(oiAboutIntent);
}
}
};
private final DialogInterface.OnClickListener mOpenGPSTrackerDownloadDialogListener = new DialogInterface.OnClickListener()
{
public void onClick(DialogInterface dialog, int which)
{
Uri marketUri = Uri.parse("market://details?id=nl.sogeti.android.gpstracker");
Intent downloadIntent = new Intent(Intent.ACTION_VIEW, marketUri);
try
{
startActivity(downloadIntent);
}
catch (ActivityNotFoundException e)
{
showAlert(R.string.dialog_failinstallopengpstracker_message);
}
}
};
// Create an anonymous implementation of OnClickListener
private View.OnClickListener roadRatingButtonListener = new View.OnClickListener()
{
public void onClick(View v)
{
for (int i = 0; i < roadRatingButtons.length; i++)
{
if (v.getId() == roadRatingButtons[i].getId())
{
trackingState.roadRating = i;
}
}
trackingState.newRoadRating = true;
drawRoadRating();
sendRoadRating();
}
};
private final ContentObserver trackingObserver = new ContentObserver(new Handler())
{
@Override
public void onChange(boolean selfUpdate)
{
if (!selfUpdate)
{
onTrackingUpdate();
Log.d(TAG, "trackingObserver onTrackingUpdate lastWaypointId=" + trackingState.waypoint.id);
} else
{
Log.w(TAG, "trackingObserver skipping change");
}
}
};
private final SharedPreferences.OnSharedPreferenceChangeListener sharedPreferenceChangeListener = new SharedPreferences.OnSharedPreferenceChangeListener()
{
public void onSharedPreferenceChanged(SharedPreferences sharedPreferences, String key)
{
if (key.equals(Constants.DISABLEBLANKING))
{
updateBlankingBehavior();
}
}
};
}
| Java |
package br.fbv.anotaFacil.view;
import br.fbv.anotaFacil.R;
import android.app.Activity;
import android.os.Bundle;
public class ProjetoAndroidActivity extends Activity {
/** Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.inicio);
// final Button button = (Button) findViewById(R.id.btnApresentacao);
// button.setOnClickListener(new View.OnClickListener() {
// public void onClick(View v) {
//
// setContentView(R.layout.main);
// }
// });
}
} | Java |
package br.fbv.anotaFacil.view;
import br.fbv.anotaFacil.R;
import android.app.Activity;
import android.os.Bundle;
import android.widget.ListView;
public class AppLista extends Activity {
public ListView lista;
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.menu);
// ArrayAdapter<String> adapter = new ArrayAdapter<String>(this,
// android.R.layout.simple_list_item_1, contatos);
// lista = (ListView) findViewById(R.id.listView1);
// lista.setAdapter(adapter);
// lista.setOnItemClickListener(new OnItemClickListener() {
// public void onItemClick(AdapterView arg0, View arg1, int arg2,
// long arg3) {
// if (lista.getSelectedItem() != null) {
// AlertDialog.Builder dialogo = new AlertDialog.Builder(
// AppLista.this);
// dialogo.setTitle("Contato selecionado");
// dialogo.setMessage(lista.getSelectedItem().toString());
// dialogo.setNeutralButton("OK", null);
// dialogo.show();
// }
// }
// });
}
static final String[] contatos = new String[] { "Alline", "Lucas",
"Rafael", "Gabriela", "Silvana" };
} | Java |
package br.fbv.anotaFacil.view;
import br.fbv.anotaFacil.R;
import android.app.Activity;
import android.os.Bundle;
public class ProjetoAnotaFacilActivity extends Activity {
/** Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
}
} | Java |
package br.fbv.anotaFacil.view;
import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.ListView;
import br.fbv.anotaFacil.R;
public class InicioAnotaFacilActivity extends Activity {
/**
* @see android.app.Activity#onCreate(Bundle)
*/
public ListView lista;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.apresentacao);
final Button button = (Button) findViewById(R.id.btnApresentacao);
button.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
setContentView(R.layout.menu);
// ArrayAdapter<String> adapter = new
// ArrayAdapter<String>(InicioProjetoActivity.this,
// android.R.layout.simple_list_item_1, contatos);
// lista = (ListView) findViewById(R.id.listView1);
// lista.setAdapter(adapter);
// lista.setOnItemClickListener(new OnItemClickListener() {
// public void onItemClick(AdapterView<?> arg0, View arg1, int
// arg2,
// long arg3) {
// if (lista.getSelectedItem() != null) {
// AlertDialog.Builder dialogo = new AlertDialog.Builder(
// InicioProjetoActivity.this);
// dialogo.setTitle("Contato selecionado");
// dialogo.setMessage(lista.getSelectedItem().toString());
// dialogo.setNeutralButton("OK", null);
// dialogo.show();
// }
// }
// });
}
});
}
public void clickDosBotoes(View v) {
Intent it = null;
switch (v.getId()) {
case R.id.btncadastro:
// it.putExtra("layout", R.layout.main);
break;
case R.id.btnConsulta:
// it.putExtra("layout", R.layout.main);
break;
case R.id.btnWEbServices:
it = new Intent(this, WebServicesActivity.class);
it.putExtra("layout", R.layout.main);
break;
case R.id.btnUtilitarios:
// it.putExtra("layout", R.layout.main);
break;
}
startActivity(it);
}
}
| Java |
package br.fbv.anotaFacil.view;
import br.fbv.anotaFacil.R;
import android.app.Activity;
import android.os.Bundle;
public class WebServicesActivity extends Activity {
/** Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.apresentacao);
// final Button button = (Button) findViewById(R.id.btnApresentacao);
// button.setOnClickListener(new View.OnClickListener() {
// public void onClick(View v) {
//
// setContentView(R.layout.main);
// }
// });
}
} | Java |
package br.fbv.anotaFacil.model;
import java.util.ArrayList;
public class Supermercado {
private String nome;
private int idSupermercado;
private String localizacao;
private ArrayList<Produto> listaProdutos;
public String getNome() {
return nome;
}
public void setNome(String nome) {
this.nome = nome;
}
public int getIdSupermercado() {
return idSupermercado;
}
public void setIdSupermercado(int idSupermercado) {
this.idSupermercado = idSupermercado;
}
public String getLocalizacao() {
return localizacao;
}
public void setLocalizacao(String localizacao) {
this.localizacao = localizacao;
}
public ArrayList<Produto> getListaProdutos() {
return listaProdutos;
}
public void setListaProdutos(ArrayList<Produto> listaProdutos) {
this.listaProdutos = listaProdutos;
}
}
| Java |
package br.fbv.anotaFacil.model;
public class Produto {
private String nome;
private int id;
private int idSupermercado;
private double preco;
public String getNome() {
return nome;
}
public void setNome(String nome) {
this.nome = nome;
}
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public int getIdSupermercado() {
return idSupermercado;
}
public void setIdSupermercado(int idSupermercado) {
this.idSupermercado = idSupermercado;
}
public double getPreco() {
return preco;
}
public void setPreco(double preco) {
this.preco = preco;
}
}
| Java |
/*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
package BUS;
import java.util.List;
/**
*
* @author Anonymous
*/
public class ChuyenXeBUS {
public boolean ThemChuyenXe(DTO.ChuyenXeDTO chuyenxedto){
return DAO.ChuyenXeDAO.ThemChuyenXe(chuyenxedto);
}
public boolean CnChuyenXe(DTO.ChuyenXeDTO chuyenxedto){
return DAO.ChuyenXeDAO.CnChuyenXe(chuyenxedto);
}
public List<DTO.ChuyenXeDTO> dsChuyenXe(){
return DAO.ChuyenXeDAO.dsChuyenXe();
}
public List<DTO.ChuyenXeDTO> dsChuyenXecl(){
return DAO.ChuyenXeDAO.dsChuyenXecl();
}
public boolean XoaChuyenXe(int machuyen){
return DAO.ChuyenXeDAO.XoaChuyenXe(machuyen);
}
public DTO.ChuyenXeDTO ttChuyenXe(int machuyen){
return DAO.ChuyenXeDAO.ttChuyenXe(machuyen);
}
}
| Java |
/*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
package BUS;
/**
*
* @author Anonymous
*/
public class DatVeBUS {
public boolean ThemDatVe(DTO.DatVeDTO dvdto){
return DAO.DatVeDAO.ThemDatVe(dvdto);
}
}
| Java |
/*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
package DTO;
import java.io.Serializable;
/**
*
* @author Anonymous
*/
public class PacketDTO implements Serializable{
private int Command;
private Object Data;
private boolean Flag;
public int getCommand(){
return Command;
}
public void setCommand(int command){
this.Command=command;
}
public Object getData(){
return Data;
}
public void setData(Object data){
this.Data=data;
}
public boolean getFlag(){
return Flag;
}
public void setFlag(boolean flag){
this.Flag=flag;
}
}
| Java |
/*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
package DTO;
import java.io.Serializable;
import java.util.Date;
/**
*
* @author Anonymous
*/
public class ChuyenXeDTO implements Serializable{
private int MaChuyen;
private int SoLuongVe;
private int GioiHanVe;
private String GaBatDau;
private String GaKetThuc;
private Date ThoiGianChay;
private int VeDaDat;
private int GiaTien;
public int getVeDaDat(){
return VeDaDat;
}
public void setVeDaDat(int veDaDat){
this.VeDaDat=veDaDat;
}
public int getMaChuyen(){
return MaChuyen;
}
public void setMaChuyen(int maChuyen){
this.MaChuyen=maChuyen;
}
public int getSoLuongVe(){
return SoLuongVe;
}
public void setSoLuongVe(int soLuongVe){
this.SoLuongVe=soLuongVe;
}
public int getGioiHanVe(){
return GioiHanVe;
}
public void setGioiHanVe(int gioiHanVe){
this.GioiHanVe=gioiHanVe;
}
public String getGaBatDau()
{
return GaBatDau;
}
public void setGatBatDau(String gaBatDau)
{
this.GaBatDau=gaBatDau;
}
public String getGaKetThuc()
{
return GaKetThuc;
}
public void setGaKetThuc(String gaKetThuc)
{
this.GaKetThuc=gaKetThuc;
}
public Date getThoiGianChay()
{
return ThoiGianChay;
}
public void setThoiGianChay(Date thoiGianChay)
{
this.ThoiGianChay=thoiGianChay;
}
public int getGiaTien(){
return GiaTien;
}
public void setGiaTien(int giaTien){
this.GiaTien=giaTien;
}
}
| Java |
/*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
package DTO;
import java.io.Serializable;
import java.util.Date;
/**
*
* @author Anonymous
*/
public class DatVeDTO implements Serializable{
private int MaDatVe;
private int MaChuyen;
private int SoLuongVe;
private String CMND;
private Date NgayDat;
private int DaThanhToan;//0: chua - 1: da thanh toan
private int TrangThai;//0: con han thanh toan - 1: het han thanh toan
public int getMaDatVe(){
return MaDatVe;
}
public void setMaDatVe(int maDatVe){
this.MaDatVe=maDatVe;
}
public int getMaChuyen(){
return MaChuyen;
}
public void setMaChuyen(int maChuyen){
this.MaChuyen=maChuyen;
}
public int getSoLuongVe(){
return SoLuongVe;
}
public void setSoLuongVe(int soLuongVe){
this.SoLuongVe=soLuongVe;
}
public String getCMND()
{
return CMND;
}
public void setCMND(String cMND)
{
this.CMND=cMND;
}
public int getDaThanhToan(){
return DaThanhToan;
}
public void setDaThanhToan(int daThanhToan){
this.DaThanhToan=daThanhToan;
}
public Date getNgayDat()
{
return NgayDat;
}
public void setNgayDat(Date ngayDat)
{
this.NgayDat=ngayDat;
}
public int getTrangThai(){
return TrangThai;
}
public void setTrangThai(int trangThai){
this.TrangThai=trangThai;
}
}
| Java |
/*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
package GUI;
import MAIN.DateLabelFormatter;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.swing.JOptionPane;
import net.sourceforge.jdatepicker.impl.JDatePanelImpl;
import net.sourceforge.jdatepicker.impl.JDatePickerImpl;
import net.sourceforge.jdatepicker.impl.UtilDateModel;
/**
*
* @author Anonymous
*/
public class ChuyenXeCN2 extends javax.swing.JFrame {
/**
* Creates new form ChuyenXeCN
*/
//Dùng để tạo ra khung chọn ngày tháng năm
private JDatePickerImpl chonNgay;
private UtilDateModel model = new UtilDateModel();//lưu dữ liệu ngày tháng năm đang chọn
private int slv;//Lưu số lượng vé đang chọn
public ChuyenXeCN2()
{
initComponents();
//Lưu thông tin chuyến xe với mã MAIN.MAIN.IDRide (đã chọn bên giao diện MAIN) vào cxdto
DTO.ChuyenXeDTO cxdto=new DTO.ChuyenXeDTO();
BUS.ChuyenXeBUS cxbus=new BUS.ChuyenXeBUS();
cxdto=cxbus.ttChuyenXe(MAIN.MAIN.IDRide);
//Thể hiện các giá trị đó ra giao diện
txtMaChuyen.setText(Integer.toString(MAIN.MAIN.IDRide));
txtMaChuyen.setEnabled(false);
txtGaBatDau.setText(cxdto.getGaBatDau());
txtGaKetThuc.setText(cxdto.getGaKetThuc());
spSoLV.setModel(new javax.swing.SpinnerNumberModel(cxdto.getSoLuongVe(), cxdto.getVeDaDat(), null, 1));
spSoLV.setValue(cxdto.getSoLuongVe());
slv=cxdto.getGioiHanVe();
spGioiHanVe.setModel(new javax.swing.SpinnerNumberModel(slv, 1, cxdto.getSoLuongVe(), 1));
Date tgc=cxdto.getThoiGianChay();
Calendar cal = Calendar.getInstance();
cal.setTime(tgc);
spGio.setValue(cal.get(Calendar.HOUR_OF_DAY));
spPhut.setValue(cal.get(Calendar.MINUTE));
model.setDate(cal.get(Calendar.YEAR) ,cal.get(Calendar.MONTH) , cal.get(Calendar.DAY_OF_MONTH) );
model.setSelected(true);
spGiaTien.setModel(new javax.swing.SpinnerNumberModel(cxdto.getGiaTien(), 5000, null, 5000));
spGiaTien.setValue(cxdto.getGiaTien());
}
/**
* This method is called from within the constructor to initialize the form.
* WARNING: Do NOT modify this code. The content of this method is always
* regenerated by the Form Editor.
*/
@SuppressWarnings("unchecked")
// <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
private void initComponents() {
btnUpdate = new java.awt.Button();
jLabel6 = new javax.swing.JLabel();
txtMaChuyen = new javax.swing.JTextField();
spPhut = new javax.swing.JSpinner();
spGio = new javax.swing.JSpinner();
jLabel11 = new javax.swing.JLabel();
spGioiHanVe = new javax.swing.JSpinner();
spSoLV = new javax.swing.JSpinner();
jLabel7 = new javax.swing.JLabel();
jLabel4 = new javax.swing.JLabel();
jLabel5 = new javax.swing.JLabel();
jLabel9 = new javax.swing.JLabel();
jButton1 = new javax.swing.JButton();
jLabel8 = new javax.swing.JLabel();
txtGaBatDau = new javax.swing.JTextField();
jLabel10 = new javax.swing.JLabel();
txtGaKetThuc = new javax.swing.JTextField();
spGiaTien = new javax.swing.JSpinner();
jLabel12 = new javax.swing.JLabel();
setDefaultCloseOperation(javax.swing.WindowConstants.DISPOSE_ON_CLOSE);
setTitle("Cập Nhật Chuyến Xe");
btnUpdate.setLabel("Cập Nhật Chuyến Xe");
btnUpdate.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
btnUpdateActionPerformed(evt);
}
});
jLabel6.setText("Mã Chuyến Xe");
spPhut.setModel(new javax.swing.SpinnerNumberModel(0, 0, 60, 1));
spGio.setModel(new javax.swing.SpinnerNumberModel(0, 0, 23, 1));
jLabel11.setText("Phút");
spGioiHanVe.setModel(new javax.swing.SpinnerNumberModel(Integer.valueOf(1), Integer.valueOf(1), null, Integer.valueOf(1)));
spSoLV.setModel(new javax.swing.SpinnerNumberModel(Integer.valueOf(1), Integer.valueOf(1), null, Integer.valueOf(1)));
spSoLV.addChangeListener(new javax.swing.event.ChangeListener() {
public void stateChanged(javax.swing.event.ChangeEvent evt) {
spSoLVStateChanged(evt);
}
});
jLabel7.setText("Thời Gian Chạy");
jLabel4.setText("Ga Bắt Đầu");
jLabel5.setText("Ga Kết Thúc");
jLabel9.setText("Số Lượng Vé");
jButton1.setText("Chọn Ngày");
jLabel8.setText("Giờ :");
jLabel10.setText("Giới Hạn Vé");
spGiaTien.setModel(new javax.swing.SpinnerNumberModel(Integer.valueOf(5000), Integer.valueOf(5000), null, Integer.valueOf(5000)));
jLabel12.setText("Giá Tiền");
javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
getContentPane().setLayout(layout);
layout.setHorizontalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addGap(264, 264, 264)
.addComponent(btnUpdate, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
.addGroup(layout.createSequentialGroup()
.addGap(18, 18, 18)
.addComponent(jLabel6)
.addGap(18, 18, 18)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addComponent(txtMaChuyen, javax.swing.GroupLayout.PREFERRED_SIZE, 205, javax.swing.GroupLayout.PREFERRED_SIZE)
.addGap(0, 0, Short.MAX_VALUE))
.addGroup(layout.createSequentialGroup()
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(jLabel10)
.addComponent(jLabel5)
.addComponent(jLabel4)
.addComponent(jLabel7)
.addComponent(jLabel9)
.addComponent(jLabel12))
.addGap(56, 56, 56)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addGap(1, 1, 1)
.addComponent(spGio, javax.swing.GroupLayout.PREFERRED_SIZE, 45, javax.swing.GroupLayout.PREFERRED_SIZE)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(jLabel8)
.addGap(18, 18, 18)
.addComponent(spPhut, javax.swing.GroupLayout.DEFAULT_SIZE, 45, Short.MAX_VALUE)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
.addComponent(jLabel11, javax.swing.GroupLayout.PREFERRED_SIZE, 36, javax.swing.GroupLayout.PREFERRED_SIZE)
.addGap(38, 38, 38)
.addComponent(jButton1))
.addGroup(layout.createSequentialGroup()
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(spGiaTien, javax.swing.GroupLayout.PREFERRED_SIZE, 160, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(txtGaKetThuc, javax.swing.GroupLayout.PREFERRED_SIZE, 205, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(txtGaBatDau, javax.swing.GroupLayout.PREFERRED_SIZE, 205, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(spSoLV, javax.swing.GroupLayout.PREFERRED_SIZE, 50, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(spGioiHanVe, javax.swing.GroupLayout.PREFERRED_SIZE, 50, javax.swing.GroupLayout.PREFERRED_SIZE))
.addGap(0, 0, Short.MAX_VALUE)))))))
.addGap(95, 95, 95))
);
layout.setVerticalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addContainerGap()
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(txtMaChuyen, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(jLabel6))
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, 45, Short.MAX_VALUE)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(txtGaBatDau, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(jLabel4))
.addGap(18, 18, 18)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(txtGaKetThuc, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(jLabel5))
.addGap(18, 18, 18)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(jButton1)
.addComponent(jLabel7))
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(spGio, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(jLabel8)
.addComponent(spPhut, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(jLabel11)))
.addGap(18, 18, 18)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(jLabel9)
.addComponent(spSoLV, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
.addGap(18, 18, 18)
.addComponent(jLabel10))
.addComponent(spGioiHanVe, javax.swing.GroupLayout.Alignment.TRAILING, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
.addGap(14, 14, 14)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(jLabel12)
.addComponent(spGiaTien, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
.addGap(17, 17, 17)
.addComponent(btnUpdate, javax.swing.GroupLayout.PREFERRED_SIZE, 36, javax.swing.GroupLayout.PREFERRED_SIZE)
.addContainerGap())
);
model = new UtilDateModel();
JDatePanelImpl datePanel = new JDatePanelImpl(model);
chonNgay = new JDatePickerImpl(datePanel,new DateLabelFormatter());
jButton1.add(chonNgay);
pack();
}// </editor-fold>//GEN-END:initComponents
private void btnUpdateActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnUpdateActionPerformed
// TODO add your handling code here:
//Lưu giá trị ngày chọn được vào tam
Date tam=(Date) chonNgay.getModel().getValue();
if(ktDauVao() && tam!=null)//Nếu giá trị ngày khác null và kiểm tra đầu vào hợp lệ
{
//Gán các thông tin chuyến xe vào cxdto
DTO.ChuyenXeDTO cxdto=new DTO.ChuyenXeDTO();
cxdto.setMaChuyen(Integer.parseInt(txtMaChuyen.getText()));
cxdto.setGatBatDau(txtGaBatDau.getText().trim());
cxdto.setGaKetThuc(txtGaKetThuc.getText().trim());
cxdto.setSoLuongVe((int)spSoLV.getValue());
cxdto.setGioiHanVe((int)spGioiHanVe.getValue());
cxdto.setGiaTien((int)spGiaTien.getValue());
//Tính toán và gán ngày giờ theo định dạng vào cxdto
SimpleDateFormat simpleDateFormat = new SimpleDateFormat("hh:mm dd-MM-yyyy");
Calendar cal = Calendar.getInstance();
cal.setTime(tam);
try {
cxdto.setThoiGianChay(simpleDateFormat.parse((int)spGio.getValue()+":"+(int)spPhut.getValue()+" "+cal.get(Calendar.DAY_OF_MONTH)+"-"+(cal.get(Calendar.MONTH)+1)+"-"+cal.get(Calendar.YEAR)));
} catch (ParseException ex) {
Logger.getLogger(ChuyenXeCN2.class.getName()).log(Level.SEVERE, null, ex);
}
BUS.ChuyenXeBUS xpbus=new BUS.ChuyenXeBUS();
if(xpbus.CnChuyenXe(cxdto)){//Nếu cập nhật chuyến xe thành công
//Show thông báo thành công
JOptionPane.showMessageDialog(this,
"Cập nhật chuyến xe thành công!",
"Thông báo",
JOptionPane.INFORMATION_MESSAGE);
}
else{
//Show thông báo thất bại
JOptionPane.showMessageDialog(this,
"Cập nhật chuyến xe thất bại!",
"Thông báo lỗi",
JOptionPane.ERROR_MESSAGE);
}
}
else
{
//Show thông báo lỗi đầu vào
JOptionPane.showMessageDialog(this,
"Bạn chưa nhập đủ thông tin hoặc thông tin không hợp lệ.",
"Thông báo lỗi",
JOptionPane.ERROR_MESSAGE);
}
}//GEN-LAST:event_btnUpdateActionPerformed
//Hàm kiểm tra các dữ liệu đầu vào
private boolean ktDauVao()
{
Date tam=(Date) chonNgay.getModel().getValue();//lấy ngày được chọn
Date tam2 = null;//lưu ngày giờ được chọn
Date tam3=new java.util.Date();//lấy ngày giờ hiện tại
SimpleDateFormat simpleDateFormat = new SimpleDateFormat("hh:mm dd-MM-yyyy");
Calendar cal = Calendar.getInstance();
cal.setTime(tam);
try {
tam2=simpleDateFormat.parse((int)spGio.getValue()+":"+(int)spPhut.getValue()+" "+cal.get(Calendar.DAY_OF_MONTH)+"-"+(cal.get(Calendar.MONTH)+1)+"-"+cal.get(Calendar.YEAR));
} catch (ParseException ex) {
Logger.getLogger(ChuyenXeCN.class.getName()).log(Level.SEVERE, null, ex);
}
boolean flag=false;//lưu giá trị trả về là false
if(!"".equals(txtGaBatDau.getText().trim()) && //Nếu dữ liệu Ga bắt đầu và Ga kết thúc không trống
!"".equals(txtGaKetThuc.getText().trim()) && tam2.after(tam3))//Và ngày giờ được chọn nằm sau ngày giờ hiện tại
flag=true;//gán giá trị trả về là true
return flag;
}
//Sự kiện khi giá trị spin Số lượng vé thay đổi
private void spSoLVStateChanged(javax.swing.event.ChangeEvent evt) {//GEN-FIRST:event_spSoLVStateChanged
// TODO add your handling code here:
if(slv>(int)spSoLV.getValue() && //Nếu số lượng vé vừa được chọn nhỏ hơn trước đó
(int)spGioiHanVe.getValue()>(int)spSoLV.getValue())//và số lượng vé vừa chọn nhỏ hơn giới hạn vé đang chọn
//gán lại khoảng giá trị cho spin Giới hạn vé (giá trị:số lượng vé vừa chọn,min:1,max:số lượng vé vừa chọn)
spGioiHanVe.setModel(new javax.swing.SpinnerNumberModel((int)spSoLV.getValue(), 1, (int)spSoLV.getValue(), 1));
else//Ngược lại
//gán lại khoảng giá trị cho spin Giới hạn vé (giá trị:giới hạn vé vừa chọn,min:1,max:số lượng vé vừa chọn)
spGioiHanVe.setModel(new javax.swing.SpinnerNumberModel((int)spGioiHanVe.getValue(), 1, (int)spSoLV.getValue(), 1));
slv=(int)spSoLV.getValue();//Gán lại giá trị cho số lượng vé
}//GEN-LAST:event_spSoLVStateChanged
/**
* @param args the command line arguments
*/
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 | InstantiationException | IllegalAccessException | javax.swing.UnsupportedLookAndFeelException ex) {
java.util.logging.Logger.getLogger(ChuyenXeCN2.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
}
//</editor-fold>
/* Create and display the form */
java.awt.EventQueue.invokeLater(new Runnable() {
@Override
public void run() {
new ChuyenXeCN2().setVisible(true);
}
});
}
// Variables declaration - do not modify//GEN-BEGIN:variables
private java.awt.Button btnUpdate;
private javax.swing.JButton jButton1;
private javax.swing.JLabel jLabel10;
private javax.swing.JLabel jLabel11;
private javax.swing.JLabel jLabel12;
private javax.swing.JLabel jLabel4;
private javax.swing.JLabel jLabel5;
private javax.swing.JLabel jLabel6;
private javax.swing.JLabel jLabel7;
private javax.swing.JLabel jLabel8;
private javax.swing.JLabel jLabel9;
private javax.swing.JSpinner spGiaTien;
private javax.swing.JSpinner spGio;
private javax.swing.JSpinner spGioiHanVe;
private javax.swing.JSpinner spPhut;
private javax.swing.JSpinner spSoLV;
private javax.swing.JTextField txtGaBatDau;
private javax.swing.JTextField txtGaKetThuc;
private javax.swing.JTextField txtMaChuyen;
// End of variables declaration//GEN-END:variables
}
| Java |
/*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
package GUI;
import java.util.prefs.Preferences;
import javax.swing.JOptionPane;
/**
*
* @author Anonymous
*/
public class ConfigGUI extends javax.swing.JFrame {
/**
* Creates new form ConfigGUI
*/
//Các từ khóa prefs (prefs mục tiêu là lưu các chuỗi vào phần mềm để lần sau có thể truy xuất)
protected static final String PREF_TENSV = "TENSV";
protected static final String PREF_TENCSDL = "TENCSDL";
protected static final String PREF_TENDN = "TENDN";
protected static final String PREF_MK = "MK";
public ConfigGUI() {
initComponents();
}
/**
* This method is called from within the constructor to initialize the form.
* WARNING: Do NOT modify this code. The content of this method is always
* regenerated by the Form Editor.
*/
@SuppressWarnings("unchecked")
// <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
private void initComponents() {
jLabel1 = new javax.swing.JLabel();
txtServer = new javax.swing.JTextField();
txtData = new javax.swing.JTextField();
jLabel3 = new javax.swing.JLabel();
txtUser = new javax.swing.JTextField();
jLabel4 = new javax.swing.JLabel();
jLabel5 = new javax.swing.JLabel();
pwPass = new javax.swing.JPasswordField();
btnTest = new javax.swing.JButton();
setDefaultCloseOperation(javax.swing.WindowConstants.DISPOSE_ON_CLOSE);
setTitle("Config");
jLabel1.setText("Server");
jLabel3.setText("Database name");
jLabel4.setText("User");
jLabel5.setText("Password");
pwPass.setText("jPasswordField1");
btnTest.setText("Kết nối thử và lưu cấu hình");
btnTest.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
btnTestActionPerformed(evt);
}
});
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(39, 39, 39)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(jLabel3)
.addComponent(jLabel1)
.addComponent(jLabel5)
.addComponent(jLabel4))
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addGap(66, 66, 66)
.addComponent(txtData, javax.swing.GroupLayout.PREFERRED_SIZE, 191, javax.swing.GroupLayout.PREFERRED_SIZE))
.addGroup(layout.createSequentialGroup()
.addGap(64, 64, 64)
.addComponent(txtServer, javax.swing.GroupLayout.PREFERRED_SIZE, 191, javax.swing.GroupLayout.PREFERRED_SIZE))
.addGroup(layout.createSequentialGroup()
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(txtUser, javax.swing.GroupLayout.PREFERRED_SIZE, 191, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(pwPass, javax.swing.GroupLayout.PREFERRED_SIZE, 155, javax.swing.GroupLayout.PREFERRED_SIZE))))
.addContainerGap(29, Short.MAX_VALUE))
.addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
.addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
.addComponent(btnTest, javax.swing.GroupLayout.PREFERRED_SIZE, 173, javax.swing.GroupLayout.PREFERRED_SIZE)
.addGap(83, 83, 83))
);
layout.setVerticalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addGap(28, 28, 28)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
.addGroup(layout.createSequentialGroup()
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
.addComponent(txtServer, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(jLabel1))
.addGap(18, 18, 18)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
.addComponent(txtData, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(jLabel3))
.addGap(18, 18, 18)
.addComponent(txtUser, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
.addComponent(jLabel4))
.addGap(31, 31, 31)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(pwPass, javax.swing.GroupLayout.Alignment.TRAILING, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(jLabel5, javax.swing.GroupLayout.Alignment.TRAILING))
.addGap(44, 44, 44)
.addComponent(btnTest, javax.swing.GroupLayout.PREFERRED_SIZE, 36, javax.swing.GroupLayout.PREFERRED_SIZE)
.addContainerGap(45, Short.MAX_VALUE))
);
pack();
}// </editor-fold>//GEN-END:initComponents
//Xử lý sự kiện khi nhấp nút "kết nối thử và lưu cấu hình"
private void btnTestActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnTestActionPerformed
// TODO add your handling code here:
String tamMK=String.valueOf(pwPass.getPassword()); //lưu chuỗi password vào tamMK
//Nếu có thể kết nối từ các thông tin cấu hình
if(DAO.Connect.connectT(txtServer.getText(), txtData.getText(), txtUser.getText(), tamMK)){
//Lưu thông tin vào các prefs (prefs mục tiêu là lưu các chuỗi vào phần mềm để lần sau có thể truy xuất)
Preferences prefs = Preferences.userNodeForPackage(ConfigGUI.class);
prefs.put(PREF_TENSV, txtServer.getText());
prefs.put(PREF_TENCSDL, txtData.getText());
prefs.put(PREF_TENDN, txtUser.getText());
prefs.put(PREF_MK, tamMK);
//Show thông báo thành công
JOptionPane.showMessageDialog(null,
"Kết nối thành công.");
new MAIN.MAIN().setVisible(true);
this.dispose();
}
else{
//Show thông báo thất bại
JOptionPane.showMessageDialog(null,
"Kết nối thất bại.");
}
}//GEN-LAST:event_btnTestActionPerformed
/**
* @param args the command line arguments
*/
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 | InstantiationException | IllegalAccessException | javax.swing.UnsupportedLookAndFeelException ex) {
java.util.logging.Logger.getLogger(ConfigGUI.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
}
//</editor-fold>
/* Create and display the form */
java.awt.EventQueue.invokeLater(new Runnable() {
@Override
public void run() {
new ConfigGUI().setVisible(true);
}
});
}
// Variables declaration - do not modify//GEN-BEGIN:variables
private javax.swing.JButton btnTest;
private javax.swing.JLabel jLabel1;
private javax.swing.JLabel jLabel3;
private javax.swing.JLabel jLabel4;
private javax.swing.JLabel jLabel5;
private javax.swing.JPasswordField pwPass;
private javax.swing.JTextField txtData;
private javax.swing.JTextField txtServer;
private javax.swing.JTextField txtUser;
// End of variables declaration//GEN-END:variables
}
| Java |
/*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
package GUI;
import MAIN.DateLabelFormatter;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.Locale;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.swing.JOptionPane;
import net.sourceforge.jdatepicker.impl.JDatePanelImpl;
import net.sourceforge.jdatepicker.impl.JDatePickerImpl;
import net.sourceforge.jdatepicker.impl.UtilDateModel;
/**
*
* @author Anonymous
*/
public class ChuyenXeCN extends javax.swing.JFrame {
/**
* Creates new form ChuyenXeCN
*/
private JDatePickerImpl chonNgay;//Dùng để tạo ra khung chọn ngày tháng năm
private int slv;//lưu số lượng vé đang được chọn
public ChuyenXeCN() {
initComponents();
slv=1;//số lượng vé khởi tạo=1
}
/**
* This method is called from within the constructor to initialize the form.
* WARNING: Do NOT modify this code. The content of this method is always
* regenerated by the Form Editor.
*/
@SuppressWarnings("unchecked")
// <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
private void initComponents() {
txtGaBatDau = new javax.swing.JTextField();
txtGaKetThuc = new javax.swing.JTextField();
jLabel4 = new javax.swing.JLabel();
jLabel5 = new javax.swing.JLabel();
jLabel7 = new javax.swing.JLabel();
button1 = new java.awt.Button();
jButton1 = new javax.swing.JButton();
jLabel9 = new javax.swing.JLabel();
jLabel10 = new javax.swing.JLabel();
jLabel8 = new javax.swing.JLabel();
jLabel11 = new javax.swing.JLabel();
spSoLV = new javax.swing.JSpinner();
spGioiHanVe = new javax.swing.JSpinner();
spGio = new javax.swing.JSpinner();
spPhut = new javax.swing.JSpinner();
jLabel12 = new javax.swing.JLabel();
spGiaTien = new javax.swing.JSpinner();
setDefaultCloseOperation(javax.swing.WindowConstants.DISPOSE_ON_CLOSE);
setTitle("Thêm Chuyến Xe");
jLabel4.setText("Ga Bắt Đầu");
jLabel5.setText("Ga Kết Thúc");
jLabel7.setText("Thời Gian Chạy");
button1.setLabel("Thêm Chuyến Xe");
button1.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
button1ActionPerformed(evt);
}
});
jButton1.setText("Chọn Ngày");
jLabel9.setText("Số Lượng Vé");
jLabel10.setText("Giới Hạn Vé");
jLabel8.setText("Giờ :");
jLabel11.setText("Phút");
spSoLV.setModel(new javax.swing.SpinnerNumberModel(Integer.valueOf(1), Integer.valueOf(1), null, Integer.valueOf(1)));
spSoLV.addChangeListener(new javax.swing.event.ChangeListener() {
public void stateChanged(javax.swing.event.ChangeEvent evt) {
spSoLVStateChanged(evt);
}
});
spGioiHanVe.setModel(new javax.swing.SpinnerNumberModel(1, 1, 1, 1));
spGio.setModel(new javax.swing.SpinnerNumberModel(0, 0, 23, 1));
spPhut.setModel(new javax.swing.SpinnerNumberModel(0, 0, 60, 1));
jLabel12.setText("Giá Tiền");
spGiaTien.setModel(new javax.swing.SpinnerNumberModel(Integer.valueOf(5000), Integer.valueOf(5000), null, Integer.valueOf(5000)));
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(40, 40, 40)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(jLabel10)
.addComponent(jLabel5)
.addComponent(jLabel4)
.addComponent(jLabel7)
.addComponent(jLabel9)
.addComponent(jLabel12))
.addGap(56, 56, 56)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
.addGroup(layout.createSequentialGroup()
.addGap(0, 0, Short.MAX_VALUE)
.addComponent(button1, javax.swing.GroupLayout.PREFERRED_SIZE, 119, javax.swing.GroupLayout.PREFERRED_SIZE))
.addGroup(layout.createSequentialGroup()
.addGap(1, 1, 1)
.addComponent(spGio)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
.addComponent(jLabel8)
.addGap(18, 18, 18)
.addComponent(spPhut)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
.addComponent(jLabel11, javax.swing.GroupLayout.PREFERRED_SIZE, 36, javax.swing.GroupLayout.PREFERRED_SIZE)))
.addGap(38, 38, 38)
.addComponent(jButton1))
.addGroup(layout.createSequentialGroup()
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(txtGaKetThuc, javax.swing.GroupLayout.PREFERRED_SIZE, 205, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(txtGaBatDau, javax.swing.GroupLayout.PREFERRED_SIZE, 205, javax.swing.GroupLayout.PREFERRED_SIZE)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING, false)
.addComponent(spGioiHanVe, javax.swing.GroupLayout.Alignment.LEADING, javax.swing.GroupLayout.DEFAULT_SIZE, 51, Short.MAX_VALUE)
.addComponent(spSoLV, javax.swing.GroupLayout.Alignment.LEADING)))
.addGap(0, 0, Short.MAX_VALUE)))
.addGap(120, 120, 120))
.addGroup(layout.createSequentialGroup()
.addComponent(spGiaTien, javax.swing.GroupLayout.PREFERRED_SIZE, 160, javax.swing.GroupLayout.PREFERRED_SIZE)
.addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))))
);
layout.setVerticalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addGap(43, 43, 43)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(txtGaBatDau, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(jLabel4))
.addGap(18, 18, 18)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(txtGaKetThuc, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(jLabel5))
.addGap(18, 18, 18)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(jButton1)
.addComponent(jLabel7))
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(spGio, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(jLabel8)
.addComponent(spPhut, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(jLabel11)))
.addGap(18, 18, 18)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(jLabel9)
.addComponent(spSoLV, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
.addGap(18, 18, 18)
.addComponent(jLabel10))
.addComponent(spGioiHanVe, javax.swing.GroupLayout.Alignment.TRAILING, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
.addGap(18, 18, 18)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(jLabel12, javax.swing.GroupLayout.Alignment.TRAILING)
.addComponent(spGiaTien, javax.swing.GroupLayout.Alignment.TRAILING, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, 30, Short.MAX_VALUE)
.addComponent(button1, javax.swing.GroupLayout.PREFERRED_SIZE, 36, javax.swing.GroupLayout.PREFERRED_SIZE)
.addGap(42, 42, 42))
);
UtilDateModel model = new UtilDateModel();
JDatePanelImpl datePanel = new JDatePanelImpl(model);
chonNgay = new JDatePickerImpl(datePanel,new DateLabelFormatter());
jButton1.add(chonNgay);
pack();
}// </editor-fold>//GEN-END:initComponents
private void button1ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_button1ActionPerformed
// TODO add your handling code here:
//Lưu giá trị ngày chọn được vào tam
Date tam=(Date) chonNgay.getModel().getValue();
if(tam!=null && ktDauVao())//Nếu giá trị ngày khác null và kiểm tra đầu vào hợp lệ
{
//Gán các thông tin chuyến xe vào cxdto
DTO.ChuyenXeDTO cxdto=new DTO.ChuyenXeDTO();
cxdto.setGatBatDau(txtGaBatDau.getText().trim());
cxdto.setGaKetThuc(txtGaKetThuc.getText().trim());
cxdto.setSoLuongVe((int)spSoLV.getValue());
cxdto.setGioiHanVe((int)spGioiHanVe.getValue());
cxdto.setGiaTien((int)spGiaTien.getValue());
//Tính toán và gán ngày giờ theo định dạng vào cxdto
SimpleDateFormat simpleDateFormat = new SimpleDateFormat("hh:mm dd-MM-yyyy");
Calendar cal = Calendar.getInstance();
cal.setTime(tam);
try {
cxdto.setThoiGianChay(simpleDateFormat.parse((int)spGio.getValue()+":"+(int)spPhut.getValue()+" "+cal.get(Calendar.DAY_OF_MONTH)+"-"+(cal.get(Calendar.MONTH)+1)+"-"+cal.get(Calendar.YEAR)));
} catch (ParseException ex) {
Logger.getLogger(ChuyenXeCN.class.getName()).log(Level.SEVERE, null, ex);
}
BUS.ChuyenXeBUS xpbus=new BUS.ChuyenXeBUS();
if(xpbus.ThemChuyenXe(cxdto)){//Nếu thêm chuyến xe thành công
//Show thông báo thành công
JOptionPane.showMessageDialog(this,
"Thêm chuyến đi thành công!",
"Thông báo",
JOptionPane.INFORMATION_MESSAGE);
}
else{//ngược lại
//Show thông báo thất bại
JOptionPane.showMessageDialog(this,
"Thêm chuyến đi thất bại!",
"Thông báo lỗi",
JOptionPane.ERROR_MESSAGE);
}
}
else
{
//Ngược lại show thông báo lỗi đầu vào
JOptionPane.showMessageDialog(this,
"Bạn chưa nhập đủ thông tin hoặc thông tin không hợp lệ.",
"Thông báo lỗi",
JOptionPane.ERROR_MESSAGE);
}
}//GEN-LAST:event_button1ActionPerformed
//Hàm kiểm tra các dữ liệu đầu vào
private boolean ktDauVao()
{
Date tam=(Date) chonNgay.getModel().getValue();//lấy ngày được chọn
Date tam2 = null;//lưu ngày giờ được chọn
Date tam3=new java.util.Date();//lấy ngày giờ hiện tại
SimpleDateFormat simpleDateFormat = new SimpleDateFormat("hh:mm dd-MM-yyyy");
Calendar cal = Calendar.getInstance();
cal.setTime(tam);
try {
tam2=simpleDateFormat.parse((int)spGio.getValue()+":"+(int)spPhut.getValue()+" "+cal.get(Calendar.DAY_OF_MONTH)+"-"+(cal.get(Calendar.MONTH)+1)+"-"+cal.get(Calendar.YEAR));
} catch (ParseException ex) {
Logger.getLogger(ChuyenXeCN.class.getName()).log(Level.SEVERE, null, ex);
}
boolean flag=false;//lưu giá trị trả về là false
if(!"".equals(txtGaBatDau.getText().trim()) && //Nếu dữ liệu Ga bắt đầu và Ga kết thúc không trống
!"".equals(txtGaKetThuc.getText().trim()) && tam2.after(tam3))//Và ngày giờ được chọn nằm sau ngày giờ hiện tại
flag=true;//gán giá trị trả về là true
return flag;
}
//Sự kiện khi giá trị spin Số lượng vé thay đổi
private void spSoLVStateChanged(javax.swing.event.ChangeEvent evt) {//GEN-FIRST:event_spSoLVStateChanged
// TODO add your handling code here:
if(slv>(int)spSoLV.getValue() && //Nếu số lượng vé vừa được chọn nhỏ hơn trước đó
(int)spGioiHanVe.getValue()>(int)spSoLV.getValue())//và số lượng vé vừa chọn nhỏ hơn giới hạn vé đang chọn
//gán lại khoảng giá trị cho spin Giới hạn vé (giá trị:số lượng vé vừa chọn,min:1,max:số lượng vé vừa chọn)
spGioiHanVe.setModel(new javax.swing.SpinnerNumberModel((int)spSoLV.getValue(), 1, (int)spSoLV.getValue(), 1));
else//Ngược lại
//gán lại khoảng giá trị cho spin Giới hạn vé (giá trị:giới hạn vé vừa chọn,min:1,max:số lượng vé vừa chọn)
spGioiHanVe.setModel(new javax.swing.SpinnerNumberModel((int)spGioiHanVe.getValue(), 1, (int)spSoLV.getValue(), 1));
slv=(int)spSoLV.getValue();//Gán lại giá trị cho số lượng vé
}//GEN-LAST:event_spSoLVStateChanged
/**
* @param args the command line arguments
*/
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 | InstantiationException | IllegalAccessException | javax.swing.UnsupportedLookAndFeelException ex) {
java.util.logging.Logger.getLogger(ChuyenXeCN.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
}
//</editor-fold>
/* Create and display the form */
java.awt.EventQueue.invokeLater(new Runnable() {
@Override
public void run() {
new ChuyenXeCN().setVisible(true);
}
});
}
// Variables declaration - do not modify//GEN-BEGIN:variables
private java.awt.Button button1;
private javax.swing.JButton jButton1;
private javax.swing.JLabel jLabel10;
private javax.swing.JLabel jLabel11;
private javax.swing.JLabel jLabel12;
private javax.swing.JLabel jLabel4;
private javax.swing.JLabel jLabel5;
private javax.swing.JLabel jLabel7;
private javax.swing.JLabel jLabel8;
private javax.swing.JLabel jLabel9;
private javax.swing.JSpinner spGiaTien;
private javax.swing.JSpinner spGio;
private javax.swing.JSpinner spGioiHanVe;
private javax.swing.JSpinner spPhut;
private javax.swing.JSpinner spSoLV;
private javax.swing.JTextField txtGaBatDau;
private javax.swing.JTextField txtGaKetThuc;
// End of variables declaration//GEN-END:variables
}
| Java |
package MAIN;
import com.sun.org.apache.xerces.internal.impl.dv.util.Base64;
import java.security.PublicKey;
import sun.security.x509.CertAndKeyGen;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.math.BigInteger;
import java.security.GeneralSecurityException;
import java.security.KeyPair;
import java.security.KeyStore;
import java.security.PrivateKey;
import java.security.PublicKey;
import java.security.SecureRandom;
import java.security.cert.CertPath;
import java.security.cert.CertPathValidator;
import java.security.cert.Certificate;
import java.security.cert.CertificateFactory;
import java.security.cert.PKIXCertPathValidatorResult;
import java.security.cert.PKIXParameters;
import java.security.cert.TrustAnchor;
import java.security.cert.X509Certificate;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Date;
import java.util.List;
import sun.security.x509.AlgorithmId;
import sun.security.x509.CertAndKeyGen;
import sun.security.x509.CertificateAlgorithmId;
import sun.security.x509.CertificateIssuerName;
import sun.security.x509.CertificateSerialNumber;
import sun.security.x509.CertificateSubjectName;
import sun.security.x509.CertificateValidity;
import sun.security.x509.CertificateVersion;
import sun.security.x509.CertificateX509Key;
import sun.security.x509.X500Name;
import sun.security.x509.X509CertImpl;
import sun.security.x509.X509CertInfo;
//CERTIFICATE AUTHORITY: VERISIGN
public class usc_Certificate
{
public static PublicKey pubKey = null;
public static PrivateKey privKey = null;
public static final String commonName = "SERVER"; //~CN
public static final String organizationalUnit = "12HC-IT";//~OU
public static final String organization = "Khoa Hoc Tu Nhien";//~O
public static final String city = "HCM";//~L
public static final String state = "HCM";//~ST
public static final String country = "VN";//~C
public static final long validity = 1096; // 3 years
public static final String alias = "FIT";
public static final char[] keyPass = "changeit".toCharArray();//the password to protect the key
public static X509Certificate generateCertificate(
String dn, KeyPair pair, int days, String algorithm)
throws GeneralSecurityException, IOException
{
/*http://stackoverflow.com/questions/1615871/creating-an-x509-certificate-in-java-without-bouncycastle
* Create a self-signed X.509 Certificate
* @param dn the X.509 Distinguished Name, eg "CN=Test, L=London, C=GB"
* @param pair the KeyPair
* @param days how many days from now the Certificate is valid for
* @param algorithm the signing algorithm, eg "SHA1withRSA"
*/
PrivateKey privkey = pair.getPrivate();
X509CertInfo info = new X509CertInfo();
Date from = new Date();
Date to = new Date(from.getTime() + days * 86400000l);
CertificateValidity interval = new CertificateValidity(from, to);
BigInteger sn = new BigInteger(64, new SecureRandom());
X500Name owner = new X500Name(dn);
info.set(X509CertInfo.VALIDITY, interval);
info.set(X509CertInfo.SERIAL_NUMBER, new CertificateSerialNumber(sn));
info.set(X509CertInfo.SUBJECT, new CertificateSubjectName(owner));
info.set(X509CertInfo.ISSUER, new CertificateIssuerName(owner));
info.set(X509CertInfo.KEY, new CertificateX509Key(pair.getPublic()));
info.set(X509CertInfo.VERSION, new CertificateVersion(CertificateVersion.V3));
AlgorithmId algo = new AlgorithmId(AlgorithmId.md5WithRSAEncryption_oid);
info.set(X509CertInfo.ALGORITHM_ID, new CertificateAlgorithmId(algo));
// Sign the cert to identify the algorithm that's used.
X509CertImpl cert = new X509CertImpl(info);
cert.sign(privkey, algorithm);
// Update the algorith, and resign.
algo = (AlgorithmId)cert.get(X509CertImpl.SIG_ALG);
info.set(CertificateAlgorithmId.NAME + "." + CertificateAlgorithmId.ALGORITHM, algo);
cert = new X509CertImpl(info);
cert.sign(privkey, algorithm);
return cert;
}
public static void createCertificate(String fileName) throws Exception
{
KeyPair kp = new KeyPair(pubKey, privKey);
String dn = "";
dn+= "CN=" + commonName + ", ";
dn+= "OU=" + organizationalUnit + ", ";
dn+= "O=" + organization + ", ";
dn+= "L=" + city +", ";
dn+= "C=" + country + "";
X509Certificate cert = generateCertificate(dn, kp, 60, "SHA256WithRSA");
FileOutputStream os = new FileOutputStream(fileName);
os.write(cert.getEncoded());
os.close();
//SHA1withDSA,SHA1withRSA,SHA256withRSA is Sig algo supported by Java platform.
}
public static void validateCertificate(String certFileName)
{
try
{
CertificateFactory cf = CertificateFactory.getInstance("X.509");
FileInputStream is = new FileInputStream(new File(certFileName));
Certificate cert = cf.generateCertificate(is);
List mylist = new ArrayList();
mylist.add(cert);
CertPath cp = cf.generateCertPath(mylist);
Certificate trust = cert;
TrustAnchor anchor = new TrustAnchor((X509Certificate) trust, null);
PKIXParameters params = new PKIXParameters(Collections.singleton(anchor));
params.setRevocationEnabled(false);
CertPathValidator cpv = CertPathValidator.getInstance("PKIX");
/*
PKIXCertPathValidatorResult represents the successful result of the PKIX certification path validation algorithm.
Instances of PKIXCertPathValidatorResult are returned by the validate method of CertPathValidator objects implementing the PKIX algorithm.
*/
PKIXCertPathValidatorResult result = (PKIXCertPathValidatorResult) cpv.validate(cp, params);
System.out.println(result);
}
catch(Exception ex)
{
System.out.println("Invalid Input!!!");
}
}
public static boolean validateCertificate(Certificate _cer)
{
boolean f = false;
try
{
CertificateFactory cf = CertificateFactory.getInstance("X.509");
Certificate cert = _cer;
List mylist = new ArrayList();
mylist.add(cert);
CertPath cp = cf.generateCertPath(mylist);
Certificate trust = cert;
TrustAnchor anchor = new TrustAnchor((X509Certificate) trust, null);
PKIXParameters params = new PKIXParameters(Collections.singleton(anchor));
params.setRevocationEnabled(false);
CertPathValidator cpv = CertPathValidator.getInstance("PKIX");
/*
PKIXCertPathValidatorResult represents the successful result of the PKIX certification path validation algorithm.
Instances of PKIXCertPathValidatorResult are returned by the validate method of CertPathValidator objects implementing the PKIX algorithm.
*/
PKIXCertPathValidatorResult result = (PKIXCertPathValidatorResult) cpv.validate(cp, params);
//System.out.println(result);
f = true;
}
catch(Exception ex)
{
System.out.println("Invalid Input!!!");
}
return f;
}
public static void main(String[] args) throws Exception
{
usc_RSAKeyPair.PUBLIC_KEY_FILE = "public.key";
pubKey = usc_RSAKeyPair.readPublicKey();
usc_RSAKeyPair.PRIVATE_KEY_FILE = "private.key";
privKey = usc_RSAKeyPair.readPrivateKey();
//System.out.println(pubKey);
//System.out.println(privKey);
//createCertificate("resource/GUEST.cer");
//Read Certificate file
FileInputStream is = new FileInputStream(new File("SERVER.cer"));
CertificateFactory cf = CertificateFactory.getInstance("X.509");
Certificate cert = cf.generateCertificate(is);
//System.out.println(cert);
validateCertificate(cert);
//Validate Certificate file
//validateCertificate("SERVER.cer");
}
}
| Java |
/*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
package MAIN;
import java.sql.SQLException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.GregorianCalendar;
import java.util.List;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.swing.JOptionPane;
import javax.swing.ListSelectionModel;
import javax.swing.event.ListSelectionEvent;
import javax.swing.event.ListSelectionListener;
import javax.swing.table.AbstractTableModel;
/**
*
* @author Anonymous
*/
public class MAIN extends javax.swing.JFrame {
/**
* Creates new form Main
*/
public static int IDRide;//Đây là biến dùng để lưu mã chuyến xe của 1 chuyến khi mình nhấp vào chuyến đó
//có tác dụng khi xóa hoặc cập nhật chuyến xe
private int Tickets;//Đây là biến dùng để lưu số lượng vé đã đặt của 1 chuyến khi mình nhấp vào chuyến đó
//có tác dụng khi xóa hoặc cập nhật chuyến xe
private MyTableModel model;//Biến dùng để lưu cấu trúc bảng lưu dữ liệu
//Hàm này sẽ chạy sau khi hàm giao diện thực hiện
public MAIN() {
initComponents();
Tickets=0;//Khởi tạo giá trị cho số vé đã đặt của chuyến xe được chọn là 0
btnUpdate.setEnabled(false);//Không cho nút "cập nhật chuyến xe" xử lý sử kiện nhấp chuột
btnDelete.setEnabled(false);//Không cho nút "xóa chuyến xe" xử lý sử kiện nhấp chuột
DAO.Connect.ListenServer();//Hàm server dùng để lắng nghe client
//Tạo 1 thread mới dùng làm đồng hồ hiển thị tại nút Time
new Thread()
{
@Override
public void run()
{
boolean fa=false;
while(true)//Chạy liên tục
{
Calendar cal=new GregorianCalendar();//Khởi tạo biến này để lưu ngày giờ hiện tại của máy
int hour=cal.get(Calendar.HOUR_OF_DAY);//lưu giờ vào biến
int min=cal.get(Calendar.MINUTE);//lưu phút vào biến
int sec=cal.get(Calendar.SECOND);//lưu giây vào biến
int day=cal.get(Calendar.DAY_OF_MONTH);//lưu ngày vào biến
int mon=cal.get(Calendar.MONTH);//lưu tháng vào biến
int year=cal.get(Calendar.YEAR);//lưu năm vào biến
//Đưa thông tin vào chuỗi time
String time=hour +":"+min+":"+sec+" "+day+"-"+(mon+1)+"-"+year;
btnTime.setLabel(time);//Thể hiện chuỗi time trên nút Time
if(min%30==0)//Mỗi 30 phút kiểm tra và xử lý những đặt vé đã hết hạn thanh toán
{
new Thread()
{
@Override
public void run()
{
DAO.DatVeDAO.ktHanDatVe();
}
}.start();
}
}
}
}.start();
}
/**
* This method is called from within the constructor to initialize the form.
* WARNING: Do NOT modify this code. The content of this method is always
* regenerated by the Form Editor.
*/
//Phần này là netbeans tự tạo khi mình thiết kế giao diện
@SuppressWarnings("unchecked")
// <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
private void initComponents() {
btnInsertRide = new java.awt.Button();
jScrollPane1 = new javax.swing.JScrollPane();
tbRide = new javax.swing.JTable();
btnUpdate = new java.awt.Button();
btnDelete = new java.awt.Button();
btnRefresh = new java.awt.Button();
btnTime = new java.awt.Button();
setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
setTitle("HTBVTQM_SERVER");
btnInsertRide.setActionCommand("Insert");
btnInsertRide.setLabel("Thêm Chuyến Xe");
btnInsertRide.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
btnInsertRideActionPerformed(evt);
}
});
model = new MyTableModel();
tbRide.setAutoCreateRowSorter(true);
tbRide.setModel(model);
ListenTable();
jScrollPane1.setViewportView(tbRide);
btnUpdate.setLabel("Cập Nhật Chuyến Xe");
btnUpdate.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
btnUpdateActionPerformed(evt);
}
});
btnDelete.setLabel("Xóa Chuyến Xe");
btnDelete.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
btnDeleteActionPerformed(evt);
}
});
btnRefresh.setLabel("Làm mới danh sách");
btnRefresh.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
btnRefreshActionPerformed(evt);
}
});
btnTime.setLabel("Time");
btnTime.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
btnTimeActionPerformed(evt);
}
});
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(41, 41, 41)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addComponent(btnInsertRide, javax.swing.GroupLayout.PREFERRED_SIZE, 126, javax.swing.GroupLayout.PREFERRED_SIZE)
.addGap(241, 241, 241)
.addComponent(btnRefresh, javax.swing.GroupLayout.PREFERRED_SIZE, 150, javax.swing.GroupLayout.PREFERRED_SIZE)
.addGap(0, 0, Short.MAX_VALUE))
.addGroup(layout.createSequentialGroup()
.addComponent(jScrollPane1, javax.swing.GroupLayout.PREFERRED_SIZE, 740, javax.swing.GroupLayout.PREFERRED_SIZE)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false)
.addComponent(btnUpdate, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
.addComponent(btnDelete, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))))
.addContainerGap())
.addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
.addGap(0, 0, Short.MAX_VALUE)
.addComponent(btnTime, javax.swing.GroupLayout.PREFERRED_SIZE, 268, javax.swing.GroupLayout.PREFERRED_SIZE))
);
layout.setVerticalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addComponent(btnTime, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addGap(14, 14, 14)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(btnInsertRide, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(btnRefresh, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(jScrollPane1, javax.swing.GroupLayout.PREFERRED_SIZE, 242, javax.swing.GroupLayout.PREFERRED_SIZE)
.addGroup(layout.createSequentialGroup()
.addComponent(btnDelete, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(btnUpdate, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)))
.addGap(20, 20, 20))
);
btnInsertRide.getAccessibleContext().setAccessibleName("Insert");
pack();
}// </editor-fold>//GEN-END:initComponents
//Hàm xử lý sử kiện khi nhấp vào nút Thêm chuyến xe
private void btnInsertRideActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnInsertRideActionPerformed
// TODO add your handling code here:
java.awt.EventQueue.invokeLater(new Runnable() {
@Override
public void run() {
//Ta chạy màn hình ChuyenXeCN trong packet GUI để thêm mới 1 chuyến xe
new GUI.ChuyenXeCN().setVisible(true);
}
});
}//GEN-LAST:event_btnInsertRideActionPerformed
//Hàm xử lý sử kiện khi nhấp vào nút Cập nhật chuyến xe
private void btnUpdateActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnUpdateActionPerformed
// TODO add your handling code here:
java.awt.EventQueue.invokeLater(new Runnable() {
@Override
public void run() {
//Ta chạy màn hình ChuyenXeCN2 trong packet GUI để cập nhật 1 chuyến xe
new GUI.ChuyenXeCN2().setVisible(true);
}
});
}//GEN-LAST:event_btnUpdateActionPerformed
//Hàm xử lý sử kiện khi nhấp vào nút xóa chuyến xe
private void btnDeleteActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnDeleteActionPerformed
// TODO add your handling code here:
if(Tickets==0)//Nếu chưa có người đặt vé
{
BUS.ChuyenXeBUS cxbus=new BUS.ChuyenXeBUS();//Khởi tạo biến cxbus
//xem lại mô hình 3 lớp
//hoặc vào packet BUS xem chi tiết
if(cxbus.XoaChuyenXe(IDRide)){//Nếu xóa chuyến xe thành công (chạy hàm xóa chuyến xe trong câu if luôn)
//Show ra màn hình thông báo xóa chuyến xe thành công
JOptionPane.showMessageDialog(this,
"Xóa chuyến xe thành công!",
"Thông báo",
JOptionPane.INFORMATION_MESSAGE);
}
else{
//Ngược lại show ra màn hình thông báo xóa chuyến xe thất bại
JOptionPane.showMessageDialog(null,
"Xóa chuyến xe thất bại",
"Thông báo lỗi",
JOptionPane.ERROR_MESSAGE);
}
LoadTable();//làm mới lại bảng dữ liệu
}
else
{
//Ngược lại show ra màn hình thông báo xóa chuyến xe thất bại do đã có người đặt vé
JOptionPane.showMessageDialog(null,
"Không thể xóa chuyến đi do đã có người đặt vé",
"Thông báo lỗi",
JOptionPane.ERROR_MESSAGE);
}
}//GEN-LAST:event_btnDeleteActionPerformed
//Hàm xử lý sử kiện khi nhấp vào nút Làm mới danh sách
private void btnRefreshActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnRefreshActionPerformed
// TODO add your handling code here:
LoadTable();//làm mới lại bảng dữ liệu
}//GEN-LAST:event_btnRefreshActionPerformed
private void btnTimeActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnTimeActionPerformed
// TODO add your handling code here:
}//GEN-LAST:event_btnTimeActionPerformed
//Đây là hàm làm mới lại dữ liệu, trả lại true nếu làm mới dữ liệu thành công, ngược lại là false
private boolean LoadTable(){
if(DAO.Connect.connect()){//Nếu kết nối được với sql server
try {
DAO.Connect.con.close();//Đóng kết nối lại
} catch (SQLException ex) {
Logger.getLogger(MAIN.class.getName()).log(Level.SEVERE, null, ex);
}
model = new MyTableModel();//Tạo mới cấu trúc dùng để lưu bảng dữ liệu
tbRide.setAutoCreateRowSorter(true);
tbRide.setModel(model);//Cài đặt cấu trúc đó vào biến bảng dữ liệu
ListenTable();//Nghe sự kiện khi nhấp chuột vào mỗi dòng dữ liệu trong bảng
jScrollPane1.setViewportView(tbRide);
btnUpdate.setEnabled(false);//Không cho nút "cập nhật chuyến xe" xử lý sử kiện nhấp chuột
btnDelete.setEnabled(false);//Không cho nút "xóa chuyến xe" xử lý sử kiện nhấp chuột
return true;
}
else{
}
return false;
}
//Hàm nghe sự kiện khi nhấp chuột vào mỗi dòng dữ liệu trong bảng
private void ListenTable(){
//Các dòng ở đây là hàm bắt buộc phải có khi lắng nghe, vào tutorial của oracle để thêm chi tiết
tbRide.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
tbRide.getSelectionModel().addListSelectionListener(
new ListSelectionListener() {
@Override
public void valueChanged(ListSelectionEvent event) {
int viewRow = tbRide.getSelectedRow();
if (viewRow < 0) {//Nếu không nhấp vào dòng dữ liệu nào
//Selection got filtered away.
btnUpdate.setEnabled(false);//Không cho nút "cập nhật chuyến xe" xử lý sử kiện nhấp chuột
btnDelete.setEnabled(false);//Không cho nút "xóa chuyến xe" xử lý sử kiện nhấp chuột
} else {//ngược lại khi nhấp vào 1 dòng dữ liệu chuyến xe
//Nếu dòng này không có dòng dữ Da Chay ở cột TT, nghĩa là xe chưa chạy
if(!"Da Chay".equals(String.valueOf(tbRide.getValueAt(viewRow, 7)))) {
btnUpdate.setEnabled(true);//Cho phép nút Cập nhật chuyến xe xử lý sự kiện nhấp chuột
btnDelete.setEnabled(true);//Cho phép nút Xóa chuyến xe xử lý sự kiện nhấp chuột
//Lưu mã chuyến xe lại
IDRide=Integer.parseInt(String.valueOf(tbRide.getValueAt(viewRow, 0)));
//Nếu có chữ FULL ở cột VeDaDat
if("FULL".equals(String.valueOf(tbRide.getValueAt(viewRow, 6))))
//Lưu số vé đã đặt ở cột SLVe
Tickets=Integer.parseInt(String.valueOf(tbRide.getValueAt(viewRow, 4)));
else//Ngược lại
//Lưu số vé đã đặt ở cột VeDaDat
Tickets=Integer.parseInt(String.valueOf(tbRide.getValueAt(viewRow, 6)));
}
else//Ngược lại
{
btnUpdate.setEnabled(false);//Không cho nút "cập nhật chuyến xe" xử lý sử kiện nhấp chuột
btnDelete.setEnabled(false);//Không cho nút "xóa chuyến xe" xử lý sử kiện nhấp chuột
}
}
}
}
);
}
//Đối tượng để lưu dữ liệu cho bảng,tham khảo của oracle
class MyTableModel extends AbstractTableModel {
//Đặt tên hiển thị cho các cột
private String[] columnNames={"MaCX",
"GaBatDau",
"GaKetThuc","ThoiGianChay","SLVe","GHVe","VeDaDat","GiaTien","TT"};;
public Object[][] data;//Dùng để chứa dữ liệu
public MyTableModel(){//Ta chỉ quan tâm đến hàm này, nhiệm vụ đưa dữ liệu vào đối tượng
if(DAO.Connect.connect()){//Nếu kết nối thành công với sql server
try {
DAO.Connect.con.close();//Đóng kết nối lại
} catch (SQLException ex) {
Logger.getLogger(MAIN.class.getName()).log(Level.SEVERE, null, ex);
}
try
{
//3 dòng sau làm nhiệm vụ lấy về danh sách tất cả các chuyến xe đưa vào biến Lcxdto
BUS.ChuyenXeBUS cxbus=new BUS.ChuyenXeBUS();
List<DTO.ChuyenXeDTO> Lcxdto= new ArrayList<DTO.ChuyenXeDTO>();
Lcxdto=cxbus.dsChuyenXe();
//khai báo du liệu gồm 8 cột và Lcxdto.size()(độ lớn của danh sách chuyến xe) dòng
data=new Object[Lcxdto.size()][9];
//Lưu định dạng ngày tháng
SimpleDateFormat simpleDateFormat = new SimpleDateFormat("HH:mm dd-MM-yyyy");
java.util.Date tam=new java.util.Date();//tam lưu ngày giờ hiện tại của máy đang sử dụng
int cot=0;//lưu chỉ số cột
int dong=0;//lưu chỉ số dòng
for(int i=0;i<Lcxdto.size();i++)//Đưa danh sách chuyến xe vào từng dòng và cột
{
//bắt đầu từ cột 0 sau đó cộng dần lên
data[dong][cot++]=Lcxdto.get(i).getMaChuyen();
data[dong][cot++]=Lcxdto.get(i).getGaBatDau();
data[dong][cot++]=Lcxdto.get(i).getGaKetThuc();
//Định dạng lại kiểu ngày tháng
data[dong][cot++]=simpleDateFormat.format(Lcxdto.get(i).getThoiGianChay());
data[dong][cot++]=Lcxdto.get(i).getSoLuongVe();
data[dong][cot++]=Lcxdto.get(i).getGioiHanVe();
//Nếu vé đã đặt=số lượng vé thì ghi FULL= đã hết vé vào cột này
if(Lcxdto.get(i).getVeDaDat()==Lcxdto.get(i).getSoLuongVe())
data[dong][cot++]="FULL";
else
data[dong][cot++]=Lcxdto.get(i).getVeDaDat();
data[dong][cot++]=Lcxdto.get(i).getGiaTien();
//Nếu thời gian hiện hành sau thời gian chạy thì ghi Da Chay = Đã chạy vào cột này
if(tam.after(Lcxdto.get(i).getThoiGianChay()))
data[dong][cot++]="Da Chay";
else
//Ngược lại ghi Chua Chay= chưa chạy
data[dong][cot++]="Chua Chay";
cot=0;//gán lại cột =0
dong++;// tăng chỉ số dòng lên
}
}
catch (Exception ex)
{
data=new Object[0][9];
System.out.println(ex.getMessage());
}
}
else
{
data=new Object[0][9];
}
}
@Override
public int getColumnCount() {
return columnNames.length;
}
@Override
public int getRowCount() {
return data.length;
}
@Override
public String getColumnName(int col) {
return columnNames[col];
}
@Override
public Object getValueAt(int row, int col) {
return data[row][col];
}
/*
* JTable uses this method to determine the default renderer/
* editor for each cell. If we didn't implement this method,
* then the last column would contain text ("true"/"false"),
* rather than a check box.
*/
@Override
public Class getColumnClass(int c) {
return getValueAt(0, c).getClass();
}
/*
* Don't need to implement this method unless your table's
* editable.
*/
@Override
public boolean isCellEditable(int row, int col) {
//Note that the data/cell address is constant,
//no matter where the cell appears onscreen.
//if (col < 2) {
return false;//Không cho sữa dữ liệu ngay trên bảng
//} else {
// return true;
//}
}
/*
* Don't need to implement this method unless your table's
* data can change.
*/
@Override
public void setValueAt(Object value, int row, int col) {
if (true) {
System.out.println("Setting value at " + row + "," + col
+ " to " + value
+ " (an instance of "
+ value.getClass() + ")");
}
data[row][col] = value;
fireTableCellUpdated(row, col);
if (true) {
System.out.println("New value of data:");
printDebugData();
}
}
private void printDebugData() {
int numRows = getRowCount();
int numCols = getColumnCount();
for (int i=0; i < numRows; i++) {
System.out.print(" row " + i + ":");
for (int j=0; j < numCols; j++) {
System.out.print(" " + data[i][j]);
}
System.out.println();
}
System.out.println("--------------------------");
}
}
/**
* @param args the command line arguments
*/
//đây là file đầu tiên mà chương trình sẽ chạy
public static void main(String args[]) {//ở đây là hàm đầu tiên mà file này sẽ chạy
/* 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 | InstantiationException | IllegalAccessException | javax.swing.UnsupportedLookAndFeelException ex) {
java.util.logging.Logger.getLogger(MAIN.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
}
//</editor-fold>
/* Create and display the form */
java.awt.EventQueue.invokeLater(new Runnable() {//Phần ở trên là do netbeans tự tạo ra nên không cần quan tâm
@Override
public void run() {
if(!DAO.Connect.ktKetNoi()){//Nếu server không thể kết nối với sql server
//Ta chạy màn hình cấu hình cho sql server
new GUI.ConfigGUI().setVisible(true);//Đây là hàm chạy giao diện, hiểu thêm các bạn google tên hàm
}
else{
//Ngược lại ta chạy màn hình MAIN đã thiết kế cho file này
new MAIN().setVisible(true);
}
}
});
}
// Variables declaration - do not modify//GEN-BEGIN:variables
private java.awt.Button btnDelete;
private java.awt.Button btnInsertRide;
private java.awt.Button btnRefresh;
private java.awt.Button btnTime;
private java.awt.Button btnUpdate;
private javax.swing.JScrollPane jScrollPane1;
private javax.swing.JTable tbRide;
// End of variables declaration//GEN-END:variables
}
| Java |
package MAIN;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.security.Key;
import java.util.Arrays;
import java.util.Random;
import javax.crypto.Cipher;
import javax.crypto.KeyGenerator;
import javax.crypto.Mac;
import javax.crypto.SecretKey;
import javax.crypto.SecretKeyFactory;
import javax.crypto.spec.PBEKeySpec;
import javax.crypto.spec.PBEParameterSpec;
import javax.crypto.spec.SecretKeySpec;
import sun.misc.BASE64Decoder;
import sun.misc.BASE64Encoder;
/*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
/**
*
* @author Messi
*/
public class usc_sessionkey_mac {
static final String AZ = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ"
+ "abcdefghijklmnopqrstuvwxyz"
+ "!@#$%^&*()-_+=";
static Random rnd = new Random();
public static String randomString(int len)
{
StringBuilder sb = new StringBuilder( len );
for( int i = 0; i < len; i++ )
sb.append( AZ.charAt( rnd.nextInt(AZ.length()) ) );
return sb.toString();
}
public static byte[] generateMAC(String inputString, String secreteKeyString) throws Exception
{
byte[] macBytes = null;
//KeyGenerator keyGen = KeyGenerator.getInstance("HmacMD5");
//SecretKey secretKey = keyGen.generateKey();
byte[] encodedKey = secreteKeyString.getBytes();
SecretKey secretKey = new SecretKeySpec(encodedKey,0,encodedKey.length,"HmacSHA256");
Mac mac = Mac.getInstance(secretKey.getAlgorithm());
mac.init(secretKey);
byte[] byteData = inputString.getBytes("UTF8");
macBytes = mac.doFinal(byteData);
return macBytes;
}
public static String xorMessage(String message, String key)
{
try
{
if (message==null || key==null ) return null;
char[] keys=key.toCharArray();
char[] mesg=message.toCharArray();
int ml=mesg.length;
int kl=keys.length;
char[] newmsg=new char[ml];
for (int i=0; i<ml; i++){
newmsg[i]=(char)(mesg[i]^keys[i%kl]);
}//for i
mesg=null; keys=null;
return new String(newmsg);
}
catch ( Exception e )
{
return null;
}
}//xorMessage
public static final String DEFAULT_ENCODING="UTF-8";
static BASE64Encoder enc=new BASE64Encoder();
static BASE64Decoder dec=new BASE64Decoder();
public static String base64encode(String text){
try {
String rez = enc.encode( text.getBytes( DEFAULT_ENCODING ) );
return rez;
}
catch (Exception e ) {
return null;
}
}//base64encode
public static String base64decode(String text){
try {
return new String(dec.decodeBuffer( text ),DEFAULT_ENCODING);
}
catch (Exception e ) {
return null;
}
}//base64decode
public static int Compare2MAC(byte[] mac1, byte[] mac2)
{
if(Arrays.equals(mac2, mac1))
return 1;
return 0;
}
//**http://stackoverflow.com/questions/5837698/converting-any-object-to-a-byte-array-in-java
//Convert Object to byte[]
public static byte[] serialize(Object obj) throws IOException {
ByteArrayOutputStream b = new ByteArrayOutputStream();
ObjectOutputStream o = new ObjectOutputStream(b);
o.writeObject(obj);
return b.toByteArray();
}
//Convert byte[] to Object
public static Object deserialize(byte[] bytes) throws IOException, ClassNotFoundException {
ByteArrayInputStream b = new ByteArrayInputStream(bytes);
ObjectInputStream o = new ObjectInputStream(b);
return o.readObject();
}
//**http://stackoverflow.com/questions/1132567/encrypt-password-in-configuration-files-java
public static byte[] Encrypt(String secretKeyString, Object input) throws Exception
{
if(input==null || secretKeyString == null)
{
System.out.println("Dau vao null!");
}
byte[] re = null;
byte[] data = serialize(input);
char[] PASSWORD = secretKeyString.toCharArray();
byte[] SALT = {
(byte) 0xde, (byte) 0x33, (byte) 0x10, (byte) 0x12,
(byte) 0xde, (byte) 0x33, (byte) 0x10, (byte) 0x12,
};
SecretKeyFactory keyFactory = SecretKeyFactory.getInstance("PBEWithMD5AndDES");
SecretKey key = keyFactory.generateSecret(new PBEKeySpec(PASSWORD));
Cipher pbeCipher = Cipher.getInstance("PBEWithMD5AndDES/CBC/PKCS5Padding");
pbeCipher.init(Cipher.ENCRYPT_MODE, key, new PBEParameterSpec(SALT,20));
re = pbeCipher.doFinal(data);
return re;
}
public static Object Decrypt(String secretKeyString, byte[] input) throws Exception
{
if(input==null || secretKeyString == null)
{
System.out.println("Dau vao null!");
}
Object re = null;
char[] PASSWORD = secretKeyString.toCharArray();
byte[] SALT = {
(byte) 0xde, (byte) 0x33, (byte) 0x10, (byte) 0x12,
(byte) 0xde, (byte) 0x33, (byte) 0x10, (byte) 0x12,
};
SecretKeyFactory keyFactory = SecretKeyFactory.getInstance("PBEWithMD5AndDES");
SecretKey key = keyFactory.generateSecret(new PBEKeySpec(PASSWORD));
Cipher pbeCipher = Cipher.getInstance("PBEWithMD5AndDES/CBC/PKCS5Padding");
pbeCipher.init(Cipher.DECRYPT_MODE, key, new PBEParameterSpec(SALT, 20));
byte[] temp1 = pbeCipher.doFinal(input);
re = deserialize(temp1);
return re;
}
public static void main(String[] args) throws Exception
{
//Random String for Secrete Key (Session Key)
String s1 = randomString(50);
//System.out.println(s1);
/*
//Use Secrete Key to encrypt and decrypt
String txt="Anh là ĐQM Dũng" ;
String key = s1;
System.out.println(txt+" XOR-ed to: "+(txt=xorMessage(txt,key)));
String encoded=base64encode( txt );
System.out.println( " is encoded to: "+encoded+" and that is decoding to: "+ (txt=base64decode(encoded)));
System.out.println( "XOR-ing back to original: "+xorMessage(txt,key));
*/
/*
//Use Secrete Key to create MAC
s1 = "secreteKeySring";//
byte[] b = generateMAC("ABC",s1);
String s2 = new String(b,"UTF-8");
String endcoded = base64encode(s2);
System.out.println(endcoded);
//Compare 2 byte array (MAC)
byte[] c = b;
if(Compare2MAC(c, b)==1)
{
System.out.println("Two MAC is Equal.");
}
else
{
System.out.println("Two MAC is Not Equal.");
}
*/
/*
//Use Secrete Key to create MAC
s1 = "secreteKeySring";//
byte[] b = generateMAC("ABC",s1);
String s2 = new String(b,"UTF-8");
String endcoded = base64encode(s2);
System.out.println(endcoded);
//Compare 2 byte array (MAC)
byte[] c = b;
if(Compare2MAC(c, b)==1)
{
System.out.println("Two MAC is Equal.");
}
else
{
System.out.println("Two MAC is Not Equal.");
}
*/
String keyString = randomString(50);
System.out.println("Plaintext: " + s1);
System.out.println("KeyString: " + keyString);
System.out.println("Encrypt & Decypt");
System.out.println("Encrypt...");
byte[] encrypt = Encrypt(keyString, s1);
Object obj1 = encrypt;
byte[] encrypt2 = (byte[])obj1;
String decrypt = (String)Decrypt(keyString, encrypt2);
System.out.println("Decrypt: " + decrypt);
System.out.println();
}
}
| Java |
/*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
package MAIN;
/**
*
* @author Anonymous
*/
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import javax.swing.JFormattedTextField.AbstractFormatter;
public class DateLabelFormatter extends AbstractFormatter {
private String datePattern = "dd-MM-yyyy";
private SimpleDateFormat dateFormatter = new SimpleDateFormat(datePattern);
@Override
public Object stringToValue(String text) throws ParseException {
return dateFormatter.parseObject(text);
}
@Override
public String valueToString(Object value) throws ParseException {
if (value != null) {
Calendar cal = (Calendar) value;
return dateFormatter.format(cal.getTime());
}
return "";
}
} | Java |
package MAIN;
import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.math.BigInteger;
import java.nio.charset.Charset;
import java.security.KeyFactory;
import java.security.KeyPair;
import java.security.KeyPairGenerator;
import java.security.PrivateKey;
import java.security.PublicKey;
import java.security.spec.RSAPrivateKeySpec;
import java.security.spec.RSAPublicKeySpec;
import javax.crypto.Cipher;
//http://www.javamex.com/tutorials/cryptography/rsa_encryption.shtml
public class usc_RSAKeyPair
{
/*
* the public key consists of the "modulus" and a "public exponent";
* the private key consists of that same "modulus" plus a "private exponent";
*/
public static String PUBLIC_KEY_FILE = "";
public static String PRIVATE_KEY_FILE = "";
public static void generate() throws Exception
{
KeyPairGenerator kpg = KeyPairGenerator.getInstance("RSA");
kpg.initialize(2048);
KeyPair kp = kpg.genKeyPair();
KeyFactory fact = KeyFactory.getInstance("RSA");
RSAPublicKeySpec pub = fact.getKeySpec(kp.getPublic(),RSAPublicKeySpec.class);
saveToFile(PUBLIC_KEY_FILE, pub.getModulus(), pub.getPublicExponent());
//System.out.println("public exponent: " + pub.getPublicExponent());
RSAPrivateKeySpec priv = fact.getKeySpec(kp.getPrivate(), RSAPrivateKeySpec.class);
saveToFile(PRIVATE_KEY_FILE, priv.getModulus(), priv.getPrivateExponent());
//System.out.println("private exponent: " + priv.getPrivateExponent());
}
private static void saveToFile(String fileName,
BigInteger mod, BigInteger exp) throws Exception
{
ObjectOutputStream oout = new ObjectOutputStream(
new BufferedOutputStream(new FileOutputStream(fileName)));
try {
oout.writeObject(mod);
oout.writeObject(exp);
} catch (Exception e) {
throw new Exception(e);
} finally {
oout.flush();
oout.close();
}
//System.out.println("exponent: " + exp.toString());
}
public static PublicKey readPublicKey() throws Exception
{
InputStream in = new FileInputStream(PUBLIC_KEY_FILE);
ObjectInputStream oin =
new ObjectInputStream(new BufferedInputStream(in));
try {
BigInteger m = (BigInteger) oin.readObject();
BigInteger e = (BigInteger) oin.readObject();
RSAPublicKeySpec keySpec = new RSAPublicKeySpec(m, e);
KeyFactory fact = KeyFactory.getInstance("RSA");
PublicKey pubKey = fact.generatePublic(keySpec);
return pubKey;
} catch (Exception e) {
throw new Exception(e);
} finally {
oin.close();
}
}
public static PrivateKey readPrivateKey() throws Exception
{
InputStream in = new FileInputStream(PRIVATE_KEY_FILE);
ObjectInputStream oin =
new ObjectInputStream(new BufferedInputStream(in));
try {
BigInteger m = (BigInteger) oin.readObject();
BigInteger e = (BigInteger) oin.readObject();
RSAPrivateKeySpec keySpec = new RSAPrivateKeySpec(m, e);
KeyFactory fact = KeyFactory.getInstance("RSA");
PrivateKey privKey = fact.generatePrivate(keySpec);
return privKey;
} catch (Exception e) {
throw new Exception(e);
} finally {
oin.close();
}
}
public static byte[] PAIR1_Encrypt(byte[] input, PrivateKey privKey) throws Exception
{
byte[] output = null;
Cipher cipher = Cipher.getInstance("RSA");
cipher.init(Cipher.ENCRYPT_MODE, privKey);
output = cipher.doFinal(input);
return output;
}
public static byte[] PAIR1_Decrypt(byte[] input, PublicKey pubKey) throws Exception
{
byte[] output = null;
Cipher cipher = Cipher.getInstance("RSA");
cipher.init(Cipher.DECRYPT_MODE, pubKey);
output = cipher.doFinal(input);
return output;
}
public static byte[] PAIR2_Encrypt(byte[] input, PublicKey pubKey) throws Exception
{
byte[] output = null;
Cipher cipher = Cipher.getInstance("RSA");
cipher.init(Cipher.ENCRYPT_MODE, pubKey);
output = cipher.doFinal(input);
return output;
}
public static byte[] PAIR2_Decrypt(byte[] input, PrivateKey privKey) throws Exception
{
byte[] output = null;
Cipher cipher = Cipher.getInstance("RSA");
cipher.init(Cipher.DECRYPT_MODE, privKey);
output = cipher.doFinal(input);
return output;
}
//=====================================================
public static void main(String[] args) throws Exception
{
usc_RSAKeyPair.PUBLIC_KEY_FILE = "resource/publickey_server";
usc_RSAKeyPair.PRIVATE_KEY_FILE = "resource/privatekey_server";
//usc_RSAKeyPair.generate();
PublicKey pubKey = usc_RSAKeyPair.readPublicKey();
PrivateKey privKey = usc_RSAKeyPair.readPrivateKey();
System.out.println(pubKey);
System.out.println("================");
System.out.println(privKey);
//~~~~~~Encrypt and Decrypt~~~~~~~
System.out.println("--- --- --- --- --- --- --- --- ---");
String s1 = "Anh yêu em";
System.out.println("User input: " + s1);
byte[] s1_b = s1.getBytes(Charset.forName("UTF-8"));
//byte[] s1_b_encrypted = PAIR1_Encrypt(s1_b, privKey);
byte[] s1_b_encrypted = PAIR2_Encrypt(s1_b, pubKey);
String s1_b_encrypted_out = new String(s1_b_encrypted,"UTF-8");
System.out.println("Encrypted output: " + s1_b_encrypted_out);
//byte[] s1_b_decrypted = PAIR1_Decrypt(s1_b_encrypted, pubKey);
byte[] s1_b_decrypted = PAIR2_Decrypt(s1_b_encrypted, privKey);
String s1_b_decrypted_out = new String(s1_b_decrypted,"UTF-8");
System.out.println("Decrypted output: " + s1_b_decrypted_out);
}
}
| Java |
/*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
package MAIN;
/**
*
* @author anhdung
*/
import DAO.Connect;
import java.security.KeyPairGenerator;
import java.security.KeyPair;
import java.security.PrivateKey;
import java.security.PublicKey;
import java.security.KeyFactory;
import java.security.spec.InvalidKeySpecException;
import java.security.NoSuchAlgorithmException;
import java.security.spec.*;
import java.io.*;
import java.math.BigInteger;
import java.security.Key;
import java.security.SecureRandom;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.crypto.Cipher;
public class GeneratePublicPrivateKeys {
public void generateKeys() {
try {
// Get the public/private key pair
KeyPairGenerator keyGen = KeyPairGenerator.getInstance("RSA");
keyGen.initialize(1024);
KeyPair keyPair = keyGen.genKeyPair();
PrivateKey privateKey = keyPair.getPrivate();
PublicKey publicKey = keyPair.getPublic();
// Get the bytes of the public and private keys
byte[] privateKeyBytes = privateKey.getEncoded();
byte[] publicKeyBytes = publicKey.getEncoded();
//converting byte arrays to strings
String privateString = new String(privateKeyBytes);
String publicString = new String(publicKeyBytes);
KeyFactory fact = KeyFactory.getInstance("RSA");
RSAPublicKeySpec pub = fact.getKeySpec(keyPair.getPublic(),RSAPublicKeySpec.class);
RSAPrivateKeySpec priv = fact.getKeySpec(keyPair.getPrivate(),RSAPrivateKeySpec.class);
saveToFile("public.key", pub.getModulus(), pub.getPublicExponent());
saveToFile("private.key", priv.getModulus(), priv.getPrivateExponent());
} catch (InvalidKeySpecException specException) {
System.out.println("Exception");
System.out.println("Invalid Key Spec Exception");
} catch (NoSuchAlgorithmException e) {
System.out.println("Exception");
System.out.println("No such algorithm: " + "RSA");
}
catch(IOException e) {
System.out.println("IO exception");
}
}
private void saveToFile(String fileName,
BigInteger mod, BigInteger exp) throws IOException {
try (ObjectOutputStream oout = new ObjectOutputStream(
new BufferedOutputStream(new FileOutputStream(fileName)))) {
oout.writeObject(mod);
oout.writeObject(exp);
} catch (Exception e) {
throw new IOException("Unexpected error", e);
}
}
public PublicKey readPubKeyFromFile(String keyFileName) throws IOException {
FileInputStream in = new FileInputStream(keyFileName);
ObjectInputStream oin =
new ObjectInputStream(new BufferedInputStream(in));
try {
BigInteger m = (BigInteger) oin.readObject();
BigInteger e = (BigInteger) oin.readObject();
RSAPublicKeySpec keySpec = new RSAPublicKeySpec(m, e);
KeyFactory fact = KeyFactory.getInstance("RSA");
PublicKey pubKey = fact.generatePublic(keySpec);
return pubKey;
} catch (Exception e) {
throw new RuntimeException("Spurious serialisation error", e);
} finally {
oin.close();
}
}
/* THis function implements the reading of the private key from the keyFileName*/
public PrivateKey readPriKeyFromFile(String keyFileName) throws IOException {
FileInputStream in = new FileInputStream(keyFileName);
ObjectInputStream oin =
new ObjectInputStream(new BufferedInputStream(in));
try {
BigInteger m = (BigInteger) oin.readObject();
BigInteger e = (BigInteger) oin.readObject();
RSAPrivateKeySpec keySpec = new RSAPrivateKeySpec(m, e);
KeyFactory fact = KeyFactory.getInstance("RSA");
PrivateKey priKey = fact.generatePrivate(keySpec);
return priKey;
} catch (Exception e) {
throw new RuntimeException("Spurious serialisation error", e);
} finally {
oin.close();
}
}
public byte[] encrypt(byte[] data) {
try {
PublicKey pubKey = readPubKeyFromFile("public.key");
Cipher cipher = Cipher.getInstance("RSA/ECB/PKCS1Padding");
cipher.init(Cipher.ENCRYPT_MODE, pubKey);
byte[] cipherData = cipher.doFinal(data);
return cipherData;
} catch(Exception e) { e.printStackTrace();return null;}
}
/*Decrypting here*/
public byte[] decrypt(byte[] data) {
try {
PrivateKey priKey = readPriKeyFromFile("private.key");
Cipher dcipher = Cipher.getInstance("RSA/ECB/PKCS1Padding");
dcipher.init(Cipher.DECRYPT_MODE, priKey);
byte[] cipherData = dcipher.doFinal(data);
return cipherData;
} catch(Exception e) { e.printStackTrace();return null;}
}
public static void main(String[] args) throws Exception
{
//tao public va private key
GeneratePublicPrivateKeys gk = new GeneratePublicPrivateKeys();
gk.generateKeys();
PrivateKey privk = gk.readPriKeyFromFile("private.key");
PublicKey pubk = gk.readPubKeyFromFile("public.key");
System.out.println(privk);
System.out.println(pubk);
//Tiep theo, tao Cert tuong ung voi public key boi VeriSign
usc_Certificate.privKey = privk;
usc_Certificate.pubKey = pubk;
usc_Certificate.createCertificate("SERVER.cer");
//Nho VeriSign xem GUEST.cer co hop le
usc_Certificate.validateCertificate("SERVER.cer");
}
}
| Java |
package MAIN;
import java.io.IOException;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import static java.lang.String.format;
import java.security.MessageDigest;
import java.math.BigInteger;
public class Hash_SHA256 {
public static String sha256(String text) throws Exception
{
MessageDigest md = MessageDigest.getInstance("SHA-256");
md.update(text.getBytes("UTF8"), 0, text.length());
String s = convertToHex(md.digest());
//System.out.println(s);
return s;
}
public static String sha1(String text) throws Exception
{
MessageDigest md = MessageDigest.getInstance("SHA-1");
md.update(text.getBytes("UTF8"), 0, text.length());
String s = convertToHex(md.digest());
//System.out.println(s);
return s;
}
private static String convertToHex(byte[] data)
{
StringBuffer buf = new StringBuffer();
for (int i = 0; i < data.length; i++) {
int halfbyte = (data[i] >>> 4) & 0x0F;
int two_halfs = 0;
do {
if ((0 <= halfbyte) && (halfbyte <= 9))
buf.append((char) ('0' + halfbyte));
else
buf.append((char) ('a' + (halfbyte - 10)));
halfbyte = data[i] & 0x0F;
} while (two_halfs++ < 1);
}
return buf.toString();
}
public static void main(String[] args) throws Exception
{
//Test SHA-256
String input = "Anh la Dung";
Hash_SHA256.sha256(input);
}
}
| Java |
/*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
package DAO;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.logging.Level;
import java.util.logging.Logger;
/**
*
* @author Anonymous
*/
public class DatVeDAO {
//Hàm đặt vé
public static boolean ThemDatVe(DTO.DatVeDTO dvdto){
if(VeChuaDat(dvdto.getSoLuongVe(),dvdto.getMaChuyen(),dvdto.getCMND()))
{
int ms=LayMa();
dvdto.setNgayDat(new java.util.Date());//lấy ngày giờ hiện tại
java.sql.Date datet = new java.sql.Date(dvdto.getNgayDat().getTime());//gán vào ngày giờ hiện tại vào datet
try{
//ma hoa so luong ve
String soluongve=MaHoa.MaHoa(dvdto.getSoLuongVe()+"");
//ma hoa cmnd
String CMND=MaHoa.MaHoa(dvdto.getCMND());
//ma hoa thanh toan
String ThanhToan=MaHoa.MaHoa("0");
//ma hoa trangthai
String TrangThai=MaHoa.MaHoa("0");
Connect.connect();
PreparedStatement ps;
//Thực hiện đặt vé vào sql server
ps= Connect.con.prepareCall("insert into T_DatVe(MaDatVe,MaChuyen,SoLuongVe,NgayDat,CMND,DaThanhToan,TrangThai) "
+ "values(?,?,?,?,?,?,?)");
ps.setInt(1, ms);
ps.setInt(2, dvdto.getMaChuyen());
ps.setNString(3, soluongve);
ps.setTimestamp(4,new java.sql.Timestamp(datet.getTime()));
ps.setNString(5, CMND);
ps.setNString(6, ThanhToan);
ps.setNString(7, TrangThai);
if(ps.executeUpdate()!=0){//Nếu thành công
System.out.println("insert successfull");
Connect.con.close();
return true;
}
else{
System.out.println("insert fail");
Connect.con.close();
return false;
}
}
catch (SQLException ex) {
Logger.getLogger(ChuyenXeDAO.class.getName()).log(Level.SEVERE, null, ex);
}
try {
Connect.con.close();
} catch (SQLException ex) {
Logger.getLogger(ChuyenXeDAO.class.getName()).log(Level.SEVERE, null, ex);
}
return false;
}
else
return false;
}
//Hàm tạo mã cho đặt vé
public static int LayMa(){
String sql = "select top 1 MaDatVe from T_DatVe order by MaDatVe desc";
ResultSet kq=Connect.Xlsql(sql);//thực hiện câu truy vấn đưa kết quả vào resultset
int maso = 0;
try{
if(kq.next()){
maso=kq.getInt("MaDatVe");
Connect.con.close();
}
}
catch(SQLException ex){
System.out.println(ex.getMessage());
}
return maso+1;
}
//Hàm lấy số vé chưa đặt
public static boolean VeChuaDat(int sv,int mc,String CMND){
sv=sv+SoVeDD(mc,CMND);
BUS.ChuyenXeBUS cxbus=new BUS.ChuyenXeBUS();
DTO.ChuyenXeDTO cxdto=cxbus.ttChuyenXe(mc);
if(cxdto.getGioiHanVe()>=sv)
{
int vdd=DAO.ChuyenXeDAO.SoVeDD(mc);
int slv=cxdto.getSoLuongVe();
int ct=slv-vdd;
return (ct-sv>=0);
}
else
return false;
}
public static int SoVeDD(int machuyen,String cmND){
int sv=0;
//ma hoa cmnd
String CMND=MaHoa.MaHoa(cmND);
//ma hoa trangthai
String trangthai=MaHoa.MaHoa("0");
String sql = "select * from T_DatVe where MaChuyen="+machuyen +" AND CMND=N'"+CMND+"' AND TrangThai=N'"+trangthai+"'";
ResultSet kq=Connect.Xlsql(sql);//thực hiện câu truy vấn đưa kết quả vào resultset
try {
while(kq.next()){
String sovedat=kq.getNString("SoLuongVe");
int svdat=Integer.parseInt(MaHoa.GiaiMa(sovedat));
sv+=svdat;
}
Connect.con.close();
} catch (SQLException ex) {
Logger.getLogger(ChuyenXeDAO.class.getName()).log(Level.SEVERE, null, ex);
}
return sv;
}
//Hàm lấy kiểm tra hết hạn thanh toán thì thiết lập TrangThai=1 : hết hạn
public static boolean ktHanDatVe(){
java.util.Date tam=new java.util.Date();
java.sql.Date datet = new java.sql.Date(tam.getTime()-(1000*60*60*24));
//ma hoa dathanhtoan
String dathanhtoan=MaHoa.MaHoa("0");
//ma hoa trangthai
String trangthai=MaHoa.MaHoa("0");
String sql = "select * from T_DatVe where DaThanhToan=N'"+dathanhtoan+"' AND TrangThai=N'"+trangthai+"' AND NgayDat<'"+new java.sql.Timestamp(datet.getTime())+"'";
ResultSet kq=Connect.Xlsql(sql);//thực hiện câu truy vấn đưa kết quả vào resultset
try {
while(kq.next()){
CnDatVe(kq.getInt("MaDatVe"));
}
Connect.con.close();
} catch (SQLException ex) {
Logger.getLogger(ChuyenXeDAO.class.getName()).log(Level.SEVERE, null, ex);
return false;
}
return true;
}
//Hàm cập nhật hết hạn thanh toán đặt vé
public static boolean CnDatVe(int MaDV) {
//ma hoa trangthai
String trangthai=MaHoa.MaHoa("1");
try{
Connect.connect();//mở kết nối sql server
//Cập nhật thông tin chuyến xe
PreparedStatement ps;
ps= Connect.con.prepareCall("update T_DatVe set TrangThai=? where MaDatVe=?");
ps.setInt(2, MaDV);
ps.setNString(1, trangthai);
if(ps.executeUpdate()!=0){//Nếu cập nhật thành công
System.out.println("update successfull");
Connect.con.close();//đóng kết nối sql server
return true;
}
else{//ngược lại nếu thất bại
System.out.println("update fail");
Connect.con.close();//đóng kết nối sql server
return false;
}
}
catch (SQLException ex) {
Logger.getLogger(DatVeDAO.class.getName()).log(Level.SEVERE, null, ex);
}
try {
Connect.con.close();//đóng kết nối sql server
} catch (SQLException ex) {
Logger.getLogger(DatVeDAO.class.getName()).log(Level.SEVERE, null, ex);
}
return false;
}
} | Java |
/*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
package DAO;
import java.io.IOException;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.logging.Level;
import java.util.logging.Logger;
/**
*
* @author Anonymous
*/
public class ServerControl extends Thread{
private int portS;//port của server
public ServerControl(int port) {//gán port
super("ServerControl");
this.portS = port;
}
@Override
public void run()
{
//Lắng nghe client, nếu có kết nối đến thì tạo 1 Serverthread mới để trao đổi với client đó
//sau đó quay lại tiếp tục lắng nghe
while(true){//chạy liên tục
try (ServerSocket serverSocket = new ServerSocket(portS)) {
Socket cl=serverSocket.accept();//Lắng nghe, chỉ khi có client kết nối mới chuyển xuống xử lý hàm tiếp theo
//tạo 1 serverthread để trao đổi dữ liệu với client
ServerThread t1=new ServerThread(cl);
t1.start();
} catch (IOException ex) {
Logger.getLogger(Connect.class.getName()).log(Level.SEVERE, null, ex);
}
}
}
} | Java |
/*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
package DAO;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;
import java.util.logging.Level;
import java.util.logging.Logger;
/**
*
* @author Anonymous
*/
public class ChuyenXeDAO {
//Hàm thêm 1 chuyến xe
public static boolean ThemChuyenXe(DTO.ChuyenXeDTO chuyenxedto){
int ms=LayMa();//tạo mã chuyến xe mới nhất
//gán thời gian chạy vào datet
java.sql.Date datet = new java.sql.Date(chuyenxedto.getThoiGianChay().getTime());
try{
//ma hoa ga bat dau
String gabd=MaHoa.MaHoa(chuyenxedto.getGaBatDau());
//ma hoa ga ket thuc
String gakt=MaHoa.MaHoa(chuyenxedto.getGaKetThuc());
//ma hoa so luong ve
String soluongve=MaHoa.MaHoa(chuyenxedto.getSoLuongVe()+"");
//ma hoa gioi han ve
String gioihanve=MaHoa.MaHoa(chuyenxedto.getGioiHanVe()+"");
//ma hoa gia tien
String giatien=MaHoa.MaHoa(chuyenxedto.getGiaTien()+"");
Connect.connect();//mở kết nối với sql server
//thực hiện thêm chuyến xe
PreparedStatement ps;
ps= Connect.con.prepareCall("insert into T_ChuyenXe(MaChuyen,GaBatDau,GaKetThuc,ThoiGianChay,SoLuongVe,SoVeDuocMua,GiaTien) "
+ "values(?,?,?,?,?,?,?)");
ps.setInt(1, ms);
ps.setNString(2, gabd);
ps.setNString(3, gakt);
ps.setTimestamp(4,new java.sql.Timestamp(datet.getTime()));
ps.setNString(5, soluongve);
ps.setNString(6, gioihanve);
ps.setNString(7, giatien);
if(ps.executeUpdate()!=0){//Nếu thêm thành công
System.out.println("insert successfull");
Connect.con.close();//đóng kết nối sql server
return true;
}
else{//Ngược lại nếu thất bại
System.out.println("insert fail");
Connect.con.close();//đóng kết nối sql server
return false;
}
}
catch (SQLException ex) {
Logger.getLogger(ChuyenXeDAO.class.getName()).log(Level.SEVERE, null, ex);
}
try {
Connect.con.close();//đóng kết nối sql server
} catch (SQLException ex) {
Logger.getLogger(ChuyenXeDAO.class.getName()).log(Level.SEVERE, null, ex);
}
return false;
}
//Hàm cập nhật chuyến xe
public static boolean CnChuyenXe(DTO.ChuyenXeDTO chuyenxedto) {
//gán thời gian chạy vào datet
java.sql.Date datet = new java.sql.Date(chuyenxedto.getThoiGianChay().getTime());
//ma hoa ga bat dau
String gabd=MaHoa.MaHoa(chuyenxedto.getGaBatDau());
//ma hoa ga ket thuc
String gakt=MaHoa.MaHoa(chuyenxedto.getGaKetThuc());
//ma hoa so luong ve
String soluongve=MaHoa.MaHoa(chuyenxedto.getSoLuongVe()+"");
//ma hoa gioi han ve
String gioihanve=MaHoa.MaHoa(chuyenxedto.getGioiHanVe()+"");
//ma hoa gia tien
String giatien=MaHoa.MaHoa(chuyenxedto.getGiaTien()+"");
try{
Connect.connect();//mở kết nối sql server
//Cập nhật thông tin chuyến xe
PreparedStatement ps;
ps= Connect.con.prepareCall("update T_ChuyenXe set GaBatDau=?,GaKetThuc=?,ThoiGianChay=?,SoLuongVe=?,SoVeDuocMua=?,GiaTien=? where MaChuyen=?");
ps.setInt(7, chuyenxedto.getMaChuyen());
ps.setNString(1, gabd);
ps.setNString(2, gakt);
ps.setTimestamp(3,new java.sql.Timestamp(datet.getTime()));
ps.setNString(4, soluongve );
ps.setNString(5, gioihanve);
ps.setNString(6, giatien);
if(ps.executeUpdate()!=0){//Nếu cập nhật thành công
System.out.println("update successfull");
Connect.con.close();//đóng kết nối sql server
return true;
}
else{//ngược lại nếu thất bại
System.out.println("update fail");
Connect.con.close();//đóng kết nối sql server
return false;
}
}
catch (SQLException ex) {
Logger.getLogger(ChuyenXeDAO.class.getName()).log(Level.SEVERE, null, ex);
}
try {
Connect.con.close();//đóng kết nối sql server
} catch (SQLException ex) {
Logger.getLogger(ChuyenXeDAO.class.getName()).log(Level.SEVERE, null, ex);
}
return false;
}
//Hàm tạo mã cho chuyến xe
public static int LayMa(){
String sql = "select top 1 MaChuyen from T_ChuyenXe order by MaChuyen desc";
ResultSet kq=Connect.Xlsql(sql);//thực hiện câu truy vấn đưa kết quả vào resultset
int maso = 0;
try{
if(kq.next()){
maso=kq.getInt("MaChuyen");
Connect.con.close();
}
}
catch(SQLException ex){
System.out.println(ex.getMessage());
}
return maso+1;
}
//Hàm lấy danh sách chuyến xe
public static List<DTO.ChuyenXeDTO> dsChuyenXe(){
List<DTO.ChuyenXeDTO> Lchuyenxedto= new ArrayList<DTO.ChuyenXeDTO>();
DTO.ChuyenXeDTO chuyenxedto;
String sql = "select * from T_ChuyenXe order by ThoiGianChay DESC";
ResultSet kq=Connect.Xlsql(sql);//thực hiện câu truy vấn đưa kết quả vào resultset
try {
while(kq.next()){
chuyenxedto=new DTO.ChuyenXeDTO();
chuyenxedto.setMaChuyen(kq.getInt("MaChuyen"));
//giai ma ga bat dau
String gabd=kq.getNString("GaBatDau");
chuyenxedto.setGatBatDau(MaHoa.GiaiMa(gabd));
//giai ma ga ket thuc
String gakt=kq.getNString("GaKetThuc");
chuyenxedto.setGaKetThuc(MaHoa.GiaiMa(gakt));
chuyenxedto.setThoiGianChay(kq.getTimestamp("ThoiGianChay"));
//giai ma so luong ve
String soluongve=kq.getNString("SoLuongVe");
int slv=Integer.parseInt(MaHoa.GiaiMa(soluongve));
chuyenxedto.setSoLuongVe(slv);
//giai ma so luong ve duoc mua
String sovedat=kq.getNString("SoVeDuocMua");
int svdat=Integer.parseInt(MaHoa.GiaiMa(sovedat));
chuyenxedto.setGioiHanVe(svdat);
chuyenxedto.setVeDaDat(SoVeDD(chuyenxedto.getMaChuyen()));
//giai ma gia tien
String giatien=kq.getNString("GiaTien");
int gt=Integer.parseInt(MaHoa.GiaiMa(giatien));
chuyenxedto.setGiaTien(gt);
Lchuyenxedto.add(chuyenxedto);
}
Connect.con.close();
} catch (SQLException ex) {
Logger.getLogger(ChuyenXeDAO.class.getName()).log(Level.SEVERE, null, ex);
}
return Lchuyenxedto;
}
//Hàm lấy danh sách chuyến xe chưa chạy
public static List<DTO.ChuyenXeDTO> dsChuyenXecl(){
List<DTO.ChuyenXeDTO> Lchuyenxedto= new ArrayList<DTO.ChuyenXeDTO>();
DTO.ChuyenXeDTO chuyenxedto;
java.util.Date tam=new java.util.Date();
java.sql.Date datet = new java.sql.Date(tam.getTime());
String sql = "select * from T_ChuyenXe where ThoiGianChay >'"+new java.sql.Timestamp(datet.getTime())+"' order by ThoiGianChay DESC";
ResultSet kq=Connect.Xlsql(sql);//thực hiện câu truy vấn đưa kết quả vào resultset
try {
while(kq.next()){
chuyenxedto=new DTO.ChuyenXeDTO();
chuyenxedto.setMaChuyen(kq.getInt("MaChuyen"));
//giai ma ga bat dau
String gabd=kq.getNString("GaBatDau");
chuyenxedto.setGatBatDau(MaHoa.GiaiMa(gabd));
//giai ma ga ket thuc
String gakt=kq.getNString("GaKetThuc");
chuyenxedto.setGaKetThuc(MaHoa.GiaiMa(gakt));
chuyenxedto.setThoiGianChay(kq.getTimestamp("ThoiGianChay"));
//giai ma so luong ve
String soluongve=kq.getNString("SoLuongVe");
int slv=Integer.parseInt(MaHoa.GiaiMa(soluongve));
chuyenxedto.setSoLuongVe(slv);
//giai ma so luong ve duoc mua
String sovedat=kq.getNString("SoVeDuocMua");
int svdat=Integer.parseInt(MaHoa.GiaiMa(sovedat));
chuyenxedto.setGioiHanVe(svdat);
chuyenxedto.setVeDaDat(SoVeDD(chuyenxedto.getMaChuyen()));
//giai ma gia tien
String giatien=kq.getNString("GiaTien");
int gt=Integer.parseInt(MaHoa.GiaiMa(giatien));
chuyenxedto.setGiaTien(gt);
Lchuyenxedto.add(chuyenxedto);
}
Connect.con.close();
} catch (SQLException ex) {
Logger.getLogger(ChuyenXeDAO.class.getName()).log(Level.SEVERE, null, ex);
}
return Lchuyenxedto;
}
//Hàm lấy thông tin 1 chuyến xe với đầu vào là mã chuyến
public static DTO.ChuyenXeDTO ttChuyenXe(int machuyen) {
DTO.ChuyenXeDTO chuyenxedto=new DTO.ChuyenXeDTO();
String sql = "select * from T_ChuyenXe where MaChuyen="+machuyen+" order by ThoiGianChay DESC";
ResultSet kq=Connect.Xlsql(sql);//thực hiện câu truy vấn đưa kết quả vào resultset
try {
while(kq.next()){
chuyenxedto.setMaChuyen(kq.getInt("MaChuyen"));
//giai ma ga bat dau
String gabd=kq.getNString("GaBatDau");
chuyenxedto.setGatBatDau(MaHoa.GiaiMa(gabd));
//giai ma ga ket thuc
String gakt=kq.getNString("GaKetThuc");
chuyenxedto.setGaKetThuc(MaHoa.GiaiMa(gakt));
chuyenxedto.setThoiGianChay(kq.getTimestamp("ThoiGianChay"));
//giai ma so luong ve
String soluongve=kq.getNString("SoLuongVe");
int slv=Integer.parseInt(MaHoa.GiaiMa(soluongve));
chuyenxedto.setSoLuongVe(slv);
//giai ma so luong ve duoc mua
String sovedat=kq.getNString("SoVeDuocMua");
int svdat=Integer.parseInt(MaHoa.GiaiMa(sovedat));
chuyenxedto.setGioiHanVe(svdat);
chuyenxedto.setVeDaDat(SoVeDD(chuyenxedto.getMaChuyen()));
//giai ma gia tien
String giatien=kq.getNString("GiaTien");
int gt=Integer.parseInt(MaHoa.GiaiMa(giatien));
chuyenxedto.setGiaTien(gt);
}
Connect.con.close();
} catch (SQLException ex) {
Logger.getLogger(ChuyenXeDAO.class.getName()).log(Level.SEVERE, null, ex);
}
return chuyenxedto;
}
//Hàm lấy số vé đã đặt cho chuyến xe có đầu vào là mã chuyến
public static int SoVeDD(int machuyen){
int sv=0;
//ma hoa trangthai
String trangthai=MaHoa.MaHoa("0");
String sql = "select * from T_DatVe where MaChuyen="+machuyen+" AND TrangThai=N'"+trangthai+"'";
ResultSet kq=Connect.Xlsql(sql);//thực hiện câu truy vấn đưa kết quả vào resultset
try {
while(kq.next()){
String sovedat=kq.getNString("SoLuongVe");
int svdat=Integer.parseInt(MaHoa.GiaiMa(sovedat));
sv+=svdat;
}
Connect.con.close();
} catch (SQLException ex) {
Logger.getLogger(ChuyenXeDAO.class.getName()).log(Level.SEVERE, null, ex);
}
return sv;
}
//Hàm xóa chuyến xe
public static boolean XoaChuyenXe(int machuyen){
String caulenh="delete T_ChuyenXe where MaChuyen=" + machuyen;
return Connect.Xlsql2(caulenh);//thực hiện câu sql và trả về thành công hay thất bại
}
}
| Java |
package DAO;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.logging.Level;
import java.util.logging.Logger;
import java.util.prefs.Preferences;
/*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
/**
*
* @author Anonymous
*/
public class Connect {
public static java.sql.Connection con;
protected static final String PREF_TENSV = "TENSV";
protected static final String PREF_TENCSDL = "TENCSDL";
protected static final String PREF_TENDN = "TENDN";
protected static final String PREF_MK = "MK";
protected static String TenSV ;
protected static String TenCSDL ;
protected static String TenDN ;
protected static String MK ;
protected static int portS ;
public static boolean connectT(String tTenSV,String tTenCSDL,String tTenDN,String tMK)
{
try
{
Class.forName("com.microsoft.sqlserver.jdbc.SQLServerDriver");
String connectionUrl = "jdbc:sqlserver://"+tTenSV+";databaseName="
+tTenCSDL+";user="+tTenDN+";password="+tMK;
con = DriverManager.getConnection(connectionUrl);
if (con != null)
{
Preferences prefs = Preferences.userNodeForPackage(Connect.class);
prefs.put(PREF_TENSV, tTenSV);
prefs.put(PREF_TENCSDL,tTenCSDL);
prefs.put(PREF_TENDN,tTenDN);
prefs.put(PREF_MK,tMK);
con.close();
return true;
}
else{
return false;
}
}
catch (ClassNotFoundException ex)
{
System.out.println(ex.getMessage());
} catch (SQLException ex) {
Logger.getLogger(Connect.class.getName()).log(Level.SEVERE, null, ex);
}
return false;
}
public static boolean connect()
{
Preferences prefs = Preferences.userNodeForPackage(Connect.class);
// prefs.put(PREF_NAME, newValue);
//Lay thong tin server sql tu pref
TenSV = prefs.get(PREF_TENSV, "localhost");
TenCSDL = prefs.get(PREF_TENCSDL, "db_HTBVTQM");
TenDN = prefs.get(PREF_TENDN, "");
MK = prefs.get(PREF_MK, "");
try
{
Class.forName("com.microsoft.sqlserver.jdbc.SQLServerDriver");
String connectionUrl = "jdbc:sqlserver://"+TenSV+";databaseName="+TenCSDL+";user="
+TenDN+ ";password="+MK;
con = DriverManager.getConnection(connectionUrl);
if (con != null)
{
return true;
}
else{
return false;
}
}
catch (ClassNotFoundException ex)
{
System.out.println(ex.getMessage());
} catch (SQLException ex) {
Logger.getLogger(Connect.class.getName()).log(Level.SEVERE, null, ex);
}
return false;
}
public static boolean ktKetNoi()
{
Preferences prefs = Preferences.userNodeForPackage(Connect.class);
//Lay thong tin server sql tu pref
// prefs.put(PREF_TENSV, "");
// prefs.put(PREF_TENCSDL, "");
// prefs.put(PREF_TENDN, "");
// prefs.put(PREF_MK,"");
TenSV = prefs.get(PREF_TENSV, "localhost");
TenCSDL = prefs.get(PREF_TENCSDL, "db_HTBVTQM");
TenDN = prefs.get(PREF_TENDN, "");
MK = prefs.get(PREF_MK, "");
try
{
Class.forName("com.microsoft.sqlserver.jdbc.SQLServerDriver");
String connectionUrl = "jdbc:sqlserver://"+TenSV+";databaseName="+TenCSDL+";user="
+TenDN+ ";password="+MK;
con = DriverManager.getConnection(connectionUrl);
if (con != null)
{
con.close();
return true;
}
else{
return false;
}
}
catch (ClassNotFoundException ex)
{
System.out.println(ex.getMessage());
} catch (SQLException ex) {
Logger.getLogger(Connect.class.getName()).log(Level.SEVERE, null, ex);
}
return false;
}
public static ResultSet Xlsql(String sql)
{
Preferences prefs = Preferences.userNodeForPackage(Connect.class);
// prefs.put(PREF_NAME, newValue);
//Lay thong tin server sql tu pref
TenSV = prefs.get(PREF_TENSV, "localhost");
TenCSDL = prefs.get(PREF_TENCSDL, "db_HTBVTQM");
TenDN = prefs.get(PREF_TENDN, "");
MK = prefs.get(PREF_MK, "");
ResultSet rs=null;
try{
Class.forName("com.microsoft.sqlserver.jdbc.SQLServerDriver");
String connectionUrl = "jdbc:sqlserver://"+TenSV+";databaseName="+TenCSDL+";user="
+TenDN+ ";password="+MK;
con = DriverManager.getConnection(connectionUrl);
if(con!=null){
Statement st = con.createStatement();
rs = st.executeQuery(sql);
}
}
catch(SQLException ex)
{
System.out.println(ex.getMessage());
} catch (ClassNotFoundException ex) {
Logger.getLogger(Connect.class.getName()).log(Level.SEVERE, null, ex);
}
return rs;
}
public static boolean Xlsql2(String sql)
{
Preferences prefs = Preferences.userNodeForPackage(Connect.class);
// prefs.put(PREF_NAME, newValue);
//Lay thong tin server sql tu pref
TenSV = prefs.get(PREF_TENSV, "localhost");
TenCSDL = prefs.get(PREF_TENCSDL, "db_HTBVTQM");
TenDN = prefs.get(PREF_TENDN, "");
MK = prefs.get(PREF_MK, "");
try
{
Class.forName("com.microsoft.sqlserver.jdbc.SQLServerDriver");
String connectionUrl = "jdbc:sqlserver://"+TenSV+";databaseName="+TenCSDL+";user="
+TenDN+ ";password="+MK;
con = DriverManager.getConnection(connectionUrl);
if(con!=null){
Statement st = con.createStatement();
if(st.executeUpdate(sql)==0){
return false;
}
con.close();
return true;
}
}
catch (SQLException ex)
{
System.out.println(ex.getMessage());
} catch (ClassNotFoundException ex) {
Logger.getLogger(Connect.class.getName()).log(Level.SEVERE, null, ex);
}
return false;
}
public static void ListenServer()
{
portS= 1234;
ServerControl t1=new ServerControl(portS);
t1.start();
}
}
| Java |
/*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
package DAO;
import DTO.PacketDTO;
import MAIN.GeneratePublicPrivateKeys;
import MAIN.Hash_SHA256;
import MAIN.usc_Certificate;
import MAIN.usc_RSAKeyPair;
import static MAIN.usc_sessionkey_mac.Decrypt;
import static MAIN.usc_sessionkey_mac.Encrypt;
import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.io.OutputStream;
import java.io.UnsupportedEncodingException;
import java.math.BigInteger;
import java.net.Socket;
import java.nio.charset.Charset;
import java.security.InvalidKeyException;
import java.security.Key;
import java.security.KeyFactory;
import java.security.KeyPair;
import java.security.KeyPairGenerator;
import java.security.NoSuchAlgorithmException;
import java.security.PrivateKey;
import java.security.PublicKey;
import java.security.cert.Certificate;
import java.security.cert.CertificateException;
import java.security.cert.CertificateFactory;
import java.security.cert.X509Certificate;
import java.security.spec.InvalidKeySpecException;
import java.security.spec.KeySpec;
import java.security.spec.RSAPrivateKeySpec;
import java.security.spec.RSAPublicKeySpec;
import java.util.ArrayList;
import java.util.List;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.crypto.BadPaddingException;
import javax.crypto.Cipher;
import javax.crypto.IllegalBlockSizeException;
import javax.crypto.NoSuchPaddingException;
import javax.crypto.SecretKey;
import javax.crypto.spec.SecretKeySpec;
/**
*
* @author Anonymous
*/
public class ServerThread extends Thread{
private SecretKey key;//ko su dung
private static String secret_key = "default";
public static boolean use_secret_key = false;//=true, after Certificate period.
private Socket clientSocket;
public ServerThread(Socket cl) {//gán socket
super("ServerThread");
clientSocket = cl;
}
@Override
public void run()
{
try {
//Đầu tiên gán giá trị lấy được vào gói tin nhận
DTO.PacketDTO pkdtor=new DTO.PacketDTO();
pkdtor=(DTO.PacketDTO)receiveData(clientSocket);//lấy giá trị từ client
if(pkdtor==null)
{
return;
}
if(pkdtor.getCommand()==1)//nếu lệnh là 1 : lấy danh sách chuyến xe
{
//Lấy danh sách chuyến xe chưa đi từ sql server vào biến Lcxdto
BUS.ChuyenXeBUS cxbus=new BUS.ChuyenXeBUS();
List<DTO.ChuyenXeDTO> Lcxdto= new ArrayList<DTO.ChuyenXeDTO>();
Lcxdto=cxbus.dsChuyenXecl();
//Đưa dữ liệu danh sách chuyến xe vào gói tin gửi pkdtos
DTO.PacketDTO pkdtos=new DTO.PacketDTO();
pkdtos.setData(Lcxdto);//gán giá trị
if(Lcxdto!=null)//Nếu danh sách không trống thì gán flag là true
pkdtos.setFlag(true);
else
//ngược lại gán false
pkdtos.setFlag(false);
sendData(clientSocket,pkdtos);//gửi gói tin cho client
}
if(pkdtor.getCommand()==2)//nếu lệnh là 2 : đặt vé
{
BUS.DatVeBUS dvbus=new BUS.DatVeBUS();
DTO.DatVeDTO dvdto= new DTO.DatVeDTO();
dvdto=(DTO.DatVeDTO)pkdtor.getData();//gán giá trị đặt vé đã nhận từ pkdtor vào biến dvdto
//Đưa gói tin xác nhận thành công hay thất bại cho client
DTO.PacketDTO pkdtos=new DTO.PacketDTO();
pkdtos.setFlag(dvbus.ThemDatVe(dvdto));//tiến hành đặt vé và gán flag vào gói tin
sendData(clientSocket,pkdtos);//gửi gói tin cho client
}
if(pkdtor.getCommand()==101)//nếu lệnh là 101: nhan GUEST.cer
{
//Nhan GUEST.cer
Certificate guest_cer = (Certificate)pkdtor.getData();
System.out.println("== == == == == == == == == ==");
System.out.println("Client has sent you GUEST.cer");
boolean f1 = MAIN.usc_Certificate.validateCertificate(guest_cer);
if(f1 == true)
{
System.out.println("You have had GUEST.cer. It is VALID.");
//Luu GUEST.cer
FileOutputStream os = new FileOutputStream("GUEST.cer");
os.write(guest_cer.getEncoded());
os.close();
//Gui SERVER.cer
//**Tao public va private key
GeneratePublicPrivateKeys gk = new GeneratePublicPrivateKeys();
gk.generateKeys();
PrivateKey privk = gk.readPriKeyFromFile("private.key");
PublicKey pubk = gk.readPubKeyFromFile("public.key");
//System.out.println(privk);
//System.out.println(pubk);
//**Tao Cert tuong ung voi public key
usc_Certificate.privKey = privk;
usc_Certificate.pubKey = pubk;
usc_Certificate.createCertificate("SERVER.cer");
DTO.PacketDTO pkdtos=new DTO.PacketDTO();
pkdtos.setFlag(true);
FileInputStream is = new FileInputStream(new File("SERVER.cer"));
CertificateFactory cf = CertificateFactory.getInstance("X.509");
Certificate server_cer = cf.generateCertificate(is);
pkdtos.setData(server_cer);
sendData(clientSocket,pkdtos);
}
else
{
System.out.println("You have had GUEST.cer. It is INVALID.");
//Gui canh bao toi Client va ngat ket noi.
DTO.PacketDTO pkdtos=new DTO.PacketDTO();
pkdtos.setFlag(false);
pkdtos.setData("Invalid Certificate.");
sendData(clientSocket,pkdtos);
}
}
if(pkdtor.getCommand()==102)//nếu lệnh là 102: Client từ chối SERVER.cer va ngat ket noi
{
System.out.println("Client says: " + pkdtor.getData().toString());
//đóng kết nối: thoat ra khoi if.
clientSocket.close();
return;
}
if(pkdtor.getCommand()==103)//lenh 103: Kiem Tra Public-Private key, yeu cau Secret-key
{
//Kiem tra Public-Private Key cua Client
System.out.println("== == == == == == == == == ==");
FileInputStream is = new FileInputStream(new File("GUEST.cer"));
CertificateFactory cf = CertificateFactory.getInstance("X.509");
Certificate client_cer = cf.generateCertificate(is);
PublicKey client_pubkey = client_cer.getPublicKey();
//System.out.println("Client's Public key: " + client_pubkey);
//Nhan goi tin tu Client.
byte[][] data_1_C = (byte[][])pkdtor.getData();
String plaintext_C = new String(data_1_C[0],"UTF-8");
System.out.println("Client has sent a plaintext: " + plaintext_C);
//******
byte[] encrypted_digest_1 = data_1_C[1];
//*****
byte[] decrypted_digest_1 = usc_RSAKeyPair.PAIR2_Decrypt(encrypted_digest_1, usc_Certificate.privKey);
System.out.println("-->Use Server PRIVATE KEY to decrypt.");
String digest_1 = new String(decrypted_digest_1,"UTF-8");
System.out.println("With SHA-256 Digest: " + digest_1);
System.out.print("Comparing SHA-256 Digest: ");
String hash_result = MAIN.Hash_SHA256.sha256(plaintext_C);
if(hash_result.equals(digest_1)==false)
{
System.out.println("NOT CORRECT! That is not my guest. Disconect...");
pkdtor = new PacketDTO();
pkdtor.setFlag(false);
pkdtor.setData("Client Key Pair is not valid. Disconect!");
sendData(clientSocket,pkdtor);
clientSocket.close();
return;
}
System.out.println("CORRECT! That is my GUEST.");
System.out.println("-----");
//Kiem tra Public-Private Key cua Server, gui Secret-key cho Client
String plaintext_S = MAIN.usc_sessionkey_mac.randomString(50);
secret_key = MAIN.usc_sessionkey_mac.xorMessage(plaintext_S, plaintext_C);
secret_key = Hash_SHA256.sha256(secret_key);
String encrypted_secret_key = MAIN.usc_sessionkey_mac.xorMessage(secret_key, plaintext_C);
plaintext_S = encrypted_secret_key;
byte[] encrypted_plaintext_S = usc_RSAKeyPair.PAIR2_Encrypt(
plaintext_S.getBytes(Charset.forName("UTF-8")), client_pubkey);
String digest_2 = Hash_SHA256.sha256(plaintext_S);
byte[] encrypted_digest_2 = usc_RSAKeyPair.PAIR2_Encrypt(
digest_2.getBytes(Charset.forName("UTF-8")), client_pubkey);
byte[][] data_2_S = new byte[2][];
//data_2_S[0] = plaintext_S.getBytes(Charset.forName("UTF-8"));
data_2_S[0] = encrypted_plaintext_S;
data_2_S[1] = encrypted_digest_2;
pkdtor = new PacketDTO();
pkdtor.setFlag(true);
pkdtor.setData((Object)data_2_S);
sendData(clientSocket, pkdtor);
System.out.println("You have sent to Client a plaintext: " + plaintext_S);
System.out.println("And it's SHA-256 digest: " + digest_2);
System.out.println("-->Use Client PUBLIC KEY to encrypt.");
System.out.println("SECRET KEY: " + secret_key);
}
if(pkdtor.getCommand()==104)//ket qua kt Server public key ben Client khong thanh cong.
{
System.out.println("Client says: " + pkdtor.getData().toString());
//đóng kết nối: thoat ra khoi if.
clientSocket.close();
return;
}
if(pkdtor.getCommand()==105)//phan hoi da nhan Secret key tu Client.
{
System.out.println();
System.out.println("-> Secret Key was validated by CLient.");
System.out.println("Now. use_secret_key is ON.");
use_secret_key = true;
System.out.println("== == == == == == == == == ==");
}
if(pkdtor.getCommand()==106)//Test Secret-key: Command 106
{
Object obj = pkdtor.getData();
String s3 = obj.toString();
System.out.println("Receive: " + s3);
String s4 = "Yes. I give praise to Father.";
pkdtor.setData(s4);
sendData(clientSocket, pkdtor);
System.out.println("Send: " + s4);
}
clientSocket.close();//đóng kết nối
} catch (IOException ex) {
Logger.getLogger(Connect.class.getName()).log(Level.SEVERE, null, ex);
} catch (CertificateException ex) {
Logger.getLogger(ServerThread.class.getName()).log(Level.SEVERE, null, ex);
} catch (Exception ex) {
Logger.getLogger(ServerThread.class.getName()).log(Level.SEVERE, null, ex);
}
}
//Hàm chuyển dữ liệu đến cient đầu vào là socket client và gói tin pkdto
public static boolean sendData(Socket clientSocket,DTO.PacketDTO pkdto)
{
try {
String secret_key2 = "default";
if(use_secret_key==true)
{
secret_key2 = secret_key;
}
byte[] encrypt = Encrypt(secret_key2, pkdto);
//System.out.println("sendData>secret_key: " + secret_key2);
OutputStream os = clientSocket.getOutputStream();
ObjectOutputStream oos = new ObjectOutputStream(os);
oos.writeObject(encrypt);
/*
OutputStream os = clientSocket.getOutputStream();
ObjectOutputStream oos = new ObjectOutputStream(os);
oos.writeObject(pkdto);
*/
return true;
} catch (IOException ex) {
Logger.getLogger(Connect.class.getName()).log(Level.SEVERE, null, ex);
} catch (Exception ex) {
Logger.getLogger(ServerThread.class.getName()).log(Level.SEVERE, null, ex);
}
return false;
}
//Hàm nhận dữ liệu từ client đầu ra là pkdto tùy vào bên client, mặc định là DTO.PacketDTO
public static Object receiveData(Socket clientSocket)
{
try {
InputStream is = clientSocket.getInputStream();
ObjectInputStream ois = new ObjectInputStream(is);
Object obj = ois.readObject();
byte[] encrypt = (byte[])obj;
Object pkdto = Decrypt(secret_key, encrypt);
/*
InputStream is = clientSocket.getInputStream();
ObjectInputStream ois = new ObjectInputStream(is);
Object pkdto = ois.readObject();
*/
return pkdto;
} catch (IOException | ClassNotFoundException ex) {
//Logger.getLogger(Connect.class.getName()).log(Level.SEVERE, null, ex);
} catch (Exception ex) {
//Logger.getLogger(ServerThread.class.getName()).log(Level.SEVERE, null, ex);
}
return null;
}
public void generateKeys() {
try {
// Get the public/private key pair
KeyPairGenerator keyGen = KeyPairGenerator.getInstance("RSA");
keyGen.initialize(1024);
KeyPair keyPair = keyGen.genKeyPair();
PrivateKey privateKey = keyPair.getPrivate();
PublicKey publicKey = keyPair.getPublic();
// Get the bytes of the public and private keys
byte[] privateKeyBytes = privateKey.getEncoded();
byte[] publicKeyBytes = publicKey.getEncoded();
//converting byte arrays to strings
String privateString = new String(privateKeyBytes);
String publicString = new String(publicKeyBytes);
KeyFactory fact = KeyFactory.getInstance("RSA");
RSAPublicKeySpec pub = fact.getKeySpec(keyPair.getPublic(),RSAPublicKeySpec.class);
RSAPrivateKeySpec priv = fact.getKeySpec(keyPair.getPrivate(),RSAPrivateKeySpec.class);
saveToFile("public.key", pub.getModulus(), pub.getPublicExponent());
saveToFile("private.key", priv.getModulus(), priv.getPrivateExponent());
} catch (InvalidKeySpecException specException) {
System.out.println("Exception");
System.out.println("Invalid Key Spec Exception");
} catch (NoSuchAlgorithmException e) {
System.out.println("Exception");
System.out.println("No such algorithm: " + "RSA");
}
catch(IOException e) {
System.out.println("IO exception");
}
}
private static void saveToFile(String fileName, BigInteger mod, BigInteger exp) throws IOException {
try (ObjectOutputStream oout = new ObjectOutputStream(
new BufferedOutputStream(new FileOutputStream(fileName)))) {
oout.writeObject(mod);
oout.writeObject(exp);
} catch (Exception e) {
throw new IOException("Unexpected error", e);
}
}
public boolean receiveExKey(Object data) {
//Object data = receiveData(clientSocket);
byte[] command = new byte[4];
try {
ObjectInputStream objectInput = new ObjectInputStream((ObjectInputStream) data);
objectInput.read(command);
BigInteger m = (BigInteger) objectInput.readObject();
BigInteger e = (BigInteger) objectInput.readObject();
RSAPublicKeySpec keySpec = new RSAPublicKeySpec(m, e);
KeyFactory fact = KeyFactory.getInstance("RSA");
PublicKey pubKey = fact.generatePublic(keySpec);
saveToFile("session.key", m, e);
return true;
} catch (IOException ex) {
Logger.getLogger(GeneratePublicPrivateKeys.class.getName()).log(Level.SEVERE, null, ex);
} catch (ClassNotFoundException ex) {
Logger.getLogger(GeneratePublicPrivateKeys.class.getName()).log(Level.SEVERE, null, ex);
} catch (NoSuchAlgorithmException ex) {
Logger.getLogger(GeneratePublicPrivateKeys.class.getName()).log(Level.SEVERE, null, ex);
} catch (InvalidKeySpecException ex) {
Logger.getLogger(GeneratePublicPrivateKeys.class.getName()).log(Level.SEVERE, null, ex);
}
return false;
}
private PublicKey readPubKeyFromFile(String keyFileName) throws IOException {
FileInputStream in = new FileInputStream(keyFileName);
ObjectInputStream oin =
new ObjectInputStream(new BufferedInputStream(in));
try {
BigInteger m = (BigInteger) oin.readObject();
BigInteger e = (BigInteger) oin.readObject();
RSAPublicKeySpec keySpec = new RSAPublicKeySpec(m, e);
KeyFactory fact = KeyFactory.getInstance("RSA");
PublicKey pubKey = fact.generatePublic(keySpec);
return pubKey;
} catch (Exception e) {
throw new RuntimeException("Spurious serialisation error", e);
} finally {
oin.close();
}
}
public boolean sendPubKey() {
try {
PublicKey pubKey = readPubKeyFromFile("public.key");
byte[] pubKeyData = pubKey.getEncoded();
DTO.PacketDTO pkdto=new DTO.PacketDTO();
pkdto.setData(pubKeyData);
ServerThread.sendData(clientSocket, pkdto);
return true;
} catch (IOException ex) {
Logger.getLogger(GeneratePublicPrivateKeys.class.getName()).log(Level.SEVERE, null, ex);
}
return false;
}
public boolean receivePubKey() {
Object data = receiveData(clientSocket);
byte[] command = new byte[4];
try {
ObjectInputStream objectInput = new ObjectInputStream((ObjectInputStream) data);
objectInput.read(command);
BigInteger m = (BigInteger) objectInput.readObject();
BigInteger e = (BigInteger) objectInput.readObject();
RSAPublicKeySpec keySpec = new RSAPublicKeySpec(m, e);
KeyFactory fact = KeyFactory.getInstance("RSA");
PublicKey pubKey = fact.generatePublic(keySpec);
saveToFile("public.client.key", m, e);
return true;
} catch (IOException ex) {
Logger.getLogger(GeneratePublicPrivateKeys.class.getName()).log(Level.SEVERE, null, ex);
} catch (ClassNotFoundException ex) {
Logger.getLogger(GeneratePublicPrivateKeys.class.getName()).log(Level.SEVERE, null, ex);
} catch (NoSuchAlgorithmException ex) {
Logger.getLogger(GeneratePublicPrivateKeys.class.getName()).log(Level.SEVERE, null, ex);
} catch (InvalidKeySpecException ex) {
Logger.getLogger(GeneratePublicPrivateKeys.class.getName()).log(Level.SEVERE, null, ex);
}
return false;
}
private static PrivateKey readPriKeyFromFile(String keyFileName) throws IOException {
FileInputStream in = new FileInputStream(keyFileName);
ObjectInputStream oin =
new ObjectInputStream(new BufferedInputStream(in));
try {
BigInteger m = (BigInteger) oin.readObject();
BigInteger e = (BigInteger) oin.readObject();
RSAPrivateKeySpec keySpec = new RSAPrivateKeySpec(m, e);
KeyFactory fact = KeyFactory.getInstance("RSA");
PrivateKey priKey = fact.generatePrivate(keySpec);
return priKey;
} catch (Exception e) {
throw new RuntimeException("Spurious serialisation error", e);
} finally {
oin.close();
}
}
private byte[] decryptSessionKey() {
try {
PrivateKey sessionKey = readPriKeyFromFile("session.key");
byte[] sessionKeyData = sessionKey.getEncoded();
PrivateKey priKeyServer = readPriKeyFromFile("private.key");
byte[] priKeyData = priKeyServer.getEncoded();
PublicKey pubKeyClient = readPubKeyFromFile("public.client.key");
byte[] pubKeyData = pubKeyClient.getEncoded();
//decypt by private key of server
Cipher cipherPri = Cipher.getInstance("RSA/ECB/PKCS1Padding");
cipherPri.init(Cipher.DECRYPT_MODE, priKeyServer);
byte[] cipherDataPri = cipherPri.doFinal(sessionKeyData);
//decrypt by public key of client
Cipher cipherPub = Cipher.getInstance("RSA/ECB/PKSC1Padding");
cipherPub.init(Cipher.DECRYPT_MODE, pubKeyClient);
byte[] cipherDataPub = cipherPub.doFinal(cipherDataPri);
return cipherDataPub;
}
catch (Exception e) {
e.printStackTrace();
}
return null;
}
private byte[] encrypt(byte[] data) throws IllegalBlockSizeException,
BadPaddingException, NoSuchAlgorithmException,
NoSuchPaddingException, InvalidKeyException,
UnsupportedEncodingException {
key = new SecretKeySpec(decryptSessionKey(), 0, decryptSessionKey().length, "DES/ECB/PKCS5Padding");
// Get a cipher object.
Cipher cipher = Cipher.getInstance("DES/ECB/PKCS5Padding");
cipher.init(Cipher.ENCRYPT_MODE, key);
// encrypt using the cypher
byte[] raw = cipher.doFinal(data);
return raw;
}
private byte[] decrypt(byte[] data) throws InvalidKeyException,
NoSuchAlgorithmException, NoSuchPaddingException,
IllegalBlockSizeException, BadPaddingException, IOException {
key = new SecretKeySpec(decryptSessionKey(), 0, decryptSessionKey().length, "DES/ECB/PKCS5Padding");
// Get a cipher object.
Cipher cipher = Cipher.getInstance("DES/ECB/PKCS5Padding");
cipher.init(Cipher.DECRYPT_MODE, key);
//decode the message
byte[] result = cipher.doFinal(data);
return result;
}
} | Java |
/*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
package DAO;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.security.InvalidKeyException;
import java.security.NoSuchAlgorithmException;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.crypto.BadPaddingException;
import javax.crypto.Cipher;
import javax.crypto.IllegalBlockSizeException;
import javax.crypto.NoSuchPaddingException;
import javax.crypto.spec.SecretKeySpec;
import sun.misc.BASE64Decoder;
import sun.misc.BASE64Encoder;
/**
*
* @author Anonymous
*/
public class MaHoa {
//Hàm mã hóa dữ liệu string -> string
public static String MaHoa(String raw)
{
String rs = null;
FileInputStream is = null;
try {
is = new FileInputStream("key.txt"); //duong dan toi khoa
} catch (FileNotFoundException ex) {
Logger.getLogger(ChuyenXeDAO.class.getName()).log(Level.SEVERE, null, ex);
}
byte[] buffer = null;
try {
buffer = new byte[is.available()-2];
} catch (IOException ex) {
Logger.getLogger(ChuyenXeDAO.class.getName()).log(Level.SEVERE, null, ex);
}
while(true)
{
int read = 0;
try {
read = is.read(buffer);
} catch (IOException ex) {
Logger.getLogger(ChuyenXeDAO.class.getName()).log(Level.SEVERE, null, ex);
}
if ( read < 0 )
{
break;
}
}
System.out.println("byte Encryted : " + buffer);
SecretKeySpec myDesKey = new SecretKeySpec(buffer,"DES");
Cipher desCipher = null;
try {
desCipher = Cipher.getInstance("DES");
} catch ( NoSuchAlgorithmException | NoSuchPaddingException ex) {
Logger.getLogger(ChuyenXeDAO.class.getName()).log(Level.SEVERE, null, ex);
}
try {
desCipher.init(Cipher.ENCRYPT_MODE, myDesKey);
} catch (InvalidKeyException ex) {
Logger.getLogger(ChuyenXeDAO.class.getName()).log(Level.SEVERE, null, ex);
}
//ma hoa ga bat dau
byte[] gabatdau = raw.getBytes();
byte[] textEncryptedgabd = null;
try {
textEncryptedgabd = desCipher.doFinal(gabatdau);
} catch ( IllegalBlockSizeException | BadPaddingException ex) {
Logger.getLogger(ChuyenXeDAO.class.getName()).log(Level.SEVERE, null, ex);
}
BASE64Encoder encoder1=new BASE64Encoder();
rs=encoder1.encode(textEncryptedgabd);
return rs;
}
//Hàm giải mã dữ liệu string -> string
public static String GiaiMa(String data)
{
String rs = null;
FileInputStream is = null;
try {
is = new FileInputStream("key.txt"); //duong dan toi khoa
} catch (FileNotFoundException ex) {
Logger.getLogger(ChuyenXeDAO.class.getName()).log(Level.SEVERE, null, ex);
}
byte[] buffer = null;
try {
buffer = new byte[is.available()-2];
} catch (IOException ex) {
Logger.getLogger(ChuyenXeDAO.class.getName()).log(Level.SEVERE, null, ex);
}
while(true)
{
int read = 0;
try {
read = is.read(buffer);
} catch (IOException ex) {
Logger.getLogger(ChuyenXeDAO.class.getName()).log(Level.SEVERE, null, ex);
}
if ( read < 0 )
{
break;
}
}
System.out.println("byte Encryted : " + buffer);
SecretKeySpec myDesKey = new SecretKeySpec(buffer,"DES");
Cipher desCipher = null;
try {
desCipher = Cipher.getInstance("DES");
} catch ( NoSuchAlgorithmException | NoSuchPaddingException ex) {
Logger.getLogger(ChuyenXeDAO.class.getName()).log(Level.SEVERE, null, ex);
}
try {
desCipher.init(Cipher.DECRYPT_MODE,myDesKey );
} catch (InvalidKeyException ex) {
Logger.getLogger(ChuyenXeDAO.class.getName()).log(Level.SEVERE, null, ex);
}
BASE64Decoder decodergabd=new BASE64Decoder();
byte[] tam = null;
try {
tam = decodergabd.decodeBuffer(data);
} catch (IOException ex) {
Logger.getLogger(ChuyenXeDAO.class.getName()).log(Level.SEVERE, null, ex);
}
byte[] textDecryptedgabd = null;
try {
textDecryptedgabd = desCipher.doFinal(tam);
} catch ( IllegalBlockSizeException | BadPaddingException ex) {
Logger.getLogger(ChuyenXeDAO.class.getName()).log(Level.SEVERE, null, ex);
}
rs=new String(textDecryptedgabd);
return rs;
}
}
| Java |
/*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
package BUS;
import java.util.List;
/**
*
* @author Anonymous
*/
public class ChuyenXeBUS {
// public boolean ThemChuyenXe(DTO.ChuyenXeDTO chuyenxedto){
// return DAO.ChuyenXeDAO.ThemChuyenXe(chuyenxedto);
// }
// public boolean CnChuyenXe(DTO.ChuyenXeDTO chuyenxedto){
// return DAO.ChuyenXeDAO.CnChuyenXe(chuyenxedto);
// }
public List<DTO.ChuyenXeDTO> dsChuyenXe(){
return DAO.ChuyenXeDAO.dsChuyenXe();
}
// public boolean XoaChuyenXe(int machuyen){
// return DAO.ChuyenXeDAO.XoaChuyenXe(machuyen);
// }
// public DTO.ChuyenXeDTO ttChuyenXe(int machuyen){
// return DAO.ChuyenXeDAO.ttChuyenXe(machuyen);
// }
}
| Java |
/*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
package BUS;
import java.util.List;
/**
*
* @author Anonymous
*/
public class DatVeBUS {
public boolean ThemDatVe(DTO.DatVeDTO dvdto){
return DAO.DatVeDAO.ThemDatVe(dvdto);
}
}
| Java |
/*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
package DTO;
import java.io.Serializable;
/**
*
* @author Anonymous
*/
public class PacketDTO implements Serializable{
private int Command;
private Object Data;
private boolean Flag;
public int getCommand(){
return Command;
}
public void setCommand(int command){
this.Command=command;
}
public Object getData(){
return Data;
}
public void setData(Object data){
this.Data=data;
}
public boolean getFlag(){
return Flag;
}
public void setFlag(boolean flag){
this.Flag=flag;
}
}
| Java |
/*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
package DTO;
import java.io.Serializable;
import java.util.Date;
/**
*
* @author Anonymous
*/
public class ChuyenXeDTO implements Serializable{
private int MaChuyen;
private int SoLuongVe;
private int GioiHanVe;
private String GaBatDau;
private String GaKetThuc;
private Date ThoiGianChay;
private int VeDaDat;
private int GiaTien;
public int getVeDaDat(){
return VeDaDat;
}
public void setVeDaDat(int veDaDat){
this.VeDaDat=veDaDat;
}
public int getMaChuyen(){
return MaChuyen;
}
public void setMaChuyen(int maChuyen){
this.MaChuyen=maChuyen;
}
public int getSoLuongVe(){
return SoLuongVe;
}
public void setSoLuongVe(int soLuongVe){
this.SoLuongVe=soLuongVe;
}
public int getGioiHanVe(){
return GioiHanVe;
}
public void setGioiHanVe(int gioiHanVe){
this.GioiHanVe=gioiHanVe;
}
public String getGaBatDau()
{
return GaBatDau;
}
public void setGatBatDau(String gaBatDau)
{
this.GaBatDau=gaBatDau;
}
public String getGaKetThuc()
{
return GaKetThuc;
}
public void setGaKetThuc(String gaKetThuc)
{
this.GaKetThuc=gaKetThuc;
}
public Date getThoiGianChay()
{
return ThoiGianChay;
}
public void setThoiGianChay(Date thoiGianChay)
{
this.ThoiGianChay=thoiGianChay;
}
public int getGiaTien(){
return GiaTien;
}
public void setGiaTien(int giaTien){
this.GiaTien=giaTien;
}
}
| Java |
/*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
package DTO;
import java.io.Serializable;
import java.util.Date;
/**
*
* @author Anonymous
*/
public class DatVeDTO implements Serializable{
private int MaDatVe;
private int MaChuyen;
private int SoLuongVe;
private String CMND;
private Date NgayDat;
private int DaThanhToan;//0: chua - 1: da thanh toan
private int TrangThai;//0: con han thanh toan - 1: het han thanh toan
public int getMaDatVe(){
return MaDatVe;
}
public void setMaDatVe(int maDatVe){
this.MaDatVe=maDatVe;
}
public int getMaChuyen(){
return MaChuyen;
}
public void setMaChuyen(int maChuyen){
this.MaChuyen=maChuyen;
}
public int getSoLuongVe(){
return SoLuongVe;
}
public void setSoLuongVe(int soLuongVe){
this.SoLuongVe=soLuongVe;
}
public String getCMND()
{
return CMND;
}
public void setCMND(String cMND)
{
this.CMND=cMND;
}
public int getDaThanhToan(){
return DaThanhToan;
}
public void setDaThanhToan(int daThanhToan){
this.DaThanhToan=daThanhToan;
}
public Date getNgayDat()
{
return NgayDat;
}
public void setNgayDat(Date ngayDat)
{
this.NgayDat=ngayDat;
}
public int getTrangThai(){
return TrangThai;
}
public void setTrangThai(int trangThai){
this.TrangThai=trangThai;
}
}
| Java |
/*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
package GUI;
import java.util.logging.Level;
import java.util.logging.Logger;
import java.util.prefs.Preferences;
import javax.swing.JOptionPane;
/**
*
* @author Anonymous
*/
public class ConfigGUI extends javax.swing.JFrame {
/**
* Creates new form ConfigGUI
*/
//Các từ khóa prefs
protected static final String PREF_TENSV = "TENSV";
protected static final String PREF_PORT = "PORT";
public ConfigGUI() {
initComponents();
}
/**
* This method is called from within the constructor to initialize the form.
* WARNING: Do NOT modify this code. The content of this method is always
* regenerated by the Form Editor.
*/
@SuppressWarnings("unchecked")
// <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
private void initComponents() {
jLabel1 = new javax.swing.JLabel();
txtServer = new javax.swing.JTextField();
txtPort = new javax.swing.JTextField();
jLabel3 = new javax.swing.JLabel();
btnTest = new javax.swing.JButton();
setDefaultCloseOperation(javax.swing.WindowConstants.DISPOSE_ON_CLOSE);
setTitle("Config");
jLabel1.setText("Server");
txtServer.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
txtServerActionPerformed(evt);
}
});
jLabel3.setText("Port");
btnTest.setText("Kết nối thử và lưu cấu hình");
btnTest.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
btnTestActionPerformed(evt);
}
});
javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
getContentPane().setLayout(layout);
layout.setHorizontalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addGap(39, 39, 39)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(jLabel3)
.addComponent(jLabel1))
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addGap(64, 64, 64)
.addComponent(txtServer, javax.swing.GroupLayout.PREFERRED_SIZE, 191, javax.swing.GroupLayout.PREFERRED_SIZE))
.addGroup(layout.createSequentialGroup()
.addGap(66, 66, 66)
.addComponent(txtPort, javax.swing.GroupLayout.PREFERRED_SIZE, 74, javax.swing.GroupLayout.PREFERRED_SIZE))))
.addGroup(layout.createSequentialGroup()
.addGap(114, 114, 114)
.addComponent(btnTest)))
.addContainerGap(74, Short.MAX_VALUE))
);
layout.setVerticalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addGap(28, 28, 28)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
.addComponent(txtServer, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(jLabel1))
.addGap(18, 18, 18)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
.addComponent(txtPort, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(jLabel3))
.addGap(27, 27, 27)
.addComponent(btnTest, javax.swing.GroupLayout.PREFERRED_SIZE, 35, javax.swing.GroupLayout.PREFERRED_SIZE)
.addContainerGap(32, Short.MAX_VALUE))
);
pack();
}// </editor-fold>//GEN-END:initComponents
private void txtServerActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_txtServerActionPerformed
// TODO add your handling code here:
}//GEN-LAST:event_txtServerActionPerformed
//Khi nhấp nút kết nối thử và lưu cấu hình
private void btnTestActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnTestActionPerformed
// TODO add your handling code here:
//Nếu kết nối thành công
if(DAO.Connect.ConnectT(txtServer.getText().trim(), Integer.parseInt(txtPort.getText().trim()))){
//Lưu thông tin cấu hình vào prefs
Preferences prefs = Preferences.userNodeForPackage(ConfigGUI.class);
prefs.put(PREF_TENSV, txtServer.getText().trim());
prefs.put(PREF_PORT, txtPort.getText().trim());
JOptionPane.showMessageDialog(null,
"Kết nối thành công.");
java.awt.EventQueue.invokeLater(new Runnable() {
@Override
public void run() {//kích hoạt màn hình chính
try {
new MAIN.MAIN().setVisible(true);
} catch (Exception ex) {
Logger.getLogger(ConfigGUI.class.getName()).log(Level.SEVERE, null, ex);
}
}
});
this.dispose();//tự tắt màn hình
}
else{
JOptionPane.showMessageDialog(null,
"Kết nối thất bại.");
}
}//GEN-LAST:event_btnTestActionPerformed
/**
* @param args the command line arguments
*/
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 | InstantiationException | IllegalAccessException | javax.swing.UnsupportedLookAndFeelException ex) {
java.util.logging.Logger.getLogger(ConfigGUI.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
}
//</editor-fold>
/* Create and display the form */
java.awt.EventQueue.invokeLater(new Runnable() {
@Override
public void run() {
new ConfigGUI().setVisible(true);
}
});
}
// Variables declaration - do not modify//GEN-BEGIN:variables
private javax.swing.JButton btnTest;
private javax.swing.JLabel jLabel1;
private javax.swing.JLabel jLabel3;
private javax.swing.JTextField txtPort;
private javax.swing.JTextField txtServer;
// End of variables declaration//GEN-END:variables
}
| Java |
/*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
package GUI;
import javax.swing.JOptionPane;
/**
*
* @author Anonymous
*/
public class DatVeGUI extends javax.swing.JFrame {
/**
* Creates new form DatVeGUI
*/
public DatVeGUI() {
initComponents();
//gán các giá trị lấy được từ màn hình chính
txtMaChuyen.setText(Integer.toString(MAIN.MAIN.macxcn));
txtGioiHan.setText(Integer.toString(MAIN.MAIN.gh));
//Thực hiện xác định miền giá trị cho số lượng vé muốn đặt
if(MAIN.MAIN.gh>MAIN.MAIN.chotrong)//Nếu giới hạn lớn hơn chỗ trống
//Miền giá trị 1->số chỗ trống
spSoLV.setModel(new javax.swing.SpinnerNumberModel(1, 1, MAIN.MAIN.chotrong, 1));
else
//Ngược lại miền giá trị 1-> giới hạn
spSoLV.setModel(new javax.swing.SpinnerNumberModel(1, 1, MAIN.MAIN.gh, 1));
txtGiaTien.setText(Integer.toString(MAIN.MAIN.giatien*(int)spSoLV.getValue()));
}
/**
* This method is called from within the constructor to initialize the form.
* WARNING: Do NOT modify this code. The content of this method is always
* regenerated by the Form Editor.
*/
@SuppressWarnings("unchecked")
// <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
private void initComponents() {
txtMaChuyen = new javax.swing.JTextField();
jLabel7 = new javax.swing.JLabel();
btnDatVe = new java.awt.Button();
jLabel9 = new javax.swing.JLabel();
txtCMND = new javax.swing.JTextField();
jLabel10 = new javax.swing.JLabel();
jLabel11 = new javax.swing.JLabel();
txtGioiHan = new javax.swing.JTextField();
spSoLV = new javax.swing.JSpinner();
txtGiaTien = new javax.swing.JTextField();
jLabel12 = new javax.swing.JLabel();
setDefaultCloseOperation(javax.swing.WindowConstants.DISPOSE_ON_CLOSE);
setTitle("Thêm Chuyến Xe");
txtMaChuyen.setEnabled(false);
jLabel7.setText("Mã Chuyến");
btnDatVe.setLabel("Đặt Vé");
btnDatVe.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
btnDatVeActionPerformed(evt);
}
});
jLabel9.setText("Số Lượng Vé");
jLabel10.setText("CMND");
jLabel11.setText("Giới hạn");
txtGioiHan.setEnabled(false);
spSoLV.setModel(new javax.swing.SpinnerNumberModel(1, 1, MAIN.MAIN.gh, 1));
spSoLV.addChangeListener(new javax.swing.event.ChangeListener() {
public void stateChanged(javax.swing.event.ChangeEvent evt) {
spSoLVStateChanged(evt);
}
});
txtGiaTien.setEnabled(false);
jLabel12.setText("Tổng Tiền");
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(38, 38, 38)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(jLabel10)
.addComponent(jLabel7)
.addComponent(jLabel9)
.addComponent(jLabel12))
.addGap(56, 56, 56)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(txtCMND, javax.swing.GroupLayout.PREFERRED_SIZE, 205, javax.swing.GroupLayout.PREFERRED_SIZE)
.addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
.addComponent(spSoLV)
.addGap(53, 53, 53)
.addComponent(jLabel11)
.addGap(18, 18, 18)
.addComponent(txtGioiHan, javax.swing.GroupLayout.PREFERRED_SIZE, 45, javax.swing.GroupLayout.PREFERRED_SIZE))
.addComponent(txtMaChuyen, javax.swing.GroupLayout.PREFERRED_SIZE, 59, javax.swing.GroupLayout.PREFERRED_SIZE))
.addContainerGap(42, Short.MAX_VALUE))
.addGroup(layout.createSequentialGroup()
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(btnDatVe, javax.swing.GroupLayout.PREFERRED_SIZE, 119, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(txtGiaTien, javax.swing.GroupLayout.PREFERRED_SIZE, 140, javax.swing.GroupLayout.PREFERRED_SIZE))
.addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))))
);
layout.setVerticalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addGap(28, 28, 28)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(txtMaChuyen, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(jLabel7))
.addGap(18, 18, 18)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(jLabel9)
.addComponent(txtGioiHan, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(jLabel11)
.addComponent(spSoLV, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
.addGap(18, 18, 18)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(txtCMND, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(jLabel10))
.addGap(18, 18, 18)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(txtGiaTien, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(jLabel12))
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, 38, Short.MAX_VALUE)
.addComponent(btnDatVe, javax.swing.GroupLayout.PREFERRED_SIZE, 36, javax.swing.GroupLayout.PREFERRED_SIZE)
.addGap(33, 33, 33))
);
pack();
}// </editor-fold>//GEN-END:initComponents
//Khi nhấp vào nút đặt vé
private void btnDatVeActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnDatVeActionPerformed
// TODO add your handling code here:
if(ktDauVao())//Nếu đầu vào hợp lệ
{
//Đưa thông tin đặt vé vào dvdto
DTO.DatVeDTO dvdto=new DTO.DatVeDTO();
dvdto.setSoLuongVe((int)spSoLV.getValue());
dvdto.setCMND(txtCMND.getText().toUpperCase());
dvdto.setMaChuyen(Integer.parseInt(txtMaChuyen.getText()));
BUS.DatVeBUS dvbus=new BUS.DatVeBUS();
if(dvbus.ThemDatVe(dvdto))//Nếu đặt vé thành công
{
JOptionPane.showMessageDialog(this,
"Đặt vé thành công!",
"Thông báo",
JOptionPane.INFORMATION_MESSAGE);
}
else{
JOptionPane.showMessageDialog(this,
"Đặt vé thất bại!",
"Thông báo lỗi",
JOptionPane.ERROR_MESSAGE);
}
}
else
{
JOptionPane.showMessageDialog(this,
"Bạn chưa nhập đủ thông tin hoặc thông tin không hợp lệ.",
"Thông báo lỗi",
JOptionPane.ERROR_MESSAGE);
}
}//GEN-LAST:event_btnDatVeActionPerformed
private void spSoLVStateChanged(javax.swing.event.ChangeEvent evt) {//GEN-FIRST:event_spSoLVStateChanged
// TODO add your handling code here:
txtGiaTien.setText(Integer.toString(MAIN.MAIN.giatien*(int)spSoLV.getValue()));
}//GEN-LAST:event_spSoLVStateChanged
//Hàm kiểm tra đầu vào
private boolean ktDauVao()
{
boolean flag=false;
if(!"".equals(txtCMND.getText().trim()))//Nếu cmnd đã có giá trị
flag=true;
return flag;
}
/**
* @param args the command line arguments
*/
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 | InstantiationException | IllegalAccessException | javax.swing.UnsupportedLookAndFeelException ex) {
java.util.logging.Logger.getLogger(DatVeGUI.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
}
//</editor-fold>
/* Create and display the form */
java.awt.EventQueue.invokeLater(new Runnable() {
@Override
public void run() {
new DatVeGUI().setVisible(true);
}
});
}
// Variables declaration - do not modify//GEN-BEGIN:variables
private java.awt.Button btnDatVe;
private javax.swing.JLabel jLabel10;
private javax.swing.JLabel jLabel11;
private javax.swing.JLabel jLabel12;
private javax.swing.JLabel jLabel7;
private javax.swing.JLabel jLabel9;
private javax.swing.JSpinner spSoLV;
private javax.swing.JTextField txtCMND;
private javax.swing.JTextField txtGiaTien;
private javax.swing.JTextField txtGioiHan;
private javax.swing.JTextField txtMaChuyen;
// End of variables declaration//GEN-END:variables
}
| Java |
package MAIN;
import com.sun.org.apache.xerces.internal.impl.dv.util.Base64;
import java.security.PublicKey;
import sun.security.x509.CertAndKeyGen;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.math.BigInteger;
import java.security.GeneralSecurityException;
import java.security.KeyPair;
import java.security.KeyStore;
import java.security.PrivateKey;
import java.security.PublicKey;
import java.security.SecureRandom;
import java.security.cert.CertPath;
import java.security.cert.CertPathValidator;
import java.security.cert.Certificate;
import java.security.cert.CertificateFactory;
import java.security.cert.PKIXCertPathValidatorResult;
import java.security.cert.PKIXParameters;
import java.security.cert.TrustAnchor;
import java.security.cert.X509Certificate;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Date;
import java.util.List;
import sun.security.x509.AlgorithmId;
import sun.security.x509.CertAndKeyGen;
import sun.security.x509.CertificateAlgorithmId;
import sun.security.x509.CertificateIssuerName;
import sun.security.x509.CertificateSerialNumber;
import sun.security.x509.CertificateSubjectName;
import sun.security.x509.CertificateValidity;
import sun.security.x509.CertificateVersion;
import sun.security.x509.CertificateX509Key;
import sun.security.x509.X500Name;
import sun.security.x509.X509CertImpl;
import sun.security.x509.X509CertInfo;
//CERTIFICATE AUTHORITY: VERISIGN
public class usc_Certificate
{
public static PublicKey pubKey = null;
public static PrivateKey privKey = null;
public static final String commonName = "GUEST"; //~CN
public static final String organizationalUnit = "12HC-IT";//~OU
public static final String organization = "Khoa Hoc Tu Nhien";//~O
public static final String city = "HCM";//~L
public static final String state = "HCM";//~ST
public static final String country = "VN";//~C
public static final long validity = 1096; // 3 years
public static final String alias = "FIT";
public static final char[] keyPass = "changeit".toCharArray();//the password to protect the key
public static X509Certificate generateCertificate(
String dn, KeyPair pair, int days, String algorithm)
throws GeneralSecurityException, IOException
{
/*http://stackoverflow.com/questions/1615871/creating-an-x509-certificate-in-java-without-bouncycastle
* Create a self-signed X.509 Certificate
* @param dn the X.509 Distinguished Name, eg "CN=Test, L=London, C=GB"
* @param pair the KeyPair
* @param days how many days from now the Certificate is valid for
* @param algorithm the signing algorithm, eg "SHA1withRSA"
*/
PrivateKey privkey = pair.getPrivate();
X509CertInfo info = new X509CertInfo();
Date from = new Date();
Date to = new Date(from.getTime() + days * 86400000l);
CertificateValidity interval = new CertificateValidity(from, to);
BigInteger sn = new BigInteger(64, new SecureRandom());
X500Name owner = new X500Name(dn);
info.set(X509CertInfo.VALIDITY, interval);
info.set(X509CertInfo.SERIAL_NUMBER, new CertificateSerialNumber(sn));
info.set(X509CertInfo.SUBJECT, new CertificateSubjectName(owner));
info.set(X509CertInfo.ISSUER, new CertificateIssuerName(owner));
info.set(X509CertInfo.KEY, new CertificateX509Key(pair.getPublic()));
info.set(X509CertInfo.VERSION, new CertificateVersion(CertificateVersion.V3));
AlgorithmId algo = new AlgorithmId(AlgorithmId.md5WithRSAEncryption_oid);
info.set(X509CertInfo.ALGORITHM_ID, new CertificateAlgorithmId(algo));
// Sign the cert to identify the algorithm that's used.
X509CertImpl cert = new X509CertImpl(info);
cert.sign(privkey, algorithm);
// Update the algorith, and resign.
algo = (AlgorithmId)cert.get(X509CertImpl.SIG_ALG);
info.set(CertificateAlgorithmId.NAME + "." + CertificateAlgorithmId.ALGORITHM, algo);
cert = new X509CertImpl(info);
cert.sign(privkey, algorithm);
return cert;
}
public static void createCertificate(String fileName) throws Exception
{
KeyPair kp = new KeyPair(pubKey, privKey);
String dn = "";
dn+= "CN=" + commonName + ", ";
dn+= "OU=" + organizationalUnit + ", ";
dn+= "O=" + organization + ", ";
dn+= "L=" + city +", ";
dn+= "C=" + country + "";
X509Certificate cert = generateCertificate(dn, kp, 60, "SHA256WithRSA");
FileOutputStream os = new FileOutputStream(fileName);
os.write(cert.getEncoded());
os.close();
//SHA1withDSA,SHA1withRSA,SHA256withRSA is Sig algo supported by Java platform.
}
public static void validateCertificate(String certFileName)
{
try
{
CertificateFactory cf = CertificateFactory.getInstance("X.509");
FileInputStream is = new FileInputStream(new File(certFileName));
Certificate cert = cf.generateCertificate(is);
List mylist = new ArrayList();
mylist.add(cert);
CertPath cp = cf.generateCertPath(mylist);
Certificate trust = cert;
TrustAnchor anchor = new TrustAnchor((X509Certificate) trust, null);
PKIXParameters params = new PKIXParameters(Collections.singleton(anchor));
params.setRevocationEnabled(false);
CertPathValidator cpv = CertPathValidator.getInstance("PKIX");
/*
PKIXCertPathValidatorResult represents the successful result of the PKIX certification path validation algorithm.
Instances of PKIXCertPathValidatorResult are returned by the validate method of CertPathValidator objects implementing the PKIX algorithm.
*/
PKIXCertPathValidatorResult result = (PKIXCertPathValidatorResult) cpv.validate(cp, params);
System.out.println(result);
}
catch(Exception ex)
{
System.out.println("Invalid Input!!!");
}
}
public static boolean validateCertificate(Certificate _cer)
{
boolean f = false;
try
{
CertificateFactory cf = CertificateFactory.getInstance("X.509");
Certificate cert = _cer;
List mylist = new ArrayList();
mylist.add(cert);
CertPath cp = cf.generateCertPath(mylist);
Certificate trust = cert;
TrustAnchor anchor = new TrustAnchor((X509Certificate) trust, null);
PKIXParameters params = new PKIXParameters(Collections.singleton(anchor));
params.setRevocationEnabled(false);
CertPathValidator cpv = CertPathValidator.getInstance("PKIX");
/*
PKIXCertPathValidatorResult represents the successful result of the PKIX certification path validation algorithm.
Instances of PKIXCertPathValidatorResult are returned by the validate method of CertPathValidator objects implementing the PKIX algorithm.
*/
PKIXCertPathValidatorResult result = (PKIXCertPathValidatorResult) cpv.validate(cp, params);
//System.out.println(result);
f = true;
}
catch(Exception ex)
{
System.out.println("Invalid Input!!!");
}
return f;
}
public static void main(String[] args) throws Exception
{
usc_RSAKeyPair.PUBLIC_KEY_FILE = "public.key";
pubKey = usc_RSAKeyPair.readPublicKey();
usc_RSAKeyPair.PRIVATE_KEY_FILE = "private.key";
privKey = usc_RSAKeyPair.readPrivateKey();
//System.out.println(pubKey);
//System.out.println(privKey);
//createCertificate("resource/GUEST.cer");
//Read Certificate file
FileInputStream is = new FileInputStream(new File("GUEST.cer"));
CertificateFactory cf = CertificateFactory.getInstance("X.509");
Certificate cert = cf.generateCertificate(is);
//System.out.println(cert);
validateCertificate(cert);
//Validate Certificate file
//validateCertificate("GUEST.cer");
}
}
| Java |
/*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
package MAIN;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.GregorianCalendar;
import java.util.List;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.swing.ListSelectionModel;
import javax.swing.event.ListSelectionEvent;
import javax.swing.event.ListSelectionListener;
import javax.swing.table.AbstractTableModel;
/**
*
* @author Anonymous
*/
public class MAIN extends javax.swing.JFrame {
/**
* Creates new form Main
*/
public static int macxcn;//Mã chuyến xe đang chọn
public static int gh;//Giới hạn vé chuyến xe đang chọn
public static int chotrong;//Chỗ trống chuyến xe đang chọn
public static int giatien;//Giá tiền chuyến xe đang chọn
private MyTableModel model;//Lưu dữ liệu bảng
public MAIN() {
try {
//Kiểm tra Certificate, khởi tạo mã hóa
GeneratePublicPrivateKeys.Certificate_And_SecretKey();
} catch (Exception ex) {
Logger.getLogger(MAIN.class.getName()).log(Level.SEVERE, null, ex);
}
//Kết thúc kiểm tra Certificate, khởi tạo mã hóa
initComponents();
//Khởi tạo giá trị ban đầu
btnDatVe.setEnabled(false);//Khi mới vào không cho nút đặt vé xử lý sự kiện nhấp chuột
macxcn=0;
gh=0;
chotrong=0;
giatien=5000;
new Thread()//code tạo đồng hồ gán vào nút Time
{
@Override
public void run()
{
while(true)
{
Calendar cal=new GregorianCalendar();
int hour=cal.get(Calendar.HOUR_OF_DAY);
int min=cal.get(Calendar.MINUTE);
int sec=cal.get(Calendar.SECOND);
int day=cal.get(Calendar.DAY_OF_MONTH);
int mon=cal.get(Calendar.MONTH);
int year=cal.get(Calendar.YEAR);
String time=hour +":"+min+":"+sec+" "+day+"-"+(mon+1)+"-"+year;
btnTime.setLabel(time);
}
}
}.start();
}
/**
* This method is called from within the constructor to initialize the form.
* WARNING: Do NOT modify this code. The content of this method is always
* regenerated by the Form Editor.
*/
@SuppressWarnings("unchecked")
// <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
private void initComponents() {
btnDatVe = new java.awt.Button();
jScrollPane1 = new javax.swing.JScrollPane();
tbChuyenXe = new javax.swing.JTable();
btnRefresh = new java.awt.Button();
btnTime = new java.awt.Button();
setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
setTitle("HTBVTQM_CLIENT");
btnDatVe.setActionCommand("Insert");
btnDatVe.setLabel("Đặt vé");
btnDatVe.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
btnDatVeActionPerformed(evt);
}
});
model = new MyTableModel();
tbChuyenXe.setAutoCreateRowSorter(true);
tbChuyenXe.setModel(model);
ngheBang();
jScrollPane1.setViewportView(tbChuyenXe);
btnRefresh.setLabel("Làm mới danh sách");
btnRefresh.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
btnRefreshActionPerformed(evt);
}
});
btnTime.setLabel("Time");
javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
getContentPane().setLayout(layout);
layout.setHorizontalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addContainerGap(45, Short.MAX_VALUE)
.addComponent(jScrollPane1, javax.swing.GroupLayout.PREFERRED_SIZE, 740, javax.swing.GroupLayout.PREFERRED_SIZE))
.addGroup(layout.createSequentialGroup()
.addComponent(btnTime, javax.swing.GroupLayout.PREFERRED_SIZE, 268, javax.swing.GroupLayout.PREFERRED_SIZE)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
.addComponent(btnRefresh, javax.swing.GroupLayout.PREFERRED_SIZE, 192, javax.swing.GroupLayout.PREFERRED_SIZE)))
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(btnDatVe, javax.swing.GroupLayout.PREFERRED_SIZE, 126, javax.swing.GroupLayout.PREFERRED_SIZE)
.addContainerGap())
);
layout.setVerticalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addGap(22, 22, 22)
.addComponent(btnRefresh, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
.addComponent(btnTime, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addComponent(btnDatVe, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addGap(0, 0, Short.MAX_VALUE))
.addComponent(jScrollPane1, javax.swing.GroupLayout.DEFAULT_SIZE, 267, Short.MAX_VALUE))
.addContainerGap())
);
btnDatVe.getAccessibleContext().setAccessibleName("Insert");
pack();
}// </editor-fold>//GEN-END:initComponents
//Sự kiện nhấp chuột vào nút Đặt vé
private void btnDatVeActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnDatVeActionPerformed
// TODO add your handling code here:
java.awt.EventQueue.invokeLater(new Runnable() {
@Override
public void run() {
new GUI.DatVeGUI().setVisible(true);
}
});
}//GEN-LAST:event_btnDatVeActionPerformed
//Sự kiện nhấp vào nút làm mới danh sách
private void btnRefreshActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnRefreshActionPerformed
// TODO add your handling code here:
loadBang();//Tải lại danh sách dữ liệu trong bảng
}//GEN-LAST:event_btnRefreshActionPerformed
//Hàm load dữ liệu vào bảng
private boolean loadBang(){
if(DAO.Connect.tConnect()){//Nếu kết nối với server thành công
model = new MyTableModel();//Thực hiện lấy dữ liệu từ server
tbChuyenXe.setModel(model);//đưa dữ liệu đó vào bảng
ngheBang();//Nghe sự kiện khi nhấp chuột vào từng danh sách trong bảng
btnDatVe.setEnabled(false);//hủy kích hoạt nút đặt vé khi làm mới danh sách
return true;
}
else{
}
return false;
}
//Hàm nghe sự kiện trong bảng dữ liệu
private void ngheBang(){
tbChuyenXe.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
tbChuyenXe.getSelectionModel().addListSelectionListener(
new ListSelectionListener() {
@Override
public void valueChanged(ListSelectionEvent event) {
int viewRow = tbChuyenXe.getSelectedRow();
if (viewRow < 0) {//Nếu chưa chọn dòng nào
//Selection got filtered away.
btnDatVe.setEnabled(false);//hủy kích hoạt nút đặt vé
} else {//Nếu chọn 1 dòng trong danh sách
//Nếu còn có thể đặt vé
if(!"FULL".equals(String.valueOf(tbChuyenXe.getValueAt(viewRow, 6)))) {
btnDatVe.setEnabled(true);//Kích hoạt nút
//lưu các giá trị cần thiết chuyến xe để chuẩn bị chuyển sang màn hình đặt vé
macxcn=Integer.parseInt(String.valueOf(tbChuyenXe.getValueAt(viewRow, 0)));
gh=Integer.parseInt(String.valueOf(tbChuyenXe.getValueAt(viewRow, 5)));
giatien=Integer.parseInt(String.valueOf(tbChuyenXe.getValueAt(viewRow, 6)));
int vdd=Integer.parseInt(String.valueOf(tbChuyenXe.getValueAt(viewRow, 7)));
int sl=Integer.parseInt(String.valueOf(tbChuyenXe.getValueAt(viewRow, 4)));
chotrong=sl-vdd;
}
else
btnDatVe.setEnabled(false);
}
}
}
);
}
//Đối tượng lưu dữ liệu cho bảng
class MyTableModel extends AbstractTableModel {
private String[] columnNames={"MaCX",
"GaBatDau",
"GaKetThuc","ThoiGianChay","SLVe","GHVe","GiaTien","VeDaDat"};;
public Object[][] data;
public MyTableModel(){
int cot=0;
int dong=0;
if(DAO.Connect.tConnect()){//Nếu kết nối với server thành công
try
{
//Lấy dữ liệu từ server về
BUS.ChuyenXeBUS cxbus=new BUS.ChuyenXeBUS();
List<DTO.ChuyenXeDTO> Lcxdto= new ArrayList<DTO.ChuyenXeDTO>();//Biến lưu danh sách chuyến xe
Lcxdto=cxbus.dsChuyenXe();//hàm phụ trách lấy dữ liệu server về
//Thực hiện đưa dữ liệu vào bảng
data=new Object[Lcxdto.size()][8];
SimpleDateFormat simpleDateFormat = new SimpleDateFormat("HH:mm dd-MM-yyyy");
for(int i=0;i<Lcxdto.size();i++)
{
data[dong][cot++]=Lcxdto.get(i).getMaChuyen();
data[dong][cot++]=Lcxdto.get(i).getGaBatDau();
data[dong][cot++]=Lcxdto.get(i).getGaKetThuc();
data[dong][cot++]=simpleDateFormat.format(Lcxdto.get(i).getThoiGianChay());
data[dong][cot++]=Lcxdto.get(i).getSoLuongVe();
data[dong][cot++]=Lcxdto.get(i).getGioiHanVe();
data[dong][cot++]=Lcxdto.get(i).getGiaTien();
if(Lcxdto.get(i).getVeDaDat()==Lcxdto.get(i).getSoLuongVe())
data[dong][cot++]="FULL";
else
data[dong][cot++]=Lcxdto.get(i).getVeDaDat();
cot=0;
dong++;
}
}
catch (Exception ex)
{
data=new Object[0][8];
System.out.println(ex.getMessage());
}
}
else
{
data=new Object[0][8];
}
}
@Override
public int getColumnCount() {
return columnNames.length;
}
@Override
public int getRowCount() {
return data.length;
}
@Override
public String getColumnName(int col) {
return columnNames[col];
}
@Override
public Object getValueAt(int row, int col) {
return data[row][col];
}
/*
* JTable uses this method to determine the default renderer/
* editor for each cell. If we didn't implement this method,
* then the last column would contain text ("true"/"false"),
* rather than a check box.
*/
@Override
public Class getColumnClass(int c) {
return getValueAt(0, c).getClass();
}
/*
* Don't need to implement this method unless your table's
* editable.
*/
@Override
public boolean isCellEditable(int row, int col) {
//Note that the data/cell address is constant,
//no matter where the cell appears onscreen.
//if (col < 2) {
return false;
//} else {
// return true;
//}
}
/*
* Don't need to implement this method unless your table's
* data can change.
*/
@Override
public void setValueAt(Object value, int row, int col) {
if (true) {
System.out.println("Setting value at " + row + "," + col
+ " to " + value
+ " (an instance of "
+ value.getClass() + ")");
}
data[row][col] = value;
fireTableCellUpdated(row, col);
if (true) {
System.out.println("New value of data:");
printDebugData();
}
}
private void printDebugData() {
int numRows = getRowCount();
int numCols = getColumnCount();
for (int i=0; i < numRows; i++) {
System.out.print(" row " + i + ":");
for (int j=0; j < numCols; j++) {
System.out.print(" " + data[i][j]);
}
System.out.println();
}
System.out.println("--------------------------");
}
}
/**
* @param args the command line arguments
*/
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 | InstantiationException | IllegalAccessException | javax.swing.UnsupportedLookAndFeelException ex) {
java.util.logging.Logger.getLogger(MAIN.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
}
//</editor-fold>
/* Create and display the form */
java.awt.EventQueue.invokeLater(new Runnable() {
@Override
public void run() {
if(!DAO.Connect.tConnect()){//Nếu kết nối server thất bại
//kích hoạt màn hình cấu hình server mặc định là 127.0.0.1 port 1234
new GUI.ConfigGUI().setVisible(true);
}
else{
//Ngược lại kích hoạt màn hình chính
new MAIN().setVisible(true);
}
}
});
}
// Variables declaration - do not modify//GEN-BEGIN:variables
private java.awt.Button btnDatVe;
private java.awt.Button btnRefresh;
private java.awt.Button btnTime;
private javax.swing.JScrollPane jScrollPane1;
private javax.swing.JTable tbChuyenXe;
// End of variables declaration//GEN-END:variables
}
| Java |
package MAIN;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.security.Key;
import java.util.Arrays;
import java.util.Random;
import javax.crypto.Cipher;
import javax.crypto.KeyGenerator;
import javax.crypto.Mac;
import javax.crypto.SecretKey;
import javax.crypto.SecretKeyFactory;
import javax.crypto.spec.PBEKeySpec;
import javax.crypto.spec.PBEParameterSpec;
import javax.crypto.spec.SecretKeySpec;
import sun.misc.BASE64Decoder;
import sun.misc.BASE64Encoder;
/*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
/**
*
* @author Messi
*/
public class usc_sessionkey_mac {
static final String AZ = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ"
+ "abcdefghijklmnopqrstuvwxyz"
+ "!@#$%^&*()-_+=";
static Random rnd = new Random();
public static String randomString(int len)
{
StringBuilder sb = new StringBuilder( len );
for( int i = 0; i < len; i++ )
sb.append( AZ.charAt( rnd.nextInt(AZ.length()) ) );
return sb.toString();
}
public static byte[] generateMAC(String inputString, String secreteKeyString) throws Exception
{
byte[] macBytes = null;
//KeyGenerator keyGen = KeyGenerator.getInstance("HmacMD5");
//SecretKey secretKey = keyGen.generateKey();
byte[] encodedKey = secreteKeyString.getBytes();
SecretKey secretKey = new SecretKeySpec(encodedKey,0,encodedKey.length,"HmacSHA256");
Mac mac = Mac.getInstance(secretKey.getAlgorithm());
mac.init(secretKey);
byte[] byteData = inputString.getBytes("UTF8");
macBytes = mac.doFinal(byteData);
return macBytes;
}
public static String xorMessage(String message, String key)
{
try
{
if (message==null || key==null ) return null;
char[] keys=key.toCharArray();
char[] mesg=message.toCharArray();
int ml=mesg.length;
int kl=keys.length;
char[] newmsg=new char[ml];
for (int i=0; i<ml; i++){
newmsg[i]=(char)(mesg[i]^keys[i%kl]);
}//for i
mesg=null; keys=null;
return new String(newmsg);
}
catch ( Exception e )
{
return null;
}
}//xorMessage
public static final String DEFAULT_ENCODING="UTF-8";
static BASE64Encoder enc=new BASE64Encoder();
static BASE64Decoder dec=new BASE64Decoder();
public static String base64encode(String text){
try {
String rez = enc.encode( text.getBytes( DEFAULT_ENCODING ) );
return rez;
}
catch (Exception e ) {
return null;
}
}//base64encode
public static String base64decode(String text){
try {
return new String(dec.decodeBuffer( text ),DEFAULT_ENCODING);
}
catch (Exception e ) {
return null;
}
}//base64decode
public static int Compare2MAC(byte[] mac1, byte[] mac2)
{
if(Arrays.equals(mac2, mac1))
return 1;
return 0;
}
//**http://stackoverflow.com/questions/5837698/converting-any-object-to-a-byte-array-in-java
//Convert Object to byte[]
public static byte[] serialize(Object obj) throws IOException {
ByteArrayOutputStream b = new ByteArrayOutputStream();
ObjectOutputStream o = new ObjectOutputStream(b);
o.writeObject(obj);
return b.toByteArray();
}
//Convert byte[] to Object
public static Object deserialize(byte[] bytes) throws IOException, ClassNotFoundException {
ByteArrayInputStream b = new ByteArrayInputStream(bytes);
ObjectInputStream o = new ObjectInputStream(b);
return o.readObject();
}
//**http://stackoverflow.com/questions/1132567/encrypt-password-in-configuration-files-java
public static byte[] Encrypt(String secretKeyString, Object input) throws Exception
{
if(input==null || secretKeyString == null)
{
System.out.println("Dau vao null!");
}
byte[] re = null;
byte[] data = serialize(input);
char[] PASSWORD = secretKeyString.toCharArray();
byte[] SALT = {
(byte) 0xde, (byte) 0x33, (byte) 0x10, (byte) 0x12,
(byte) 0xde, (byte) 0x33, (byte) 0x10, (byte) 0x12,
};
SecretKeyFactory keyFactory = SecretKeyFactory.getInstance("PBEWithMD5AndDES");//PBEWithMD5AndDES
SecretKey key = keyFactory.generateSecret(new PBEKeySpec(PASSWORD));
Cipher pbeCipher = Cipher.getInstance("PBEWithMD5AndDES/CBC/PKCS5Padding");
pbeCipher.init(Cipher.ENCRYPT_MODE, key, new PBEParameterSpec(SALT,20));
re = pbeCipher.doFinal(data);
return re;
}
public static Object Decrypt(String secretKeyString, byte[] input) throws Exception
{
if(input==null || secretKeyString == null)
{
System.out.println("Dau vao null!");
}
Object re = null;
char[] PASSWORD = secretKeyString.toCharArray();
byte[] SALT = {
(byte) 0xde, (byte) 0x33, (byte) 0x10, (byte) 0x12,
(byte) 0xde, (byte) 0x33, (byte) 0x10, (byte) 0x12,
};
SecretKeyFactory keyFactory = SecretKeyFactory.getInstance("PBEWithMD5AndDES");
SecretKey key = keyFactory.generateSecret(new PBEKeySpec(PASSWORD));
Cipher pbeCipher = Cipher.getInstance("PBEWithMD5AndDES/CBC/PKCS5Padding");
pbeCipher.init(Cipher.DECRYPT_MODE, key, new PBEParameterSpec(SALT, 20));
byte[] temp1 = pbeCipher.doFinal(input);
re = deserialize(temp1);
return re;
}
public static void main(String[] args) throws Exception
{
//Random String for Secrete Key (Session Key)
String s1 = randomString(50);
//System.out.println(s1);
/*
//Use Secrete Key to encrypt and decrypt
String txt="Anh là ĐQM Dũng" ;
String key = s1;
System.out.println(txt+" XOR-ed to: "+(txt=xorMessage(txt,key)));
String encoded=base64encode( txt );
System.out.println( " is encoded to: "+encoded+" and that is decoding to: "+ (txt=base64decode(encoded)));
System.out.println( "XOR-ing back to original: "+xorMessage(txt,key));
*/
/*
//Use Secrete Key to create MAC
s1 = "secreteKeySring";//
byte[] b = generateMAC("ABC",s1);
String s2 = new String(b,"UTF-8");
String endcoded = base64encode(s2);
System.out.println(endcoded);
//Compare 2 byte array (MAC)
byte[] c = b;
if(Compare2MAC(c, b)==1)
{
System.out.println("Two MAC is Equal.");
}
else
{
System.out.println("Two MAC is Not Equal.");
}
*/
String keyString = randomString(50);
System.out.println("Plaintext: " + s1);
System.out.println("KeyString: " + keyString);
System.out.println("Encrypt & Decypt");
System.out.println("Encrypt...");
byte[] encrypt = Encrypt(keyString, s1);
String decrypt = (String)Decrypt(keyString, encrypt);
System.out.println("Decrypt: " + decrypt);
System.out.println();
}
}
| Java |
package MAIN;
import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.math.BigInteger;
import java.nio.charset.Charset;
import java.security.KeyFactory;
import java.security.KeyPair;
import java.security.KeyPairGenerator;
import java.security.PrivateKey;
import java.security.PublicKey;
import java.security.spec.RSAPrivateKeySpec;
import java.security.spec.RSAPublicKeySpec;
import javax.crypto.Cipher;
//http://www.javamex.com/tutorials/cryptography/rsa_encryption.shtml
public class usc_RSAKeyPair
{
/*
* the public key consists of the "modulus" and a "public exponent";
* the private key consists of that same "modulus" plus a "private exponent";
*/
public static String PUBLIC_KEY_FILE = "";
public static String PRIVATE_KEY_FILE = "";
public static void generate() throws Exception
{
KeyPairGenerator kpg = KeyPairGenerator.getInstance("RSA");
kpg.initialize(2048);
KeyPair kp = kpg.genKeyPair();
KeyFactory fact = KeyFactory.getInstance("RSA");
RSAPublicKeySpec pub = fact.getKeySpec(kp.getPublic(),RSAPublicKeySpec.class);
saveToFile(PUBLIC_KEY_FILE, pub.getModulus(), pub.getPublicExponent());
//System.out.println("public exponent: " + pub.getPublicExponent());
RSAPrivateKeySpec priv = fact.getKeySpec(kp.getPrivate(), RSAPrivateKeySpec.class);
saveToFile(PRIVATE_KEY_FILE, priv.getModulus(), priv.getPrivateExponent());
//System.out.println("private exponent: " + priv.getPrivateExponent());
}
private static void saveToFile(String fileName,
BigInteger mod, BigInteger exp) throws Exception
{
ObjectOutputStream oout = new ObjectOutputStream(
new BufferedOutputStream(new FileOutputStream(fileName)));
try {
oout.writeObject(mod);
oout.writeObject(exp);
} catch (Exception e) {
throw new Exception(e);
} finally {
oout.flush();
oout.close();
}
//System.out.println("exponent: " + exp.toString());
}
public static PublicKey readPublicKey() throws Exception
{
InputStream in = new FileInputStream(PUBLIC_KEY_FILE);
ObjectInputStream oin =
new ObjectInputStream(new BufferedInputStream(in));
try {
BigInteger m = (BigInteger) oin.readObject();
BigInteger e = (BigInteger) oin.readObject();
RSAPublicKeySpec keySpec = new RSAPublicKeySpec(m, e);
KeyFactory fact = KeyFactory.getInstance("RSA");
PublicKey pubKey = fact.generatePublic(keySpec);
return pubKey;
} catch (Exception e) {
throw new Exception(e);
} finally {
oin.close();
}
}
public static PrivateKey readPrivateKey() throws Exception
{
InputStream in = new FileInputStream(PRIVATE_KEY_FILE);
ObjectInputStream oin =
new ObjectInputStream(new BufferedInputStream(in));
try {
BigInteger m = (BigInteger) oin.readObject();
BigInteger e = (BigInteger) oin.readObject();
RSAPrivateKeySpec keySpec = new RSAPrivateKeySpec(m, e);
KeyFactory fact = KeyFactory.getInstance("RSA");
PrivateKey privKey = fact.generatePrivate(keySpec);
return privKey;
} catch (Exception e) {
throw new Exception(e);
} finally {
oin.close();
}
}
public static byte[] PAIR1_Encrypt(byte[] input, PrivateKey privKey) throws Exception
{
byte[] output = null;
Cipher cipher = Cipher.getInstance("RSA");
cipher.init(Cipher.ENCRYPT_MODE, privKey);
output = cipher.doFinal(input);
return output;
}
public static byte[] PAIR1_Decrypt(byte[] input, PublicKey pubKey) throws Exception
{
byte[] output = null;
Cipher cipher = Cipher.getInstance("RSA");
cipher.init(Cipher.DECRYPT_MODE, pubKey);
output = cipher.doFinal(input);
return output;
}
public static byte[] PAIR2_Encrypt(byte[] input, PublicKey pubKey) throws Exception
{
byte[] output = null;
Cipher cipher = Cipher.getInstance("RSA");
cipher.init(Cipher.ENCRYPT_MODE, pubKey);
output = cipher.doFinal(input);
return output;
}
public static byte[] PAIR2_Decrypt(byte[] input, PrivateKey privKey) throws Exception
{
byte[] output = null;
Cipher cipher = Cipher.getInstance("RSA");
cipher.init(Cipher.DECRYPT_MODE, privKey);
output = cipher.doFinal(input);
return output;
}
//=====================================================
public static void main(String[] args) throws Exception
{
usc_RSAKeyPair.PUBLIC_KEY_FILE = "resource/publickey_server";
usc_RSAKeyPair.PRIVATE_KEY_FILE = "resource/privatekey_server";
//usc_RSAKeyPair.generate();
PublicKey pubKey = usc_RSAKeyPair.readPublicKey();
PrivateKey privKey = usc_RSAKeyPair.readPrivateKey();
System.out.println(pubKey);
System.out.println("================");
System.out.println(privKey);
//~~~~~~Encrypt and Decrypt~~~~~~~
System.out.println("--- --- --- --- --- --- --- --- ---");
String s1 = "Anh yêu em";
System.out.println("User input: " + s1);
byte[] s1_b = s1.getBytes(Charset.forName("UTF-8"));
//byte[] s1_b_encrypted = PAIR1_Encrypt(s1_b, privKey);
byte[] s1_b_encrypted = PAIR2_Encrypt(s1_b, pubKey);
String s1_b_encrypted_out = new String(s1_b_encrypted,"UTF-8");
System.out.println("Encrypted output: " + s1_b_encrypted_out);
//byte[] s1_b_decrypted = PAIR1_Decrypt(s1_b_encrypted, pubKey);
byte[] s1_b_decrypted = PAIR2_Decrypt(s1_b_encrypted, privKey);
String s1_b_decrypted_out = new String(s1_b_decrypted,"UTF-8");
System.out.println("Decrypted output: " + s1_b_decrypted_out);
}
}
| Java |
/*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
package MAIN;
/**
*
* @author anhdung
*/
import DAO.Connect;
import DTO.PacketDTO;
import java.security.KeyPairGenerator;
import java.security.KeyPair;
import java.security.PrivateKey;
import java.security.PublicKey;
import java.security.KeyFactory;
import java.security.spec.InvalidKeySpecException;
import java.security.NoSuchAlgorithmException;
import java.security.spec.*;
import java.io.*;
import java.math.BigInteger;
import java.security.InvalidKeyException;
import java.security.Key;
import java.security.SecureRandom;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.crypto.BadPaddingException;
import javax.crypto.Cipher;
import javax.crypto.IllegalBlockSizeException;
import javax.crypto.KeyGenerator;
import javax.crypto.NoSuchPaddingException;
import javax.crypto.SecretKey;
import static DAO.Connect.Connect;
import static DAO.Connect.CloseConnect;
import java.nio.charset.Charset;
import java.security.cert.Certificate;
import java.security.cert.CertificateFactory;
import java.security.cert.X509Certificate;
public class GeneratePublicPrivateKeys {
private Key key;//khong su dung.
public static String secret_key = "default";//Session-key (Secret-key)
public static boolean use_secret_key = false;
public void generateKeys() {
try {
// Get the public/private key pair
KeyPairGenerator keyGen = KeyPairGenerator.getInstance("RSA");
keyGen.initialize(1024);
KeyPair keyPair = keyGen.genKeyPair();
PrivateKey privateKey = keyPair.getPrivate();
PublicKey publicKey = keyPair.getPublic();
// Get the bytes of the public and private keys
byte[] privateKeyBytes = privateKey.getEncoded();
byte[] publicKeyBytes = publicKey.getEncoded();
//converting byte arrays to strings
String privateString = new String(privateKeyBytes);
String publicString = new String(publicKeyBytes);
KeyFactory fact = KeyFactory.getInstance("RSA");
RSAPublicKeySpec pub = fact.getKeySpec(keyPair.getPublic(),RSAPublicKeySpec.class);
RSAPrivateKeySpec priv = fact.getKeySpec(keyPair.getPrivate(),RSAPrivateKeySpec.class);
saveToFile("public.key", pub.getModulus(), pub.getPublicExponent());
saveToFile("private.key", priv.getModulus(), priv.getPrivateExponent());
} catch (InvalidKeySpecException specException) {
System.out.println("Exception");
System.out.println("Invalid Key Spec Exception");
} catch (NoSuchAlgorithmException e) {
System.out.println("Exception");
System.out.println("No such algorithm: " + "RSA");
}
catch(IOException e) {
System.out.println("IO exception");
}
}
private void generateSessionKey() throws NoSuchAlgorithmException {
KeyGenerator generator;
generator = KeyGenerator.getInstance("DES");
generator.init(new SecureRandom());
key = generator.generateKey();
}
private byte[] encrypt(byte[] data) throws IllegalBlockSizeException,
BadPaddingException, NoSuchAlgorithmException,
NoSuchPaddingException, InvalidKeyException,
UnsupportedEncodingException {
// Get a cipher object.
Cipher cipher = Cipher.getInstance("DES/ECB/PKCS5Padding");
cipher.init(Cipher.ENCRYPT_MODE, key);
// encrypt using the cypher
byte[] raw = cipher.doFinal(data);
return raw;
}
private byte[] decrypt(byte[] data) throws InvalidKeyException,
NoSuchAlgorithmException, NoSuchPaddingException,
IllegalBlockSizeException, BadPaddingException, IOException {
// Get a cipher object.
Cipher cipher = Cipher.getInstance("DES/ECB/PKCS5Padding");
cipher.init(Cipher.DECRYPT_MODE, key);
//decode the message
byte[] result = cipher.doFinal(data);
return result;
}
private void saveToFile(String fileName,
BigInteger mod, BigInteger exp) throws IOException {
try (ObjectOutputStream oout = new ObjectOutputStream(
new BufferedOutputStream(new FileOutputStream(fileName)))) {
oout.writeObject(mod);
oout.writeObject(exp);
} catch (Exception e) {
throw new IOException("Unexpected error", e);
}
}
private PublicKey readPubKeyFromFile(String keyFileName) throws IOException {
FileInputStream in = new FileInputStream(keyFileName);
ObjectInputStream oin =
new ObjectInputStream(new BufferedInputStream(in));
try {
BigInteger m = (BigInteger) oin.readObject();
BigInteger e = (BigInteger) oin.readObject();
RSAPublicKeySpec keySpec = new RSAPublicKeySpec(m, e);
KeyFactory fact = KeyFactory.getInstance("RSA");
PublicKey pubKey = fact.generatePublic(keySpec);
return pubKey;
} catch (Exception e) {
throw new RuntimeException("Spurious serialisation error", e);
} finally {
oin.close();
}
}
/* THis function implements the reading of the private key from the keyFileName*/
private PrivateKey readPriKeyFromFile(String keyFileName) throws IOException {
FileInputStream in = new FileInputStream(keyFileName);
ObjectInputStream oin =
new ObjectInputStream(new BufferedInputStream(in));
try {
BigInteger m = (BigInteger) oin.readObject();
BigInteger e = (BigInteger) oin.readObject();
RSAPrivateKeySpec keySpec = new RSAPrivateKeySpec(m, e);
KeyFactory fact = KeyFactory.getInstance("RSA");
PrivateKey priKey = fact.generatePrivate(keySpec);
return priKey;
} catch (Exception e) {
throw new RuntimeException("Spurious serialisation error", e);
} finally {
oin.close();
}
}
// public static byte[] encryptKey(byte[] data) {
// try {
// PublicKey pubKey = readPubKeyFromFile("public.key");
// Cipher cipher = Cipher.getInstance("RSA/ECB/PKCS1Padding");
// cipher.init(Cipher.ENCRYPT_MODE, pubKey);
// byte[] cipherData = cipher.doFinal(data);
// return cipherData;
// } catch(Exception e) { e.printStackTrace();return null;}
//
// }
// /*Decrypting here*/
// public static byte[] decryptKey(byte[] data) {
// try {
// PrivateKey priKey = readPriKeyFromFile("private.key");
// Cipher dcipher = Cipher.getInstance("RSA/ECB/PKCS1Padding");
// dcipher.init(Cipher.DECRYPT_MODE, priKey);
// byte[] cipherData = dcipher.doFinal(data);
// return cipherData;
// } catch(Exception e) { e.printStackTrace();return null;}
//
// }
public boolean sendPubKey() {
try {
PublicKey pubKey = readPubKeyFromFile("public.key");
byte[] pubKeyData = pubKey.getEncoded();
DTO.PacketDTO pkdto=new DTO.PacketDTO();
pkdto.setData(pubKeyData);
Connect.sendData(pkdto);
return true;
} catch (IOException ex) {
Logger.getLogger(GeneratePublicPrivateKeys.class.getName()).log(Level.SEVERE, null, ex);
}
return false;
}
public boolean receivePubKey() {
Object data = Connect.receiveData();
byte[] command = new byte[4];
try {
ObjectInputStream objectInput = new ObjectInputStream((ObjectInputStream) data);
objectInput.read(command);
BigInteger m = (BigInteger) objectInput.readObject();
BigInteger e = (BigInteger) objectInput.readObject();
RSAPublicKeySpec keySpec = new RSAPublicKeySpec(m, e);
KeyFactory fact = KeyFactory.getInstance("RSA");
PublicKey pubKey = fact.generatePublic(keySpec);
saveToFile("public.server.key", m, e);
return true;
} catch (IOException ex) {
Logger.getLogger(GeneratePublicPrivateKeys.class.getName()).log(Level.SEVERE, null, ex);
} catch (ClassNotFoundException ex) {
Logger.getLogger(GeneratePublicPrivateKeys.class.getName()).log(Level.SEVERE, null, ex);
} catch (NoSuchAlgorithmException ex) {
Logger.getLogger(GeneratePublicPrivateKeys.class.getName()).log(Level.SEVERE, null, ex);
} catch (InvalidKeySpecException ex) {
Logger.getLogger(GeneratePublicPrivateKeys.class.getName()).log(Level.SEVERE, null, ex);
}
return false;
}
public boolean exchangeKey(PublicKey server_pubkey) {
try {
generateSessionKey();
PrivateKey priKeyClient = readPriKeyFromFile("private.key");
byte[] priKeyData = priKeyClient.getEncoded();
//PublicKey pubKeyServer = readPubKeyFromFile("public.server.key");
PublicKey pubKeyServer = server_pubkey;
byte[] pubKeyData = pubKeyServer.getEncoded();
//encypt by private key of client
Cipher cipherPri = Cipher.getInstance("RSA");//--"RSA/ECB/PKSC1Padding"
cipherPri.init(Cipher.ENCRYPT_MODE, priKeyClient);
byte[] cipherDataPri = cipherPri.doFinal(key.getEncoded());
System.out.println("input length? " + cipherDataPri.length);
//encrypt by public key of server
Cipher cipherPub = Cipher.getInstance("RSA");//--"RSA/ECB/PKSC1Padding"
cipherPub.init(Cipher.ENCRYPT_MODE, pubKeyServer);
byte[] cipherDataPub = cipherPub.doFinal(cipherDataPri);
DTO.PacketDTO pkdto=new DTO.PacketDTO();
pkdto.setData(cipherDataPub);
pkdto.setCommand(105);//Dung moi them vo
Connect.sendData(pkdto);
return true;
}
catch (Exception e) {
e.printStackTrace();
return false;
}
}
public static void Certificate_And_SecretKey() throws Exception
{
//========Phan Chung Thuc=======
Connect();//gui-nhan lan 1: Certificate va Public Key
//**Tao public va private key
GeneratePublicPrivateKeys gk = new GeneratePublicPrivateKeys();
gk.generateKeys();
PrivateKey privk = gk.readPriKeyFromFile("private.key");
PublicKey pubk = gk.readPubKeyFromFile("public.key");
//System.out.println(privk);
//System.out.println(pubk);
//**Tao Cert tuong ung voi public key
usc_Certificate.privKey = privk;
usc_Certificate.pubKey = pubk;
usc_Certificate.createCertificate("GUEST.cer");
//**Gui GUEST.cer cho Server
FileInputStream is = new FileInputStream(new File("GUEST.cer"));
CertificateFactory cf = CertificateFactory.getInstance("X.509");
Certificate guest_cer = cf.generateCertificate(is);
DTO.PacketDTO pdto = new PacketDTO();
pdto.setCommand(101);//ti nua, ben Server nhan so 101 thi biet la nhan GUEST.cer
pdto.setData(guest_cer);
Connect.sendData(pdto);
//Nhan phan hoi tu Server
Object obj = Connect.receiveData();
pdto = new PacketDTO();
pdto = (PacketDTO)obj;
if(pdto.getFlag()==false)//Neu Server thay GUEST.cer khong hop le
{
System.out.println("Server says: " + pdto.getData().toString());
CloseConnect();
return;
//Close all
}
//**Nhan SERVER.cer tu Server
System.out.println("== == == == == == == == == ==");
System.out.println("Server has sent you SERVER.cer ");
Certificate server_cer = (Certificate)pdto.getData();
boolean f1 = usc_Certificate.validateCertificate(server_cer);
if(f1==false)
{
System.out.println("You have had SERVER.cer. It is INVALID.");
//Gui canh bao toi Server va ngat ket noi.
pdto = new DTO.PacketDTO();
pdto.setFlag(false);
pdto.setCommand(102);///ti nua, ben Server nhan so 102 thi biet la SERVER.cer khong hop le
pdto.setData("Invalid Certificate.");
Connect.sendData(pdto);
CloseConnect();
return;
//Close all
}
System.out.println("You have had SERVER.cer. It is VALID.");
//Luu SERVER.cer
FileOutputStream os = new FileOutputStream("SERVER.cer");
os.write(server_cer.getEncoded());
os.close();
System.out.println("== == == == == == == == == ==");
PublicKey server_pubkey = server_cer.getPublicKey();
//
//Kiem tra Public-Private Key cua Server
String plaintext_C = usc_sessionkey_mac.randomString(50);
String digest_1 = Hash_SHA256.sha256(plaintext_C);
byte[] encrypted_digest_1 = usc_RSAKeyPair.PAIR2_Encrypt(
digest_1.getBytes(Charset.forName("UTF-8")), server_pubkey);
byte[][] data_1_C = new byte[2][];
data_1_C[0] = plaintext_C.getBytes(Charset.forName("UTF-8"));
data_1_C[1] = encrypted_digest_1;
//**Gui chung cho Server
pdto = new PacketDTO();
pdto.setCommand(103);//lenh 103: Kiem Tra Public-Private key, yeu cau Secret-key
pdto.setData((Object)data_1_C);
System.out.println("You have sent to Server a plaintext: " + plaintext_C);
System.out.println("And it's SHA-256 digest: " + digest_1);
System.out.println("-->Use Server PUBLIC KEY to encrypt.");
Connect();//gui-nhan lan 2: {plaintext + encrypted(hash)} .
Connect.sendData(pdto);
System.out.println("-----");
obj = new Object();
obj = Connect.receiveData();
pdto = new PacketDTO();
pdto = (PacketDTO)obj;
if(pdto.getFlag()==false)
{
System.out.println("Server says: " + pdto.getData());
CloseConnect();
return;
}
//Kiem tra Public-Private Key cua Client, kem nhan luon secret-key (session-key)
byte[][] data_2_S = (byte[][])pdto.getData();
byte[] encrypted_plaintext_S = data_2_S[0];
byte[] decrypted_plaintext_S = usc_RSAKeyPair.PAIR2_Decrypt(encrypted_plaintext_S, usc_Certificate.privKey);
//String plaintext_S = new String(data_2_S[0],"UTF-8");
String plaintext_S = new String(decrypted_plaintext_S,"UTF-8");
System.out.println("Server has sent a plaintext: " + plaintext_S);
byte[] encrypted_digest_2 = data_2_S[1];
byte[] decrypted_digest_2 = usc_RSAKeyPair.PAIR2_Decrypt(encrypted_digest_2, usc_Certificate.privKey);
System.out.println("-->Use Client PRIVATE KEY to decrypt.");
String digest_2 = new String(decrypted_digest_2,"UTF-8");
System.out.println("With SHA-256 Digest: " + digest_2);
System.out.print("Comparing SHA-256 Digest: ");
String hash_result = Hash_SHA256.sha256(plaintext_S);
if(hash_result.equals(digest_2)==false)
{
Connect();
System.out.println("NOT CORRECT! That is not my server. Disconect...");
pdto = new PacketDTO();
pdto.setCommand(104);
pdto.setData("Server Key Pair is not valid. Disconect!");
Connect.sendData(pdto);
CloseConnect();
return;
}
System.out.println("CORRECT! That is my SERVER.");
//~~~~~SECRET-KEY
secret_key = usc_sessionkey_mac.xorMessage(plaintext_S, plaintext_C) ;
System.out.println("SECRET KEY: " + secret_key);
use_secret_key=true;
//Bao lai cho Server da nhan duoc Secret key
Connect();
pdto = new PacketDTO();
pdto.setCommand(105);
Connect.sendData(pdto);
System.out.println();
System.out.println("-> Send reponse to Server about receiving Secret Key.");
System.out.println("Now. use_secret_key is ON.");
System.out.println("== == == == == == == == == ==");
CloseConnect();
/*
//Su dung exchangeKey that bai, vi input.length=128 trong khi gioi han input RSA la 117
GeneratePublicPrivateKeys g = new GeneratePublicPrivateKeys();
g.exchangeKey(server_pubkey);
*/
}
public static void main(String[] args) throws Exception
{
//**Trao doi Certificate, tao Secret Key (Session Key)
//Certificate_And_SecretKey();
/*
//**Su dung Secret Key de trao doi, co kem MAC = HASH{plaintext, secret key}
//System.out.println("secret_key: " + secret_key);
String data = "Lenh dat ve.";
byte[] macBytes = null;
macBytes = usc_sessionkey_mac.generateMAC(data, secret_key);
String MAC = new String(macBytes,"UTF-8");
byte[] macBytesAfter = MAC.getBytes(Charset.forName("UTF-8"));
if(macBytesAfter.equals(macBytes)==true)
{
System.out.println("2 MAC is equal.");
}
else
{
System.out.println("2 MAC is not equal. You shoudn't use String for MAC");
}
DTO.PacketDTO pdto = new PacketDTO();
pdto.setData(null);
pdto.setCommand(106);//ti nua, ben Server nhan so 106 thi biet la test Secret-key va MAC.
Connect();
Connect.sendData(pdto);
*/
/*
//Test Secret-key: Command 106
Connect();
String s = "I am talent.";
PacketDTO pdto = new PacketDTO();
pdto.setCommand(106);
pdto.setData(s);
Connect.sendData(pdto);
System.out.println("Send: " + s);
Object reobj = Connect.receiveData();
pdto = (PacketDTO)reobj;
String s2 = pdto.getData().toString();
System.out.println("Receive: " + s2);
CloseConnect();
*/
//System.out.println("END.");
}
}
| Java |
package MAIN;
import java.io.IOException;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import static java.lang.String.format;
import java.security.MessageDigest;
import java.math.BigInteger;
public class Hash_SHA256 {
public static String sha256(String text) throws Exception
{
MessageDigest md = MessageDigest.getInstance("SHA-256");
md.update(text.getBytes("UTF8"), 0, text.length());
String s = convertToHex(md.digest());
//System.out.println(s);
return s;
}
public static String sha1(String text) throws Exception
{
MessageDigest md = MessageDigest.getInstance("SHA-1");
md.update(text.getBytes("UTF8"), 0, text.length());
String s = convertToHex(md.digest());
//System.out.println(s);
return s;
}
private static String convertToHex(byte[] data)
{
StringBuffer buf = new StringBuffer();
for (int i = 0; i < data.length; i++) {
int halfbyte = (data[i] >>> 4) & 0x0F;
int two_halfs = 0;
do {
if ((0 <= halfbyte) && (halfbyte <= 9))
buf.append((char) ('0' + halfbyte));
else
buf.append((char) ('a' + (halfbyte - 10)));
halfbyte = data[i] & 0x0F;
} while (two_halfs++ < 1);
}
return buf.toString();
}
public static void main(String[] args) throws Exception
{
//Test SHA-256
String input = "Anh la Dung";
Hash_SHA256.sha256(input);
}
}
| Java |
/*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
package DAO;
import static DAO.Connect.CloseConnect;
import static DAO.Connect.Connect;
import static DAO.Connect.receiveData;
import static DAO.Connect.sendData;
/**
*
* @author Anonymous
*/
public class DatVeDAO {
//Hàm đặt vé
public static boolean ThemDatVe(DTO.DatVeDTO dvdto){
if(Connect())//Nếu kết nối được với server và mở kết nối
{
//gán giá trị cho pkdtos gói tin chuyển đi
DTO.PacketDTO pkdtos=new DTO.PacketDTO();
pkdtos.setData(dvdto);//gán thông tin đặt vé
pkdtos.setCommand(2);//gán lệnh
sendData(pkdtos);//chuyển dữ liệu đến server
DTO.PacketDTO pkdtor=new DTO.PacketDTO();
pkdtor=(DTO.PacketDTO)receiveData();////gán giá trị cho pkdtor gói tin nhận về
CloseConnect();//Đóng kết nối
return pkdtor.getFlag();//Trả về thành công hoặc thất bại tùy vào flag trong gói tin
}
return false;
}
} | Java |
/*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
package DAO;
import static DAO.Connect.CloseConnect;
import static DAO.Connect.Connect;
import static DAO.Connect.receiveData;
import static DAO.Connect.sendData;
import java.util.ArrayList;
import java.util.List;
/**
*
* @author Anonymous
*/
public class ChuyenXeDAO {
//Hàm lấy danh sách chuyến xe từ server về
public static List<DTO.ChuyenXeDTO> dsChuyenXe(){
if(Connect())//Nếu kết nối thành công và mở kết nối
{
//Gán giá trị vào pkdtos để chuẩn bị gửi cho server
DTO.PacketDTO pkdtos=new DTO.PacketDTO();
pkdtos.setCommand(1);//gán lệnh ở đây không cần gán giá trị cho pkdtos
sendData(pkdtos);
//Gán giá trị lấy được từ server vào pkdtor
DTO.PacketDTO pkdtor=new DTO.PacketDTO();
pkdtor=(DTO.PacketDTO)receiveData();//lấy giá trị từ server
//Đưa dữ liệu từ pkdtor vào biến lưu danh sách chuyến xe
List<DTO.ChuyenXeDTO> Lcxdto= new ArrayList<DTO.ChuyenXeDTO>();
Lcxdto=(ArrayList<DTO.ChuyenXeDTO>)pkdtor.getData();
CloseConnect();//Đóng kết nối
return Lcxdto;
}
return null;
}
}
| Java |
package DAO;
import MAIN.GeneratePublicPrivateKeys;
import MAIN.usc_Certificate;
import static MAIN.usc_sessionkey_mac.Decrypt;
import static MAIN.usc_sessionkey_mac.Encrypt;
import java.io.IOException;
import java.io.InputStream;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.io.OutputStream;
import java.net.Socket;
import java.net.UnknownHostException;
import java.util.logging.Level;
import java.util.logging.Logger;
import java.util.prefs.Preferences;
/*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
/**
*
* @author Anonymous
*/
public class Connect {
public static java.sql.Connection con;
//Các giá trị prefs
protected static final String PREF_TENSV = "TENSV";
protected static final String PREF_PORT = "PORT";
protected static String TenSV ; //địa chỉ server
protected static int portS ;//port server
protected static Socket echoSocket;
//Hàm kết nối thử đến server đầu vào là tên server và port (dùng khi kiểm tra kết nối thử và lưu cấu hình)
public static boolean ConnectT(String tTenSV,int tPort)
{
try
{
echoSocket = new Socket(tTenSV, tPort);
echoSocket.close();
return true;
} catch (UnknownHostException ex) {
Logger.getLogger(Connect.class.getName()).log(Level.SEVERE, null, ex);
} catch (IOException ex) {
Logger.getLogger(Connect.class.getName()).log(Level.SEVERE, null, ex);
}
return false;
}
//Hàm kết nối thử đến server dùng thông tin server đã được lưu
public static boolean tConnect()
{
Preferences prefs = Preferences.userNodeForPackage(Connect.class);
// prefs.put(PREF_TENSV, "");
//prefs.put(PREF_PORT, "");
TenSV = prefs.get(PREF_TENSV, "localhost");
portS = prefs.getInt(PREF_PORT, 1234);
try
{
echoSocket = new Socket(TenSV, portS);
echoSocket.close();
return true;
} catch (UnknownHostException ex) {
Logger.getLogger(Connect.class.getName()).log(Level.SEVERE, null, ex);
} catch (IOException ex) {
Logger.getLogger(Connect.class.getName()).log(Level.SEVERE, null, ex);
}
return false;
}
//Hàm mở kết nối đến server để trao đổi thông tin
public static boolean Connect()//khi su dung can dung ham closeconnect de dong ket noi sau khi giao tiep xong
{
Preferences prefs = Preferences.userNodeForPackage(Connect.class);
// prefs.put(PREF_TENSV, "");
//prefs.put(PREF_PORT, "");
TenSV = prefs.get(PREF_TENSV, "localhost");
portS = prefs.getInt(PREF_PORT, 1234);
try
{
echoSocket = new Socket(TenSV, portS);
return true;
} catch (UnknownHostException ex) {
Logger.getLogger(Connect.class.getName()).log(Level.SEVERE, null, ex);
} catch (IOException ex) {
Logger.getLogger(Connect.class.getName()).log(Level.SEVERE, null, ex);
}
return false;
}
//Hàm đóng kết nối
public static boolean CloseConnect()
{
try {
echoSocket.close();
return true;
} catch (IOException ex) {
Logger.getLogger(Connect.class.getName()).log(Level.SEVERE, null, ex);
}
return false;
}
//Hàm chuyển dữ liệu đến server đầu vào là pkdto
public static boolean sendData(DTO.PacketDTO pkdto)
{
try {
//
String secret_key = MAIN.GeneratePublicPrivateKeys.secret_key;
String secret_key2 = "default";
boolean use_secret_key = MAIN.GeneratePublicPrivateKeys.use_secret_key;
if(use_secret_key==true)
{
secret_key2 = secret_key;
//System.out.println("Su dung secret_key khac default.");
}
byte[] encrypt = Encrypt(secret_key2, pkdto);
OutputStream os = echoSocket.getOutputStream();
ObjectOutputStream oos = new ObjectOutputStream(os);
oos.writeObject(encrypt);
//
/*
OutputStream os = echoSocket.getOutputStream();
ObjectOutputStream oos = new ObjectOutputStream(os);
oos.writeObject(pkdto);
*/
return true;
} catch (IOException ex) {
Logger.getLogger(Connect.class.getName()).log(Level.SEVERE, null, ex);
} catch (Exception ex) {
Logger.getLogger(Connect.class.getName()).log(Level.SEVERE, null, ex);
}
return false;
}
//Hàm nhận dữ liệu từ server đầu ra là pkdto tùy vào đối tượng server gửi đến mặc định là DTO.PacketDTO
public static Object receiveData()
{
try {
String secret_key = MAIN.GeneratePublicPrivateKeys.secret_key;
InputStream is = echoSocket.getInputStream();
ObjectInputStream ois = new ObjectInputStream(is);
Object obj = ois.readObject();
byte[] encrypt = (byte[])obj;
Object pkdto = Decrypt(secret_key, encrypt);
/*
InputStream is = echoSocket.getInputStream();
ObjectInputStream ois = new ObjectInputStream(is);
Object pkdto=ois.readObject();
*/
return pkdto;
} catch (IOException | ClassNotFoundException ex) {
Logger.getLogger(Connect.class.getName()).log(Level.SEVERE, null, ex);
} catch (Exception ex) {
Logger.getLogger(Connect.class.getName()).log(Level.SEVERE, null, ex);
}
return null;
}
}
| Java |
package kr.ac.mlb.vo;
public class ContentVo {
private int id;
private String time;
private String content;
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getTime() {
return time;
}
public void setTime(String time) {
this.time = time;
}
public String getContent() {
return content;
}
public void setContent(String content) {
this.content = content;
}
}
| Java |
package kr.ac.mlb.mvc;
import java.net.URLEncoder;
import javax.servlet.RequestDispatcher;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
public class HttpUtil {
public static void forward(HttpServletRequest request, HttpServletResponse response, String path ) {
try{
String mobile = request.getParameter("mobile");
if("1".equals(mobile)){
path = path.replace(".jsp", "_m.jsp");
}
RequestDispatcher dispatcher = request.getRequestDispatcher(path);
dispatcher.forward(request, response);
} catch( Exception ex ) {
throw new RuntimeException( "forward Exception : " + ex);
}
}
public static void redirect(
HttpServletRequest request,
HttpServletResponse response,
String path ){
try{
String mobile = request.getParameter("mobile");
if( "1".equals(mobile) ){
path = path + ( path.contains("?") ? "&mobile=1" : "?mobile=1" );
}
response.sendRedirect( path );
} catch( Exception ex ) {
throw new RuntimeException("redirect 오류 : " + ex);
}
}
public static String encoding( String url, String charset ){
try{
url = URLEncoder.encode( url, charset );
}catch(Exception ex){
throw new RuntimeException("URL 인코딩 시 오류 : " + ex);
}
return url;
}
}
| Java |
package kr.ac.mlb.mvc;
import java.io.IOException;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
public abstract class Action {
public abstract void execute(HttpServletRequest request, HttpServletResponse response) throws IOException, ServletException;
}
| Java |
package kr.ac.mlb.servlet;
import java.io.IOException;
import java.io.PrintWriter;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import kr.ac.mlb.action.MainAction;
import kr.ac.mlb.action.ListAction;
import kr.ac.mlb.action.WriteAction;
import kr.ac.mlb.mvc.Action;
@WebServlet("/list")
public class ListServlet extends HttpServlet {
private static final long serialVersionUID = 1L;
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
doPost(request, response);
}
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
String a = request.getParameter("a");
response.setContentType("text/html; charset=utf-8");
PrintWriter out = response.getWriter();
Action action = null;
if("list".equals(a)){
action = new ListAction();
}else{
action = new ListAction();
}
action.execute(request, response);
out.print(request.getAttribute("json"));
}
} | Java |
package kr.ac.mlb.servlet;
import java.io.IOException;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import kr.ac.mlb.action.MainAction;
import kr.ac.mlb.action.WriteAction;
import kr.ac.mlb.action.ListAction;
import kr.ac.mlb.mvc.Action;
@WebServlet("/write")
public class WriteServlet extends HttpServlet {
private static final long serialVersionUID = 1L;
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
// TODO Auto-generated method stub
doPost(request, response);
}
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
// TODO Auto-generated method stub
String a = request.getParameter("a");
Action action = null;
if("add".equals(a)){
action = new WriteAction();
// System.out.println("addaction");
}else{
action = new MainAction();
}
action.execute(request, response);
}
}
| Java |
package kr.ac.mlb.servlet;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.List;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import kr.ac.mlb.dao.ListDao;
import kr.ac.mlb.vo.ContentVo;
import org.json.simple.*;
@WebServlet("/JSon")
public class JsonServlet extends HttpServlet {
private static final long serialVersionUID = 1L;
protected void doGet(HttpServletRequest request,
HttpServletResponse response) throws ServletException, IOException {
doPost(request, response);
}
protected void doPost(HttpServletRequest request,
HttpServletResponse response) throws ServletException, IOException {
ListDao dao = new ListDao();
List<ContentVo> list = dao.getList();
int length = list.size();
String jsonStr = "";
response.setContentType("text/html; charset=utf-8");
jsonStr += "{";
jsonStr += "\"data\":[";
for (int i = 0; i < length; i++) {
jsonStr += "{";
jsonStr += "\"content\":\"" + list.get(i).getContent() + "\",";
jsonStr += "\"time\":\"" + list.get(i).getTime() + "\"";
jsonStr += "}";
if (i < length - 1)
jsonStr += ",";
}
jsonStr += "]";
jsonStr += "}";
PrintWriter out = response.getWriter();
out.println(jsonStr);
}
}
| Java |
package kr.ac.mlb.servlet;
import java.io.IOException;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import kr.ac.mlb.action.MainAction;
import kr.ac.mlb.mvc.Action;
@WebServlet("/main")
public class MainServlet extends HttpServlet {
private static final long serialVersionUID = 1L;
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
doPost(request, response);
}
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
String a = request.getParameter("a");
Action action = null;
if("main".equals(a)){
action = new MainAction();
}else{
action = new MainAction();
}
action.execute(request, response);
}
}
| Java |
package kr.ac.mlb.dao;
import java.sql.*;
import java.io.*;
import java.util.*;
import kr.ac.mlb.vo.ContentVo;
public class ListDao {
//SOCCER 관심사 테이블에 데이터 추가
public void Soccer(String str,String str2)
{
Connection conn = null;
Statement stmt= null;
String dburl = "jdbc:mysql://localhost:3306/test";
String id = "root";
String pw = "123456789";
try{
Class.forName("com.mysql.jdbc.Driver");
}
catch(ClassNotFoundException e){
System.out.println("Driver Failed");
System.out.println(e.toString());
return;
}
try{
conn = DriverManager.getConnection(dburl, id, pw);
// System.out.println("Connection Success!");
}
catch(Exception e){
System.out.println("Connection Failed");
System.out.println(e.toString());
return;
}
try {
stmt = conn.createStatement();
String sql ="insert into soccer (content,time) values ('"+str+"','"+str2+"')";
//ResultSet rs = stmt.executeQuery(sql);
stmt.executeUpdate(sql);
//rs.close();
}catch (Exception ex){
ex.printStackTrace();
}
}
public void insert(ContentVo vo){
Connection conn = null;
Statement stmt= null;
String dburl = "jdbc:mysql://localhost:3306/test";
String id = "root";
String pw = "123456789";
try{
Class.forName("com.mysql.jdbc.Driver");
}
catch(ClassNotFoundException e){
System.out.println("Driver Failed");
System.out.println(e.toString());
return;
}
try{
conn = DriverManager.getConnection(dburl, id, pw);
// System.out.println("Connection Success!");
}
catch(Exception e){
System.out.println("Connection Failed");
System.out.println(e.toString());
return;
}
try {
stmt = conn.createStatement();
String sql = "insert into content (content, time) values ('"+vo.getContent()+"', '"+vo.getTime()+"')";
//ResultSet rs = stmt.executeQuery(sql);
stmt.executeUpdate(sql);
//rs.close();
}catch (Exception ex){
ex.printStackTrace();
}
}
public List<ContentVo> getList(){
List<ContentVo> list = new ArrayList<ContentVo>();
Connection conn = null;
Statement stmt= null;
String dburl = "jdbc:mysql://localhost:3306/test";
String id = "root";
String pw = "123456789";
try{
Class.forName("com.mysql.jdbc.Driver");
}
catch(ClassNotFoundException e){
System.out.println("getList Driver Failed");
System.out.println(e.toString());
return null;
}
try{
conn = DriverManager.getConnection(dburl, id, pw);
// System.out.println("Connection Success!");
}
catch(Exception e){
System.out.println("Connection Failed");
System.out.println(e.toString());
return null;
}
try {
stmt = conn.createStatement();
String sql = "select content, time from content order by con_id desc";
ResultSet rs = stmt.executeQuery(sql);
while(rs.next()){
ContentVo vo = new ContentVo();
vo.setContent(rs.getString(1));
vo.setTime(rs.getString(2));
list.add(vo);
}
rs.close();
}catch (Exception ex){
ex.printStackTrace();
}
return list;
}
}
| Java |
package kr.ac.mlb.action;
import java.sql.Statement;
import java.util.List;
//import javax.swing.text.AbstractDocument.Content;
import kr.ac.mlb.dao.ListDao;
import kr.ac.mlb.vo.ContentVo;
public class StringParser {
static int soccer = 0; // 관심사 축구
static int something = 0; // 관심사 기타
String sql;
Statement stmt = null;
ContentVo vo = new ContentVo();
public void search(String str,String str2)
{
String orgin = str;//원본 문장 저장
//System.out.println(orgin);
String result = str.replaceAll("\\p{Z}", "");//축구 단어 찾기 위해 문장 다 붙임
//System.out.println(result);
ListDao insert = new ListDao();
if (result.matches(".*축구.*")) {//붙인문장에 축구 단어 있는지 검색 있으면
soccer++;
insert.Soccer(orgin,str2);//원본문장과 시간을 SOCCER함수로 넘김
} else {
something++;
}
//System.out.println("축구: " + soccer);
//System.out.println("기타: " + something);
}
public void proceed() {
String str,str2;
ListDao dao = new ListDao();
List<ContentVo> list = dao.getList();
int length = list.size();
for (int i = 0; i < length; i++) {
str = list.get(i).getContent();
str2 = list.get(i).getTime();
//System.out.println(str);
search(str,str2);
}
}
}
| Java |
package kr.ac.mlb.action;
import java.io.IOException;
import java.util.List;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import kr.ac.mlb.dao.ListDao;
import kr.ac.mlb.mvc.Action;
import kr.ac.mlb.mvc.HttpUtil;
import kr.ac.mlb.vo.ContentVo;
public class MainAction extends Action {
@Override
public void execute(HttpServletRequest request, HttpServletResponse response)
throws IOException, ServletException {
// TODO Auto-generated method stub
//리스트가져오기
ListDao dao = new ListDao();
List<ContentVo> list = dao.getList();
//리쿼스트에 list 객체 저장
request.setAttribute("list", list);
HttpUtil.forward(request, response, "/views/main.jsp");
}
}
| Java |
package kr.ac.mlb.action;
import java.io.IOException;
import java.util.List;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import kr.ac.mlb.dao.ListDao;
import kr.ac.mlb.mvc.Action;
import kr.ac.mlb.mvc.HttpUtil;
import kr.ac.mlb.vo.ContentVo;
public class ListAction extends Action {
@Override
public void execute(HttpServletRequest request, HttpServletResponse response)
throws IOException, ServletException {
// TODO Auto-generated method stub
String jsonStr = "";
//리스트가져오기
ListDao dao = new ListDao();
List<ContentVo> list = dao.getList();
int length = list.size();
System.out.println(length);
jsonStr += "{";
jsonStr += "\"AnnoymousSNS\":[";
for(int i = 0; i < length; i++){
jsonStr += "{";
jsonStr += "\"content\":\"" + list.get(i).getContent() + "\",";
jsonStr += "\"time\":\"" + list.get(i).getTime() + "\"";
jsonStr += "}";
if(i < length - 1) jsonStr += ",";
}
jsonStr += "]";
jsonStr += "}";
// System.out.println(jsonStr);
request.setAttribute("json", jsonStr);
}
}
| Java |
package kr.ac.mlb.action;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import kr.ac.mlb.dao.ListDao;
import kr.ac.mlb.mvc.Action;
import kr.ac.mlb.mvc.HttpUtil;
import kr.ac.mlb.vo.ContentVo;
public class WriteAction extends Action {
@Override
public void execute(HttpServletRequest request, HttpServletResponse response)
throws IOException, ServletException {
// TODO Auto-generated method stub
String content = request.getParameter("content");
System.out.println(content);
// content = new String(content.getBytes("8859_1"), "UTF-8");//한글깨짐없앰
System.out.println("content : "+content);
String time;
ContentVo vo = new ContentVo();
Calendar calendar = Calendar.getInstance();
SimpleDateFormat dataFormat = new SimpleDateFormat("yy.MM.dd HH:mm:ss");
time = dataFormat.format(calendar.getTime());
vo.setContent(content);
vo.setTime(time);
////////StringParser 객체 생성/////////
StringParser sp = new StringParser();
sp.proceed();
///////////////////////////////////
ListDao dao = new ListDao();
dao.insert(vo);
// HttpUtil.redirect(request, response, "/mediaLogBook/main");
}
}
| Java |
package ac.kr.ml.vo;
public class ReplyVo {
private int re_id;
private int countent_id;
private String commend;
public int getRe_id() {
return re_id;
}
public void setRe_id(int re_id) {
this.re_id = re_id;
}
public int getCountent_id() {
return countent_id;
}
public void setCountent_id(int countent_id) {
this.countent_id = countent_id;
}
public String getCommend() {
return commend;
}
public void setCommend(String commend) {
this.commend = commend;
}
}
| Java |
package ac.kr.ml.vo;
public class ContentVo {
private int con_id;
private String time;
private String content;
private int good;
private int bad;
private int reply_cont;
//addressinfo
private int empID;
private int deptID;
private String deptName;
private String posName;
private String userName;
private String email;
private String hp;
//Friend db
private int fmpID;
private String fmpList;
public void setfmpList(String fmpList)
{
this.fmpList=fmpList;
}
public String getfmpList()
{
return fmpList;
}
public int getfmpID()
{
return fmpID;
}
public void setfmpID(int empID)
{
this.fmpID=empID;
}
//Freind db
//adrressinfo db
public int getempID()
{
return empID;
}
public void setempID(int empID)
{
this.empID=empID;
}
public int getdeptID()
{
return deptID;
}
public void setdeptID(int deptID)
{
this.deptID=deptID;
}
public String getdeptName()
{
return deptName;
}
public void setdeptName(String deptName)
{
this.deptName=deptName;
}
public String getposName()
{
return posName;
}
public void setposName(String posName)
{
this.posName=posName;
}
public String getuserName()
{
return userName;
}
public void setuserName(String userName)
{
this.userName=userName;
}
public String getemail()
{
return email;
}
public void setemail(String email)
{
this.email=email;
}
public String gethp()
{
return hp;
}
public void sethp(String hp)
{
this.hp=hp;
}
//addressinfo db
public int getCon_id() {
return con_id;
}
public void setCon_id(int con_id) {
this.con_id = con_id;
}
public String getTime() {
return time;
}
public void setTime(String time) {
this.time = time;
}
public String getContent() {
return content;
}
public void setContent(String content) {
this.content = content;
}
public int getGood() {
return good;
}
public void setGood(int good) {
this.good = good;
}
public int getBad() {
return bad;
}
public void setBad(int bad) {
this.bad = bad;
}
public int getReply_cont() {
return reply_cont;
}
public void setReply_cont(int reply_cont) {
this.reply_cont = reply_cont;
}
}
| Java |
package kr.ac.ml.mvc;
import java.net.URLEncoder;
import javax.servlet.RequestDispatcher;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
public class HttpUtil {
public static void forward(HttpServletRequest request, HttpServletResponse response, String path ) {
try{
String mobile = request.getParameter("mobile");
if("1".equals(mobile)){
path = path.replace(".jsp", "_m.jsp");
}
System.out.println( path );
RequestDispatcher dispatcher = request.getRequestDispatcher(path);
dispatcher.forward(request, response);
} catch( Exception ex ) {
throw new RuntimeException( "forward Exception : " + ex);
}
}
public static void redirect(
HttpServletRequest request,
HttpServletResponse response,
String path ){
try{
String mobile = request.getParameter("mobile");
if( "1".equals(mobile) ){
path = path + ( path.contains("?") ? "&mobile=1" : "?mobile=1" );
}
response.sendRedirect( path );
} catch( Exception ex ) {
throw new RuntimeException("redirect 오류 : " + ex);
}
}
public static String encoding( String url, String charset ){
try{
url = URLEncoder.encode( url, charset );
}catch(Exception ex){
throw new RuntimeException("URL 인코딩 시 오류 : " + ex);
}
return url;
}
}
| Java |
package kr.ac.ml.mvc;
import java.io.IOException;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
public abstract class Action {
public abstract void execute(HttpServletRequest request, HttpServletResponse response) throws IOException, ServletException;
}
| Java |
package kr.ac.ml.servlet;
import java.io.IOException;
import java.io.PrintWriter;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import kr.ac.ml.action.ConfirmAction;
import kr.ac.ml.action.ErrorAction;
import kr.ac.ml.action.JSonAction;
import kr.ac.ml.action.MainAction;
import kr.ac.ml.mvc.Action;
/**
* Servlet implementation class Jsonservlet
*/
@WebServlet("/json")
public class Jsonservlet extends HttpServlet {
private static final long serialVersionUID = 1L;
/**
* @see HttpServlet#HttpServlet()
*/
public Jsonservlet() {
super();
// TODO Auto-generated constructor stub
}
/**
* @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
*/
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
// TODO Auto-generated method stub
doPost(request, response);
}
/**
* @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
*/
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
// TODO Auto-generated method stub
String a = request.getParameter("a");
String content = request.getParameter("content");
Action action = null;
System.out.println("mainservlet");
System.out.println("a : " + a);
System.out.println("content : " + content );
if("confirm".equals(a)){
action = new ConfirmAction();
}else if("transform".equals(a)){
action = new JSonAction();
}else
action = new ErrorAction();
action.execute(request, response);
System.out.println(request.getAttribute("json"));
response.setContentType("text/html; charset=utf-8");
PrintWriter out = response.getWriter();
out.print(request.getAttribute("json"));
}
}
| Java |
package kr.ac.ml.action;
import java.io.IOException;
import java.util.List;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import ac.kr.ml.dao.ListDao;
import ac.kr.ml.vo.ContentVo;
import kr.ac.ml.mvc.Action;
public class DeptListAction extends Action {
@Override
public void execute(HttpServletRequest request, HttpServletResponse response)
throws IOException, ServletException {
// TODO Auto-generated method stub
System.out.println("DeptListAction");
ListDao dao = new ListDao();
List<ContentVo> list = dao.getDeptList("deptName");
int length = list.size();
String jsonStr = "";
jsonStr += "{";
jsonStr += "\"data\":[";
for (int i = 0; i < length; i++) {
jsonStr += "{";
jsonStr += "\"deptName\":\"" + list.get(i).getdeptName() + "\",";
if(i<length-1)
{
jsonStr += "},";
}
else
jsonStr += "}";
}
jsonStr += "]";
jsonStr += "}";
request.setAttribute("json", jsonStr);
}
}
| Java |
package kr.ac.ml.action;
import java.io.IOException;
import java.util.List;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.json.simple.JSONArray;
import org.json.simple.JSONObject;
import org.json.simple.JSONValue;
import org.json.simple.parser.JSONParser;
import ac.kr.ml.dao.ListDao;
import ac.kr.ml.vo.ContentVo;
import kr.ac.ml.mvc.Action;
public class MakeFriendTable extends Action {
@Override
public void execute(HttpServletRequest request, HttpServletResponse response)
throws IOException, ServletException {
// TODO Auto-generated method stub
System.out.println("MakeFriendTable");
String emp_ID = request.getParameter("emp_ID");
int empID = Integer.parseInt(emp_ID);
String fmp_ID = request.getParameter("fmp_ID");
int fmpID=Integer.parseInt(fmp_ID);
ContentVo vo = new ContentVo();
vo.setempID(empID);
vo.setfmpID(fmpID);
ListDao dao = new ListDao();
dao.insertFriend(vo);
}
}
| Java |
package kr.ac.ml.action;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import ac.kr.ml.dao.ListDao;
import ac.kr.ml.vo.ContentVo;
import kr.ac.ml.mvc.Action;
import kr.ac.ml.mvc.HttpUtil;
public class MainAction extends Action {
@Override
public void execute(HttpServletRequest request, HttpServletResponse response)
throws IOException, ServletException {
// TODO Auto-generated method stub
// ListDao dao = new ListDao();
//
// List<ContentVo> list = new ArrayList<ContentVo>();
//
// list = dao.getList();
//
// request.setAttribute("list", list);
System.out.println("Mainaction");
HttpUtil.forward(request, response, "/views/main.jsp");
}
}
| Java |
package kr.ac.ml.action;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.List;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import ac.kr.ml.dao.ListDao;
import ac.kr.ml.vo.ContentVo;
import kr.ac.ml.mvc.Action;
public class JSonAction extends Action {
@Override
public void execute(HttpServletRequest request, HttpServletResponse response)
throws IOException, ServletException {
// TODO Auto-generated method stub
System.out.println("JSonAction");
ListDao dao = new ListDao();
List<ContentVo> list = dao.getAddressList();
int length = list.size();
String jsonStr = "";
response.setContentType("text/html; charset=utf-8");
jsonStr += "{";
jsonStr += "\"data\":[";
for (int i = 0; i < length; i++) {
jsonStr += "{";
jsonStr += "\"empID\":\"" + list.get(i).getempID() + "\",";
jsonStr += "\"deptID\":\"" + list.get(i).getdeptID() + "\",";
jsonStr += "\"deptName\":\"" + list.get(i).getdeptName() + "\",";
jsonStr += "\"posName\":\"" + list.get(i).getposName() + "\",";
jsonStr += "\"userName\":\"" + list.get(i).getuserName() + "\",";
jsonStr += "\"email\":\"" + list.get(i).getemail() + "\",";
jsonStr += "\"hp\":\"" + list.get(i).gethp() + "\"";
if (i < length - 1) {
jsonStr += "},";
} else
jsonStr += "}";
}
jsonStr += "]";
jsonStr += "}";
// PrintWriter out = response.getWriter();
// out.println(jsonStr);
// out.println(1011);
request.setAttribute("json", jsonStr);
}
}
| Java |
package ac.kr.ml.vo;
public class ReplyVo {
private int re_id;
private int countent_id;
private String commend;
public int getRe_id() {
return re_id;
}
public void setRe_id(int re_id) {
this.re_id = re_id;
}
public int getCountent_id() {
return countent_id;
}
public void setCountent_id(int countent_id) {
this.countent_id = countent_id;
}
public String getCommend() {
return commend;
}
public void setCommend(String commend) {
this.commend = commend;
}
}
| Java |
package ac.kr.ml.vo;
public class ContentVo {
private int con_id;
private String time;
private String content;
private int good;
private int bad;
private int reply_cont;
//addressinfo
private int empID;
private int deptID;
private String deptName;
private String posName;
private String userName;
private String email;
private String hp;
//adrressinfo db
public int getempID()
{
return empID;
}
public void setempID(int empID)
{
this.empID=empID;
}
public int getdeptID()
{
return deptID;
}
public void setdeptID(int deptID)
{
this.deptID=deptID;
}
public String getdeptName()
{
return deptName;
}
public void setdeptName(String deptName)
{
this.deptName=deptName;
}
public String getposName()
{
return posName;
}
public void setposName(String posName)
{
this.posName=posName;
}
public String getuserName()
{
return userName;
}
public void setuserName(String userName)
{
this.userName=userName;
}
public String getemail()
{
return email;
}
public void setemail(String email)
{
this.email=email;
}
public String gethp()
{
return hp;
}
public void sethp(String hp)
{
this.hp=hp;
}
//addressinfo db
public int getCon_id() {
return con_id;
}
public void setCon_id(int con_id) {
this.con_id = con_id;
}
public String getTime() {
return time;
}
public void setTime(String time) {
this.time = time;
}
public String getContent() {
return content;
}
public void setContent(String content) {
this.content = content;
}
public int getGood() {
return good;
}
public void setGood(int good) {
this.good = good;
}
public int getBad() {
return bad;
}
public void setBad(int bad) {
this.bad = bad;
}
public int getReply_cont() {
return reply_cont;
}
public void setReply_cont(int reply_cont) {
this.reply_cont = reply_cont;
}
}
| Java |
package ac.kr.ml.dao;
import java.sql.DriverManager;
import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.ArrayList;
import java.util.List;
import ac.kr.ml.vo.ContentVo;
public class ListDao {
public void insert(ContentVo vo){
Connection conn = null;
Statement stmt= null;
try {
Class.forName("com.mysql.jdbc.Driver");
// String dburl = "jdbc:mysql://partner.medialog.co.kr:3306/freshman";
// conn = DriverManager.getConnection(dburl, "freshman", "freshman!$");
String dburl = "jdbc:mysql://partner.medialog.co.kr:3306/freshman";
conn = DriverManager.getConnection(dburl, "freshman", "freshman!$");
stmt = conn.createStatement();
String sql = "insert into CONTENT (content, time, good, bad, reply_cont) values ('"
+vo.getContent()+"', '"+vo.getTime()+"', '"
+vo.getGood()+"', '"+vo.getBad()+"', '"
+vo.getReply_cont()+"')";
//ResultSet rs = stmt.executeQuery(sql);
stmt.executeUpdate(sql);
//rs.close();
} catch (ClassNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (SQLException ex){
ex.printStackTrace();
} finally{
try{
stmt.close();
}catch(SQLException e){}
if(conn != null){
try{
conn.close();
}catch(SQLException e){}
}
}
}
public List<ContentVo> getAddressList()
{
List<ContentVo> list = new ArrayList<ContentVo>();
Connection conn = null;
Statement stmt = null;
try {
Class.forName("com.mysql.jdbc.Driver");
String dburl = "jdbc:mysql://partner.medialog.co.kr:3306/freshman";
conn = DriverManager.getConnection(dburl, "freshman", "freshman!$");
stmt = conn.createStatement();
String sql = "select * from addressinfo order by empID asc";
ResultSet rs = stmt.executeQuery(sql);
while(rs.next()){
ContentVo vo = new ContentVo();
vo.setempID(rs.getInt(1));
vo.setdeptID(rs.getInt(2));
vo.setdeptName(rs.getString(3));
vo.setposName(rs.getString(4));
vo.setuserName(rs.getString(5));
vo.setemail(rs.getString(6));
vo.sethp(rs.getString(7));
list.add(vo);
}
rs.close();
} catch (ClassNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (SQLException ex){
ex.printStackTrace();
} finally{
try{
stmt.close();
}catch(SQLException e){}
if(conn != null){
try{
conn.close();
}catch(SQLException e){}
}
}
return list;
}
public List<ContentVo> getList(){
List<ContentVo> list = new ArrayList<ContentVo>();
Connection conn = null;
Statement stmt= null;
try {
Class.forName("com.mysql.jdbc.Driver");
String dburl = "jdbc:mysql://partner.medialog.co.kr:3306/freshman";
conn = DriverManager.getConnection(dburl, "freshman", "freshman!$");
stmt = conn.createStatement();
String sql = "select * from CONTENT order by con_id desc";
ResultSet rs = stmt.executeQuery(sql);
while(rs.next()){
ContentVo vo = new ContentVo();
vo.setCon_id(rs.getInt(1));
vo.setContent(rs.getString(2));
vo.setTime(rs.getString(3));
vo.setGood(rs.getInt(4));
vo.setBad(rs.getInt(5));
vo.setReply_cont(rs.getInt(6));
list.add(vo);
}
rs.close();
} catch (ClassNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (SQLException ex){
ex.printStackTrace();
} finally{
try{
stmt.close();
}catch(SQLException e){}
if(conn != null){
try{
conn.close();
}catch(SQLException e){}
}
}
return list;
}
public ContentVo getList(int con_id){
ContentVo vo = new ContentVo();
Connection conn = null;
Statement stmt= null;
try {
Class.forName("com.mysql.jdbc.Driver");
String dburl = "jdbc:mysql://partner.medialog.co.kr:3306/freshman";
conn = DriverManager.getConnection(dburl, "freshman", "freshman!$");
stmt = conn.createStatement();
String sql = "select * from CONTENT where con_id="+con_id;
ResultSet rs = stmt.executeQuery(sql);
while(rs.next()){
vo.setCon_id(rs.getInt(1));
vo.setContent(rs.getString(2));
vo.setTime(rs.getString(3));
vo.setGood(rs.getInt(4));
vo.setBad(rs.getInt(5));
vo.setReply_cont(rs.getInt(6));
}
rs.close();
} catch (ClassNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (SQLException ex){
ex.printStackTrace();
} finally{
try{
stmt.close();
}catch(SQLException e){}
if(conn != null){
try{
conn.close();
}catch(SQLException e){}
}
}
return vo;
}
public void upGood(int good,int con_id){
int up = 0;
up = good +1;
Connection conn = null;
Statement stmt= null;
try {
Class.forName("com.mysql.jdbc.Driver");
String dburl = "jdbc:mysql://partner.medialog.co.kr:3306/freshman";
conn = DriverManager.getConnection(dburl, "freshman", "freshman!$");
stmt = conn.createStatement();
String sql = "update CONTENT set good="+up+" where con_id="+con_id;
//ResultSet rs = stmt.executeQuery(sql);
stmt.executeUpdate(sql);
//rs.close();
} catch (ClassNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (SQLException ex){
ex.printStackTrace();
} finally{
try{
stmt.close();
}catch(SQLException e){}
if(conn != null){
try{
conn.close();
}catch(SQLException e){}
}
}
}
public void upbad(int bad,int con_id){
int up = 0;
up = bad +1;
Connection conn = null;
Statement stmt= null;
try {
Class.forName("com.mysql.jdbc.Driver");
String dburl = "jdbc:mysql://partner.medialog.co.kr:3306/freshman";
conn = DriverManager.getConnection(dburl, "freshman", "freshman!$");
stmt = conn.createStatement();
String sql = "update CONTENT set bad="+up+" where con_id="+con_id;
//ResultSet rs = stmt.executeQuery(sql);
stmt.executeUpdate(sql);
//rs.close();
} catch (ClassNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (SQLException ex){
ex.printStackTrace();
} finally{
try{
stmt.close();
}catch(SQLException e){}
if(conn != null){
try{
conn.close();
}catch(SQLException e){}
}
}
}
public void upReplyCont(int reply_cont,int con_id){
int up = 0;
up = reply_cont +1;
Connection conn = null;
Statement stmt= null;
try {
Class.forName("com.mysql.jdbc.Driver");
String dburl = "jdbc:mysql://partner.medialog.co.kr:3306/freshman";
conn = DriverManager.getConnection(dburl, "freshman", "freshman!$");
stmt = conn.createStatement();
String sql = "update CONTENT set reply_cont="+up+" where con_id="+con_id;
//ResultSet rs = stmt.executeQuery(sql);
stmt.executeUpdate(sql);
//rs.close();
} catch (ClassNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (SQLException ex){
ex.printStackTrace();
} finally{
try{
stmt.close();
}catch(SQLException e){}
if(conn != null){
try{
conn.close();
}catch(SQLException e){}
}
}
}
}
| Java |
package kr.ac.ml.mvc;
import java.net.URLEncoder;
import javax.servlet.RequestDispatcher;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
public class HttpUtil {
public static void forward(HttpServletRequest request, HttpServletResponse response, String path ) {
try{
String mobile = request.getParameter("mobile");
if("1".equals(mobile)){
path = path.replace(".jsp", "_m.jsp");
}
System.out.println( path );
RequestDispatcher dispatcher = request.getRequestDispatcher(path);
dispatcher.forward(request, response);
} catch( Exception ex ) {
throw new RuntimeException( "forward Exception : " + ex);
}
}
public static void redirect(
HttpServletRequest request,
HttpServletResponse response,
String path ){
try{
String mobile = request.getParameter("mobile");
if( "1".equals(mobile) ){
path = path + ( path.contains("?") ? "&mobile=1" : "?mobile=1" );
}
response.sendRedirect( path );
} catch( Exception ex ) {
throw new RuntimeException("redirect 오류 : " + ex);
}
}
public static String encoding( String url, String charset ){
try{
url = URLEncoder.encode( url, charset );
}catch(Exception ex){
throw new RuntimeException("URL 인코딩 시 오류 : " + ex);
}
return url;
}
}
| Java |
package kr.ac.ml.mvc;
import java.io.IOException;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
public abstract class Action {
public abstract void execute(HttpServletRequest request, HttpServletResponse response) throws IOException, ServletException;
}
| Java |
package kr.ac.ml.servlet;
import java.io.IOException;
import java.io.PrintWriter;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import kr.ac.ml.action.JSonAction;
import kr.ac.ml.action.ListAction;
import kr.ac.ml.action.MainAction;
import kr.ac.ml.action.WriteAction;
import kr.ac.ml.mvc.Action;
@WebServlet("/main")
public class mainserlvet extends HttpServlet {
private static final long serialVersionUID = 1L;
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
// TODO Auto-generated method stub
doPost(request, response);
}
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
// TODO Auto-generated method stub
String a = request.getParameter("a");
String content = request.getParameter("content");
Action action = null;
System.out.println("mainservlet");
System.out.println("a : " + a);
System.out.println("content : " + content );
if("write".equals(a)){
action = new WriteAction();
}else if("list".equals(a)){
action = new ListAction();
}else if("JSon".equals(a)){
action = new JSonAction();
}else{
action = new MainAction();
}
action.execute(request, response);
System.out.println(request.getAttribute("json"));
response.setContentType("text/html; charset=utf-8");
PrintWriter out = response.getWriter();
out.print(request.getAttribute("json"));
}
}
| Java |
package kr.ac.ml.action;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import ac.kr.ml.dao.ListDao;
import ac.kr.ml.vo.ContentVo;
import kr.ac.ml.mvc.Action;
import kr.ac.ml.mvc.HttpUtil;
public class MainAction extends Action {
@Override
public void execute(HttpServletRequest request, HttpServletResponse response)
throws IOException, ServletException {
// TODO Auto-generated method stub
// ListDao dao = new ListDao();
//
// List<ContentVo> list = new ArrayList<ContentVo>();
//
// list = dao.getList();
//
// request.setAttribute("list", list);
System.out.println("Mainaction");
HttpUtil.forward(request, response, "/views/main.jsp");
}
}
| Java |
package kr.ac.ml.action;
import java.io.IOException;
import java.util.List;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import ac.kr.ml.dao.ListDao;
import ac.kr.ml.vo.ContentVo;
import kr.ac.ml.mvc.Action;
public class ListAction extends Action {
@Override
public void execute(HttpServletRequest request, HttpServletResponse response)
throws IOException, ServletException {
// TODO Auto-generated method stub
System.out.println("Listaction");
//리스트가져오기
ListDao dao = new ListDao();
List<ContentVo> list = dao.getList();
int length = list.size();
String jsonStr = "";
jsonStr += "{";
jsonStr += "\"AnnoymousSNS\":[";
for(int i = 0; i < length; i++){
jsonStr += "{";
jsonStr += "\"con_id\":\"" + list.get(i).getCon_id() + "\",";
jsonStr += "\"content\":\"" + list.get(i).getContent() + "\",";
jsonStr += "\"time\":\"" + list.get(i).getTime() + "\",";
jsonStr += "\"good\":\"" + list.get(i).getGood() + "\",";
jsonStr += "\"bad\":\"" + list.get(i).getBad() + "\",";
jsonStr += "\"reply_cont\":\"" + list.get(i).getReply_cont() + "\"";
jsonStr += "}";
if(i < length - 1) jsonStr += ",";
}
jsonStr += "]";
jsonStr += "}";
// System.out.println(jsonStr);
request.setAttribute("json", jsonStr);
}
}
| Java |
package kr.ac.ml.action;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.List;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import ac.kr.ml.dao.ListDao;
import ac.kr.ml.vo.ContentVo;
import kr.ac.ml.mvc.Action;
public class JSonAction extends Action {
@Override
public void execute(HttpServletRequest request, HttpServletResponse response)
throws IOException, ServletException {
// TODO Auto-generated method stub
System.out.println("JSonAction");
ListDao dao = new ListDao();
List<ContentVo> list = dao.getAddressList();
int length = list.size();
String jsonStr = "";
response.setContentType("text/html; charset=utf-8");
jsonStr += "{";
jsonStr += "\"data\":[";
for (int i = 0; i < length; i++) {
jsonStr += "{";
jsonStr += "\"empID\":\"" + list.get(i).getempID()+ "\",";
jsonStr += "\"deptID\":\"" + list.get(i).getdeptID() + "\"";
jsonStr += "\"deptName\":\"" + list.get(i).getdeptName() + "\"";
jsonStr += "\"posName\":\"" + list.get(i).getposName() + "\"";
jsonStr += "\"userName\":\"" + list.get(i).getuserName() + "\"";
jsonStr += "\"email\":\"" + list.get(i).getemail() + "\"";
jsonStr += "\"hp\":\"" + list.get(i).gethp() + "\"";
jsonStr += "}";
if (i < length - 1)
jsonStr += ",";
}
jsonStr += "]";
jsonStr += "}";
PrintWriter out = response.getWriter();
out.println(jsonStr);
}
}
| Java |
package kr.ac.ml.action;
import java.io.IOException;
import java.io.PrintWriter;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.HashMap;
import java.util.Map;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import net.sf.json.JSONObject;
import ac.kr.ml.dao.ListDao;
import ac.kr.ml.vo.ContentVo;
import kr.ac.ml.mvc.Action;
public class WriteAction extends Action {
@Override
public void execute(HttpServletRequest request, HttpServletResponse response)
throws IOException, ServletException {
System.out.println("WriteAction");
String content = request.getParameter("content");
String time;
ContentVo vo = new ContentVo();
Calendar calendar = Calendar.getInstance();
SimpleDateFormat dataFormat = new SimpleDateFormat("yy.MM.dd HH:mm:ss");
time = dataFormat.format(calendar.getTime());
vo.setContent(content);
vo.setTime(time);
vo.setBad(0);
vo.setGood(0);
vo.setReply_cont(0);
ListDao dao = new ListDao();
dao.insert(vo);
String jsonstr = "";
jsonstr +="{";
jsonstr +="\"content\":[";
jsonstr += "{";
jsonstr += "\"con_id\":\"" +vo.getCon_id() + "\",";
jsonstr += "\"content\":\"" + vo.getContent() + "\",";
jsonstr += "\"time\":\"" + vo.getTime() + "\",";
jsonstr += "\"good\":\"" + vo.getGood() + "\",";
jsonstr += "\"bad\":\"" + vo.getBad() + "\",";
jsonstr += "\"reply_cont\":\"" + vo.getReply_cont() + "\"";
jsonstr += "}";
jsonstr += "]";
jsonstr += "}";
// response.setContentType("text/html; charset=utf-8");
// PrintWriter out = response.getWriter();
// out.print(jsonstr);
request.setAttribute("json", jsonstr);
}
}
| Java |
package ac.kr.ml.vo;
public class ReplyVo {
private int re_id;
private int countent_id;
private String commend;
public int getRe_id() {
return re_id;
}
public void setRe_id(int re_id) {
this.re_id = re_id;
}
public int getCountent_id() {
return countent_id;
}
public void setCountent_id(int countent_id) {
this.countent_id = countent_id;
}
public String getCommend() {
return commend;
}
public void setCommend(String commend) {
this.commend = commend;
}
}
| Java |
package ac.kr.ml.vo;
public class ContentVo {
private int con_id;
private String time;
private String content;
private int good;
private int bad;
private int reply_cont;
//addressinfo
private int empID;
private int deptID;
private String deptName;
private String posName;
private String userName;
private String email;
private String hp;
//Friend db
private int fmpID;
private String fmpList;
public void setfmpList(String fmpList)
{
this.fmpList=fmpList;
}
public String getfmpList()
{
return fmpList;
}
public int getfmpID()
{
return fmpID;
}
public void setfmpID(int empID)
{
this.fmpID=empID;
}
//Freind db
//adrressinfo db
public int getempID()
{
return empID;
}
public void setempID(int empID)
{
this.empID=empID;
}
public int getdeptID()
{
return deptID;
}
public void setdeptID(int deptID)
{
this.deptID=deptID;
}
public String getdeptName()
{
return deptName;
}
public void setdeptName(String deptName)
{
this.deptName=deptName;
}
public String getposName()
{
return posName;
}
public void setposName(String posName)
{
this.posName=posName;
}
public String getuserName()
{
return userName;
}
public void setuserName(String userName)
{
this.userName=userName;
}
public String getemail()
{
return email;
}
public void setemail(String email)
{
this.email=email;
}
public String gethp()
{
return hp;
}
public void sethp(String hp)
{
this.hp=hp;
}
//addressinfo db
public int getCon_id() {
return con_id;
}
public void setCon_id(int con_id) {
this.con_id = con_id;
}
public String getTime() {
return time;
}
public void setTime(String time) {
this.time = time;
}
public String getContent() {
return content;
}
public void setContent(String content) {
this.content = content;
}
public int getGood() {
return good;
}
public void setGood(int good) {
this.good = good;
}
public int getBad() {
return bad;
}
public void setBad(int bad) {
this.bad = bad;
}
public int getReply_cont() {
return reply_cont;
}
public void setReply_cont(int reply_cont) {
this.reply_cont = reply_cont;
}
}
| Java |
package kr.ac.ml.mvc;
import java.net.URLEncoder;
import javax.servlet.RequestDispatcher;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
public class HttpUtil {
public static void forward(HttpServletRequest request, HttpServletResponse response, String path ) {
try{
String mobile = request.getParameter("mobile");
if("1".equals(mobile)){
path = path.replace(".jsp", "_m.jsp");
}
System.out.println( path );
RequestDispatcher dispatcher = request.getRequestDispatcher(path);
dispatcher.forward(request, response);
} catch( Exception ex ) {
throw new RuntimeException( "forward Exception : " + ex);
}
}
public static void redirect(
HttpServletRequest request,
HttpServletResponse response,
String path ){
try{
String mobile = request.getParameter("mobile");
if( "1".equals(mobile) ){
path = path + ( path.contains("?") ? "&mobile=1" : "?mobile=1" );
}
response.sendRedirect( path );
} catch( Exception ex ) {
throw new RuntimeException("redirect 오류 : " + ex);
}
}
public static String encoding( String url, String charset ){
try{
url = URLEncoder.encode( url, charset );
}catch(Exception ex){
throw new RuntimeException("URL 인코딩 시 오류 : " + ex);
}
return url;
}
}
| Java |
package kr.ac.ml.mvc;
import java.io.IOException;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
public abstract class Action {
public abstract void execute(HttpServletRequest request, HttpServletResponse response) throws IOException, ServletException;
}
| Java |
package kr.ac.ml.servlet;
import java.io.IOException;
import java.io.PrintWriter;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.json.simple.JSONObject;
import org.json.simple.JSONValue;
import kr.ac.ml.action.ConfirmAction;
import kr.ac.ml.action.JSonAction;
import kr.ac.ml.action.ListAction;
import kr.ac.ml.action.MainAction;
import kr.ac.ml.action.WriteAction;
import kr.ac.ml.mvc.Action;
@WebServlet("/main")
public class mainserlvet extends HttpServlet {
private static final long serialVersionUID = 1L;
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
// TODO Auto-generated method stub
doPost(request, response);
}
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
// TODO Auto-generated method stub
String a = request.getParameter("a");
String content = request.getParameter("content");
Action action = null;
System.out.println("mainservlet");
System.out.println("a : " + a);
System.out.println("content : " + content );
if("write".equals(a)){
action = new WriteAction();
}else if("list".equals(a)){
action = new ListAction();
}else if("JSon".equals(a)){
action = new JSonAction();
}else if("confirm".equals(a)){
action = new ConfirmAction();
}else
action = new MainAction();
action.execute(request, response);
System.out.println(request.getAttribute("json"));
response.setContentType("text/html; charset=utf-8");
PrintWriter out = response.getWriter();
out.print(request.getAttribute("json"));
}
}
| Java |
package kr.ac.ml.action;
import java.io.IOException;
import java.util.List;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.json.simple.JSONArray;
import org.json.simple.JSONObject;
import org.json.simple.JSONValue;
import org.json.simple.parser.JSONParser;
import ac.kr.ml.dao.ListDao;
import ac.kr.ml.vo.ContentVo;
import kr.ac.ml.mvc.Action;
public class MakeFriendTable extends Action {
@Override
public void execute(HttpServletRequest request, HttpServletResponse response)
throws IOException, ServletException {
// TODO Auto-generated method stub
System.out.println("MakeFriendTable");
String emp_ID = request.getParameter("emp_ID");
int empID = Integer.parseInt(emp_ID);
String fmp_ID = request.getParameter("fmp_ID");
int fmpID=Integer.parseInt(fmp_ID);
ContentVo vo = new ContentVo();
vo.setempID(empID);
vo.setfmpID(fmpID);
ListDao dao = new ListDao();
dao.insertFriend(vo);
}
}
| Java |
package kr.ac.ml.action;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import ac.kr.ml.dao.ListDao;
import ac.kr.ml.vo.ContentVo;
import kr.ac.ml.mvc.Action;
import kr.ac.ml.mvc.HttpUtil;
public class MainAction extends Action {
@Override
public void execute(HttpServletRequest request, HttpServletResponse response)
throws IOException, ServletException {
// TODO Auto-generated method stub
// ListDao dao = new ListDao();
//
// List<ContentVo> list = new ArrayList<ContentVo>();
//
// list = dao.getList();
//
// request.setAttribute("list", list);
System.out.println("Mainaction");
HttpUtil.forward(request, response, "/views/main.jsp");
}
}
| Java |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.