diff options
author | Paul Pazderski | 2019-06-19 21:19:47 +0000 |
---|---|---|
committer | Lars Vogel | 2019-08-15 15:35:35 +0000 |
commit | caf52d6d0540fc44f47f9472475b1e71d9cadb5f (patch) | |
tree | eed674969a42d4042a19d60afb84889d01089335 | |
parent | 2253a11bb08205dda51d512a8e6d7c03a3ee39cd (diff) | |
download | rt.equinox.bundles-caf52d6d0540fc44f47f9472475b1e71d9cadb5f.tar.gz rt.equinox.bundles-caf52d6d0540fc44f47f9472475b1e71d9cadb5f.tar.xz rt.equinox.bundles-caf52d6d0540fc44f47f9472475b1e71d9cadb5f.zip |
Bug 547578 - Space / tab cleanup in rt.equinox.bundlesY20190819-0900I20190819-0600I20190818-1800I20190817-1800I20190816-1800I20190816-0155
This change fixes all space or mixed tab/space indentations in all Java
files. The change includes only whitespace formatting and no code
changes.
Change-Id: I6273144b49d81def3518b867bf036b11afc18188
Signed-off-by: Paul Pazderski <paul-eclipse@ppazderski.de>
67 files changed, 3384 insertions, 3384 deletions
diff --git a/bundles/org.eclipse.equinox.app/osgi/org/osgi/service/application/ApplicationAdminPermission.java b/bundles/org.eclipse.equinox.app/osgi/org/osgi/service/application/ApplicationAdminPermission.java index d3217381d..5fe9fdd7f 100644 --- a/bundles/org.eclipse.equinox.app/osgi/org/osgi/service/application/ApplicationAdminPermission.java +++ b/bundles/org.eclipse.equinox.app/osgi/org/osgi/service/application/ApplicationAdminPermission.java @@ -41,7 +41,7 @@ import org.osgi.framework.InvalidSyntaxException; */ public class ApplicationAdminPermission extends Permission { private static final long serialVersionUID = 1L; - + /** * Allows the lifecycle management of the target applications. */ @@ -154,7 +154,7 @@ public class ApplicationAdminPermission extends Permission { } } else - newPerm = new ApplicationAdminPermission( this.applicationDescriptor, this.actions ); + newPerm = new ApplicationAdminPermission( this.applicationDescriptor, this.actions ); newPerm.applicationID = applicationId; @@ -181,177 +181,177 @@ public class ApplicationAdminPermission extends Permission { * @return true if this permission implies the {@code otherPermission}, false otherwise. */ @Override - public boolean implies(Permission otherPermission) { - if( otherPermission == null ) - return false; - - if(!(otherPermission instanceof ApplicationAdminPermission)) - return false; + public boolean implies(Permission otherPermission) { + if( otherPermission == null ) + return false; + + if(!(otherPermission instanceof ApplicationAdminPermission)) + return false; - ApplicationAdminPermission other = (ApplicationAdminPermission) otherPermission; + ApplicationAdminPermission other = (ApplicationAdminPermission) otherPermission; - if( !filter.equals("*") ) { - if( other.applicationDescriptor == null ) - return false; - - if( filter.equals( "<<SELF>>") ) { - if( other.applicationID == null ) - return false; /* it cannot be, this might be a bug */ - - if( !other.applicationID.equals( other.applicationDescriptor.getApplicationId() ) ) - return false; - } - else { - Hashtable props = new Hashtable(); - props.put( "pid", other.applicationDescriptor.getApplicationId() ); - props.put( "signer", new SignerWrapper( other.applicationDescriptor ) ); - - Filter flt = getFilter(); - if( flt == null ) - return false; - - if( !flt.match( props ) ) - return false; - } - } - - if( !actionsVector.containsAll( other.actionsVector ) ) - return false; - - return true; - } + if( !filter.equals("*") ) { + if( other.applicationDescriptor == null ) + return false; + + if( filter.equals( "<<SELF>>") ) { + if( other.applicationID == null ) + return false; /* it cannot be, this might be a bug */ + + if( !other.applicationID.equals( other.applicationDescriptor.getApplicationId() ) ) + return false; + } + else { + Hashtable props = new Hashtable(); + props.put( "pid", other.applicationDescriptor.getApplicationId() ); + props.put( "signer", new SignerWrapper( other.applicationDescriptor ) ); + + Filter flt = getFilter(); + if( flt == null ) + return false; + + if( !flt.match( props ) ) + return false; + } + } + + if( !actionsVector.containsAll( other.actionsVector ) ) + return false; + + return true; + } @Override - public boolean equals(Object with) { - if( with == null || !(with instanceof ApplicationAdminPermission) ) - return false; - - ApplicationAdminPermission other = (ApplicationAdminPermission)with; - - // Compare actions: - if( other.actionsVector.size() != actionsVector.size() ) - return false; - - for( int i=0; i != actionsVector.size(); i++ ) - if( !other.actionsVector.contains( actionsVector.get( i ) ) ) - return false; - - - return equal(this.filter, other.filter ) && equal(this.applicationDescriptor, other.applicationDescriptor) - && equal(this.applicationID, other.applicationID); - } - - /** - * Compares parameters for equality. If both object are null, they are considered - * equal. - * @param a object to compare - * @param b other object to compare - * @return true if both objects are equal or both are null - */ - private static boolean equal(Object a, Object b) { - // This equation is true if both references are null or both point - // to the same object. In both cases they are considered as equal. - if( a == b ) { - return true; - } - - return a.equals(b); - } + public boolean equals(Object with) { + if( with == null || !(with instanceof ApplicationAdminPermission) ) + return false; + + ApplicationAdminPermission other = (ApplicationAdminPermission)with; + + // Compare actions: + if( other.actionsVector.size() != actionsVector.size() ) + return false; + + for( int i=0; i != actionsVector.size(); i++ ) + if( !other.actionsVector.contains( actionsVector.get( i ) ) ) + return false; + + + return equal(this.filter, other.filter ) && equal(this.applicationDescriptor, other.applicationDescriptor) + && equal(this.applicationID, other.applicationID); + } + + /** + * Compares parameters for equality. If both object are null, they are considered + * equal. + * @param a object to compare + * @param b other object to compare + * @return true if both objects are equal or both are null + */ + private static boolean equal(Object a, Object b) { + // This equation is true if both references are null or both point + // to the same object. In both cases they are considered as equal. + if( a == b ) { + return true; + } + + return a.equals(b); + } @Override - public int hashCode() { - int hc = 0; - for( int i=0; i != actionsVector.size(); i++ ) - hc ^= ((String)actionsVector.get( i )).hashCode(); - hc ^= (null == this.filter )? 0 : this.filter.hashCode(); - hc ^= (null == this.applicationDescriptor) ? 0 : this.applicationDescriptor.hashCode(); - hc ^= (null == this.applicationID) ? 0 : this.applicationID.hashCode(); - return hc; - } + public int hashCode() { + int hc = 0; + for( int i=0; i != actionsVector.size(); i++ ) + hc ^= ((String)actionsVector.get( i )).hashCode(); + hc ^= (null == this.filter )? 0 : this.filter.hashCode(); + hc ^= (null == this.applicationDescriptor) ? 0 : this.applicationDescriptor.hashCode(); + hc ^= (null == this.applicationID) ? 0 : this.applicationID.hashCode(); + return hc; + } - /** - * Returns the actions of this permission. - * @return the actions specified when this permission was created - */ + /** + * Returns the actions of this permission. + * @return the actions specified when this permission was created + */ @Override - public String getActions() { - return actions; - } + public String getActions() { + return actions; + } - private String applicationID; + private String applicationID; - private static final Vector ACTIONS = new Vector(); - private Vector actionsVector; - private final String filter; - private final String actions; - private Filter appliedFilter = null; - - static { - ACTIONS.add(LIFECYCLE_ACTION); - ACTIONS.add(SCHEDULE_ACTION); - ACTIONS.add(LOCK_ACTION); - } + private static final Vector ACTIONS = new Vector(); + private Vector actionsVector; + private final String filter; + private final String actions; + private Filter appliedFilter = null; + + static { + ACTIONS.add(LIFECYCLE_ACTION); + ACTIONS.add(SCHEDULE_ACTION); + ACTIONS.add(LOCK_ACTION); + } - private static Vector actionsVector(String actions) { - Vector v = new Vector(); - StringTokenizer t = new StringTokenizer(actions.toUpperCase(), ","); - while (t.hasMoreTokens()) { - String action = t.nextToken().trim(); - v.add(action.toLowerCase()); - } - - if( v.contains( SCHEDULE_ACTION ) && !v.contains( LIFECYCLE_ACTION ) ) - v.add( LIFECYCLE_ACTION ); - - return v; - } - + private static Vector actionsVector(String actions) { + Vector v = new Vector(); + StringTokenizer t = new StringTokenizer(actions.toUpperCase(), ","); + while (t.hasMoreTokens()) { + String action = t.nextToken().trim(); + v.add(action.toLowerCase()); + } + + if( v.contains( SCHEDULE_ACTION ) && !v.contains( LIFECYCLE_ACTION ) ) + v.add( LIFECYCLE_ACTION ); + + return v; + } + - private static class SignerWrapper extends Object { - private String pattern; - private ApplicationDescriptor appDesc; - - /** - * @param pattern - */ - public SignerWrapper(String pattern) { - this.pattern = pattern; - } - - SignerWrapper(ApplicationDescriptor appDesc) { - this.appDesc = appDesc; - } - - @Override - public boolean equals(Object o) { - if (!(o instanceof SignerWrapper)) - return false; - SignerWrapper other = (SignerWrapper) o; - ApplicationDescriptor matchAppDesc = (ApplicationDescriptor) (appDesc != null ? appDesc : other.appDesc); - String matchPattern = appDesc != null ? other.pattern : pattern; - return matchAppDesc.matchDNChain(matchPattern); - } - } - - private void init() { + private static class SignerWrapper extends Object { + private String pattern; + private ApplicationDescriptor appDesc; + + /** + * @param pattern + */ + public SignerWrapper(String pattern) { + this.pattern = pattern; + } + + SignerWrapper(ApplicationDescriptor appDesc) { + this.appDesc = appDesc; + } + + @Override + public boolean equals(Object o) { + if (!(o instanceof SignerWrapper)) + return false; + SignerWrapper other = (SignerWrapper) o; + ApplicationDescriptor matchAppDesc = (ApplicationDescriptor) (appDesc != null ? appDesc : other.appDesc); + String matchPattern = appDesc != null ? other.pattern : pattern; + return matchAppDesc.matchDNChain(matchPattern); + } + } + + private void init() { actionsVector = actionsVector( actions ); if ( actions.equals("*") ) actionsVector = actionsVector( LIFECYCLE_ACTION + "," + SCHEDULE_ACTION + "," + LOCK_ACTION ); else if (!ACTIONS.containsAll(actionsVector)) - throw new IllegalArgumentException("Illegal action!"); + throw new IllegalArgumentException("Illegal action!"); applicationID = null; - } - - private Filter getFilter() { - if (appliedFilter == null) { - try { - appliedFilter = FrameworkUtil.createFilter(filter); - } catch (InvalidSyntaxException e) { - //we will return null - } - } - return appliedFilter; - } + } + + private Filter getFilter() { + if (appliedFilter == null) { + try { + appliedFilter = FrameworkUtil.createFilter(filter); + } catch (InvalidSyntaxException e) { + //we will return null + } + } + return appliedFilter; + } } diff --git a/bundles/org.eclipse.equinox.app/osgi/org/osgi/service/application/ApplicationException.java b/bundles/org.eclipse.equinox.app/osgi/org/osgi/service/application/ApplicationException.java index 170922efd..166bf850e 100644 --- a/bundles/org.eclipse.equinox.app/osgi/org/osgi/service/application/ApplicationException.java +++ b/bundles/org.eclipse.equinox.app/osgi/org/osgi/service/application/ApplicationException.java @@ -67,19 +67,19 @@ public class ApplicationException extends Exception { * during launch. The exception is available from {@code getCause()}. */ public static final int APPLICATION_INTERNAL_ERROR = 0x03; - - /** - * The application schedule could not be created due to some internal error - * (for example, the schedule information couldn't be saved due to some + + /** + * The application schedule could not be created due to some internal error + * (for example, the schedule information couldn't be saved due to some * storage error). - */ - public static final int APPLICATION_SCHEDULING_FAILED = 0x04; - - /** - * The application scheduling failed because the specified identifier - * is already in use. - */ - public static final int APPLICATION_DUPLICATE_SCHEDULE_ID = 0x05; + */ + public static final int APPLICATION_SCHEDULING_FAILED = 0x04; + + /** + * The application scheduling failed because the specified identifier + * is already in use. + */ + public static final int APPLICATION_DUPLICATE_SCHEDULE_ID = 0x05; /** * The exit value is not available for an application instance because the @@ -87,7 +87,7 @@ public class ApplicationException extends Exception { * * @since 1.1 */ - public static final int APPLICATION_EXITVALUE_NOT_AVAILABLE = 0x06; + public static final int APPLICATION_EXITVALUE_NOT_AVAILABLE = 0x06; /** * One of the specified startup arguments is invalid, for example its @@ -95,7 +95,7 @@ public class ApplicationException extends Exception { * * @since 1.1 */ - public static final int APPLICATION_INVALID_STARTUP_ARGUMENT = 0x07; + public static final int APPLICATION_INVALID_STARTUP_ARGUMENT = 0x07; /** * Creates an {@code ApplicationException} with the specified error code. diff --git a/bundles/org.eclipse.equinox.app/osgi/org/osgi/service/application/ScheduledApplication.java b/bundles/org.eclipse.equinox.app/osgi/org/osgi/service/application/ScheduledApplication.java index f3385ad4c..4e7a9605b 100644 --- a/bundles/org.eclipse.equinox.app/osgi/org/osgi/service/application/ScheduledApplication.java +++ b/bundles/org.eclipse.equinox.app/osgi/org/osgi/service/application/ScheduledApplication.java @@ -35,77 +35,77 @@ import java.util.Map; * @version $Id$ */ public interface ScheduledApplication { - - /** - * The property key for the identifier of the application being scheduled. - */ - public static final String APPLICATION_PID = ApplicationDescriptor.APPLICATION_PID; - - /** - * The property key for the schedule identifier. The identifier is unique - * within the scope of the application being scheduled. - */ - public static final String SCHEDULE_ID = "schedule.id"; - - /** - * The key for the startup argument used to pass the event object that - * triggered the schedule to launch the application instance. - * The event is passed in a {@link java.security.GuardedObject} - * protected by the corresponding - * {@link org.osgi.service.event.TopicPermission}. - */ - public static final String TRIGGERING_EVENT = "org.osgi.triggeringevent"; - - /** - * The topic name for the virtual timer topic. Time based schedules - * should be created using this topic. - */ - public static final String TIMER_TOPIC = "org/osgi/application/timer"; - - /** - * The name of the <i>year</i> attribute of a virtual timer event. The value is - * defined by {@link java.util.Calendar#YEAR}. - */ - public static final String YEAR = "year"; - - /** - * The name of the <i>month</i> attribute of a virtual timer event. The value is - * defined by {@link java.util.Calendar#MONTH}. - */ - public static final String MONTH = "month"; - - /** - * The name of the <i>day of month</i> attribute of a virtual timer event. The value is - * defined by {@link java.util.Calendar#DAY_OF_MONTH}. - */ - public static final String DAY_OF_MONTH = "day_of_month"; - - /** - * The name of the <i>day of week</i> attribute of a virtual timer event. The value is - * defined by {@link java.util.Calendar#DAY_OF_WEEK}. - */ - public static final String DAY_OF_WEEK = "day_of_week"; - - /** - * The name of the <i>hour of day</i> attribute of a virtual timer event. The value is - * defined by {@link java.util.Calendar#HOUR_OF_DAY}. - */ - public static final String HOUR_OF_DAY = "hour_of_day"; - - /** - * The name of the <i>minute</i> attribute of a virtual timer event. The value is - * defined by {@link java.util.Calendar#MINUTE}. - */ - public static final String MINUTE = "minute"; - - - /** - * Returns the identifier of this schedule. The identifier is unique within - * the scope of the application that the schedule is related to. - * @return the identifier of this schedule - * - */ - public String getScheduleId(); + + /** + * The property key for the identifier of the application being scheduled. + */ + public static final String APPLICATION_PID = ApplicationDescriptor.APPLICATION_PID; + + /** + * The property key for the schedule identifier. The identifier is unique + * within the scope of the application being scheduled. + */ + public static final String SCHEDULE_ID = "schedule.id"; + + /** + * The key for the startup argument used to pass the event object that + * triggered the schedule to launch the application instance. + * The event is passed in a {@link java.security.GuardedObject} + * protected by the corresponding + * {@link org.osgi.service.event.TopicPermission}. + */ + public static final String TRIGGERING_EVENT = "org.osgi.triggeringevent"; + + /** + * The topic name for the virtual timer topic. Time based schedules + * should be created using this topic. + */ + public static final String TIMER_TOPIC = "org/osgi/application/timer"; + + /** + * The name of the <i>year</i> attribute of a virtual timer event. The value is + * defined by {@link java.util.Calendar#YEAR}. + */ + public static final String YEAR = "year"; + + /** + * The name of the <i>month</i> attribute of a virtual timer event. The value is + * defined by {@link java.util.Calendar#MONTH}. + */ + public static final String MONTH = "month"; + + /** + * The name of the <i>day of month</i> attribute of a virtual timer event. The value is + * defined by {@link java.util.Calendar#DAY_OF_MONTH}. + */ + public static final String DAY_OF_MONTH = "day_of_month"; + + /** + * The name of the <i>day of week</i> attribute of a virtual timer event. The value is + * defined by {@link java.util.Calendar#DAY_OF_WEEK}. + */ + public static final String DAY_OF_WEEK = "day_of_week"; + + /** + * The name of the <i>hour of day</i> attribute of a virtual timer event. The value is + * defined by {@link java.util.Calendar#HOUR_OF_DAY}. + */ + public static final String HOUR_OF_DAY = "hour_of_day"; + + /** + * The name of the <i>minute</i> attribute of a virtual timer event. The value is + * defined by {@link java.util.Calendar#MINUTE}. + */ + public static final String MINUTE = "minute"; + + + /** + * Returns the identifier of this schedule. The identifier is unique within + * the scope of the application that the schedule is related to. + * @return the identifier of this schedule + * + */ + public String getScheduleId(); /** * Queries the topic of the triggering event. The topic may contain a diff --git a/bundles/org.eclipse.equinox.bidi/src/org/eclipse/equinox/bidi/internal/consumable/StructuredTextJava.java b/bundles/org.eclipse.equinox.bidi/src/org/eclipse/equinox/bidi/internal/consumable/StructuredTextJava.java index 7ab09a5eb..b93b36a78 100644 --- a/bundles/org.eclipse.equinox.bidi/src/org/eclipse/equinox/bidi/internal/consumable/StructuredTextJava.java +++ b/bundles/org.eclipse.equinox.bidi/src/org/eclipse/equinox/bidi/internal/consumable/StructuredTextJava.java @@ -51,14 +51,14 @@ public class StructuredTextJava extends StructuredTextTypeHandler { } /** - * Locates occurrences of 4 special strings: - * <ol> - * <li>spaces</li> - * <li>literals starting with quotation mark</li> - * <li>comments starting with slash-asterisk</li> - * <li>comments starting with slash-slash</li> - * </ol> - */ + * Locates occurrences of 4 special strings: + * <ol> + * <li>spaces</li> + * <li>literals starting with quotation mark</li> + * <li>comments starting with slash-asterisk</li> + * <li>comments starting with slash-slash</li> + * </ol> + */ @Override public int indexOfSpecial(IStructuredTextExpert expert, String text, StructuredTextCharTypes charTypes, StructuredTextOffsets offsets, int caseNumber, int fromIndex) { switch (caseNumber) { @@ -77,12 +77,12 @@ public class StructuredTextJava extends StructuredTextTypeHandler { /** * Processes the 4 special cases as follows. - * <ol> - * <li>skip the run of spaces</li> - * <li>look for a matching quotation mark and skip until after it</li> - * <li>skip until after the closing asterisk-slash</li> - * <li>skip until after a line separator</li> - * </ol> + * <ol> + * <li>skip the run of spaces</li> + * <li>look for a matching quotation mark and skip until after it</li> + * <li>skip until after the closing asterisk-slash</li> + * <li>skip until after a line separator</li> + * </ol> */ @Override public int processSpecial(IStructuredTextExpert expert, String text, StructuredTextCharTypes charTypes, StructuredTextOffsets offsets, int caseNumber, int separLocation) { diff --git a/bundles/org.eclipse.equinox.bidi/src/org/eclipse/equinox/bidi/internal/consumable/StructuredTextSql.java b/bundles/org.eclipse.equinox.bidi/src/org/eclipse/equinox/bidi/internal/consumable/StructuredTextSql.java index 4df8339f3..938cccd47 100644 --- a/bundles/org.eclipse.equinox.bidi/src/org/eclipse/equinox/bidi/internal/consumable/StructuredTextSql.java +++ b/bundles/org.eclipse.equinox.bidi/src/org/eclipse/equinox/bidi/internal/consumable/StructuredTextSql.java @@ -52,15 +52,15 @@ public class StructuredTextSql extends StructuredTextTypeHandler { } /** - * Locates occurrences of 5 special strings: - * <ol> - * <li>spaces</li> - * <li>literals starting with apostrophe</li> - * <li>identifiers starting with quotation mark</li> - * <li>comments starting with slash-asterisk</li> - * <li>comments starting with hyphen-hyphen</li> - * </ol> - */ + * Locates occurrences of 5 special strings: + * <ol> + * <li>spaces</li> + * <li>literals starting with apostrophe</li> + * <li>identifiers starting with quotation mark</li> + * <li>comments starting with slash-asterisk</li> + * <li>comments starting with hyphen-hyphen</li> + * </ol> + */ @Override public int indexOfSpecial(IStructuredTextExpert expert, String text, StructuredTextCharTypes charTypes, StructuredTextOffsets offsets, int caseNumber, int fromIndex) { switch (caseNumber) { @@ -81,13 +81,13 @@ public class StructuredTextSql extends StructuredTextTypeHandler { /** * Processes the 5 special cases as follows. - * <ol> - * <li>skip the run of spaces</li> - * <li>look for a matching apostrophe and skip until after it</li> - * <li>look for a matching quotation mark and skip until after it</li> - * <li>skip until after the closing asterisk-slash</li> - * <li>skip until after a line separator</li> - * </ol> + * <ol> + * <li>skip the run of spaces</li> + * <li>look for a matching apostrophe and skip until after it</li> + * <li>look for a matching quotation mark and skip until after it</li> + * <li>skip until after the closing asterisk-slash</li> + * <li>skip until after a line separator</li> + * </ol> */ @Override public int processSpecial(IStructuredTextExpert expert, String text, StructuredTextCharTypes charTypes, StructuredTextOffsets offsets, int caseNumber, int separLocation) { diff --git a/bundles/org.eclipse.equinox.common/src/org/eclipse/core/runtime/CoreException.java b/bundles/org.eclipse.equinox.common/src/org/eclipse/core/runtime/CoreException.java index 0e5919aaa..0e7dbd5bf 100644 --- a/bundles/org.eclipse.equinox.common/src/org/eclipse/core/runtime/CoreException.java +++ b/bundles/org.eclipse.equinox.common/src/org/eclipse/core/runtime/CoreException.java @@ -48,11 +48,11 @@ public class CoreException extends Exception { } /** - * Returns the cause of this exception, or <code>null</code> if none. - * - * @return the cause for this exception - * @since 3.4 - */ + * Returns the cause of this exception, or <code>null</code> if none. + * + * @return the cause for this exception + * @since 3.4 + */ @Override public Throwable getCause() { return status.getException(); diff --git a/bundles/org.eclipse.equinox.console.ssh.tests/src/org/eclipse/equinox/console/ssh/SshInputHandlerTests.java b/bundles/org.eclipse.equinox.console.ssh.tests/src/org/eclipse/equinox/console/ssh/SshInputHandlerTests.java index 98812da6a..561d41712 100755 --- a/bundles/org.eclipse.equinox.console.ssh.tests/src/org/eclipse/equinox/console/ssh/SshInputHandlerTests.java +++ b/bundles/org.eclipse.equinox.console.ssh.tests/src/org/eclipse/equinox/console/ssh/SshInputHandlerTests.java @@ -28,23 +28,23 @@ public class SshInputHandlerTests { private static final long WAIT_TIME = 10000; - @Test - public void testHandler() throws Exception { + @Test + public void testHandler() throws Exception { ByteArrayInputStream input = new ByteArrayInputStream("abcde".getBytes(StandardCharsets.UTF_8)); - ConsoleInputStream in = new ConsoleInputStream(); - ByteArrayOutputStream byteOut = new ByteArrayOutputStream(); - ConsoleOutputStream out = new ConsoleOutputStream(byteOut); - SshInputHandler handler = new SshInputHandler(input, in, out); - handler.start(); - - // wait for the accept thread to start execution - try { - Thread.sleep(WAIT_TIME); - } catch (InterruptedException ie) { - // do nothing - } - - String res = byteOut.toString(); - Assert.assertTrue("Wrong input. Expected abcde, read " + res, res.equals("abcde")); - } + ConsoleInputStream in = new ConsoleInputStream(); + ByteArrayOutputStream byteOut = new ByteArrayOutputStream(); + ConsoleOutputStream out = new ConsoleOutputStream(byteOut); + SshInputHandler handler = new SshInputHandler(input, in, out); + handler.start(); + + // wait for the accept thread to start execution + try { + Thread.sleep(WAIT_TIME); + } catch (InterruptedException ie) { + // do nothing + } + + String res = byteOut.toString(); + Assert.assertTrue("Wrong input. Expected abcde, read " + res, res.equals("abcde")); + } } diff --git a/bundles/org.eclipse.equinox.console.ssh.tests/src/org/eclipse/equinox/console/ssh/SshInputScannerTests.java b/bundles/org.eclipse.equinox.console.ssh.tests/src/org/eclipse/equinox/console/ssh/SshInputScannerTests.java index c2d620501..bb641ba97 100755 --- a/bundles/org.eclipse.equinox.console.ssh.tests/src/org/eclipse/equinox/console/ssh/SshInputScannerTests.java +++ b/bundles/org.eclipse.equinox.console.ssh.tests/src/org/eclipse/equinox/console/ssh/SshInputScannerTests.java @@ -28,43 +28,43 @@ public class SshInputScannerTests { private static final byte ESC = 27; @Test - public void testScan() throws Exception { - ConsoleInputStream in = new ConsoleInputStream(); - ByteArrayOutputStream byteOut = new ByteArrayOutputStream(); - ConsoleOutputStream out = new ConsoleOutputStream(byteOut); - SshInputScanner scanner = new SshInputScanner(in, out); - try { - scanner.scan((byte) 'a'); - scanner.scan((byte) 'b'); - scanner.scan((byte) 'c'); - } catch (IOException e) { - System.out.println("Error while scanning: " + e.getMessage()); - e.printStackTrace(); - throw e; - } + public void testScan() throws Exception { + ConsoleInputStream in = new ConsoleInputStream(); + ByteArrayOutputStream byteOut = new ByteArrayOutputStream(); + ConsoleOutputStream out = new ConsoleOutputStream(byteOut); + SshInputScanner scanner = new SshInputScanner(in, out); + try { + scanner.scan((byte) 'a'); + scanner.scan((byte) 'b'); + scanner.scan((byte) 'c'); + } catch (IOException e) { + System.out.println("Error while scanning: " + e.getMessage()); + e.printStackTrace(); + throw e; + } - String output = byteOut.toString(); - Assert.assertTrue("Output incorrect. Expected abc, but read " + output, output.equals("abc")); - } + String output = byteOut.toString(); + Assert.assertTrue("Output incorrect. Expected abc, but read " + output, output.equals("abc")); + } - @Test - public void testScanESC() throws Exception { - ConsoleInputStream in = new ConsoleInputStream(); - ByteArrayOutputStream byteOut = new ByteArrayOutputStream(); - ConsoleOutputStream out = new ConsoleOutputStream(byteOut); - SshInputScanner scanner = new SshInputScanner(in, out); + @Test + public void testScanESC() throws Exception { + ConsoleInputStream in = new ConsoleInputStream(); + ByteArrayOutputStream byteOut = new ByteArrayOutputStream(); + ConsoleOutputStream out = new ConsoleOutputStream(byteOut); + SshInputScanner scanner = new SshInputScanner(in, out); - try { - scanner.scan((byte) 'a'); - scanner.scan(ESC); - scanner.scan((byte) 'b'); - } catch (IOException e) { - System.out.println("Error while scanning: " + e.getMessage()); - e.printStackTrace(); - throw e; - } + try { + scanner.scan((byte) 'a'); + scanner.scan(ESC); + scanner.scan((byte) 'b'); + } catch (IOException e) { + System.out.println("Error while scanning: " + e.getMessage()); + e.printStackTrace(); + throw e; + } - String output = byteOut.toString(); - Assert.assertTrue("Output incorrect. Expected ab, but read " + output, output.equals("ab")); - } + String output = byteOut.toString(); + Assert.assertTrue("Output incorrect. Expected ab, but read " + output, output.equals("ab")); + } } diff --git a/bundles/org.eclipse.equinox.console.ssh.tests/src/org/eclipse/equinox/console/ssh/UserAdminCommandTests.java b/bundles/org.eclipse.equinox.console.ssh.tests/src/org/eclipse/equinox/console/ssh/UserAdminCommandTests.java index 3ed7b1673..5ee73275f 100755 --- a/bundles/org.eclipse.equinox.console.ssh.tests/src/org/eclipse/equinox/console/ssh/UserAdminCommandTests.java +++ b/bundles/org.eclipse.equinox.console.ssh.tests/src/org/eclipse/equinox/console/ssh/UserAdminCommandTests.java @@ -55,14 +55,14 @@ public class UserAdminCommandTests { SecureUserStore.initStorage(); CommandSession session = EasyMock.createMock(CommandSession.class); - EasyMock.expect(session.put((String)EasyMock.anyObject(), EasyMock.anyObject())).andReturn(new Object()).times(3); - EasyMock.replay(session); - - UserAdminCommand command = new UserAdminCommand(); - command.addUser(new String[] {USERNAME_OPTION, USERNAME1, PASSWORD_OPTION, PASSWORD1}); - command.addUser(new String[] {USERNAME_OPTION, USERNAME2, PASSWORD_OPTION, PASSWORD2, ROLES_OPTION, ROLES2}); - - String[] usernames = SecureUserStore.getUserNames(); + EasyMock.expect(session.put((String)EasyMock.anyObject(), EasyMock.anyObject())).andReturn(new Object()).times(3); + EasyMock.replay(session); + + UserAdminCommand command = new UserAdminCommand(); + command.addUser(new String[] {USERNAME_OPTION, USERNAME1, PASSWORD_OPTION, PASSWORD1}); + command.addUser(new String[] {USERNAME_OPTION, USERNAME2, PASSWORD_OPTION, PASSWORD2, ROLES_OPTION, ROLES2}); + + String[] usernames = SecureUserStore.getUserNames(); boolean arePresent = (usernames[0].equals(USERNAME1) || usernames[0].equals(USERNAME2)) && (usernames[1].equals(USERNAME1) || usernames[1].equals(USERNAME2)) && (!usernames[0].equals(usernames[1])); assertTrue("Usernames not correctly saved", arePresent); @@ -98,10 +98,10 @@ public class UserAdminCommandTests { @After public void cleanUp() { System.setProperty(USER_STORE_FILE_NAME_PROPERTY, ""); - File file = new File(USER_STORE_FILE_NAME); - if(file.exists()) { - file.delete(); - } + File file = new File(USER_STORE_FILE_NAME); + if(file.exists()) { + file.delete(); + } } private boolean compareRoles(String expectedRoles, String actualRoles) { diff --git a/bundles/org.eclipse.equinox.console.ssh.tests/src/org/eclipse/equinox/console/storage/DigestUtilTests.java b/bundles/org.eclipse.equinox.console.ssh.tests/src/org/eclipse/equinox/console/storage/DigestUtilTests.java index f657ae1aa..8201a1213 100755 --- a/bundles/org.eclipse.equinox.console.ssh.tests/src/org/eclipse/equinox/console/storage/DigestUtilTests.java +++ b/bundles/org.eclipse.equinox.console.ssh.tests/src/org/eclipse/equinox/console/storage/DigestUtilTests.java @@ -30,30 +30,30 @@ public class DigestUtilTests { @Test public void testEncrypt() throws Exception { MessageDigest md = MessageDigest.getInstance(MD5); - md.update(TEXT.getBytes()); - byte[] digest = md.digest(); - - char[] chars = new char[2 * digest.length]; - for (int i = 0; i < digest.length; ++i) - { - chars[2 * i] = HEX_CHARS[(digest[i] & 0xF0) >>> 4]; - chars[2 * i + 1] = HEX_CHARS[digest[i] & 0x0F]; - } - - String modifiedText = TEXT + new String(chars); - md = MessageDigest.getInstance(SHA1); - md.update(modifiedText.getBytes()); - digest = md.digest(); - - chars = new char[2 * digest.length]; - for (int i = 0; i < digest.length; ++i) - { - chars[2 * i] = HEX_CHARS[(digest[i] & 0xF0) >>> 4]; - chars[2 * i + 1] = HEX_CHARS[digest[i] & 0x0F]; - } - - String expectedEncryptedText = new String(chars); - - assertEquals("Encrypted text not as expected", expectedEncryptedText, DigestUtil.encrypt(TEXT)); + md.update(TEXT.getBytes()); + byte[] digest = md.digest(); + + char[] chars = new char[2 * digest.length]; + for (int i = 0; i < digest.length; ++i) + { + chars[2 * i] = HEX_CHARS[(digest[i] & 0xF0) >>> 4]; + chars[2 * i + 1] = HEX_CHARS[digest[i] & 0x0F]; + } + + String modifiedText = TEXT + new String(chars); + md = MessageDigest.getInstance(SHA1); + md.update(modifiedText.getBytes()); + digest = md.digest(); + + chars = new char[2 * digest.length]; + for (int i = 0; i < digest.length; ++i) + { + chars[2 * i] = HEX_CHARS[(digest[i] & 0xF0) >>> 4]; + chars[2 * i + 1] = HEX_CHARS[digest[i] & 0x0F]; + } + + String expectedEncryptedText = new String(chars); + + assertEquals("Encrypted text not as expected", expectedEncryptedText, DigestUtil.encrypt(TEXT)); } } diff --git a/bundles/org.eclipse.equinox.console.ssh.tests/src/org/eclipse/equinox/console/storage/SecureUserStoreTests.java b/bundles/org.eclipse.equinox.console.ssh.tests/src/org/eclipse/equinox/console/storage/SecureUserStoreTests.java index a407847aa..4a0204d47 100755 --- a/bundles/org.eclipse.equinox.console.ssh.tests/src/org/eclipse/equinox/console/storage/SecureUserStoreTests.java +++ b/bundles/org.eclipse.equinox.console.ssh.tests/src/org/eclipse/equinox/console/storage/SecureUserStoreTests.java @@ -91,10 +91,10 @@ public class SecureUserStoreTests { @After public void cleanUp() { System.setProperty(USER_STORE_FILE_NAME_PROPERTY, ""); - File file = new File(USER_STORE_FILE_NAME); - if(file.exists()) { - file.delete(); - } + File file = new File(USER_STORE_FILE_NAME); + if(file.exists()) { + file.delete(); + } } private boolean compareRoles(String expectedRoles, String actualRoles) { diff --git a/bundles/org.eclipse.equinox.console.ssh/src/org/eclipse/equinox/console/ssh/SshCommand.java b/bundles/org.eclipse.equinox.console.ssh/src/org/eclipse/equinox/console/ssh/SshCommand.java index 98fd230e3..064909ef6 100755 --- a/bundles/org.eclipse.equinox.console.ssh/src/org/eclipse/equinox/console/ssh/SshCommand.java +++ b/bundles/org.eclipse.equinox.console.ssh/src/org/eclipse/equinox/console/ssh/SshCommand.java @@ -39,66 +39,66 @@ import org.osgi.service.cm.ManagedService; public class SshCommand { private String defaultHost = null; private int defaultPort; - private List<CommandProcessor> processors = new ArrayList<>(); - private String host = null; - private int port; - private SshServ sshServ; - private BundleContext context; - private ServiceRegistration<?> configuratorRegistration; - private boolean isEnabled = false; - private final Object lock = new Object(); - - private static final String DEFAULT_USER = "equinox"; - private static final String DEFAULT_PASSWORD = "equinox"; - private static final String DEFAULT_USER_STORE_PROPERTY = "osgi.console.ssh.useDefaultSecureStorage"; - private static final String HOST = "host"; - private static final String PORT = "port"; - private static final String USE_CONFIG_ADMIN_PROP = "osgi.console.useConfigAdmin"; - private static final String SSH_PID = "osgi.console.ssh"; - private static final String ENABLED = "enabled"; - - public SshCommand(CommandProcessor processor, BundleContext context) { - processors.add(processor); - this.context = context; - - if ("true".equals(context.getProperty(USE_CONFIG_ADMIN_PROP))) { - Dictionary<String, String> sshProperties = new Hashtable<>(); - sshProperties.put(Constants.SERVICE_PID, SSH_PID); - try { - synchronized (lock) { - configuratorRegistration = context.registerService(ManagedService.class.getName(), new SshConfigurator(), sshProperties); - } - } catch (NoClassDefFoundError e) { - System.out.println("Configuration Admin not available!"); - return; - } - } else { - parseHostAndPort(); - } - } - - private void parseHostAndPort() { - String sshPort = null; - String consolePropValue = context.getProperty(SSH_PID); - if(consolePropValue != null) { - int index = consolePropValue.lastIndexOf(":"); - if (index > -1) { - defaultHost = consolePropValue.substring(0, index); - } - sshPort = consolePropValue.substring(index + 1); - isEnabled = true; - } - if (sshPort != null && !"".equals(sshPort)) { - try { - defaultPort = Integer.parseInt(sshPort); + private List<CommandProcessor> processors = new ArrayList<>(); + private String host = null; + private int port; + private SshServ sshServ; + private BundleContext context; + private ServiceRegistration<?> configuratorRegistration; + private boolean isEnabled = false; + private final Object lock = new Object(); + + private static final String DEFAULT_USER = "equinox"; + private static final String DEFAULT_PASSWORD = "equinox"; + private static final String DEFAULT_USER_STORE_PROPERTY = "osgi.console.ssh.useDefaultSecureStorage"; + private static final String HOST = "host"; + private static final String PORT = "port"; + private static final String USE_CONFIG_ADMIN_PROP = "osgi.console.useConfigAdmin"; + private static final String SSH_PID = "osgi.console.ssh"; + private static final String ENABLED = "enabled"; + + public SshCommand(CommandProcessor processor, BundleContext context) { + processors.add(processor); + this.context = context; + + if ("true".equals(context.getProperty(USE_CONFIG_ADMIN_PROP))) { + Dictionary<String, String> sshProperties = new Hashtable<>(); + sshProperties.put(Constants.SERVICE_PID, SSH_PID); + try { + synchronized (lock) { + configuratorRegistration = context.registerService(ManagedService.class.getName(), new SshConfigurator(), sshProperties); + } + } catch (NoClassDefFoundError e) { + System.out.println("Configuration Admin not available!"); + return; + } + } else { + parseHostAndPort(); + } + } + + private void parseHostAndPort() { + String sshPort = null; + String consolePropValue = context.getProperty(SSH_PID); + if(consolePropValue != null) { + int index = consolePropValue.lastIndexOf(":"); + if (index > -1) { + defaultHost = consolePropValue.substring(0, index); + } + sshPort = consolePropValue.substring(index + 1); + isEnabled = true; + } + if (sshPort != null && !"".equals(sshPort)) { + try { + defaultPort = Integer.parseInt(sshPort); } catch (NumberFormatException e) { // do nothing } - } - } - - public synchronized void startService() { - Dictionary<String, Object> properties = new Hashtable<>(); + } + } + + public synchronized void startService() { + Dictionary<String, Object> properties = new Hashtable<>(); properties.put("osgi.command.scope", "equinox"); properties.put("osgi.command.function", new String[] {"ssh"}); if ((port > 0 || defaultPort > 0) && isEnabled == true) { @@ -110,162 +110,162 @@ public class SshCommand { } } context.registerService(SshCommand.class.getName(), this, properties); - } + } - @Descriptor("start/stop a ssh server") - public synchronized void ssh(String[] arguments) throws Exception { - String command = null; - String newHost = null; - int newPort = 0; - - for(int i = 0; i < arguments.length; i++) { - if("-?".equals(arguments[i]) || "-help".equals(arguments[i])) { - printHelp(); - return; - } else if("start".equals(arguments[i])) { - command = "start"; - } else if ("stop".equals(arguments[i])) { - command = "stop"; - } else if ("-port".equals(arguments[i]) && (arguments.length > i + 1)) { - i++; - newPort = Integer.parseInt(arguments[i]); - } else if ("-host".equals(arguments[i]) && (arguments.length > i + 1)) { - i++; - newHost = arguments[i]; - } else { - throw new Exception("Unrecognized ssh command/option " + arguments[i]); - } - } - - if (command == null) { - throw new Exception("No ssh command specified"); - } - - if (newPort != 0) { - port = newPort; - } else if (port == 0) { - port = defaultPort; - } - - if (port == 0) { - throw new Exception("No ssh port specified"); - } - - if (newHost != null) { - host = newHost; - } else { - host = defaultHost; - } - - if ("start".equals(command)) { - if (sshServ != null) { - throw new IllegalStateException("ssh is already running on port " + port); - } - - checkPortAvailable(port); - - sshServ = new SshServ(processors, context, host, port); - sshServ.setName("equinox ssh"); - - if ("true".equals(context.getProperty(DEFAULT_USER_STORE_PROPERTY))) { - try { - checkUserStore(); - registerUserAdmin(); - } catch (NoClassDefFoundError e) { - System.out.println("If you want to use secure storage, please install Equinox security bundle and its dependencies"); - sshServ = null; - return; - } catch (IOException e) { - e.printStackTrace(); - sshServ = null; - return; - } - } - - try { + @Descriptor("start/stop a ssh server") + public synchronized void ssh(String[] arguments) throws Exception { + String command = null; + String newHost = null; + int newPort = 0; + + for(int i = 0; i < arguments.length; i++) { + if("-?".equals(arguments[i]) || "-help".equals(arguments[i])) { + printHelp(); + return; + } else if("start".equals(arguments[i])) { + command = "start"; + } else if ("stop".equals(arguments[i])) { + command = "stop"; + } else if ("-port".equals(arguments[i]) && (arguments.length > i + 1)) { + i++; + newPort = Integer.parseInt(arguments[i]); + } else if ("-host".equals(arguments[i]) && (arguments.length > i + 1)) { + i++; + newHost = arguments[i]; + } else { + throw new Exception("Unrecognized ssh command/option " + arguments[i]); + } + } + + if (command == null) { + throw new Exception("No ssh command specified"); + } + + if (newPort != 0) { + port = newPort; + } else if (port == 0) { + port = defaultPort; + } + + if (port == 0) { + throw new Exception("No ssh port specified"); + } + + if (newHost != null) { + host = newHost; + } else { + host = defaultHost; + } + + if ("start".equals(command)) { + if (sshServ != null) { + throw new IllegalStateException("ssh is already running on port " + port); + } + + checkPortAvailable(port); + + sshServ = new SshServ(processors, context, host, port); + sshServ.setName("equinox ssh"); + + if ("true".equals(context.getProperty(DEFAULT_USER_STORE_PROPERTY))) { + try { + checkUserStore(); + registerUserAdmin(); + } catch (NoClassDefFoundError e) { + System.out.println("If you want to use secure storage, please install Equinox security bundle and its dependencies"); + sshServ = null; + return; + } catch (IOException e) { + e.printStackTrace(); + sshServ = null; + return; + } + } + + try { sshServ.start(); } catch (RuntimeException e) { sshServ = null; return; } - } else if ("stop".equals(command)) { - if (sshServ == null) { - System.out.println("ssh is not running."); - return; - } - - sshServ.stopSshServer(); - sshServ = null; - } - } - - public synchronized void addCommandProcessor(CommandProcessor processor) { - processors.add(processor); - if (sshServ != null) { - sshServ.addCommandProcessor(processor); - } - } - - public synchronized void removeCommandProcessor(CommandProcessor processor) { - processors.remove(processor); - if (sshServ != null) { - sshServ.removeCommandProcessor(processor); - } - } - - private void checkPortAvailable(int port) throws Exception { - try (ServerSocket socket = new ServerSocket(port)){ - } catch (BindException e) { - throw new Exception ("Port " + port + " already in use"); - } - } - - /* - * Register user administration commands - */ - private void registerUserAdmin() { - Dictionary<String, Object> properties = new Hashtable<>(); + } else if ("stop".equals(command)) { + if (sshServ == null) { + System.out.println("ssh is not running."); + return; + } + + sshServ.stopSshServer(); + sshServ = null; + } + } + + public synchronized void addCommandProcessor(CommandProcessor processor) { + processors.add(processor); + if (sshServ != null) { + sshServ.addCommandProcessor(processor); + } + } + + public synchronized void removeCommandProcessor(CommandProcessor processor) { + processors.remove(processor); + if (sshServ != null) { + sshServ.removeCommandProcessor(processor); + } + } + + private void checkPortAvailable(int port) throws Exception { + try (ServerSocket socket = new ServerSocket(port)){ + } catch (BindException e) { + throw new Exception ("Port " + port + " already in use"); + } + } + + /* + * Register user administration commands + */ + private void registerUserAdmin() { + Dictionary<String, Object> properties = new Hashtable<>(); properties.put("osgi.command.scope", "equinox"); properties.put("osgi.command.function", new String[] {"addUser", "addUser", "deleteUser", "resetPassword", "setPassword", "addRoles", "removeRoles", "listUsers"}); context.registerService(UserAdminCommand.class.getName(), new UserAdminCommand(), properties); - } - - /* - * Create user store if not available. Add the default user, if there is no other user in the store. - */ - private void checkUserStore() throws Exception { - SecureUserStore.initStorage(); - if(SecureUserStore.getUserNames().length == 0) { - SecureUserStore.putUser(DEFAULT_USER, DigestUtil.encrypt(DEFAULT_PASSWORD), null ); - } - } - - private void printHelp() { - StringBuffer help = new StringBuffer(); - help.append("ssh - start simple ssh server"); - help.append("\n"); - help.append("Usage: ssh start | stop [-port port] [-host host]"); - help.append("\n"); - help.append("\t"); - help.append("-port"); - help.append("\t"); - help.append("listen port (default="); - help.append(defaultPort); - help.append(")"); - help.append("\n"); - help.append("\t"); - help.append("-host"); - help.append("\t"); - help.append("local host address to listen on (default is none - listen on all network interfaces)"); - help.append("\n"); - help.append("\t"); - help.append("-?, -help"); - help.append("\t"); - help.append("show help"); - System.out.println(help.toString()); - } - - class SshConfigurator implements ManagedService { + } + + /* + * Create user store if not available. Add the default user, if there is no other user in the store. + */ + private void checkUserStore() throws Exception { + SecureUserStore.initStorage(); + if(SecureUserStore.getUserNames().length == 0) { + SecureUserStore.putUser(DEFAULT_USER, DigestUtil.encrypt(DEFAULT_PASSWORD), null ); + } + } + + private void printHelp() { + StringBuffer help = new StringBuffer(); + help.append("ssh - start simple ssh server"); + help.append("\n"); + help.append("Usage: ssh start | stop [-port port] [-host host]"); + help.append("\n"); + help.append("\t"); + help.append("-port"); + help.append("\t"); + help.append("listen port (default="); + help.append(defaultPort); + help.append(")"); + help.append("\n"); + help.append("\t"); + help.append("-host"); + help.append("\t"); + help.append("local host address to listen on (default is none - listen on all network interfaces)"); + help.append("\n"); + help.append("\t"); + help.append("-?, -help"); + help.append("\t"); + help.append("show help"); + System.out.println(help.toString()); + } + + class SshConfigurator implements ManagedService { private Dictionary<String, Object> properties; @Override public synchronized void updated(Dictionary<String, ?> props) throws ConfigurationException { @@ -297,6 +297,6 @@ public class SshCommand { } } } - - } + + } } diff --git a/bundles/org.eclipse.equinox.console.ssh/src/org/eclipse/equinox/console/ssh/SshInputHandler.java b/bundles/org.eclipse.equinox.console.ssh/src/org/eclipse/equinox/console/ssh/SshInputHandler.java index 701d9702f..ac7dc2272 100755 --- a/bundles/org.eclipse.equinox.console.ssh/src/org/eclipse/equinox/console/ssh/SshInputHandler.java +++ b/bundles/org.eclipse.equinox.console.ssh/src/org/eclipse/equinox/console/ssh/SshInputHandler.java @@ -27,7 +27,7 @@ import org.eclipse.equinox.console.common.InputHandler; */ public class SshInputHandler extends InputHandler { public SshInputHandler(InputStream input, ConsoleInputStream in, ConsoleOutputStream out) { - super(input, in, out); - inputScanner = new SshInputScanner(in, out); - } + super(input, in, out); + inputScanner = new SshInputScanner(in, out); + } } diff --git a/bundles/org.eclipse.equinox.console.ssh/src/org/eclipse/equinox/console/ssh/SshInputScanner.java b/bundles/org.eclipse.equinox.console.ssh/src/org/eclipse/equinox/console/ssh/SshInputScanner.java index f0b106c0f..c7207bf9b 100755 --- a/bundles/org.eclipse.equinox.console.ssh/src/org/eclipse/equinox/console/ssh/SshInputScanner.java +++ b/bundles/org.eclipse.equinox.console.ssh/src/org/eclipse/equinox/console/ssh/SshInputScanner.java @@ -31,11 +31,11 @@ public class SshInputScanner extends Scanner { public SshInputScanner(ConsoleInputStream toShell, OutputStream toTelnet) { super(toShell, toTelnet); - TerminalTypeMappings currentMapping = supportedEscapeSequences.get(DEFAULT_TTYPE); - currentEscapesToKey = currentMapping.getEscapesToKey(); - escapes = currentMapping.getEscapes(); - setBackspace(currentMapping.getBackspace()); - setDel(currentMapping.getDel()); + TerminalTypeMappings currentMapping = supportedEscapeSequences.get(DEFAULT_TTYPE); + currentEscapesToKey = currentMapping.getEscapesToKey(); + escapes = currentMapping.getEscapes(); + setBackspace(currentMapping.getBackspace()); + setDel(currentMapping.getDel()); } @Override @@ -43,37 +43,37 @@ public class SshInputScanner extends Scanner { b &= 0xFF; if (isEsc) { - scanEsc(b); - } else { - switch (b) { - case ESC: - startEsc(); - toShell.add(new byte[]{(byte) b}); - break; - default: - if (b >= SPACE && b < MAX_CHAR) { - echo((byte) b); - flush(); - } - toShell.add(new byte[]{(byte) b}); - } - } + scanEsc(b); + } else { + switch (b) { + case ESC: + startEsc(); + toShell.add(new byte[]{(byte) b}); + break; + default: + if (b >= SPACE && b < MAX_CHAR) { + echo((byte) b); + flush(); + } + toShell.add(new byte[]{(byte) b}); + } + } } @Override protected void scanEsc(int b) throws IOException { esc += (char) b; - toShell.add(new byte[]{(byte) b}); - KEYS key = checkEscape(esc); - if (key == KEYS.UNFINISHED) { - return; - } - if (key == KEYS.UNKNOWN) { - isEsc = false; - scan(b); - return; - } - isEsc = false; + toShell.add(new byte[]{(byte) b}); + KEYS key = checkEscape(esc); + if (key == KEYS.UNFINISHED) { + return; + } + if (key == KEYS.UNKNOWN) { + isEsc = false; + scan(b); + return; + } + isEsc = false; } } diff --git a/bundles/org.eclipse.equinox.console.ssh/src/org/eclipse/equinox/console/ssh/SshServ.java b/bundles/org.eclipse.equinox.console.ssh/src/org/eclipse/equinox/console/ssh/SshServ.java index 6f2efb4d5..27c537c1e 100644 --- a/bundles/org.eclipse.equinox.console.ssh/src/org/eclipse/equinox/console/ssh/SshServ.java +++ b/bundles/org.eclipse.equinox.console.ssh/src/org/eclipse/equinox/console/ssh/SshServ.java @@ -47,55 +47,55 @@ public class SshServ extends Thread { private static final String SSH_CUSTOM_PUBLIC_KEY_AUTHENTICATION = "ssh.custom.publickeys.auth"; private static final String EQUINOX_CONSOLE_DOMAIN = "equinox_console"; - public SshServ(List<CommandProcessor> processors, BundleContext context, String host, int port) { - this.context = context; + public SshServ(List<CommandProcessor> processors, BundleContext context, String host, int port) { + this.context = context; this.host = host; - this.port = port; - shellFactory = new SshShellFactory(processors, context); - } + this.port = port; + shellFactory = new SshShellFactory(processors, context); + } - @Override + @Override public void run() throws RuntimeException { - sshServer = SshServer.setUpDefaultServer(); + sshServer = SshServer.setUpDefaultServer(); if (host != null) { sshServer.setHost(host); } - sshServer.setPort(port); - sshServer.setKeyPairProvider(new SimpleGeneratorHostKeyProvider(Paths.get(System.getProperty(SSH_KEYSTORE_PROP, SSH_KEYSTORE_PROP_DEFAULT)))); - sshServer.setShellFactory(shellFactory); - sshServer.setPasswordAuthenticator(createJaasPasswordAuthenticator()); - sshServer.setPublickeyAuthenticator(createSimpleAuthorizedKeysAuthenticator()); - try { + sshServer.setPort(port); + sshServer.setKeyPairProvider(new SimpleGeneratorHostKeyProvider(Paths.get(System.getProperty(SSH_KEYSTORE_PROP, SSH_KEYSTORE_PROP_DEFAULT)))); + sshServer.setShellFactory(shellFactory); + sshServer.setPasswordAuthenticator(createJaasPasswordAuthenticator()); + sshServer.setPublickeyAuthenticator(createSimpleAuthorizedKeysAuthenticator()); + try { sshServer.start(); } catch (IOException e) { e.printStackTrace(); } - } + } public synchronized void stopSshServer() { - try { + try { sshServer.stop(true); } catch (IOException e) { e.printStackTrace(); } - } + } - public synchronized void addCommandProcessor(CommandProcessor processor) { - shellFactory.addCommandProcessor(processor); - } + public synchronized void addCommandProcessor(CommandProcessor processor) { + shellFactory.addCommandProcessor(processor); + } - public synchronized void removeCommandProcessor(CommandProcessor processor) { - shellFactory.removeCommandProcessor(processor); - } + public synchronized void removeCommandProcessor(CommandProcessor processor) { + shellFactory.removeCommandProcessor(processor); + } - private PasswordAuthenticator createJaasPasswordAuthenticator() { - JaasPasswordAuthenticator jaasPasswordAuthenticator = new JaasPasswordAuthenticator(); - jaasPasswordAuthenticator.setDomain(EQUINOX_CONSOLE_DOMAIN); - return jaasPasswordAuthenticator; - } + private PasswordAuthenticator createJaasPasswordAuthenticator() { + JaasPasswordAuthenticator jaasPasswordAuthenticator = new JaasPasswordAuthenticator(); + jaasPasswordAuthenticator.setDomain(EQUINOX_CONSOLE_DOMAIN); + return jaasPasswordAuthenticator; + } - private PublickeyAuthenticator createSimpleAuthorizedKeysAuthenticator() { + private PublickeyAuthenticator createSimpleAuthorizedKeysAuthenticator() { // use authorized keys file if property is set final String authorizedKeysFile = System.getProperty(SSH_AUTHORIZED_KEYS_FILE_PROP); if (null != authorizedKeysFile) { @@ -131,5 +131,5 @@ public class SshServ extends Thread { } return null; - } + } } diff --git a/bundles/org.eclipse.equinox.console.ssh/src/org/eclipse/equinox/console/ssh/SshSession.java b/bundles/org.eclipse.equinox.console.ssh/src/org/eclipse/equinox/console/ssh/SshSession.java index bd829a58f..601f643d5 100755 --- a/bundles/org.eclipse.equinox.console.ssh/src/org/eclipse/equinox/console/ssh/SshSession.java +++ b/bundles/org.eclipse.equinox.console.ssh/src/org/eclipse/equinox/console/ssh/SshSession.java @@ -46,14 +46,14 @@ public class SshSession extends Thread implements Closeable { private Map<String, KEYS> currentEscapesToKey; private static final String PROMPT = "prompt"; - private static final String OSGI_PROMPT = "osgi> "; - private static final String SCOPE = "SCOPE"; - private static final String EQUINOX_SCOPE = "equinox:*"; - private static final String INPUT_SCANNER = "INPUT_SCANNER"; - private static final String SSH_INPUT_SCANNER = "SSH_INPUT_SCANNER"; - private static final String USER_STORAGE_PROPERTY_NAME = "osgi.console.ssh.useDefaultSecureStorage"; - private static final String DEFAULT_USER = "equinox"; - private static final String CLOSEABLE = "CLOSEABLE"; + private static final String OSGI_PROMPT = "osgi> "; + private static final String SCOPE = "SCOPE"; + private static final String EQUINOX_SCOPE = "equinox:*"; + private static final String INPUT_SCANNER = "INPUT_SCANNER"; + private static final String SSH_INPUT_SCANNER = "SSH_INPUT_SCANNER"; + private static final String USER_STORAGE_PROPERTY_NAME = "osgi.console.ssh.useDefaultSecureStorage"; + private static final String DEFAULT_USER = "equinox"; + private static final String CLOSEABLE = "CLOSEABLE"; private static final int ADD_USER_COUNTER_LIMIT = 2; public SshSession(CommandProcessor processor, BundleContext context, SshShell sshShell, InputStream in, OutputStream out, TerminalTypeMappings currentMappings, Map<String, KEYS> currentExcapesToKey) { diff --git a/bundles/org.eclipse.equinox.console.ssh/src/org/eclipse/equinox/console/ssh/SshShell.java b/bundles/org.eclipse.equinox.console.ssh/src/org/eclipse/equinox/console/ssh/SshShell.java index a212df42e..4f0e9def3 100755 --- a/bundles/org.eclipse.equinox.console.ssh/src/org/eclipse/equinox/console/ssh/SshShell.java +++ b/bundles/org.eclipse.equinox.console.ssh/src/org/eclipse/equinox/console/ssh/SshShell.java @@ -53,23 +53,23 @@ public class SshShell implements Command { private static final String DEFAULT_TTYPE = File.separatorChar == '/' ? "XTERM" : "ANSI"; private TerminalTypeMappings currentMappings; private Map<String, KEYS> currentEscapesToKey; - private static final String TERMINAL_PROPERTY = "TERM"; + private static final String TERMINAL_PROPERTY = "TERM"; public SshShell(List<CommandProcessor> processors, BundleContext context) { this.processors = processors; this.context = context; supportedEscapeSequences = new HashMap<> (); - supportedEscapeSequences.put("ANSI", new ANSITerminalTypeMappings()); - supportedEscapeSequences.put("WINDOWS", new ANSITerminalTypeMappings()); - supportedEscapeSequences.put("VT100", new VT100TerminalTypeMappings()); - VT220TerminalTypeMappings vtMappings = new VT220TerminalTypeMappings(); - supportedEscapeSequences.put("VT220", vtMappings); - supportedEscapeSequences.put("XTERM", vtMappings); - supportedEscapeSequences.put("VT320", new VT320TerminalTypeMappings()); - supportedEscapeSequences.put("SCO", new SCOTerminalTypeMappings()); - - currentMappings = supportedEscapeSequences.get(DEFAULT_TTYPE); - currentEscapesToKey = currentMappings.getEscapesToKey(); + supportedEscapeSequences.put("ANSI", new ANSITerminalTypeMappings()); + supportedEscapeSequences.put("WINDOWS", new ANSITerminalTypeMappings()); + supportedEscapeSequences.put("VT100", new VT100TerminalTypeMappings()); + VT220TerminalTypeMappings vtMappings = new VT220TerminalTypeMappings(); + supportedEscapeSequences.put("VT220", vtMappings); + supportedEscapeSequences.put("XTERM", vtMappings); + supportedEscapeSequences.put("VT320", new VT320TerminalTypeMappings()); + supportedEscapeSequences.put("SCO", new SCOTerminalTypeMappings()); + + currentMappings = supportedEscapeSequences.get(DEFAULT_TTYPE); + currentEscapesToKey = currentMappings.getEscapesToKey(); } @Override @@ -157,8 +157,8 @@ public class SshShell implements Command { private SshSession startNewConsoleSession(CommandProcessor processor) { SshSession consoleSession = new SshSession(processor, context, this, in, out, currentMappings, currentEscapesToKey); - consoleSession.start(); - return consoleSession; + consoleSession.start(); + return consoleSession; } } diff --git a/bundles/org.eclipse.equinox.console.ssh/src/org/eclipse/equinox/console/ssh/UserAdminCommand.java b/bundles/org.eclipse.equinox.console.ssh/src/org/eclipse/equinox/console/ssh/UserAdminCommand.java index e1cdd4474..877f7c249 100755 --- a/bundles/org.eclipse.equinox.console.ssh/src/org/eclipse/equinox/console/ssh/UserAdminCommand.java +++ b/bundles/org.eclipse.equinox.console.ssh/src/org/eclipse/equinox/console/ssh/UserAdminCommand.java @@ -34,9 +34,9 @@ import org.eclipse.equinox.console.storage.SecureUserStore; * */ public class UserAdminCommand { - private static final String INPUT_SCANNER = "INPUT_SCANNER"; - private static final String SSH_INPUT_SCANNER = "SSH_INPUT_SCANNER"; - private static final String DEFAULT_USER = "equinox"; + private static final String INPUT_SCANNER = "INPUT_SCANNER"; + private static final String SSH_INPUT_SCANNER = "SSH_INPUT_SCANNER"; + private static final String DEFAULT_USER = "equinox"; private static final int MINIMAL_PASSWORD_LENGTH = 8; private static final int PASSWORD_INPUT_TRIALS_LIMIT = 3; diff --git a/bundles/org.eclipse.equinox.console.ssh/src/org/eclipse/equinox/console/storage/DigestUtil.java b/bundles/org.eclipse.equinox.console.ssh/src/org/eclipse/equinox/console/storage/DigestUtil.java index 42244b765..cba1a79d6 100755 --- a/bundles/org.eclipse.equinox.console.ssh/src/org/eclipse/equinox/console/storage/DigestUtil.java +++ b/bundles/org.eclipse.equinox.console.ssh/src/org/eclipse/equinox/console/storage/DigestUtil.java @@ -65,21 +65,21 @@ public class DigestUtil { } //byte array into hexademical string - private static String asHex(byte[] buf) - { - char[] chars = new char[2 * buf.length]; - for (int i = 0; i < buf.length; ++i) - { - chars[2 * i] = HEX_CHARS[(buf[i] & 0xF0) >>> 4]; - chars[2 * i + 1] = HEX_CHARS[buf[i] & 0x0F]; - } - return new String(chars); - } - - //generate digest byte[] - private static byte[] getDigest(byte[] inputData, String algorithm) throws NoSuchAlgorithmException { - MessageDigest md = MessageDigest.getInstance(algorithm); - md.update(inputData); - return md.digest(); - } + private static String asHex(byte[] buf) + { + char[] chars = new char[2 * buf.length]; + for (int i = 0; i < buf.length; ++i) + { + chars[2 * i] = HEX_CHARS[(buf[i] & 0xF0) >>> 4]; + chars[2 * i + 1] = HEX_CHARS[buf[i] & 0x0F]; + } + return new String(chars); + } + + //generate digest byte[] + private static byte[] getDigest(byte[] inputData, String algorithm) throws NoSuchAlgorithmException { + MessageDigest md = MessageDigest.getInstance(algorithm); + md.update(inputData); + return md.digest(); + } } diff --git a/bundles/org.eclipse.equinox.console.tests/src/org/eclipse/equinox/console/command/adapter/CommandProviderAdapterTest.java b/bundles/org.eclipse.equinox.console.tests/src/org/eclipse/equinox/console/command/adapter/CommandProviderAdapterTest.java index 0da258228..e0928c959 100755 --- a/bundles/org.eclipse.equinox.console.tests/src/org/eclipse/equinox/console/command/adapter/CommandProviderAdapterTest.java +++ b/bundles/org.eclipse.equinox.console.tests/src/org/eclipse/equinox/console/command/adapter/CommandProviderAdapterTest.java @@ -49,14 +49,14 @@ public class CommandProviderAdapterTest { } class TestCommandProvider implements CommandProvider { - public String _test(CommandInterpreter i) { - return "test"; - } - - public String _echo(CommandInterpreter i) { - return i.nextArgument(); - } - + public String _test(CommandInterpreter i) { + return "test"; + } + + public String _echo(CommandInterpreter i) { + return i.nextArgument(); + } + @Override public String getHelp() { return "this is a test command provider"; diff --git a/bundles/org.eclipse.equinox.console.tests/src/org/eclipse/equinox/console/common/ConsoleOutputStreamTests.java b/bundles/org.eclipse.equinox.console.tests/src/org/eclipse/equinox/console/common/ConsoleOutputStreamTests.java index 2e31a9afb..1d3db8f0e 100755 --- a/bundles/org.eclipse.equinox.console.tests/src/org/eclipse/equinox/console/common/ConsoleOutputStreamTests.java +++ b/bundles/org.eclipse.equinox.console.tests/src/org/eclipse/equinox/console/common/ConsoleOutputStreamTests.java @@ -21,11 +21,11 @@ import java.io.ByteArrayOutputStream; public class ConsoleOutputStreamTests { - private static final int DATA_LENGTH = 4; + private static final int DATA_LENGTH = 4; - @Test - public void testWrite() throws Exception { - ByteArrayOutputStream byteOut = new ByteArrayOutputStream(); + @Test + public void testWrite() throws Exception { + ByteArrayOutputStream byteOut = new ByteArrayOutputStream(); try (ConsoleOutputStream out = new ConsoleOutputStream(byteOut)) { byte[] data = new byte[] { 'a', 'b', 'c', 'd' }; for (byte b : data) { @@ -35,11 +35,11 @@ public class ConsoleOutputStreamTests { byte[] res = byteOut.toByteArray(); Assert.assertNotNull("Bytes not written; result null", res); - Assert.assertFalse("Bytes not written; result empty", res.length == 0); + Assert.assertFalse("Bytes not written; result empty", res.length == 0); - for (int i = 0; i < DATA_LENGTH; i++) { - Assert.assertEquals("Wrong char read. Position " + i + ", expected " + data[i] + ", read " + res[i], data[i], res[i]); - } - } - } + for (int i = 0; i < DATA_LENGTH; i++) { + Assert.assertEquals("Wrong char read. Position " + i + ", expected " + data[i] + ", read " + res[i], data[i], res[i]); + } + } + } } diff --git a/bundles/org.eclipse.equinox.console.tests/src/org/eclipse/equinox/console/common/HistoryHolderTests.java b/bundles/org.eclipse.equinox.console.tests/src/org/eclipse/equinox/console/common/HistoryHolderTests.java index 99d8d68e2..37162edcf 100755 --- a/bundles/org.eclipse.equinox.console.tests/src/org/eclipse/equinox/console/common/HistoryHolderTests.java +++ b/bundles/org.eclipse.equinox.console.tests/src/org/eclipse/equinox/console/common/HistoryHolderTests.java @@ -21,50 +21,50 @@ import org.junit.Test; public class HistoryHolderTests { @Test - public void test() { - HistoryHolder historyHolder = new HistoryHolder(); - byte[] line1 = new byte[] { 'a', 'b', 'c', 'd' }; - byte[] line2 = new byte[] { 'x', 'y', 'z' }; - byte[] line3 = new byte[] { 'k', 'l', 'm', 'n' }; + public void test() { + HistoryHolder historyHolder = new HistoryHolder(); + byte[] line1 = new byte[] { 'a', 'b', 'c', 'd' }; + byte[] line2 = new byte[] { 'x', 'y', 'z' }; + byte[] line3 = new byte[] { 'k', 'l', 'm', 'n' }; - historyHolder.add(line1); - historyHolder.add(line2); - historyHolder.add(line3); + historyHolder.add(line1); + historyHolder.add(line2); + historyHolder.add(line3); - byte[] first = historyHolder.first(); - Assert.assertEquals("Wrong length of first member", line1.length, first.length); - Assert.assertArrayEquals("Wrong first member", line1, first); + byte[] first = historyHolder.first(); + Assert.assertEquals("Wrong length of first member", line1.length, first.length); + Assert.assertArrayEquals("Wrong first member", line1, first); - byte[] last = historyHolder.last(); - Assert.assertEquals("Wrong length of last member", line3.length, last.length); - Assert.assertArrayEquals("Wrong last member", line3, last); + byte[] last = historyHolder.last(); + Assert.assertEquals("Wrong length of last member", line3.length, last.length); + Assert.assertArrayEquals("Wrong last member", line3, last); - byte[] prev = historyHolder.prev(); - Assert.assertEquals("Wrong length of previous member", line2.length, prev.length); - Assert.assertArrayEquals("Wrong previous member", line2, prev); + byte[] prev = historyHolder.prev(); + Assert.assertEquals("Wrong length of previous member", line2.length, prev.length); + Assert.assertArrayEquals("Wrong previous member", line2, prev); - byte[] next = historyHolder.next(); - Assert.assertEquals("Wrong length of next member", line3.length, next.length); - Assert.assertArrayEquals("Wrong next member", line3, next); + byte[] next = historyHolder.next(); + Assert.assertEquals("Wrong length of next member", line3.length, next.length); + Assert.assertArrayEquals("Wrong next member", line3, next); - historyHolder.first(); - historyHolder.add(new byte[] {}); - byte[] current = historyHolder.prev(); - Assert.assertEquals("Wrong length of next member", line3.length, current.length); - Assert.assertArrayEquals("Wrong next member", line3, current); + historyHolder.first(); + historyHolder.add(new byte[] {}); + byte[] current = historyHolder.prev(); + Assert.assertEquals("Wrong length of next member", line3.length, current.length); + Assert.assertArrayEquals("Wrong next member", line3, current); - historyHolder.first(); - historyHolder.add(line1); - current = historyHolder.prev(); - Assert.assertEquals("Wrong length of next member", line1.length, current.length); - Assert.assertArrayEquals("Wrong next member", line1, current); - Assert.assertArrayEquals("Second line should now be first", line2, historyHolder.first()); + historyHolder.first(); + historyHolder.add(line1); + current = historyHolder.prev(); + Assert.assertEquals("Wrong length of next member", line1.length, current.length); + Assert.assertArrayEquals("Wrong next member", line1, current); + Assert.assertArrayEquals("Second line should now be first", line2, historyHolder.first()); - historyHolder.reset(); - Assert.assertNull("History should be empty", historyHolder.first()); - Assert.assertNull("History should be empty", historyHolder.last()); - Assert.assertNull("History should be empty", historyHolder.next()); - Assert.assertNull("History should be empty", historyHolder.prev()); - } + historyHolder.reset(); + Assert.assertNull("History should be empty", historyHolder.first()); + Assert.assertNull("History should be empty", historyHolder.last()); + Assert.assertNull("History should be empty", historyHolder.next()); + Assert.assertNull("History should be empty", historyHolder.prev()); + } } diff --git a/bundles/org.eclipse.equinox.console.tests/src/org/eclipse/equinox/console/common/SimpleByteBufferTests.java b/bundles/org.eclipse.equinox.console.tests/src/org/eclipse/equinox/console/common/SimpleByteBufferTests.java index b93b9f620..275a6d86b 100755 --- a/bundles/org.eclipse.equinox.console.tests/src/org/eclipse/equinox/console/common/SimpleByteBufferTests.java +++ b/bundles/org.eclipse.equinox.console.tests/src/org/eclipse/equinox/console/common/SimpleByteBufferTests.java @@ -20,80 +20,80 @@ import org.junit.Test; public class SimpleByteBufferTests { @Test - public void testBuffer() throws Exception { - SimpleByteBuffer buffer = new SimpleByteBuffer(); - buffer.add('a'); - buffer.add('b'); - buffer.add('c'); - buffer.add('d'); + public void testBuffer() throws Exception { + SimpleByteBuffer buffer = new SimpleByteBuffer(); + buffer.add('a'); + buffer.add('b'); + buffer.add('c'); + buffer.add('d'); - Assert.assertTrue("Wrong buffer size; expected 4, actual " + buffer.getSize(), buffer.getSize() == 4); + Assert.assertTrue("Wrong buffer size; expected 4, actual " + buffer.getSize(), buffer.getSize() == 4); - check(buffer, new byte[] { 'a', 'b', 'c', 'd' }); + check(buffer, new byte[] { 'a', 'b', 'c', 'd' }); - byte[] data = buffer.getCurrentData(); - byte[] expected = new byte[] { 'a', 'b', 'c', 'd' }; + byte[] data = buffer.getCurrentData(); + byte[] expected = new byte[] { 'a', 'b', 'c', 'd' }; - Assert.assertTrue("Data not as expected: expected length " + expected.length + ", actual length " + data.length, - data.length == expected.length); + Assert.assertTrue("Data not as expected: expected length " + expected.length + ", actual length " + data.length, + data.length == expected.length); - for (int i = 0; i < data.length; i++) { - Assert.assertEquals("Incorrect data read. Position " + i + ", expected " + expected[i] + ", read " + data[i], expected[i], data[i]); - } + for (int i = 0; i < data.length; i++) { + Assert.assertEquals("Incorrect data read. Position " + i + ", expected " + expected[i] + ", read " + data[i], expected[i], data[i]); + } - buffer.insert('a'); - buffer.insert('b'); - buffer.insert('c'); - buffer.insert('d'); + buffer.insert('a'); + buffer.insert('b'); + buffer.insert('c'); + buffer.insert('d'); - int pos = buffer.getPos(); - buffer.goLeft(); - int newPos = buffer.getPos(); - Assert.assertEquals("Error while moving left; old pos: " + pos + ", new pos: ", pos - 1, newPos); + int pos = buffer.getPos(); + buffer.goLeft(); + int newPos = buffer.getPos(); + Assert.assertEquals("Error while moving left; old pos: " + pos + ", new pos: ", pos - 1, newPos); - buffer.insert('e'); - check(buffer, new byte[] { 'a', 'b', 'c', 'e', 'd' }); + buffer.insert('e'); + check(buffer, new byte[] { 'a', 'b', 'c', 'e', 'd' }); - buffer.goLeft(); - buffer.delete(); - check(buffer, new byte[] { 'a', 'b', 'c', 'd' }); + buffer.goLeft(); + buffer.delete(); + check(buffer, new byte[] { 'a', 'b', 'c', 'd' }); - pos = buffer.getPos(); - buffer.goRight(); - newPos = buffer.getPos(); - Assert.assertEquals("Error while moving right; old pos: " + pos + ", new pos: ", pos + 1, newPos); + pos = buffer.getPos(); + buffer.goRight(); + newPos = buffer.getPos(); + Assert.assertEquals("Error while moving right; old pos: " + pos + ", new pos: ", pos + 1, newPos); - buffer.backSpace(); - check(buffer, new byte[] { 'a', 'b', 'c' }); + buffer.backSpace(); + check(buffer, new byte[] { 'a', 'b', 'c' }); - buffer.delAll(); - Assert.assertTrue("Bytes in buffer not correctly deleted", (buffer.getSize() == 0) && (buffer.getPos() == 0)); + buffer.delAll(); + Assert.assertTrue("Bytes in buffer not correctly deleted", (buffer.getSize() == 0) && (buffer.getPos() == 0)); - buffer.set(new byte[] { 'a', 'b', 'c', 'd' }); - check(buffer, new byte[] { 'a', 'b', 'c', 'd' }); + buffer.set(new byte[] { 'a', 'b', 'c', 'd' }); + check(buffer, new byte[] { 'a', 'b', 'c', 'd' }); - data = buffer.copyCurrentData(); - Assert.assertArrayEquals("Buffer copy does not work properly", new byte[] { 'a', 'b', 'c', 'd' }, data); + data = buffer.copyCurrentData(); + Assert.assertArrayEquals("Buffer copy does not work properly", new byte[] { 'a', 'b', 'c', 'd' }, data); - buffer.goLeft(); - buffer.replace('e'); - check(buffer, new byte[] { 'a', 'b', 'c', 'e' }); + buffer.goLeft(); + buffer.replace('e'); + check(buffer, new byte[] { 'a', 'b', 'c', 'e' }); - buffer.resetPos(); - Assert.assertTrue("Resetting position does not work properly", buffer.getPos() == 0); + buffer.resetPos(); + Assert.assertTrue("Resetting position does not work properly", buffer.getPos() == 0); - Assert.assertEquals("Wrong current char", 'a', buffer.getCurrentChar()); - } + Assert.assertEquals("Wrong current char", 'a', buffer.getCurrentChar()); + } - private void check(SimpleByteBuffer buffer, byte[] expected) throws Exception { - byte[] data = buffer.copyCurrentData(); + private void check(SimpleByteBuffer buffer, byte[] expected) throws Exception { + byte[] data = buffer.copyCurrentData(); - Assert.assertTrue("Data not as expected: expected length " + expected.length + ", actual length " + data.length, - data.length == expected.length); + Assert.assertTrue("Data not as expected: expected length " + expected.length + ", actual length " + data.length, + data.length == expected.length); - for (int i = 0; i < data.length; i++) { - Assert.assertEquals("Incorrect data read. Position " + i + ", expected " + expected[i] + ", read " + data[i], expected[i], data[i]); - } - } + for (int i = 0; i < data.length; i++) { + Assert.assertEquals("Incorrect data read. Position " + i + ", expected " + expected[i] + ", read " + data[i], expected[i], data[i]); + } + } } diff --git a/bundles/org.eclipse.equinox.console.tests/src/org/eclipse/equinox/console/supportability/ConsoleInputScannerTests.java b/bundles/org.eclipse.equinox.console.tests/src/org/eclipse/equinox/console/supportability/ConsoleInputScannerTests.java index 6cbdb63ff..30203582c 100755 --- a/bundles/org.eclipse.equinox.console.tests/src/org/eclipse/equinox/console/supportability/ConsoleInputScannerTests.java +++ b/bundles/org.eclipse.equinox.console.tests/src/org/eclipse/equinox/console/supportability/ConsoleInputScannerTests.java @@ -47,150 +47,150 @@ import java.util.Set; public class ConsoleInputScannerTests { - private static int BS; - - private static final int LF = 10; - - private static final int CR = 13; - - private static final int ESC = 27; - - private static int DELL; - - private static int TAB = 9; - - private static final String COMMANDS = ".commands"; - - @Test - public void test() throws Exception { - Set<TerminalTypeMappings> supportedEscapeSequences = new HashSet<>(); - supportedEscapeSequences.add(new ANSITerminalTypeMappings()); - supportedEscapeSequences.add(new VT100TerminalTypeMappings()); - supportedEscapeSequences.add(new VT220TerminalTypeMappings()); - supportedEscapeSequences.add(new VT320TerminalTypeMappings()); - supportedEscapeSequences.add(new SCOTerminalTypeMappings()); - - for (TerminalTypeMappings ttMappings : supportedEscapeSequences) { - Map<String, KEYS> escapesToKey = ttMappings.getEscapesToKey(); - Map<KEYS, byte[]> keysToEscapes = new HashMap<>(); - for (Entry<String, KEYS> entry : escapesToKey.entrySet()) { - keysToEscapes.put(entry.getValue(), entry.getKey().getBytes()); - } - - BS = ttMappings.getBackspace(); - DELL = ttMappings.getDel(); - - testScan(ttMappings, keysToEscapes); - } - } - - private void testScan(TerminalTypeMappings mappings, Map<KEYS, byte[]> keysToEscapes) throws Exception { - ConsoleInputStream in = new ConsoleInputStream(); - ByteArrayOutputStream byteOut = new ByteArrayOutputStream(); - ConsoleOutputStream out = new ConsoleOutputStream(byteOut); - ConsoleInputScanner scanner = new ConsoleInputScanner(in, out); - scanner.setBackspace(mappings.getBackspace()); - scanner.setCurrentEscapesToKey(mappings.getEscapesToKey()); - scanner.setDel(mappings.getDel()); - scanner.setEscapes(mappings.getEscapes()); - - byte[] line1 = new byte[] { 'a', 'b', 'c', 'd', 'e' }; - byte[] line2 = new byte[] { 't', 'e', 's', 't' }; - byte[] line3 = new byte[] { 'l', 'a', 's', 't' }; - - addLine(scanner, line1); - checkInpusStream(in, line1); - - addLine(scanner, line2); - checkInpusStream(in, line2); - - addLine(scanner, line3); - checkInpusStream(in, line3); - - add(scanner, keysToEscapes.get(KEYS.UP)); - add(scanner, keysToEscapes.get(KEYS.UP)); - String res = byteOut.toString(); - Assert.assertTrue("Error processing up arrow; expected test, actual " + res.substring(res.length() - 4), res.endsWith("test")); - - add(scanner, keysToEscapes.get(KEYS.DOWN)); - res = byteOut.toString(); - Assert.assertTrue("Error processing down arrow; expected last, actual " + res.substring(res.length() - 4), res.endsWith("last")); - - add(scanner, keysToEscapes.get(KEYS.PGUP)); - res = byteOut.toString(); - Assert.assertTrue("Error processing PageUp; expected abcde, actual " + res.substring(res.length() - 4), res.endsWith("abcde")); - - add(scanner, keysToEscapes.get(KEYS.PGDN)); - res = byteOut.toString(); - Assert.assertTrue("Error processing PageDown; expected last, actual " + res.substring(res.length() - 4), res.endsWith("last")); - - if (BS > 0) { - scanner.scan(BS); - res = byteOut.toString(); - Assert.assertTrue("Error processing backspace; expected las, actual " + res.substring(res.length() - 3), res.endsWith("las")); - scanner.scan('t'); - } - - if (DELL > 0) { - add(scanner, keysToEscapes.get(KEYS.LEFT)); - scanner.scan(DELL); - res = byteOut.toString(); - Assert.assertTrue("Error processing del; expected las, actual " + res.substring(res.length() - 3), res.endsWith("las")); - scanner.scan('t'); - } - - add(scanner, keysToEscapes.get(KEYS.LEFT)); - add(scanner, keysToEscapes.get(KEYS.LEFT)); - add(scanner, keysToEscapes.get(KEYS.RIGHT)); - if (DELL > 0) { - scanner.scan(DELL); - } else { - add(scanner, keysToEscapes.get(KEYS.DEL)); - } - res = byteOut.toString(); - Assert.assertTrue("Error processing arrows; expected las, actual " + res.substring(res.length() - 3), res.endsWith("las")); - scanner.scan('t'); - - if (keysToEscapes.get(KEYS.DEL) != null) { - add(scanner, keysToEscapes.get(KEYS.LEFT)); - add(scanner, keysToEscapes.get(KEYS.DEL)); - res = byteOut.toString(); - Assert.assertTrue("Error processing delete; expected las, actual " + res.substring(res.length() - 3), res.endsWith("las")); - scanner.scan('t'); - } - - add(scanner, keysToEscapes.get(KEYS.HOME)); - if (DELL > 0) { - scanner.scan(DELL); - } else { - add(scanner, keysToEscapes.get(KEYS.DEL)); - } - res = byteOut.toString(); - res = res.substring(res.length() - 6, res.length() - 3); - Assert.assertTrue("Error processing Home; expected ast, actual " + res, res.equals("ast")); - scanner.scan('l'); - - add(scanner, keysToEscapes.get(KEYS.END)); - add(scanner, keysToEscapes.get(KEYS.LEFT)); - if (DELL > 0) { - scanner.scan(DELL); - } else { - add(scanner, keysToEscapes.get(KEYS.DEL)); - } - res = byteOut.toString(); - Assert.assertTrue("Error processing End; expected las, actual " + res.substring(res.length() - 3), res.endsWith("las")); - scanner.scan('t'); - - add(scanner, keysToEscapes.get(KEYS.LEFT)); - add(scanner, keysToEscapes.get(KEYS.INS)); - scanner.scan('a'); - res = byteOut.toString(); - Assert.assertTrue("Error processing Ins; expected las, actual " + res.substring(res.length() - 4), res.endsWith("lasa")); - - Filter filter = createMock(Filter.class); + private static int BS; + + private static final int LF = 10; + + private static final int CR = 13; + + private static final int ESC = 27; + + private static int DELL; + + private static int TAB = 9; + + private static final String COMMANDS = ".commands"; + + @Test + public void test() throws Exception { + Set<TerminalTypeMappings> supportedEscapeSequences = new HashSet<>(); + supportedEscapeSequences.add(new ANSITerminalTypeMappings()); + supportedEscapeSequences.add(new VT100TerminalTypeMappings()); + supportedEscapeSequences.add(new VT220TerminalTypeMappings()); + supportedEscapeSequences.add(new VT320TerminalTypeMappings()); + supportedEscapeSequences.add(new SCOTerminalTypeMappings()); + + for (TerminalTypeMappings ttMappings : supportedEscapeSequences) { + Map<String, KEYS> escapesToKey = ttMappings.getEscapesToKey(); + Map<KEYS, byte[]> keysToEscapes = new HashMap<>(); + for (Entry<String, KEYS> entry : escapesToKey.entrySet()) { + keysToEscapes.put(entry.getValue(), entry.getKey().getBytes()); + } + + BS = ttMappings.getBackspace(); + DELL = ttMappings.getDel(); + + testScan(ttMappings, keysToEscapes); + } + } + + private void testScan(TerminalTypeMappings mappings, Map<KEYS, byte[]> keysToEscapes) throws Exception { + ConsoleInputStream in = new ConsoleInputStream(); + ByteArrayOutputStream byteOut = new ByteArrayOutputStream(); + ConsoleOutputStream out = new ConsoleOutputStream(byteOut); + ConsoleInputScanner scanner = new ConsoleInputScanner(in, out); + scanner.setBackspace(mappings.getBackspace()); + scanner.setCurrentEscapesToKey(mappings.getEscapesToKey()); + scanner.setDel(mappings.getDel()); + scanner.setEscapes(mappings.getEscapes()); + + byte[] line1 = new byte[] { 'a', 'b', 'c', 'd', 'e' }; + byte[] line2 = new byte[] { 't', 'e', 's', 't' }; + byte[] line3 = new byte[] { 'l', 'a', 's', 't' }; + + addLine(scanner, line1); + checkInpusStream(in, line1); + + addLine(scanner, line2); + checkInpusStream(in, line2); + + addLine(scanner, line3); + checkInpusStream(in, line3); + + add(scanner, keysToEscapes.get(KEYS.UP)); + add(scanner, keysToEscapes.get(KEYS.UP)); + String res = byteOut.toString(); + Assert.assertTrue("Error processing up arrow; expected test, actual " + res.substring(res.length() - 4), res.endsWith("test")); + + add(scanner, keysToEscapes.get(KEYS.DOWN)); + res = byteOut.toString(); + Assert.assertTrue("Error processing down arrow; expected last, actual " + res.substring(res.length() - 4), res.endsWith("last")); + + add(scanner, keysToEscapes.get(KEYS.PGUP)); + res = byteOut.toString(); + Assert.assertTrue("Error processing PageUp; expected abcde, actual " + res.substring(res.length() - 4), res.endsWith("abcde")); + + add(scanner, keysToEscapes.get(KEYS.PGDN)); + res = byteOut.toString(); + Assert.assertTrue("Error processing PageDown; expected last, actual " + res.substring(res.length() - 4), res.endsWith("last")); + + if (BS > 0) { + scanner.scan(BS); + res = byteOut.toString(); + Assert.assertTrue("Error processing backspace; expected las, actual " + res.substring(res.length() - 3), res.endsWith("las")); + scanner.scan('t'); + } + + if (DELL > 0) { + add(scanner, keysToEscapes.get(KEYS.LEFT)); + scanner.scan(DELL); + res = byteOut.toString(); + Assert.assertTrue("Error processing del; expected las, actual " + res.substring(res.length() - 3), res.endsWith("las")); + scanner.scan('t'); + } + + add(scanner, keysToEscapes.get(KEYS.LEFT)); + add(scanner, keysToEscapes.get(KEYS.LEFT)); + add(scanner, keysToEscapes.get(KEYS.RIGHT)); + if (DELL > 0) { + scanner.scan(DELL); + } else { + add(scanner, keysToEscapes.get(KEYS.DEL)); + } + res = byteOut.toString(); + Assert.assertTrue("Error processing arrows; expected las, actual " + res.substring(res.length() - 3), res.endsWith("las")); + scanner.scan('t'); + + if (keysToEscapes.get(KEYS.DEL) != null) { + add(scanner, keysToEscapes.get(KEYS.LEFT)); + add(scanner, keysToEscapes.get(KEYS.DEL)); + res = byteOut.toString(); + Assert.assertTrue("Error processing delete; expected las, actual " + res.substring(res.length() - 3), res.endsWith("las")); + scanner.scan('t'); + } + + add(scanner, keysToEscapes.get(KEYS.HOME)); + if (DELL > 0) { + scanner.scan(DELL); + } else { + add(scanner, keysToEscapes.get(KEYS.DEL)); + } + res = byteOut.toString(); + res = res.substring(res.length() - 6, res.length() - 3); + Assert.assertTrue("Error processing Home; expected ast, actual " + res, res.equals("ast")); + scanner.scan('l'); + + add(scanner, keysToEscapes.get(KEYS.END)); + add(scanner, keysToEscapes.get(KEYS.LEFT)); + if (DELL > 0) { + scanner.scan(DELL); + } else { + add(scanner, keysToEscapes.get(KEYS.DEL)); + } + res = byteOut.toString(); + Assert.assertTrue("Error processing End; expected las, actual " + res.substring(res.length() - 3), res.endsWith("las")); + scanner.scan('t'); + + add(scanner, keysToEscapes.get(KEYS.LEFT)); + add(scanner, keysToEscapes.get(KEYS.INS)); + scanner.scan('a'); + res = byteOut.toString(); + Assert.assertTrue("Error processing Ins; expected las, actual " + res.substring(res.length() - 4), res.endsWith("lasa")); + + Filter filter = createMock(Filter.class); replay(filter); - BundleContext context = createMock(BundleContext.class); + BundleContext context = createMock(BundleContext.class); expect(context.getServiceReferences(Completer.class.getName(), null)).andReturn(null).anyTimes(); expect(context.createFilter("(objectClass=org.eclipse.equinox.console.commands.CommandsTracker)")).andReturn(filter); context.addServiceListener(isA(ServiceListener.class), isA(String.class)); @@ -207,65 +207,65 @@ public class ConsoleInputScannerTests { CommandSession session = createMock(CommandSession.class); expect(session.get(COMMANDS)).andReturn(commands).anyTimes(); replay(session); - + scanner.setContext(context); scanner.setSession(session); - scanner.scan(CR); - scanner.scan(LF); - scanner.scan('b'); - scanner.scan('u'); - scanner.scan('n'); - scanner.scan(TAB); - res = byteOut.toString(); - Assert.assertTrue("Expected completion suggestion is not contained in the output", res.contains("bundles\r\n")); - Assert.assertTrue("Expected completion suggestion is not contained in the output", res.contains("bundle\r\n")); - Assert.assertTrue("bun should be completed to bundle", res.endsWith("bundle")); - Assert.assertTrue("Expected completion suggestion is not contained in the output", res.contains("bundlebylocation\r\n")); - Assert.assertTrue("Expected completion suggestion is not contained in the output", res.contains("bundlelevel\r\n")); - Assert.assertFalse("Not expected completion suggestion", res.contains("headers\r\n")); - } - - private static void addLine(ConsoleInputScanner scanner, byte[] line) throws Exception { - for (byte b : line) { - try { - scanner.scan(b); - } catch (Exception e) { - System.out.println("Error scanning symbol " + b); - throw new Exception("Error scanning symbol" + b); - } - } - - try { - scanner.scan(CR); - } catch (Exception e) { - System.out.println("Error scanning symbol " + CR); - throw new Exception("Error scanning symbol " + CR); - } - - try { - scanner.scan(LF); - } catch (Exception e) { - System.out.println("Error scanning symbol " + LF); - throw new Exception("Error scanning symbol " + LF); - } - } - - private void add(ConsoleInputScanner scanner, byte[] sequence) throws Exception { - scanner.scan(ESC); - for (byte b : sequence) { - scanner.scan(b); - } - } - - private void checkInpusStream(ConsoleInputStream in, byte[] expected) throws Exception { - // the actual number of bytes in the stream is two more than the bytes in the array, because of the CR and LF - // symbols, added after the array - byte[] read = new byte[expected.length + 1]; - in.read(read, 0, read.length); - for (int i = 0; i < expected.length; i++) { - Assert.assertEquals("Incorrect char read. Position " + i + ", expected " + expected[i] + ", read " + read[i], expected[i], read[i]); - } - } + scanner.scan(CR); + scanner.scan(LF); + scanner.scan('b'); + scanner.scan('u'); + scanner.scan('n'); + scanner.scan(TAB); + res = byteOut.toString(); + Assert.assertTrue("Expected completion suggestion is not contained in the output", res.contains("bundles\r\n")); + Assert.assertTrue("Expected completion suggestion is not contained in the output", res.contains("bundle\r\n")); + Assert.assertTrue("bun should be completed to bundle", res.endsWith("bundle")); + Assert.assertTrue("Expected completion suggestion is not contained in the output", res.contains("bundlebylocation\r\n")); + Assert.assertTrue("Expected completion suggestion is not contained in the output", res.contains("bundlelevel\r\n")); + Assert.assertFalse("Not expected completion suggestion", res.contains("headers\r\n")); + } + + private static void addLine(ConsoleInputScanner scanner, byte[] line) throws Exception { + for (byte b : line) { + try { + scanner.scan(b); + } catch (Exception e) { + System.out.println("Error scanning symbol " + b); + throw new Exception("Error scanning symbol" + b); + } + } + + try { + scanner.scan(CR); + } catch (Exception e) { + System.out.println("Error scanning symbol " + CR); + throw new Exception("Error scanning symbol " + CR); + } + + try { + scanner.scan(LF); + } catch (Exception e) { + System.out.println("Error scanning symbol " + LF); + throw new Exception("Error scanning symbol " + LF); + } + } + + private void add(ConsoleInputScanner scanner, byte[] sequence) throws Exception { + scanner.scan(ESC); + for (byte b : sequence) { + scanner.scan(b); + } + } + + private void checkInpusStream(ConsoleInputStream in, byte[] expected) throws Exception { + // the actual number of bytes in the stream is two more than the bytes in the array, because of the CR and LF + // symbols, added after the array + byte[] read = new byte[expected.length + 1]; + in.read(read, 0, read.length); + for (int i = 0; i < expected.length; i++) { + Assert.assertEquals("Incorrect char read. Position " + i + ", expected " + expected[i] + ", read " + read[i], expected[i], read[i]); + } + } } diff --git a/bundles/org.eclipse.equinox.console.tests/src/org/eclipse/equinox/console/telnet/TelnetCommandTests.java b/bundles/org.eclipse.equinox.console.tests/src/org/eclipse/equinox/console/telnet/TelnetCommandTests.java index 9a8d05abe..21fc84ade 100755 --- a/bundles/org.eclipse.equinox.console.tests/src/org/eclipse/equinox/console/telnet/TelnetCommandTests.java +++ b/bundles/org.eclipse.equinox.console.tests/src/org/eclipse/equinox/console/telnet/TelnetCommandTests.java @@ -41,42 +41,42 @@ public class TelnetCommandTests { @Test public void testTelnetCommand() throws Exception { try (CommandSession session = EasyMock.createMock(CommandSession.class)) { - session.put((String)EasyMock.anyObject(), EasyMock.anyObject()); - EasyMock.expectLastCall().times(3); - EasyMock.expect(session.execute((String)EasyMock.anyObject())).andReturn(new Object()); - session.close(); + session.put((String)EasyMock.anyObject(), EasyMock.anyObject()); + EasyMock.expectLastCall().times(3); + EasyMock.expect(session.execute((String)EasyMock.anyObject())).andReturn(new Object()); + session.close(); EasyMock.expectLastCall(); - EasyMock.replay(session); - - CommandProcessor processor = EasyMock.createMock(CommandProcessor.class); - EasyMock.expect(processor.createSession((ConsoleInputStream)EasyMock.anyObject(), (PrintStream)EasyMock.anyObject(), (PrintStream)EasyMock.anyObject())).andReturn(session); - EasyMock.replay(processor); - - BundleContext context = EasyMock.createMock(BundleContext.class); - EasyMock.expect(context.getProperty(USE_CONFIG_ADMIN_PROP)).andReturn(FALSE); - EasyMock.expect(context.getProperty(TELNET_PORT_PROP_NAME)).andReturn(Integer.toString(TELNET_PORT)); - EasyMock.expect(context.registerService((String)EasyMock.anyObject(), EasyMock.anyObject(), (Dictionary<String, ?>)EasyMock.anyObject())).andReturn(null); - EasyMock.replay(context); - - TelnetCommand command = new TelnetCommand(processor, context); - command.startService(); - - try (Socket socketClient = new Socket(HOST, TELNET_PORT);){ - OutputStream outClient = socketClient.getOutputStream(); - outClient.write(TEST_CONTENT); - outClient.write('\n'); - outClient.flush(); + EasyMock.replay(session); + + CommandProcessor processor = EasyMock.createMock(CommandProcessor.class); + EasyMock.expect(processor.createSession((ConsoleInputStream)EasyMock.anyObject(), (PrintStream)EasyMock.anyObject(), (PrintStream)EasyMock.anyObject())).andReturn(session); + EasyMock.replay(processor); + + BundleContext context = EasyMock.createMock(BundleContext.class); + EasyMock.expect(context.getProperty(USE_CONFIG_ADMIN_PROP)).andReturn(FALSE); + EasyMock.expect(context.getProperty(TELNET_PORT_PROP_NAME)).andReturn(Integer.toString(TELNET_PORT)); + EasyMock.expect(context.registerService((String)EasyMock.anyObject(), EasyMock.anyObject(), (Dictionary<String, ?>)EasyMock.anyObject())).andReturn(null); + EasyMock.replay(context); + + TelnetCommand command = new TelnetCommand(processor, context); + command.startService(); + + try (Socket socketClient = new Socket(HOST, TELNET_PORT);){ + OutputStream outClient = socketClient.getOutputStream(); + outClient.write(TEST_CONTENT); + outClient.write('\n'); + outClient.flush(); - // wait for the accept thread to finish execution - try { - Thread.sleep(WAIT_TIME); - } catch (InterruptedException ie) { - // do nothing - } - } finally { - command.telnet(new String[] {STOP_COMMAND}); - } - EasyMock.verify(context); + // wait for the accept thread to finish execution + try { + Thread.sleep(WAIT_TIME); + } catch (InterruptedException ie) { + // do nothing + } + } finally { + command.telnet(new String[] {STOP_COMMAND}); + } + EasyMock.verify(context); } } } diff --git a/bundles/org.eclipse.equinox.console.tests/src/org/eclipse/equinox/console/telnet/TelnetCommandWithConfigAdminTests.java b/bundles/org.eclipse.equinox.console.tests/src/org/eclipse/equinox/console/telnet/TelnetCommandWithConfigAdminTests.java index 0beda3be5..1d71aea88 100755 --- a/bundles/org.eclipse.equinox.console.tests/src/org/eclipse/equinox/console/telnet/TelnetCommandWithConfigAdminTests.java +++ b/bundles/org.eclipse.equinox.console.tests/src/org/eclipse/equinox/console/telnet/TelnetCommandWithConfigAdminTests.java @@ -46,65 +46,65 @@ public class TelnetCommandWithConfigAdminTests { @Test public void testTelnetCommandWithConfigAdminEnabledTelnet() throws Exception { CommandSession session = EasyMock.createMock(CommandSession.class); - session.put((String)EasyMock.anyObject(), EasyMock.anyObject()); - EasyMock.expectLastCall().times(3); - EasyMock.expect(session.execute((String)EasyMock.anyObject())).andReturn(new Object()); - session.close(); + session.put((String)EasyMock.anyObject(), EasyMock.anyObject()); + EasyMock.expectLastCall().times(3); + EasyMock.expect(session.execute((String)EasyMock.anyObject())).andReturn(new Object()); + session.close(); EasyMock.expectLastCall(); - EasyMock.replay(session); - - CommandProcessor processor = EasyMock.createMock(CommandProcessor.class); - EasyMock.expect(processor.createSession((ConsoleInputStream)EasyMock.anyObject(), (PrintStream)EasyMock.anyObject(), (PrintStream)EasyMock.anyObject())).andReturn(session); - EasyMock.replay(processor); + EasyMock.replay(session); + + CommandProcessor processor = EasyMock.createMock(CommandProcessor.class); + EasyMock.expect(processor.createSession((ConsoleInputStream)EasyMock.anyObject(), (PrintStream)EasyMock.anyObject(), (PrintStream)EasyMock.anyObject())).andReturn(session); + EasyMock.replay(processor); - final ServiceRegistration<?> registration = EasyMock.createMock(ServiceRegistration.class); - registration.setProperties((Dictionary<String, ?>)EasyMock.anyObject()); + final ServiceRegistration<?> registration = EasyMock.createMock(ServiceRegistration.class); + registration.setProperties((Dictionary<String, ?>)EasyMock.anyObject()); - EasyMock.expectLastCall(); - EasyMock.replay(registration); + EasyMock.expectLastCall(); + EasyMock.replay(registration); - BundleContext context = EasyMock.createMock(BundleContext.class); - EasyMock.expect(context.getProperty(USE_CONFIG_ADMIN_PROP)).andReturn(TRUE); - EasyMock.expect( - (ServiceRegistration) context.registerService( - (String)EasyMock.anyObject(), - (ManagedService)EasyMock.anyObject(), - (Dictionary<String, ?>)EasyMock.anyObject()) - ).andAnswer(() -> { + BundleContext context = EasyMock.createMock(BundleContext.class); + EasyMock.expect(context.getProperty(USE_CONFIG_ADMIN_PROP)).andReturn(TRUE); + EasyMock.expect( + (ServiceRegistration) context.registerService( + (String)EasyMock.anyObject(), + (ManagedService)EasyMock.anyObject(), + (Dictionary<String, ?>)EasyMock.anyObject()) + ).andAnswer(() -> { configurator = (ManagedService) EasyMock.getCurrentArguments()[1]; return registration; }); - EasyMock.expect( - context.registerService( - (String)EasyMock.anyObject(), - (TelnetCommand)EasyMock.anyObject(), - (Dictionary<String, ?>)EasyMock.anyObject())).andReturn(null); - EasyMock.replay(context); - - TelnetCommand command = new TelnetCommand(processor, context); - command.startService(); - Dictionary<String, String> props = new Hashtable<>(); + EasyMock.expect( + context.registerService( + (String)EasyMock.anyObject(), + (TelnetCommand)EasyMock.anyObject(), + (Dictionary<String, ?>)EasyMock.anyObject())).andReturn(null); + EasyMock.replay(context); + + TelnetCommand command = new TelnetCommand(processor, context); + command.startService(); + Dictionary<String, String> props = new Hashtable<>(); props.put("port", TELNET_PORT); props.put("host", HOST); props.put("enabled", TRUE); configurator.updated(props); - try (Socket socketClient = new Socket(HOST, Integer.parseInt(TELNET_PORT));){ - OutputStream outClient = socketClient.getOutputStream(); - outClient.write(TEST_CONTENT); - outClient.write('\n'); - outClient.flush(); + try (Socket socketClient = new Socket(HOST, Integer.parseInt(TELNET_PORT));){ + OutputStream outClient = socketClient.getOutputStream(); + outClient.write(TEST_CONTENT); + outClient.write('\n'); + outClient.flush(); - // wait for the accept thread to finish execution - try { - Thread.sleep(WAIT_TIME); - } catch (InterruptedException ie) { - // do nothing - } - } finally { - command.telnet(new String[] {STOP_COMMAND}); - } - EasyMock.verify(context); + // wait for the accept thread to finish execution + try { + Thread.sleep(WAIT_TIME); + } catch (InterruptedException ie) { + // do nothing + } + } finally { + command.telnet(new String[] {STOP_COMMAND}); + } + EasyMock.verify(context); } @Test @@ -119,44 +119,44 @@ public class TelnetCommandWithConfigAdminTests { private void disabledTelnet(boolean isDefault) throws Exception { CommandSession session = EasyMock.createMock(CommandSession.class); - session.put((String)EasyMock.anyObject(), EasyMock.anyObject()); - EasyMock.expectLastCall().times(4); - EasyMock.expect(session.execute((String)EasyMock.anyObject())).andReturn(new Object()); - session.close(); + session.put((String)EasyMock.anyObject(), EasyMock.anyObject()); + EasyMock.expectLastCall().times(4); + EasyMock.expect(session.execute((String)EasyMock.anyObject())).andReturn(new Object()); + session.close(); EasyMock.expectLastCall(); - EasyMock.replay(session); - - CommandProcessor processor = EasyMock.createMock(CommandProcessor.class); - EasyMock.expect(processor.createSession((ConsoleInputStream)EasyMock.anyObject(), (PrintStream)EasyMock.anyObject(), (PrintStream)EasyMock.anyObject())).andReturn(session); - EasyMock.replay(processor); + EasyMock.replay(session); + + CommandProcessor processor = EasyMock.createMock(CommandProcessor.class); + EasyMock.expect(processor.createSession((ConsoleInputStream)EasyMock.anyObject(), (PrintStream)EasyMock.anyObject(), (PrintStream)EasyMock.anyObject())).andReturn(session); + EasyMock.replay(processor); - final ServiceRegistration<?> registration = EasyMock.createMock(ServiceRegistration.class); - registration.setProperties((Dictionary<String, ?>)EasyMock.anyObject()); + final ServiceRegistration<?> registration = EasyMock.createMock(ServiceRegistration.class); + registration.setProperties((Dictionary<String, ?>)EasyMock.anyObject()); - EasyMock.expectLastCall(); - EasyMock.replay(registration); + EasyMock.expectLastCall(); + EasyMock.replay(registration); - BundleContext context = EasyMock.createMock(BundleContext.class); - EasyMock.expect(context.getProperty(USE_CONFIG_ADMIN_PROP)).andReturn(TRUE); - EasyMock.expect( - (ServiceRegistration) context.registerService( - (String)EasyMock.anyObject(), - (ManagedService)EasyMock.anyObject(), - (Dictionary<String, ?>)EasyMock.anyObject()) - ).andAnswer(() -> { + BundleContext context = EasyMock.createMock(BundleContext.class); + EasyMock.expect(context.getProperty(USE_CONFIG_ADMIN_PROP)).andReturn(TRUE); + EasyMock.expect( + (ServiceRegistration) context.registerService( + (String)EasyMock.anyObject(), + (ManagedService)EasyMock.anyObject(), + (Dictionary<String, ?>)EasyMock.anyObject()) + ).andAnswer(() -> { configurator = (ManagedService) EasyMock.getCurrentArguments()[1]; return registration; }); - EasyMock.expect( - context.registerService( - (String)EasyMock.anyObject(), - (TelnetCommand)EasyMock.anyObject(), - (Dictionary<String, ?>)EasyMock.anyObject())).andReturn(null); - EasyMock.replay(context); - - TelnetCommand command = new TelnetCommand(processor, context); - command.startService(); - Dictionary<String, String> props = new Hashtable<>(); + EasyMock.expect( + context.registerService( + (String)EasyMock.anyObject(), + (TelnetCommand)EasyMock.anyObject(), + (Dictionary<String, ?>)EasyMock.anyObject())).andReturn(null); + EasyMock.replay(context); + + TelnetCommand command = new TelnetCommand(processor, context); + command.startService(); + Dictionary<String, String> props = new Hashtable<>(); props.put("port", TELNET_PORT); props.put("host", HOST); if (isDefault == false) { @@ -164,19 +164,19 @@ public class TelnetCommandWithConfigAdminTests { } configurator.updated(props); - try (Socket socketClient = new Socket(HOST, Integer.parseInt(TELNET_PORT))){ - - fail("It should not be possible to open a socket to " + HOST + ":" + TELNET_PORT); - } catch (IOException e) { - // this is ok, there should be an exception - } finally { - try { - command.telnet(new String[] {STOP_COMMAND}); - } catch (IllegalStateException e) { - //this is expected - } - } - EasyMock.verify(context); + try (Socket socketClient = new Socket(HOST, Integer.parseInt(TELNET_PORT))){ + + fail("It should not be possible to open a socket to " + HOST + ":" + TELNET_PORT); + } catch (IOException e) { + // this is ok, there should be an exception + } finally { + try { + command.telnet(new String[] {STOP_COMMAND}); + } catch (IllegalStateException e) { + //this is expected + } + } + EasyMock.verify(context); } } diff --git a/bundles/org.eclipse.equinox.console.tests/src/org/eclipse/equinox/console/telnet/TelnetInputHandlerTests.java b/bundles/org.eclipse.equinox.console.tests/src/org/eclipse/equinox/console/telnet/TelnetInputHandlerTests.java index 25e311268..a4708eeb9 100755 --- a/bundles/org.eclipse.equinox.console.tests/src/org/eclipse/equinox/console/telnet/TelnetInputHandlerTests.java +++ b/bundles/org.eclipse.equinox.console.tests/src/org/eclipse/equinox/console/telnet/TelnetInputHandlerTests.java @@ -26,27 +26,27 @@ import org.junit.Test; public class TelnetInputHandlerTests { - private static final long WAIT_TIME = 10000; - - @Test - public void testHandler() throws Exception { - ByteArrayInputStream input = new ByteArrayInputStream("abcde".getBytes()); - ConsoleInputStream in = new ConsoleInputStream(); - ByteArrayOutputStream byteOut = new ByteArrayOutputStream(); - ConsoleOutputStream out = new ConsoleOutputStream(byteOut); - Callback callback = createMock(Callback.class); - TelnetInputHandler handler = new TelnetInputHandler(input, in, out, callback); - handler.start(); - - // wait for the accept thread to start execution - try { - Thread.sleep(WAIT_TIME); - } catch (InterruptedException ie) { - // do nothing - } - - String res = byteOut.toString(); - Assert.assertTrue("Wrong input. Expected abcde, read " + res, res.equals("abcde")); - } + private static final long WAIT_TIME = 10000; + + @Test + public void testHandler() throws Exception { + ByteArrayInputStream input = new ByteArrayInputStream("abcde".getBytes()); + ConsoleInputStream in = new ConsoleInputStream(); + ByteArrayOutputStream byteOut = new ByteArrayOutputStream(); + ConsoleOutputStream out = new ConsoleOutputStream(byteOut); + Callback callback = createMock(Callback.class); + TelnetInputHandler handler = new TelnetInputHandler(input, in, out, callback); + handler.start(); + + // wait for the accept thread to start execution + try { + Thread.sleep(WAIT_TIME); + } catch (InterruptedException ie) { + // do nothing + } + + String res = byteOut.toString(); + Assert.assertTrue("Wrong input. Expected abcde, read " + res, res.equals("abcde")); + } } diff --git a/bundles/org.eclipse.equinox.console.tests/src/org/eclipse/equinox/console/telnet/TelnetInputScannerTests.java b/bundles/org.eclipse.equinox.console.tests/src/org/eclipse/equinox/console/telnet/TelnetInputScannerTests.java index de16ef669..5a5251de3 100755 --- a/bundles/org.eclipse.equinox.console.tests/src/org/eclipse/equinox/console/telnet/TelnetInputScannerTests.java +++ b/bundles/org.eclipse.equinox.console.tests/src/org/eclipse/equinox/console/telnet/TelnetInputScannerTests.java @@ -37,191 +37,191 @@ import java.util.Map; public class TelnetInputScannerTests { - private static final int IAC = 255; - - private static final int DO = 253; - - private static final int DO_NOT = 254; - - private static final int TTYPE = 24; - - private static final int WILL = 251; - - private static final int WILL_NOT = 252; - - private static final int SB = 250; - - private static final int SE = 240; - - private static final int EL = 248; - - private static final int SEND = 1; - - private static final int IS = 0; - - protected static final byte ESC = 27; - - @Test - public void testScan() throws Exception { - ConsoleInputStream in = new ConsoleInputStream(); - ByteArrayOutputStream byteOut = new ByteArrayOutputStream(); - ConsoleOutputStream out = new ConsoleOutputStream(byteOut); - Callback callback = createMock(Callback.class); - TelnetInputScanner scanner = new TelnetInputScanner(in, out, callback); - try { - scanner.scan((byte) SE); - scanner.scan((byte) EL); - scanner.scan((byte) SB); - scanner.scan((byte) WILL); - scanner.scan((byte) WILL_NOT); - scanner.scan((byte) DO); - scanner.scan((byte) DO_NOT); - scanner.scan((byte) 'a'); - scanner.scan((byte) 'b'); - scanner.scan((byte) 'c'); - } catch (IOException e) { - System.out.println("Error while scanning: " + e.getMessage()); - e.printStackTrace(); - throw e; - } - - String output = byteOut.toString(); - Assert.assertTrue("Output incorrect. Expected abc, but read " + output, output.equals("abc")); - } - - @Test - public void testScanESC() throws Exception { - ConsoleInputStream in = new ConsoleInputStream(); - ByteArrayOutputStream byteOut = new ByteArrayOutputStream(); - ConsoleOutputStream out = new ConsoleOutputStream(byteOut); - Callback callback = createMock(Callback.class); - TelnetInputScanner scanner = new TelnetInputScanner(in, out, callback); - - try { - scanner.scan((byte) 'a'); - scanner.scan(ESC); - scanner.scan((byte) 'b'); - } catch (IOException e) { - System.out.println("Error while scanning: " + e.getMessage()); - e.printStackTrace(); - throw e; - } - - String output = byteOut.toString(); - Assert.assertTrue("Output incorrect. Expected ab, but read " + output, output.equals("ab")); - } - - @Test - public void testTTNegotiations() throws Exception { - Map<byte[], TerminalTypeMappings> ttMappings = new HashMap<>(); - ttMappings.put(new byte[] { 'A', 'N', 'S', 'I' }, new ANSITerminalTypeMappings()); - ttMappings.put(new byte[] { 'V', 'T', '1', '0', '0' }, new VT100TerminalTypeMappings()); - ttMappings.put(new byte[] { 'V', 'T', '2', '2', '0' }, new VT220TerminalTypeMappings()); - ttMappings.put(new byte[] { 'X', 'T', 'E', 'R', 'M' }, new VT220TerminalTypeMappings()); - ttMappings.put(new byte[] { 'V', 'T', '3', '2', '0' }, new VT320TerminalTypeMappings()); - ttMappings.put(new byte[] { 'S', 'C', 'O' }, new SCOTerminalTypeMappings()); - - for (byte[] ttype : ttMappings.keySet()) { - testTerminalTypeNegotiation(ttype, ttMappings.get(ttype)); - } - } - - private void testTerminalTypeNegotiation(byte[] terminalType, TerminalTypeMappings mappings) throws Exception { - PipedInputStream clientIn = new PipedInputStream(); - PipedOutputStream serverOut = new PipedOutputStream(clientIn); - - byte[] requestNegotiation = { (byte) IAC, (byte) DO, (byte) TTYPE }; - - TestCallback testCallback = new TestCallback(); - TelnetOutputStream out = new TelnetOutputStream(serverOut); - TelnetInputScanner scanner = new TelnetInputScanner(new ConsoleInputStream(), out, testCallback); - out.write(requestNegotiation); - out.flush(); - - int read = clientIn.read(); - Assert.assertEquals("Unexpected input ", IAC, read); - read = clientIn.read(); - Assert.assertEquals("Unexpected input ", DO, read); - read = clientIn.read(); - Assert.assertEquals("Unexpected input ", TTYPE, read); - - scanner.scan(IAC); - scanner.scan(WILL); - scanner.scan(TTYPE); - - read = clientIn.read(); - Assert.assertEquals("Unexpected input ", IAC, read); - read = clientIn.read(); - Assert.assertEquals("Unexpected input ", SB, read); - read = clientIn.read(); - Assert.assertEquals("Unexpected input ", TTYPE, read); - read = clientIn.read(); - Assert.assertEquals("Unexpected input ", SEND, read); - read = clientIn.read(); - Assert.assertEquals("Unexpected input ", IAC, read); - read = clientIn.read(); - Assert.assertEquals("Unexpected input ", SE, read); - - scanner.scan(IAC); - scanner.scan(SB); - scanner.scan(TTYPE); - scanner.scan(IS); - scanner.scan('A'); - scanner.scan('B'); - scanner.scan('C'); - scanner.scan('D'); - scanner.scan('E'); - scanner.scan(IAC); - scanner.scan(SE); - - read = clientIn.read(); - Assert.assertEquals("Unexpected input ", IAC, read); - read = clientIn.read(); - Assert.assertEquals("Unexpected input ", SB, read); - read = clientIn.read(); - Assert.assertEquals("Unexpected input ", TTYPE, read); - read = clientIn.read(); - Assert.assertEquals("Unexpected input ", SEND, read); - read = clientIn.read(); - Assert.assertEquals("Unexpected input ", IAC, read); - read = clientIn.read(); - Assert.assertEquals("Unexpected input ", SE, read); - - scanner.scan(IAC); - scanner.scan(SB); - scanner.scan(TTYPE); - scanner.scan(IS); - for (byte symbol : terminalType) { - scanner.scan(symbol); - } - scanner.scan(IAC); - scanner.scan(SE); - - Assert.assertEquals("Incorrect BACKSPACE: ", mappings.getBackspace(), scanner.getBackspace()); - Assert.assertEquals("Incorrect DELL: ", mappings.getDel(), scanner.getDel()); - - Map<String, KEYS> currentEscapesToKey = scanner.getCurrentEscapesToKey(); - Map<String, KEYS> expectedEscapesToKey = mappings.getEscapesToKey(); - for (String escape : expectedEscapesToKey.keySet()) { - KEYS key = expectedEscapesToKey.get(escape); - Assert.assertEquals("Incorrect " + key.name(), key, currentEscapesToKey.get(escape)); - } - - Assert.assertTrue("Callback not called ", testCallback.getState()); - } - - class TestCallback implements Callback { - - private boolean isCalled = false; - - @Override + private static final int IAC = 255; + + private static final int DO = 253; + + private static final int DO_NOT = 254; + + private static final int TTYPE = 24; + + private static final int WILL = 251; + + private static final int WILL_NOT = 252; + + private static final int SB = 250; + + private static final int SE = 240; + + private static final int EL = 248; + + private static final int SEND = 1; + + private static final int IS = 0; + + protected static final byte ESC = 27; + + @Test + public void testScan() throws Exception { + ConsoleInputStream in = new ConsoleInputStream(); + ByteArrayOutputStream byteOut = new ByteArrayOutputStream(); + ConsoleOutputStream out = new ConsoleOutputStream(byteOut); + Callback callback = createMock(Callback.class); + TelnetInputScanner scanner = new TelnetInputScanner(in, out, callback); + try { + scanner.scan((byte) SE); + scanner.scan((byte) EL); + scanner.scan((byte) SB); + scanner.scan((byte) WILL); + scanner.scan((byte) WILL_NOT); + scanner.scan((byte) DO); + scanner.scan((byte) DO_NOT); + scanner.scan((byte) 'a'); + scanner.scan((byte) 'b'); + scanner.scan((byte) 'c'); + } catch (IOException e) { + System.out.println("Error while scanning: " + e.getMessage()); + e.printStackTrace(); + throw e; + } + + String output = byteOut.toString(); + Assert.assertTrue("Output incorrect. Expected abc, but read " + output, output.equals("abc")); + } + + @Test + public void testScanESC() throws Exception { + ConsoleInputStream in = new ConsoleInputStream(); + ByteArrayOutputStream byteOut = new ByteArrayOutputStream(); + ConsoleOutputStream out = new ConsoleOutputStream(byteOut); + Callback callback = createMock(Callback.class); + TelnetInputScanner scanner = new TelnetInputScanner(in, out, callback); + + try { + scanner.scan((byte) 'a'); + scanner.scan(ESC); + scanner.scan((byte) 'b'); + } catch (IOException e) { + System.out.println("Error while scanning: " + e.getMessage()); + e.printStackTrace(); + throw e; + } + + String output = byteOut.toString(); + Assert.assertTrue("Output incorrect. Expected ab, but read " + output, output.equals("ab")); + } + + @Test + public void testTTNegotiations() throws Exception { + Map<byte[], TerminalTypeMappings> ttMappings = new HashMap<>(); + ttMappings.put(new byte[] { 'A', 'N', 'S', 'I' }, new ANSITerminalTypeMappings()); + ttMappings.put(new byte[] { 'V', 'T', '1', '0', '0' }, new VT100TerminalTypeMappings()); + ttMappings.put(new byte[] { 'V', 'T', '2', '2', '0' }, new VT220TerminalTypeMappings()); + ttMappings.put(new byte[] { 'X', 'T', 'E', 'R', 'M' }, new VT220TerminalTypeMappings()); + ttMappings.put(new byte[] { 'V', 'T', '3', '2', '0' }, new VT320TerminalTypeMappings()); + ttMappings.put(new byte[] { 'S', 'C', 'O' }, new SCOTerminalTypeMappings()); + + for (byte[] ttype : ttMappings.keySet()) { + testTerminalTypeNegotiation(ttype, ttMappings.get(ttype)); + } + } + + private void testTerminalTypeNegotiation(byte[] terminalType, TerminalTypeMappings mappings) throws Exception { + PipedInputStream clientIn = new PipedInputStream(); + PipedOutputStream serverOut = new PipedOutputStream(clientIn); + + byte[] requestNegotiation = { (byte) IAC, (byte) DO, (byte) TTYPE }; + + TestCallback testCallback = new TestCallback(); + TelnetOutputStream out = new TelnetOutputStream(serverOut); + TelnetInputScanner scanner = new TelnetInputScanner(new ConsoleInputStream(), out, testCallback); + out.write(requestNegotiation); + out.flush(); + + int read = clientIn.read(); + Assert.assertEquals("Unexpected input ", IAC, read); + read = clientIn.read(); + Assert.assertEquals("Unexpected input ", DO, read); + read = clientIn.read(); + Assert.assertEquals("Unexpected input ", TTYPE, read); + + scanner.scan(IAC); + scanner.scan(WILL); + scanner.scan(TTYPE); + + read = clientIn.read(); + Assert.assertEquals("Unexpected input ", IAC, read); + read = clientIn.read(); + Assert.assertEquals("Unexpected input ", SB, read); + read = clientIn.read(); + Assert.assertEquals("Unexpected input ", TTYPE, read); + read = clientIn.read(); + Assert.assertEquals("Unexpected input ", SEND, read); + read = clientIn.read(); + Assert.assertEquals("Unexpected input ", IAC, read); + read = clientIn.read(); + Assert.assertEquals("Unexpected input ", SE, read); + + scanner.scan(IAC); + scanner.scan(SB); + scanner.scan(TTYPE); + scanner.scan(IS); + scanner.scan('A'); + scanner.scan('B'); + scanner.scan('C'); + scanner.scan('D'); + scanner.scan('E'); + scanner.scan(IAC); + scanner.scan(SE); + + read = clientIn.read(); + Assert.assertEquals("Unexpected input ", IAC, read); + read = clientIn.read(); + Assert.assertEquals("Unexpected input ", SB, read); + read = clientIn.read(); + Assert.assertEquals("Unexpected input ", TTYPE, read); + read = clientIn.read(); + Assert.assertEquals("Unexpected input ", SEND, read); + read = clientIn.read(); + Assert.assertEquals("Unexpected input ", IAC, read); + read = clientIn.read(); + Assert.assertEquals("Unexpected input ", SE, read); + + scanner.scan(IAC); + scanner.scan(SB); + scanner.scan(TTYPE); + scanner.scan(IS); + for (byte symbol : terminalType) { + scanner.scan(symbol); + } + scanner.scan(IAC); + scanner.scan(SE); + + Assert.assertEquals("Incorrect BACKSPACE: ", mappings.getBackspace(), scanner.getBackspace()); + Assert.assertEquals("Incorrect DELL: ", mappings.getDel(), scanner.getDel()); + + Map<String, KEYS> currentEscapesToKey = scanner.getCurrentEscapesToKey(); + Map<String, KEYS> expectedEscapesToKey = mappings.getEscapesToKey(); + for (String escape : expectedEscapesToKey.keySet()) { + KEYS key = expectedEscapesToKey.get(escape); + Assert.assertEquals("Incorrect " + key.name(), key, currentEscapesToKey.get(escape)); + } + + Assert.assertTrue("Callback not called ", testCallback.getState()); + } + + class TestCallback implements Callback { + + private boolean isCalled = false; + + @Override public void finished() { - isCalled = true; - } + isCalled = true; + } - public boolean getState() { - return isCalled; - } - } + public boolean getState() { + return isCalled; + } + } } diff --git a/bundles/org.eclipse.equinox.console.tests/src/org/eclipse/equinox/console/telnet/TelnetServerTests.java b/bundles/org.eclipse.equinox.console.tests/src/org/eclipse/equinox/console/telnet/TelnetServerTests.java index 4fdcc5fc4..ce471cd73 100755 --- a/bundles/org.eclipse.equinox.console.tests/src/org/eclipse/equinox/console/telnet/TelnetServerTests.java +++ b/bundles/org.eclipse.equinox.console.tests/src/org/eclipse/equinox/console/telnet/TelnetServerTests.java @@ -32,13 +32,13 @@ import static org.easymock.EasyMock.*; public class TelnetServerTests { - private static final String HOST = "localhost"; - private static final int PORT = 38888; - private static final long WAIT_TIME = 5000; - private static final int TEST_CONTENT = 100; + private static final String HOST = "localhost"; + private static final int PORT = 38888; + private static final long WAIT_TIME = 5000; + private static final int TEST_CONTENT = 100; - @Test - public void testTelnetServer() throws Exception { + @Test + public void testTelnetServer() throws Exception { try (CommandSession session = EasyMock.createMock(CommandSession.class)) { session.put((String) EasyMock.anyObject(), EasyMock.anyObject()); EasyMock.expectLastCall().times(3); @@ -76,9 +76,9 @@ public class TelnetServerTests { telnetServer.stopTelnetServer(); } } - } + } - @Test + @Test public void testTelnetServerWithoutHost() throws Exception { try (CommandSession session = EasyMock.createMock(CommandSession.class)) { session.put((String) EasyMock.anyObject(), EasyMock.anyObject()); diff --git a/bundles/org.eclipse.equinox.console/src/org/eclipse/equinox/console/command/adapter/Activator.java b/bundles/org.eclipse.equinox.console/src/org/eclipse/equinox/console/command/adapter/Activator.java index b0e325324..71594578b 100755 --- a/bundles/org.eclipse.equinox.console/src/org/eclipse/equinox/console/command/adapter/Activator.java +++ b/bundles/org.eclipse.equinox.console/src/org/eclipse/equinox/console/command/adapter/Activator.java @@ -133,18 +133,18 @@ public class Activator implements BundleActivator { new Thread(new Runnable() { @Override public void run() { - try { - gogoSession.put("SCOPE", "equinox:*"); - gogoSession.put("prompt", "osgi> "); - gogoSession.execute("gosh --login --noshutdown"); - } - catch (Exception e) { - e.printStackTrace(); - } - finally { - gogoSession.close(); - equinoxSession.close(); - } + try { + gogoSession.put("SCOPE", "equinox:*"); + gogoSession.put("prompt", "osgi> "); + gogoSession.execute("gosh --login --noshutdown"); + } + catch (Exception e) { + e.printStackTrace(); + } + finally { + gogoSession.close(); + equinoxSession.close(); + } } }, "Equinox Console Session").start(); return null; diff --git a/bundles/org.eclipse.equinox.console/src/org/eclipse/equinox/console/command/adapter/CustomCommandInterpreter.java b/bundles/org.eclipse.equinox.console/src/org/eclipse/equinox/console/command/adapter/CustomCommandInterpreter.java index 09a429b20..bd900e493 100755 --- a/bundles/org.eclipse.equinox.console/src/org/eclipse/equinox/console/command/adapter/CustomCommandInterpreter.java +++ b/bundles/org.eclipse.equinox.console/src/org/eclipse/equinox/console/command/adapter/CustomCommandInterpreter.java @@ -37,242 +37,242 @@ import org.osgi.framework.Bundle; * */ public class CustomCommandInterpreter implements CommandInterpreter { - private PrintStream out = System.out; - /** Strings used to format other strings */ - private String tab = "\t"; //$NON-NLS-1$ - private String newline = "\r\n"; //$NON-NLS-1$ - private final Iterator<Object> arguments; - private final CommandSession commandSession; - /** - * The maximum number of lines to print without user prompt. - * 0 means no user prompt is required, the window is scrollable. - */ - protected static int maxLineCount; + private PrintStream out = System.out; + /** Strings used to format other strings */ + private String tab = "\t"; //$NON-NLS-1$ + private String newline = "\r\n"; //$NON-NLS-1$ + private final Iterator<Object> arguments; + private final CommandSession commandSession; + /** + * The maximum number of lines to print without user prompt. + * 0 means no user prompt is required, the window is scrollable. + */ + protected static int maxLineCount; - /** The number of lines printed without user prompt.*/ - protected int currentLineCount; - - public CustomCommandInterpreter(CommandSession commandSession, List<Object> args) { - this.commandSession = commandSession; - arguments = args.iterator(); - } - - @Override + /** The number of lines printed without user prompt.*/ + protected int currentLineCount; + + public CustomCommandInterpreter(CommandSession commandSession, List<Object> args) { + this.commandSession = commandSession; + arguments = args.iterator(); + } + + @Override public Object execute(String cmd) { - try { - return commandSession.execute(cmd); - } catch (RuntimeException e) { - throw e; - } catch (Exception e) { - throw new RuntimeException(e); - } - } + try { + return commandSession.execute(cmd); + } catch (RuntimeException e) { + throw e; + } catch (Exception e) { + throw new RuntimeException(e); + } + } - @Override + @Override public String nextArgument() { - if (arguments.hasNext()) { - Object next = arguments.next(); - return next == null ? null : next.toString(); - } - return null; - } + if (arguments.hasNext()) { + Object next = arguments.next(); + return next == null ? null : next.toString(); + } + return null; + } - /** - * Prints an object to the outputstream - * - * @param o the object to be printed - */ - @Override + /** + * Prints an object to the outputstream + * + * @param o the object to be printed + */ + @Override public void print(Object o) { - check4More(); - out.print(o); - out.flush(); - } + check4More(); + out.print(o); + out.flush(); + } - /** - * Prints a empty line to the outputstream - */ - @Override + /** + * Prints a empty line to the outputstream + */ + @Override public void println() { - println(""); //$NON-NLS-1$ - } + println(""); //$NON-NLS-1$ + } - /** - * Print a stack trace including nested exceptions. - * @param t The offending exception - */ - @Override + /** + * Print a stack trace including nested exceptions. + * @param t The offending exception + */ + @Override public void printStackTrace(Throwable t) { - t.printStackTrace(out); + t.printStackTrace(out); - Method[] methods = t.getClass().getMethods(); + Method[] methods = t.getClass().getMethods(); - int size = methods.length; - Class<Throwable> throwable = Throwable.class; + int size = methods.length; + Class<Throwable> throwable = Throwable.class; - for (int i = 0; i < size; i++) { - Method method = methods[i]; + for (int i = 0; i < size; i++) { + Method method = methods[i]; - if (Modifier.isPublic(method.getModifiers()) && method.getName().startsWith("get") && throwable.isAssignableFrom(method.getReturnType()) && (method.getParameterTypes().length == 0)) { //$NON-NLS-1$ - try { - Throwable nested = (Throwable) method.invoke(t, (Object) null); + if (Modifier.isPublic(method.getModifiers()) && method.getName().startsWith("get") && throwable.isAssignableFrom(method.getReturnType()) && (method.getParameterTypes().length == 0)) { //$NON-NLS-1$ + try { + Throwable nested = (Throwable) method.invoke(t, (Object) null); - if ((nested != null) && (nested != t)) { - out.println("Nested Exception"); - printStackTrace(nested); - } - } catch (IllegalAccessException | InvocationTargetException e) { - } - } - } - } + if ((nested != null) && (nested != t)) { + out.println("Nested Exception"); + printStackTrace(nested); + } + } catch (IllegalAccessException | InvocationTargetException e) { + } + } + } + } - /** - * Prints an object to the output medium (appended with newline character). - * <p> - * If running on the target environment, the user is prompted with '--more' - * if more than the configured number of lines have been printed without user prompt. - * This enables the user of the program to have control over scrolling. - * <p> - * For this to work properly you should not embed "\n" etc. into the string. - * - * @param o the object to be printed - */ - @Override + /** + * Prints an object to the output medium (appended with newline character). + * <p> + * If running on the target environment, the user is prompted with '--more' + * if more than the configured number of lines have been printed without user prompt. + * This enables the user of the program to have control over scrolling. + * <p> + * For this to work properly you should not embed "\n" etc. into the string. + * + * @param o the object to be printed + */ + @Override public void println(Object o) { - if (o == null) { - return; - } - synchronized (out) { - check4More(); - printline(o); - currentLineCount++; - currentLineCount += o.toString().length() / 80; - } - } - - /** - * Prints a string to the output medium (appended with newline character). - * <p> - * This method does not increment the line counter for the 'more' prompt. - * - * @param o the string to be printed - */ - private void printline(Object o) { - print(o + newline); - } + if (o == null) { + return; + } + synchronized (out) { + check4More(); + printline(o); + currentLineCount++; + currentLineCount += o.toString().length() / 80; + } + } + + /** + * Prints a string to the output medium (appended with newline character). + * <p> + * This method does not increment the line counter for the 'more' prompt. + * + * @param o the string to be printed + */ + private void printline(Object o) { + print(o + newline); + } - /** - * Prints the given dictionary sorted by keys. - * - * @param dic the dictionary to print - * @param title the header to print above the key/value pairs - */ - @Override + /** + * Prints the given dictionary sorted by keys. + * + * @param dic the dictionary to print + * @param title the header to print above the key/value pairs + */ + @Override public void printDictionary(Dictionary<?,?> dic, String title) { - if (dic == null) - return; + if (dic == null) + return; - int count = dic.size(); - String[] keys = new String[count]; - Enumeration<?> keysEnum = dic.keys(); - int i = 0; - while (keysEnum.hasMoreElements()) { - keys[i++] = (String) keysEnum.nextElement(); - } - Arrays.sort(keys); + int count = dic.size(); + String[] keys = new String[count]; + Enumeration<?> keysEnum = dic.keys(); + int i = 0; + while (keysEnum.hasMoreElements()) { + keys[i++] = (String) keysEnum.nextElement(); + } + Arrays.sort(keys); - if (title != null) { - println(title); - } - for (i = 0; i < count; i++) { - println(" " + keys[i] + " = " + dic.get(keys[i])); //$NON-NLS-1$//$NON-NLS-2$ - } - println(); - } + if (title != null) { + println(title); + } + for (i = 0; i < count; i++) { + println(" " + keys[i] + " = " + dic.get(keys[i])); //$NON-NLS-1$//$NON-NLS-2$ + } + println(); + } - /** - * Prints the given bundle resource if it exists - * - * @param bundle the bundle containing the resource - * @param resource the resource to print - */ - @Override + /** + * Prints the given bundle resource if it exists + * + * @param bundle the bundle containing the resource + * @param resource the resource to print + */ + @Override public void printBundleResource(Bundle bundle, String resource) { - URL entry = null; - entry = bundle.getEntry(resource); - if (entry != null) { - try { - println(resource); - byte[] buffer = new byte[1024]; - int read = 0; - try (InputStream in = entry.openStream()) { - while ((read = in.read(buffer)) != -1) - print(new String(buffer, 0, read)); - } - } catch (Exception e) { - System.err.println(e); - } - } else { - println("CONSOLE_RESOURCE ["+resource+"] NOT_IN_BUNDLE " + bundle); - } - } - - /** - * Answers the number of lines output to the console - * window should scroll without user interaction. - * - * @return The number of lines to scroll. - */ - private int getMaximumLinesToScroll() { - return maxLineCount; - } + URL entry = null; + entry = bundle.getEntry(resource); + if (entry != null) { + try { + println(resource); + byte[] buffer = new byte[1024]; + int read = 0; + try (InputStream in = entry.openStream()) { + while ((read = in.read(buffer)) != -1) + print(new String(buffer, 0, read)); + } + } catch (Exception e) { + System.err.println(e); + } + } else { + println("CONSOLE_RESOURCE ["+resource+"] NOT_IN_BUNDLE " + bundle); + } + } + + /** + * Answers the number of lines output to the console + * window should scroll without user interaction. + * + * @return The number of lines to scroll. + */ + private int getMaximumLinesToScroll() { + return maxLineCount; + } - /** - * Displays the more... prompt if the max line count has been reached - * and waits for the operator to hit enter. - * - */ - private void check4More() { - int max = getMaximumLinesToScroll(); - if (max > 0) { - if (currentLineCount >= max) { - out.print("-- More...Press Enter to Continue..."); - out.flush(); - try { - System.in.read(); - } catch (IOException e) { - e.printStackTrace(); - } // wait for user entry - resetLineCount(); //Reset the line counter for the 'more' prompt - } - } - } + /** + * Displays the more... prompt if the max line count has been reached + * and waits for the operator to hit enter. + * + */ + private void check4More() { + int max = getMaximumLinesToScroll(); + if (max > 0) { + if (currentLineCount >= max) { + out.print("-- More...Press Enter to Continue..."); + out.flush(); + try { + System.in.read(); + } catch (IOException e) { + e.printStackTrace(); + } // wait for user entry + resetLineCount(); //Reset the line counter for the 'more' prompt + } + } + } - /** - * Resets the line counter for the 'more' prompt. - */ - private void resetLineCount() { - currentLineCount = 0; - } - - /** - Answer a string (may be as many lines as you like) with help - texts that explain the command. - */ - public String getHelp() { - StringBuilder help = new StringBuilder(256); - help.append("---Controlling the Console---"); - help.append(newline); - help.append(tab); - help.append("more - "); //$NON-NLS-1$ - help.append("More prompt for console output"); - help.append(newline); - help.append(tab); - help.append("disconnect - "); //$NON-NLS-1$ - help.append("isconnects from telnet session"); - help.append(newline); - return help.toString(); - } + /** + * Resets the line counter for the 'more' prompt. + */ + private void resetLineCount() { + currentLineCount = 0; + } + + /** + Answer a string (may be as many lines as you like) with help + texts that explain the command. + */ + public String getHelp() { + StringBuilder help = new StringBuilder(256); + help.append("---Controlling the Console---"); + help.append(newline); + help.append(tab); + help.append("more - "); //$NON-NLS-1$ + help.append("More prompt for console output"); + help.append(newline); + help.append(tab); + help.append("disconnect - "); //$NON-NLS-1$ + help.append("isconnects from telnet session"); + help.append(newline); + return help.toString(); + } } diff --git a/bundles/org.eclipse.equinox.console/src/org/eclipse/equinox/console/commands/CommandsTracker.java b/bundles/org.eclipse.equinox.console/src/org/eclipse/equinox/console/commands/CommandsTracker.java index 89cddec58..5a22f310b 100755 --- a/bundles/org.eclipse.equinox.console/src/org/eclipse/equinox/console/commands/CommandsTracker.java +++ b/bundles/org.eclipse.equinox.console/src/org/eclipse/equinox/console/commands/CommandsTracker.java @@ -26,46 +26,46 @@ import org.osgi.util.tracker.ServiceTracker; import org.osgi.util.tracker.ServiceTrackerCustomizer; public class CommandsTracker { - private Set<String> commandNames; - private ServiceTracker<Object, Set<String>> commandsTracker = null; - private static final Object lock = new Object(); - - public CommandsTracker(BundleContext bundleContext) { - commandNames = Collections.synchronizedSet(new HashSet<String>()); - try { + private Set<String> commandNames; + private ServiceTracker<Object, Set<String>> commandsTracker = null; + private static final Object lock = new Object(); + + public CommandsTracker(BundleContext bundleContext) { + commandNames = Collections.synchronizedSet(new HashSet<String>()); + try { Filter filter = bundleContext.createFilter(String.format("(&(%s=*)(%s=*))", CommandProcessor.COMMAND_SCOPE, CommandProcessor.COMMAND_FUNCTION)); commandsTracker = new ServiceTracker<>(bundleContext, filter, new CommandsTrackerCustomizer()); commandsTracker.open(); } catch (InvalidSyntaxException e) { //do nothing; } - } - - public Set<String> getCommands() { - synchronized (lock) { - return new HashSet<>(commandNames); - } - } - - class CommandsTrackerCustomizer implements ServiceTrackerCustomizer<Object, Set<String>> { - @Override + } + + public Set<String> getCommands() { + synchronized (lock) { + return new HashSet<>(commandNames); + } + } + + class CommandsTrackerCustomizer implements ServiceTrackerCustomizer<Object, Set<String>> { + @Override public Set<String> addingService(ServiceReference<Object> reference) { Object scope = reference.getProperty(CommandProcessor.COMMAND_SCOPE); - Object function = reference.getProperty(CommandProcessor.COMMAND_FUNCTION); + Object function = reference.getProperty(CommandProcessor.COMMAND_FUNCTION); - if (scope != null && function != null) { - synchronized (lock) { - if (function.getClass().isArray()) { - for (Object func : ((Object[]) function)) { - commandNames.add(scope + ":" + func); - } - } else { - commandNames.add(scope + ":" + function); - } - return commandNames; - } - } - return null; + if (scope != null && function != null) { + synchronized (lock) { + if (function.getClass().isArray()) { + for (Object func : ((Object[]) function)) { + commandNames.add(scope + ":" + func); + } + } else { + commandNames.add(scope + ":" + function); + } + return commandNames; + } + } + return null; } @Override @@ -76,18 +76,18 @@ public class CommandsTracker { @Override public void removedService(ServiceReference<Object> reference, Set<String> commandNames) { Object scope = reference.getProperty(CommandProcessor.COMMAND_SCOPE); - Object function = reference.getProperty(CommandProcessor.COMMAND_FUNCTION); + Object function = reference.getProperty(CommandProcessor.COMMAND_FUNCTION); - if (scope != null && function != null) { - if (!function.getClass().isArray()) { - commandNames.remove(scope + ":" + function); - } else { - for (Object func : (Object[]) function) { - commandNames.remove(scope + ":" + func); - } - } - } + if (scope != null && function != null) { + if (!function.getClass().isArray()) { + commandNames.remove(scope + ":" + function); + } else { + for (Object func : (Object[]) function) { + commandNames.remove(scope + ":" + func); + } + } + } } - - } + + } } diff --git a/bundles/org.eclipse.equinox.console/src/org/eclipse/equinox/console/commands/HelpCommand.java b/bundles/org.eclipse.equinox.console/src/org/eclipse/equinox/console/commands/HelpCommand.java index d13f2272b..8ee23394a 100755 --- a/bundles/org.eclipse.equinox.console/src/org/eclipse/equinox/console/commands/HelpCommand.java +++ b/bundles/org.eclipse.equinox.console/src/org/eclipse/equinox/console/commands/HelpCommand.java @@ -43,12 +43,12 @@ public class HelpCommand { private ServiceTracker<CommandsTracker, CommandsTracker> commandsTrackerTracker; private static final String COMMANDS = ".commands"; - public class CommandProviderCustomizer implements ServiceTrackerCustomizer<CommandProvider, Set<CommandProvider>> { - private BundleContext context; - public CommandProviderCustomizer(BundleContext context) { - this.context = context; - } - + public class CommandProviderCustomizer implements ServiceTrackerCustomizer<CommandProvider, Set<CommandProvider>> { + private BundleContext context; + public CommandProviderCustomizer(BundleContext context) { + this.context = context; + } + @Override public Set<CommandProvider> addingService( ServiceReference<CommandProvider> reference) { @@ -75,8 +75,8 @@ public class HelpCommand { CommandProvider provider = context.getService(reference); providers.remove(provider); } - - } + + } public HelpCommand(BundleContext context) { this.context = context; diff --git a/bundles/org.eclipse.equinox.console/src/org/eclipse/equinox/console/common/ConsoleInputHandler.java b/bundles/org.eclipse.equinox.console/src/org/eclipse/equinox/console/common/ConsoleInputHandler.java index 44d91c088..b7b304f09 100755 --- a/bundles/org.eclipse.equinox.console/src/org/eclipse/equinox/console/common/ConsoleInputHandler.java +++ b/bundles/org.eclipse.equinox.console/src/org/eclipse/equinox/console/common/ConsoleInputHandler.java @@ -24,8 +24,8 @@ import java.io.OutputStream; */ public class ConsoleInputHandler extends InputHandler { - public ConsoleInputHandler(InputStream input, ConsoleInputStream in, OutputStream out) { - super(input, in, out); - inputScanner = new ConsoleInputScanner(in, out); - } + public ConsoleInputHandler(InputStream input, ConsoleInputStream in, OutputStream out) { + super(input, in, out); + inputScanner = new ConsoleInputScanner(in, out); + } } diff --git a/bundles/org.eclipse.equinox.console/src/org/eclipse/equinox/console/common/ConsoleInputScanner.java b/bundles/org.eclipse.equinox.console/src/org/eclipse/equinox/console/common/ConsoleInputScanner.java index bb8ebd44f..9f0759dcd 100755 --- a/bundles/org.eclipse.equinox.console/src/org/eclipse/equinox/console/common/ConsoleInputScanner.java +++ b/bundles/org.eclipse.equinox.console/src/org/eclipse/equinox/console/common/ConsoleInputScanner.java @@ -32,472 +32,472 @@ import org.osgi.framework.BundleContext; public class ConsoleInputScanner extends Scanner { private static final byte TAB = 9; - private boolean isCR = false; - private boolean replace = false; - private boolean isCompletionMode = false; - // shows if command history should be saved - it is turned off in cases when passwords are to be entered - private boolean isHistoryEnabled = true; + private boolean isCR = false; + private boolean replace = false; + private boolean isCompletionMode = false; + // shows if command history should be saved - it is turned off in cases when passwords are to be entered + private boolean isHistoryEnabled = true; - private final HistoryHolder history; - private final SimpleByteBuffer buffer; - private CommandSession session; - private BundleContext context; - private Candidates candidates; - private int originalCursorPos; + private final HistoryHolder history; + private final SimpleByteBuffer buffer; + private CommandSession session; + private BundleContext context; + private Candidates candidates; + private int originalCursorPos; - public ConsoleInputScanner(ConsoleInputStream toShell, OutputStream toTelnet) { - super(toShell, toTelnet); - history = new HistoryHolder(); - buffer = new SimpleByteBuffer(); - } - - public void toggleHistoryEnabled(boolean isEnabled) { - isHistoryEnabled = isEnabled; - } - - public void setSession(CommandSession session) { - this.session = session; - } + public ConsoleInputScanner(ConsoleInputStream toShell, OutputStream toTelnet) { + super(toShell, toTelnet); + history = new HistoryHolder(); + buffer = new SimpleByteBuffer(); + } + + public void toggleHistoryEnabled(boolean isEnabled) { + isHistoryEnabled = isEnabled; + } + + public void setSession(CommandSession session) { + this.session = session; + } - public void setContext(BundleContext context) { - this.context = context; - } - - @Override + public void setContext(BundleContext context) { + this.context = context; + } + + @Override public void scan(int b) throws IOException { - b &= 0xFF; - if (isCR) { - isCR = false; - if (b == LF) { - return; - } - } - - if (b != TAB) { - if (isCompletionMode == true) { - isCompletionMode = false; - candidates = null; - originalCursorPos = 0; - } - } - - if (isEsc) { - scanEsc(b); - } else { - if (b == getBackspace()) { - backSpace(); - } else if(b == TAB) { - if (isCompletionMode == false) { - isCompletionMode = true; - processTab(); - } else { - processNextTab(); - } - } else if (b == CR) { - isCR = true; - processData(); - } else if (b == LF) { - processData(); - } else if (b == ESC) { - startEsc(); - } else if (b == getDel()) { - delete(); - } else { - if (b >= SPACE && b < MAX_CHAR) { - newChar(b); - } - } - } - } + b &= 0xFF; + if (isCR) { + isCR = false; + if (b == LF) { + return; + } + } + + if (b != TAB) { + if (isCompletionMode == true) { + isCompletionMode = false; + candidates = null; + originalCursorPos = 0; + } + } + + if (isEsc) { + scanEsc(b); + } else { + if (b == getBackspace()) { + backSpace(); + } else if(b == TAB) { + if (isCompletionMode == false) { + isCompletionMode = true; + processTab(); + } else { + processNextTab(); + } + } else if (b == CR) { + isCR = true; + processData(); + } else if (b == LF) { + processData(); + } else if (b == ESC) { + startEsc(); + } else if (b == getDel()) { + delete(); + } else { + if (b >= SPACE && b < MAX_CHAR) { + newChar(b); + } + } + } + } - private void delete() throws IOException { - clearLine(); - buffer.delete(); - echoBuff(); - flush(); - } + private void delete() throws IOException { + clearLine(); + buffer.delete(); + echoBuff(); + flush(); + } - private void backSpace() throws IOException { - clearLine(); - buffer.backSpace(); - echoBuff(); - flush(); - } + private void backSpace() throws IOException { + clearLine(); + buffer.backSpace(); + echoBuff(); + flush(); + } - protected void clearLine() throws IOException { - int size = buffer.getSize(); - int pos = buffer.getPos(); - for (int i = size - pos; i < size; i++) { - echo(BS); - } - for (int i = 0; i < size; i++) { - echo(SPACE); - } - for (int i = 0; i < size; i++) { - echo(BS); - } - } + protected void clearLine() throws IOException { + int size = buffer.getSize(); + int pos = buffer.getPos(); + for (int i = size - pos; i < size; i++) { + echo(BS); + } + for (int i = 0; i < size; i++) { + echo(SPACE); + } + for (int i = 0; i < size; i++) { + echo(BS); + } + } - protected void echoBuff() throws IOException { - byte[] data = buffer.copyCurrentData(); - for (byte b : data) { - echo(b); - } - int pos = buffer.getPos(); - for (int i = data.length; i > pos; i--) { - echo(BS); - } - } + protected void echoBuff() throws IOException { + byte[] data = buffer.copyCurrentData(); + for (byte b : data) { + echo(b); + } + int pos = buffer.getPos(); + for (int i = data.length; i > pos; i--) { + echo(BS); + } + } - protected void newChar(int b) throws IOException { - if (buffer.getPos() < buffer.getSize()) { - if (replace) { - buffer.replace(b); - } else { - buffer.insert(b); - } - clearLine(); - echoBuff(); - flush(); - } else { - if (replace) { - buffer.replace(b); - } else { - buffer.insert(b); - } - } - } - - protected void processTab() throws IOException { - CompletionHandler completionHandler = new CompletionHandler(context, session); - Map<String, Integer> completionCandidates = completionHandler.getCandidates(buffer.copyCurrentData(), buffer.getPos()); - - if (completionCandidates.size() == 1) { - completeSingleCandidate(completionCandidates); - isCompletionMode = false; - return; - } - printNewLine(); - if (completionCandidates.size() == 0) { - printCompletionError(); - isCompletionMode = false; - } else { - processCandidates(completionCandidates); - } - printNewLine(); - printPrompt(); - } - - protected void processCandidates(Map<String, Integer> completionCandidates) throws IOException{ - Set<String> candidatesNamesSet = completionCandidates.keySet(); - String[] candidatesNames = (candidatesNamesSet.toArray(new String[0])); - originalCursorPos = buffer.getPos(); - String[] candidateSuffixes = new String[candidatesNames.length]; - for (int i = 0; i < candidatesNames.length; i++) { - String candidateName = candidatesNames[i]; - candidateSuffixes[i] = getCandidateSuffix(candidateName, completionCandidates.get(candidateName), originalCursorPos); - for (byte symbol : candidateName.getBytes()) { - echo(symbol); - } - printNewLine(); - } - - String commonPrefix = getCommonPrefix(candidateSuffixes); - candidates = new Candidates(removeCommonPrefix(candidateSuffixes, commonPrefix)); - printString(commonPrefix, false); - originalCursorPos = buffer.getPos(); - } - - protected void processNextTab() throws IOException { - if (candidates == null) { - return; - } - - while (originalCursorPos < buffer.getPos()) { + protected void newChar(int b) throws IOException { + if (buffer.getPos() < buffer.getSize()) { + if (replace) { + buffer.replace(b); + } else { + buffer.insert(b); + } + clearLine(); + echoBuff(); + flush(); + } else { + if (replace) { + buffer.replace(b); + } else { + buffer.insert(b); + } + } + } + + protected void processTab() throws IOException { + CompletionHandler completionHandler = new CompletionHandler(context, session); + Map<String, Integer> completionCandidates = completionHandler.getCandidates(buffer.copyCurrentData(), buffer.getPos()); + + if (completionCandidates.size() == 1) { + completeSingleCandidate(completionCandidates); + isCompletionMode = false; + return; + } + printNewLine(); + if (completionCandidates.size() == 0) { + printCompletionError(); + isCompletionMode = false; + } else { + processCandidates(completionCandidates); + } + printNewLine(); + printPrompt(); + } + + protected void processCandidates(Map<String, Integer> completionCandidates) throws IOException{ + Set<String> candidatesNamesSet = completionCandidates.keySet(); + String[] candidatesNames = (candidatesNamesSet.toArray(new String[0])); + originalCursorPos = buffer.getPos(); + String[] candidateSuffixes = new String[candidatesNames.length]; + for (int i = 0; i < candidatesNames.length; i++) { + String candidateName = candidatesNames[i]; + candidateSuffixes[i] = getCandidateSuffix(candidateName, completionCandidates.get(candidateName), originalCursorPos); + for (byte symbol : candidateName.getBytes()) { + echo(symbol); + } + printNewLine(); + } + + String commonPrefix = getCommonPrefix(candidateSuffixes); + candidates = new Candidates(removeCommonPrefix(candidateSuffixes, commonPrefix)); + printString(commonPrefix, false); + originalCursorPos = buffer.getPos(); + } + + protected void processNextTab() throws IOException { + if (candidates == null) { + return; + } + + while (originalCursorPos < buffer.getPos()) { backSpace(); - } - - String candidate = candidates.getCurrent(); - if(!candidate.equals("")) { - printString(candidate, true); - } - } - - protected void printCandidate(String candidate, int startIndex, int completionIndex) throws IOException { - String suffix = getCandidateSuffix(candidate, startIndex, completionIndex); - if(suffix.equals("")) { - return; - } - printString(suffix, true); - } - - protected void printString(String st, boolean isEcho) throws IOException { - for (byte symbol : st.getBytes()) { - buffer.insert(symbol); - if (isEcho){ - echo(symbol); - } - } - flush(); - } - - protected String getCommonPrefix(String[] names) { - if (names.length == 0) { - return ""; - } - - if (names.length == 1) { - return names[0]; - } - - StringBuilder builder = new StringBuilder(); - char[] name = names[0].toCharArray(); - for(char c : name) { - String prefix = builder.append(c).toString(); - for (int i = 1; i < names.length; i ++) { - if (!names[i].startsWith(prefix)) { - return prefix.substring(0, prefix.length() - 1); - } - } - } - - return builder.toString(); - } - - protected String[] removeCommonPrefix(String [] names, String commonPrefix){ - ArrayList<String> result = new ArrayList<>(); - for (String name : names) { - String nameWithoutPrefix = name.substring(commonPrefix.length()); - if (nameWithoutPrefix.length() > 0) { - result.add(nameWithoutPrefix); - } - } - result.add(""); - return result.toArray(new String[0]); - } - - protected String getCandidateSuffix(String candidate, int startIndex, int completionIndex) { - int partialLength = completionIndex - startIndex; - if (partialLength >= candidate.length()) { - return ""; - } - return candidate.substring(partialLength); - } - - protected void completeSingleCandidate(Map<String, Integer> completionCandidates) throws IOException { - Set<String> keys = completionCandidates.keySet(); - String key = (keys.toArray(new String[0]))[0]; - int startIndex = completionCandidates.get(key); - printCandidate(key, startIndex, buffer.getPos()); - } - - protected void printCompletionError() throws IOException { - byte[] curr = buffer.getCurrentData(); - if (isHistoryEnabled == true) { - history.add(curr); - } - - String errorMessage = "No completion available"; - for (byte symbol : errorMessage.getBytes()) { - echo(symbol); - } - } - - protected void printNewLine() throws IOException{ - echo(CR); - echo(LF); - flush(); - } - - protected void printPrompt() throws IOException{ - echo('o'); - echo('s'); - echo('g'); - echo('i'); - echo('>'); - echo(SPACE); - echoBuff(); - flush(); - } + } + + String candidate = candidates.getCurrent(); + if(!candidate.equals("")) { + printString(candidate, true); + } + } + + protected void printCandidate(String candidate, int startIndex, int completionIndex) throws IOException { + String suffix = getCandidateSuffix(candidate, startIndex, completionIndex); + if(suffix.equals("")) { + return; + } + printString(suffix, true); + } + + protected void printString(String st, boolean isEcho) throws IOException { + for (byte symbol : st.getBytes()) { + buffer.insert(symbol); + if (isEcho){ + echo(symbol); + } + } + flush(); + } + + protected String getCommonPrefix(String[] names) { + if (names.length == 0) { + return ""; + } + + if (names.length == 1) { + return names[0]; + } + + StringBuilder builder = new StringBuilder(); + char[] name = names[0].toCharArray(); + for(char c : name) { + String prefix = builder.append(c).toString(); + for (int i = 1; i < names.length; i ++) { + if (!names[i].startsWith(prefix)) { + return prefix.substring(0, prefix.length() - 1); + } + } + } + + return builder.toString(); + } + + protected String[] removeCommonPrefix(String [] names, String commonPrefix){ + ArrayList<String> result = new ArrayList<>(); + for (String name : names) { + String nameWithoutPrefix = name.substring(commonPrefix.length()); + if (nameWithoutPrefix.length() > 0) { + result.add(nameWithoutPrefix); + } + } + result.add(""); + return result.toArray(new String[0]); + } + + protected String getCandidateSuffix(String candidate, int startIndex, int completionIndex) { + int partialLength = completionIndex - startIndex; + if (partialLength >= candidate.length()) { + return ""; + } + return candidate.substring(partialLength); + } + + protected void completeSingleCandidate(Map<String, Integer> completionCandidates) throws IOException { + Set<String> keys = completionCandidates.keySet(); + String key = (keys.toArray(new String[0]))[0]; + int startIndex = completionCandidates.get(key); + printCandidate(key, startIndex, buffer.getPos()); + } + + protected void printCompletionError() throws IOException { + byte[] curr = buffer.getCurrentData(); + if (isHistoryEnabled == true) { + history.add(curr); + } + + String errorMessage = "No completion available"; + for (byte symbol : errorMessage.getBytes()) { + echo(symbol); + } + } + + protected void printNewLine() throws IOException{ + echo(CR); + echo(LF); + flush(); + } + + protected void printPrompt() throws IOException{ + echo('o'); + echo('s'); + echo('g'); + echo('i'); + echo('>'); + echo(SPACE); + echoBuff(); + flush(); + } - private void processData() throws IOException { + private void processData() throws IOException { // buffer.add(CR); - buffer.add(LF); - echo(CR); - echo(LF); - flush(); - byte[] curr = buffer.getCurrentData(); - if (isHistoryEnabled == true) { - history.add(curr); - } - toShell.add(curr); - } + buffer.add(LF); + echo(CR); + echo(LF); + flush(); + byte[] curr = buffer.getCurrentData(); + if (isHistoryEnabled == true) { + history.add(curr); + } + toShell.add(curr); + } - public void resetHistory() { - history.reset(); - } + public void resetHistory() { + history.reset(); + } - @Override + @Override protected void scanEsc(final int b) throws IOException { - esc += (char) b; - KEYS key = checkEscape(esc); - if (key == KEYS.UNFINISHED) { - return; - } - if (key == KEYS.UNKNOWN) { - isEsc = false; - scan(b); - return; - } - isEsc = false; - switch (key) { - case UP: - processUpArrow(); - break; - case DOWN: - processDownArrow(); - break; - case RIGHT: - processRightArrow(); - break; - case LEFT: - processLeftArrow(); - break; - case HOME: - processHome(); - break; - case END: - processEnd(); - break; - case PGUP: - processPgUp(); - break; - case PGDN: - processPgDn(); - break; - case INS: - processIns(); - break; - case DEL: - delete(); - break; - default: //CENTER - break; - } - } + esc += (char) b; + KEYS key = checkEscape(esc); + if (key == KEYS.UNFINISHED) { + return; + } + if (key == KEYS.UNKNOWN) { + isEsc = false; + scan(b); + return; + } + isEsc = false; + switch (key) { + case UP: + processUpArrow(); + break; + case DOWN: + processDownArrow(); + break; + case RIGHT: + processRightArrow(); + break; + case LEFT: + processLeftArrow(); + break; + case HOME: + processHome(); + break; + case END: + processEnd(); + break; + case PGUP: + processPgUp(); + break; + case PGDN: + processPgDn(); + break; + case INS: + processIns(); + break; + case DEL: + delete(); + break; + default: //CENTER + break; + } + } - private static final byte[] INVERSE_ON = {ESC, '[', '7', 'm'}; - private static final byte[] INVERSE_OFF = {ESC, '[', '2', '7', 'm'}; + private static final byte[] INVERSE_ON = {ESC, '[', '7', 'm'}; + private static final byte[] INVERSE_OFF = {ESC, '[', '2', '7', 'm'}; - private void echo(byte[] data) throws IOException { - for (byte b : data) { - echo(b); - } - } + private void echo(byte[] data) throws IOException { + for (byte b : data) { + echo(b); + } + } - private void processIns() throws IOException { - replace = !replace; - int b = buffer.getCurrentChar(); - echo(INVERSE_ON); - echo(replace ? 'R' : 'I'); - flush(); - try { - Thread.sleep(300); - } catch (InterruptedException e) { - //do not care $JL-EXC$ - } - echo(INVERSE_OFF); - echo(BS); - echo(b == -1 ? SPACE : b); - echo(BS); - flush(); - } + private void processIns() throws IOException { + replace = !replace; + int b = buffer.getCurrentChar(); + echo(INVERSE_ON); + echo(replace ? 'R' : 'I'); + flush(); + try { + Thread.sleep(300); + } catch (InterruptedException e) { + //do not care $JL-EXC$ + } + echo(INVERSE_OFF); + echo(BS); + echo(b == -1 ? SPACE : b); + echo(BS); + flush(); + } - private void processPgDn() throws IOException { - byte[] last = history.last(); - if (last != null) { - clearLine(); - buffer.set(last); - echoBuff(); - flush(); - } - } + private void processPgDn() throws IOException { + byte[] last = history.last(); + if (last != null) { + clearLine(); + buffer.set(last); + echoBuff(); + flush(); + } + } - private void processPgUp() throws IOException { - byte[] first = history.first(); - if (first != null) { - clearLine(); - buffer.set(first); - echoBuff(); - flush(); - } - } + private void processPgUp() throws IOException { + byte[] first = history.first(); + if (first != null) { + clearLine(); + buffer.set(first); + echoBuff(); + flush(); + } + } - private void processHome() throws IOException { - int pos = buffer.resetPos(); - if (pos > 0) { - for (int i = 0; i < pos; i++) { - echo(BS); - } - flush(); - } - } + private void processHome() throws IOException { + int pos = buffer.resetPos(); + if (pos > 0) { + for (int i = 0; i < pos; i++) { + echo(BS); + } + flush(); + } + } - private void processEnd() throws IOException { - int b; - while ((b = buffer.goRight()) != -1) { - echo(b); - } - flush(); - } + private void processEnd() throws IOException { + int b; + while ((b = buffer.goRight()) != -1) { + echo(b); + } + flush(); + } - private void processLeftArrow() throws IOException { - if (buffer.goLeft()) { - echo(BS); - flush(); - } - } + private void processLeftArrow() throws IOException { + if (buffer.goLeft()) { + echo(BS); + flush(); + } + } - private void processRightArrow() throws IOException { - int b = buffer.goRight(); - if (b != -1) { - echo(b); - flush(); - } - } + private void processRightArrow() throws IOException { + int b = buffer.goRight(); + if (b != -1) { + echo(b); + flush(); + } + } - private void processDownArrow() throws IOException { - byte[] next = history.next(); - if (next != null) { - clearLine(); - buffer.set(next); - echoBuff(); - flush(); - } - } + private void processDownArrow() throws IOException { + byte[] next = history.next(); + if (next != null) { + clearLine(); + buffer.set(next); + echoBuff(); + flush(); + } + } - private void processUpArrow() throws IOException { - clearLine(); - byte[] prev = history.prev(); - buffer.set(prev); - echoBuff(); - flush(); - } - - private static class Candidates { - private String[] candidates; - private int currentCandidateIndex = 0; - - public Candidates(String[] candidates) { - this.candidates = candidates.clone(); - } - - public String getCurrent() { - if (currentCandidateIndex >= candidates.length) { - currentCandidateIndex = 0; - } - - return candidates[currentCandidateIndex++]; - } - } + private void processUpArrow() throws IOException { + clearLine(); + byte[] prev = history.prev(); + buffer.set(prev); + echoBuff(); + flush(); + } + + private static class Candidates { + private String[] candidates; + private int currentCandidateIndex = 0; + + public Candidates(String[] candidates) { + this.candidates = candidates.clone(); + } + + public String getCurrent() { + if (currentCandidateIndex >= candidates.length) { + currentCandidateIndex = 0; + } + + return candidates[currentCandidateIndex++]; + } + } } diff --git a/bundles/org.eclipse.equinox.console/src/org/eclipse/equinox/console/common/ConsoleInputStream.java b/bundles/org.eclipse.equinox.console/src/org/eclipse/equinox/console/common/ConsoleInputStream.java index 2fa7f7dbe..481f3e76e 100755 --- a/bundles/org.eclipse.equinox.console/src/org/eclipse/equinox/console/common/ConsoleInputStream.java +++ b/bundles/org.eclipse.equinox.console/src/org/eclipse/equinox/console/common/ConsoleInputStream.java @@ -22,140 +22,140 @@ import java.util.ArrayList; */ public class ConsoleInputStream extends InputStream { - private final ArrayList<byte[]> buffer = new ArrayList<>(); - private byte[] current; - private int pos; - private boolean isClosed; + private final ArrayList<byte[]> buffer = new ArrayList<>(); + private byte[] current; + private int pos; + private boolean isClosed; - @Override + @Override public synchronized int read() { - while (current == null && buffer.isEmpty() && !isClosed) { - try { - wait(); - } catch (InterruptedException e) { - return -1; - } - } - if (isClosed) { - return -1; - } + while (current == null && buffer.isEmpty() && !isClosed) { + try { + wait(); + } catch (InterruptedException e) { + return -1; + } + } + if (isClosed) { + return -1; + } - try { - if (current == null) { - current = buffer.remove(0); - return current[pos++] & 0xFF; - } else { + try { + if (current == null) { + current = buffer.remove(0); + return current[pos++] & 0xFF; + } else { - return current[pos++] & 0xFF; - } - } finally { - if (current != null) { - if (pos == current.length) { - current = null; - pos = 0; - } - } - } + return current[pos++] & 0xFF; + } + } finally { + if (current != null) { + if (pos == current.length) { + current = null; + pos = 0; + } + } + } - } + } - /*public int read(byte b[], int off, int len) throws IOException { - if (len == 0) { - return len; - } - int i = read(); - if (i == -1) { - return -1; - } - b[off] = (byte) i; - return 1; - }*/ - - /*public synchronized int read(byte b[], int off, int len) throws IOException { - if (len == 0) { - return len; - } - - int currOff = off; - int readCnt = 0; - - if (current != null) { - int i; - while (pos > 0 && readCnt < len) { - i = read(); - if (i == -1) { - return (readCnt > 0) ? readCnt : i; - } - b[currOff] = (byte) i; - currOff++; - readCnt++; - } - } else { - int i = read(); - if (i == -1) { - return i; - } - b[currOff] = (byte) i; - currOff++; - readCnt++; - while (pos > 0 && readCnt < len) { - i = read(); - if (i == -1) { - return (readCnt > 0) ? readCnt : i; - } - b[currOff] = (byte) i; - currOff++; - readCnt++; - } - } - - return readCnt; - }*/ - - @Override + /*public int read(byte b[], int off, int len) throws IOException { + if (len == 0) { + return len; + } + int i = read(); + if (i == -1) { + return -1; + } + b[off] = (byte) i; + return 1; + }*/ + + /*public synchronized int read(byte b[], int off, int len) throws IOException { + if (len == 0) { + return len; + } + + int currOff = off; + int readCnt = 0; + + if (current != null) { + int i; + while (pos > 0 && readCnt < len) { + i = read(); + if (i == -1) { + return (readCnt > 0) ? readCnt : i; + } + b[currOff] = (byte) i; + currOff++; + readCnt++; + } + } else { + int i = read(); + if (i == -1) { + return i; + } + b[currOff] = (byte) i; + currOff++; + readCnt++; + while (pos > 0 && readCnt < len) { + i = read(); + if (i == -1) { + return (readCnt > 0) ? readCnt : i; + } + b[currOff] = (byte) i; + currOff++; + readCnt++; + } + } + + return readCnt; + }*/ + + @Override public synchronized int read(byte b[], int off, int len) throws IOException { - if (len == 0) { - return len; - } - - int currOff = off; - int readCnt = 0; - int i; - - if (current == null) { - i = read(); - if (i == -1) { - return i; - } - b[currOff] = (byte) i; - currOff++; - readCnt++; - } - - while ((pos > 0 || !buffer.isEmpty()) && readCnt < len) { - i = read(); - if (i == -1) { - return (readCnt > 0) ? readCnt : i; - } - b[currOff] = (byte) i; - currOff++; - readCnt++; - } - - return readCnt; - } + if (len == 0) { + return len; + } + + int currOff = off; + int readCnt = 0; + int i; + + if (current == null) { + i = read(); + if (i == -1) { + return i; + } + b[currOff] = (byte) i; + currOff++; + readCnt++; + } + + while ((pos > 0 || !buffer.isEmpty()) && readCnt < len) { + i = read(); + if (i == -1) { + return (readCnt > 0) ? readCnt : i; + } + b[currOff] = (byte) i; + currOff++; + readCnt++; + } + + return readCnt; + } - @Override + @Override public synchronized void close() throws IOException { - isClosed = true; - notifyAll(); - } + isClosed = true; + notifyAll(); + } - public synchronized void add(byte[] data) { - if (data.length > 0) { - buffer.add(data); - notify(); - } - } + public synchronized void add(byte[] data) { + if (data.length > 0) { + buffer.add(data); + notify(); + } + } } diff --git a/bundles/org.eclipse.equinox.console/src/org/eclipse/equinox/console/common/ConsoleOutputStream.java b/bundles/org.eclipse.equinox.console/src/org/eclipse/equinox/console/common/ConsoleOutputStream.java index cbec0231c..6541fef51 100755 --- a/bundles/org.eclipse.equinox.console/src/org/eclipse/equinox/console/common/ConsoleOutputStream.java +++ b/bundles/org.eclipse.equinox.console/src/org/eclipse/equinox/console/common/ConsoleOutputStream.java @@ -23,127 +23,127 @@ import java.io.OutputStream; */ public class ConsoleOutputStream extends OutputStream { - /** - * A size of the used buffer. - */ - public static final int BUFFER_SIZE = 2048; - public final static byte CR = (byte) '\r'; - public final static byte LF = (byte) '\n'; - - OutputStream out; - OutputStream oldOut; - - private boolean isEcho = true; - private boolean queueing = false; - private byte prevByte; - private byte[] buffer; - private int pos; - - /** - * Initiates with instance of the output stream to which it will send data. Here it writes to - * a socket output stream. - * - * @param out OutputStream for console output - */ - public ConsoleOutputStream(OutputStream out) { - this.out = out; - buffer = new byte[BUFFER_SIZE]; - pos = 0; - } - - /** - * An implementation of the corresponding abstract method in OutputStream. - */ - @Override + /** + * A size of the used buffer. + */ + public static final int BUFFER_SIZE = 2048; + public final static byte CR = (byte) '\r'; + public final static byte LF = (byte) '\n'; + + OutputStream out; + OutputStream oldOut; + + private boolean isEcho = true; + private boolean queueing = false; + private byte prevByte; + private byte[] buffer; + private int pos; + + /** + * Initiates with instance of the output stream to which it will send data. Here it writes to + * a socket output stream. + * + * @param out OutputStream for console output + */ + public ConsoleOutputStream(OutputStream out) { + this.out = out; + buffer = new byte[BUFFER_SIZE]; + pos = 0; + } + + /** + * An implementation of the corresponding abstract method in OutputStream. + */ + @Override public synchronized void write(int i) throws IOException { - if (!queueing) { - if (isEcho) { - if (i == '\r' || i == '\0') { - queueing = true; - prevByte = (byte) i; - } else if (i == '\n') { - add(CR); - add(LF); - } else { - add(i); - } - } - } else { // awaiting '\n' AFTER '\r', and '\b' AFTER '\0' - if (prevByte == '\0' && i == '\b') { - isEcho = !isEcho; - } else if (isEcho) { - if (prevByte == '\r' && i == '\n') { - add(CR); - add(LF); - } else { - add(CR); - add(LF); - add(i); - } - } - - queueing = false; - flush(); - } - - } - - /** - * Empties the buffer and sends data to the socket output stream. - * - * @throws IOException - */ - @Override + if (!queueing) { + if (isEcho) { + if (i == '\r' || i == '\0') { + queueing = true; + prevByte = (byte) i; + } else if (i == '\n') { + add(CR); + add(LF); + } else { + add(i); + } + } + } else { // awaiting '\n' AFTER '\r', and '\b' AFTER '\0' + if (prevByte == '\0' && i == '\b') { + isEcho = !isEcho; + } else if (isEcho) { + if (prevByte == '\r' && i == '\n') { + add(CR); + add(LF); + } else { + add(CR); + add(LF); + add(i); + } + } + + queueing = false; + flush(); + } + + } + + /** + * Empties the buffer and sends data to the socket output stream. + * + * @throws IOException + */ + @Override public synchronized void flush() throws IOException { - if (pos > 0) { - try { + if (pos > 0) { + try { out.write(buffer, 0, pos); out.flush(); } finally { pos = 0; } - - } - } - - /** - * Adds a variable of type integer to the buffer. - * - * @param i integer to add - * @throws java.io.IOException if there are problems adding the integer - */ - private void add(int i) throws IOException { - buffer[pos] = (byte) i; - pos++; - - if (pos == buffer.length) { - flush(); - } - } - - /** - * Closes this OutputStream. - * - * @throws IOException - */ - @Override + + } + } + + /** + * Adds a variable of type integer to the buffer. + * + * @param i integer to add + * @throws java.io.IOException if there are problems adding the integer + */ + private void add(int i) throws IOException { + buffer[pos] = (byte) i; + pos++; + + if (pos == buffer.length) { + flush(); + } + } + + /** + * Closes this OutputStream. + * + * @throws IOException + */ + @Override public void close() throws IOException { - out.close(); - } - - /** - * Substitutes the output stream. The old one is stored so that it can be restored later. - * - * @param newOut new output stream to use. - */ - public void setOutput(OutputStream newOut) { - if (newOut != null) { - oldOut = out; - out = newOut; - } else { - out = oldOut; - } - - } + out.close(); + } + + /** + * Substitutes the output stream. The old one is stored so that it can be restored later. + * + * @param newOut new output stream to use. + */ + public void setOutput(OutputStream newOut) { + if (newOut != null) { + oldOut = out; + out = newOut; + } else { + out = oldOut; + } + + } } diff --git a/bundles/org.eclipse.equinox.console/src/org/eclipse/equinox/console/common/HistoryHolder.java b/bundles/org.eclipse.equinox.console/src/org/eclipse/equinox/console/common/HistoryHolder.java index 79b9e6a09..c2efb8532 100755 --- a/bundles/org.eclipse.equinox.console/src/org/eclipse/equinox/console/common/HistoryHolder.java +++ b/bundles/org.eclipse.equinox.console/src/org/eclipse/equinox/console/common/HistoryHolder.java @@ -22,78 +22,78 @@ import java.util.Arrays; */ public class HistoryHolder { - private static final int MAX = 100; - private final byte[][] history; - private int size; - private int pos; + private static final int MAX = 100; + private final byte[][] history; + private int size; + private int pos; - public HistoryHolder() { - history = new byte[MAX][]; - } + public HistoryHolder() { + history = new byte[MAX][]; + } - public synchronized void reset() { - size = 0; - pos = 0; - for (int i = 0; i < MAX; i++) { - history[i] = null; - } - } + public synchronized void reset() { + size = 0; + pos = 0; + for (int i = 0; i < MAX; i++) { + history[i] = null; + } + } - public synchronized void add(byte[] data) { - data = new String(data, StandardCharsets.US_ASCII).trim().getBytes(StandardCharsets.US_ASCII); - if (data.length == 0) { - pos = size; - return; - } - for (int i = 0; i < size; i++) { - if (Arrays.equals(history[i], data)) { - System.arraycopy(history, i + 1, history, i, size - i - 1); - history[size - 1] = data; - pos = size; - return; - } - } - if (size >= MAX) { - System.arraycopy(history, 1, history, 0, size - 1); - size--; - } - history[size++] = data; - pos = size; - } + public synchronized void add(byte[] data) { + data = new String(data, StandardCharsets.US_ASCII).trim().getBytes(StandardCharsets.US_ASCII); + if (data.length == 0) { + pos = size; + return; + } + for (int i = 0; i < size; i++) { + if (Arrays.equals(history[i], data)) { + System.arraycopy(history, i + 1, history, i, size - i - 1); + history[size - 1] = data; + pos = size; + return; + } + } + if (size >= MAX) { + System.arraycopy(history, 1, history, 0, size - 1); + size--; + } + history[size++] = data; + pos = size; + } - public synchronized byte[] next() { - if (pos >= size - 1) { - return null; - } - return history[++pos]; - } + public synchronized byte[] next() { + if (pos >= size - 1) { + return null; + } + return history[++pos]; + } - public synchronized byte[] last() { - if (size > 0) { - pos = size - 1; - return history[pos]; - } else { - return null; - } - } + public synchronized byte[] last() { + if (size > 0) { + pos = size - 1; + return history[pos]; + } else { + return null; + } + } - public synchronized byte[] first() { - if (size > 0) { - pos = 0; - return history[pos]; - } else { - return null; - } - } + public synchronized byte[] first() { + if (size > 0) { + pos = 0; + return history[pos]; + } else { + return null; + } + } - public synchronized byte[] prev() { - if (size == 0) { - return null; - } - if (pos == 0) { - return history[pos]; - } else { - return history[--pos]; - } - } + public synchronized byte[] prev() { + if (size == 0) { + return null; + } + if (pos == 0) { + return history[pos]; + } else { + return history[--pos]; + } + } } diff --git a/bundles/org.eclipse.equinox.console/src/org/eclipse/equinox/console/common/InputHandler.java b/bundles/org.eclipse.equinox.console/src/org/eclipse/equinox/console/common/InputHandler.java index 4b9712c8c..5f5659558 100755 --- a/bundles/org.eclipse.equinox.console/src/org/eclipse/equinox/console/common/InputHandler.java +++ b/bundles/org.eclipse.equinox.console/src/org/eclipse/equinox/console/common/InputHandler.java @@ -25,48 +25,48 @@ import java.io.OutputStream; */ public abstract class InputHandler extends Thread { - protected Scanner inputScanner; - protected OutputStream out; - protected ConsoleInputStream in; - protected InputStream input; - protected byte[] buffer; - protected static final int MAX_SIZE = 2048; + protected Scanner inputScanner; + protected OutputStream out; + protected ConsoleInputStream in; + protected InputStream input; + protected byte[] buffer; + protected static final int MAX_SIZE = 2048; - public InputHandler(InputStream input, ConsoleInputStream in, OutputStream out) { - this.input = input; - this.in = in; - this.out = out; - buffer = new byte[MAX_SIZE]; - } + public InputHandler(InputStream input, ConsoleInputStream in, OutputStream out) { + this.input = input; + this.in = in; + this.out = out; + buffer = new byte[MAX_SIZE]; + } - @Override + @Override public void run() { - int count; - try { - while ((count = input.read(buffer)) > -1) { - for (int i = 0; i < count; i++) { - inputScanner.scan(buffer[i]); - } - } - } catch (IOException e) { - // Printing stack trace is not needed since the streams are closed immediately - // do nothing - } finally { - try { - in.close(); - } catch (IOException e1) { - // do nothing - } - try { - out.close(); - } catch (IOException e1) { - // do nothing - } - } - } - - public Scanner getScanner() { - return inputScanner; - } + int count; + try { + while ((count = input.read(buffer)) > -1) { + for (int i = 0; i < count; i++) { + inputScanner.scan(buffer[i]); + } + } + } catch (IOException e) { + // Printing stack trace is not needed since the streams are closed immediately + // do nothing + } finally { + try { + in.close(); + } catch (IOException e1) { + // do nothing + } + try { + out.close(); + } catch (IOException e1) { + // do nothing + } + } + } + + public Scanner getScanner() { + return inputScanner; + } } diff --git a/bundles/org.eclipse.equinox.console/src/org/eclipse/equinox/console/common/KEYS.java b/bundles/org.eclipse.equinox.console/src/org/eclipse/equinox/console/common/KEYS.java index 9bf12e357..98fa9c40e 100755 --- a/bundles/org.eclipse.equinox.console/src/org/eclipse/equinox/console/common/KEYS.java +++ b/bundles/org.eclipse.equinox.console/src/org/eclipse/equinox/console/common/KEYS.java @@ -19,16 +19,16 @@ package org.eclipse.equinox.console.common; */ public enum KEYS { UP, - DOWN, - RIGHT, - LEFT, - CENTER, - HOME, - END, - PGUP, - PGDN, - INS, - DEL, - UNFINISHED, - UNKNOWN + DOWN, + RIGHT, + LEFT, + CENTER, + HOME, + END, + PGUP, + PGDN, + INS, + DEL, + UNFINISHED, + UNKNOWN } diff --git a/bundles/org.eclipse.equinox.console/src/org/eclipse/equinox/console/common/Scanner.java b/bundles/org.eclipse.equinox.console/src/org/eclipse/equinox/console/common/Scanner.java index bff3eeed0..cc3fe39f9 100755 --- a/bundles/org.eclipse.equinox.console/src/org/eclipse/equinox/console/common/Scanner.java +++ b/bundles/org.eclipse.equinox.console/src/org/eclipse/equinox/console/common/Scanner.java @@ -35,73 +35,73 @@ public abstract class Scanner { private byte BACKSPACE; private byte DEL; - protected static final byte BS = 8; - protected static final byte LF = 10; - protected static final byte CR = 13; - protected static final byte ESC = 27; - protected static final byte SPACE = 32; - protected static final byte MAX_CHAR = 127; - protected static final String DEFAULT_TTYPE = File.separatorChar == '/' ? "XTERM" : "ANSI"; - // shows if user input should be echoed to the console - private boolean isEchoEnabled = true; - - protected OutputStream toTelnet; - protected ConsoleInputStream toShell; - protected Map<String, KEYS> currentEscapesToKey; - protected final Map<String, TerminalTypeMappings> supportedEscapeSequences; - protected String[] escapes; - - public Scanner(ConsoleInputStream toShell, OutputStream toTelnet) { - this.toShell = toShell; - this.toTelnet = toTelnet; - supportedEscapeSequences = new HashMap<> (); - supportedEscapeSequences.put("ANSI", new ANSITerminalTypeMappings()); - supportedEscapeSequences.put("VT100", new VT100TerminalTypeMappings()); - VT220TerminalTypeMappings vtMappings = new VT220TerminalTypeMappings(); - supportedEscapeSequences.put("VT220", vtMappings); - supportedEscapeSequences.put("XTERM", vtMappings); - supportedEscapeSequences.put("VT320", new VT320TerminalTypeMappings()); - supportedEscapeSequences.put("SCO", new SCOTerminalTypeMappings()); - } - - public abstract void scan(int b) throws IOException; - - public void toggleEchoEnabled(boolean isEnabled) { - isEchoEnabled = isEnabled; - } - - protected void echo(int b) throws IOException { - if (isEchoEnabled) { - toTelnet.write(b); - } - } - - protected void flush() throws IOException { - toTelnet.flush(); - } - - protected KEYS checkEscape(String possibleEsc) { - if (currentEscapesToKey.get(possibleEsc) != null) { - return currentEscapesToKey.get(possibleEsc); - } - - for (String escape : escapes) { - if (escape.startsWith(possibleEsc)) { - return KEYS.UNFINISHED; - } - } - return KEYS.UNKNOWN; - } - - protected String esc; - protected boolean isEsc = false; - - protected void startEsc() { - isEsc = true; - esc = ""; - } - - protected abstract void scanEsc(final int b) throws IOException; + protected static final byte BS = 8; + protected static final byte LF = 10; + protected static final byte CR = 13; + protected static final byte ESC = 27; + protected static final byte SPACE = 32; + protected static final byte MAX_CHAR = 127; + protected static final String DEFAULT_TTYPE = File.separatorChar == '/' ? "XTERM" : "ANSI"; + // shows if user input should be echoed to the console + private boolean isEchoEnabled = true; + + protected OutputStream toTelnet; + protected ConsoleInputStream toShell; + protected Map<String, KEYS> currentEscapesToKey; + protected final Map<String, TerminalTypeMappings> supportedEscapeSequences; + protected String[] escapes; + + public Scanner(ConsoleInputStream toShell, OutputStream toTelnet) { + this.toShell = toShell; + this.toTelnet = toTelnet; + supportedEscapeSequences = new HashMap<> (); + supportedEscapeSequences.put("ANSI", new ANSITerminalTypeMappings()); + supportedEscapeSequences.put("VT100", new VT100TerminalTypeMappings()); + VT220TerminalTypeMappings vtMappings = new VT220TerminalTypeMappings(); + supportedEscapeSequences.put("VT220", vtMappings); + supportedEscapeSequences.put("XTERM", vtMappings); + supportedEscapeSequences.put("VT320", new VT320TerminalTypeMappings()); + supportedEscapeSequences.put("SCO", new SCOTerminalTypeMappings()); + } + + public abstract void scan(int b) throws IOException; + + public void toggleEchoEnabled(boolean isEnabled) { + isEchoEnabled = isEnabled; + } + + protected void echo(int b) throws IOException { + if (isEchoEnabled) { + toTelnet.write(b); + } + } + + protected void flush() throws IOException { + toTelnet.flush(); + } + + protected KEYS checkEscape(String possibleEsc) { + if (currentEscapesToKey.get(possibleEsc) != null) { + return currentEscapesToKey.get(possibleEsc); + } + + for (String escape : escapes) { + if (escape.startsWith(possibleEsc)) { + return KEYS.UNFINISHED; + } + } + return KEYS.UNKNOWN; + } + + protected String esc; + protected boolean isEsc = false; + + protected void startEsc() { + isEsc = true; + esc = ""; + } + + protected abstract void scanEsc(final int b) throws IOException; public byte getBackspace() { return BACKSPACE; @@ -128,22 +128,22 @@ public abstract class Scanner { } public String[] getEscapes() { - if (escapes != null) { - String[] copy = new String[escapes.length]; - System.arraycopy(escapes, 0, copy, 0, escapes.length); - return copy; - } else { - return null; - } + if (escapes != null) { + String[] copy = new String[escapes.length]; + System.arraycopy(escapes, 0, copy, 0, escapes.length); + return copy; + } else { + return null; + } } public void setEscapes(String[] escapes) { - if (escapes != null) { - this.escapes = new String[escapes.length]; - System.arraycopy(escapes, 0, this.escapes, 0, escapes.length); - } else { - this.escapes = null; - } + if (escapes != null) { + this.escapes = new String[escapes.length]; + System.arraycopy(escapes, 0, this.escapes, 0, escapes.length); + } else { + this.escapes = null; + } } } diff --git a/bundles/org.eclipse.equinox.console/src/org/eclipse/equinox/console/common/SimpleByteBuffer.java b/bundles/org.eclipse.equinox.console/src/org/eclipse/equinox/console/common/SimpleByteBuffer.java index 3cc780d83..7508cd036 100755 --- a/bundles/org.eclipse.equinox.console/src/org/eclipse/equinox/console/common/SimpleByteBuffer.java +++ b/bundles/org.eclipse.equinox.console/src/org/eclipse/equinox/console/common/SimpleByteBuffer.java @@ -21,131 +21,131 @@ package org.eclipse.equinox.console.common; */ public class SimpleByteBuffer { - private static int INITAL_SIZE = 13; - - private byte[] buffer; - private int pos = 0; - private int size = 0; - - public SimpleByteBuffer() { - buffer = new byte[INITAL_SIZE]; - } - - public void add(final int b) { - if (size >= buffer.length) { - rezize(); - } - buffer[size++] = (byte) b; - } - - private void rezize() { - final byte[] newbuffeer = new byte[buffer.length << 1]; - System.arraycopy(buffer, 0, newbuffeer, 0, buffer.length); - buffer = newbuffeer; - } - - public void insert(int b) { - if (size >= buffer.length) { - rezize(); - } - final int forCopy = size - pos; - if (forCopy > 0) { - System.arraycopy(buffer, pos, buffer, pos + 1, forCopy); - } - buffer[pos++] = (byte) b; - size++; - } - - public int goRight() { - if (pos < size) { - return buffer[pos++] & 0xFF; - } - return -1; - } - - public boolean goLeft() { - if (pos > 0) { - pos--; - return true; - } - return false; - } - - public void delete() { - if (pos < size) { - final int forCopy = size - pos; - System.arraycopy(buffer, pos + 1, buffer, pos, forCopy); - size--; - } - } - - public boolean backSpace() { - if (pos > 0 && size > 0) { - final int forCopy = size - pos; - System.arraycopy(buffer, pos, buffer, pos - 1, forCopy); - size--; - pos--; - return true; - } - return false; - } - - public void delAll() { - pos = 0; - size = 0; - } - - public byte[] getCurrentData() { - byte[] res = new byte[size]; - System.arraycopy(buffer, 0, res, 0, size); - pos = 0; - size = 0; - return res; - } - - public void set(byte[] newData) { - pos = 0; - size = 0; - if (newData != null) { - for (byte data : newData) { - insert(data); - } - } - } - - public int getPos() { - return pos; - } - - public byte[] copyCurrentData() { - byte[] res = new byte[size]; - System.arraycopy(buffer, 0, res, 0, size); - return res; - } - - public int getCurrentChar() { - if (pos < size) { - return buffer[pos] & 0xFF; - } else { - return -1; - } - } - - public int getSize() { - return size; - } - - public int resetPos() { - int res = pos; - pos = 0; - return res; - } - - public void replace(int b) { - if (pos == size) { - insert(b); - } else { - buffer[pos++] = (byte) b; - } - } + private static int INITAL_SIZE = 13; + + private byte[] buffer; + private int pos = 0; + private int size = 0; + + public SimpleByteBuffer() { + buffer = new byte[INITAL_SIZE]; + } + + public void add(final int b) { + if (size >= buffer.length) { + rezize(); + } + buffer[size++] = (byte) b; + } + + private void rezize() { + final byte[] newbuffeer = new byte[buffer.length << 1]; + System.arraycopy(buffer, 0, newbuffeer, 0, buffer.length); + buffer = newbuffeer; + } + + public void insert(int b) { + if (size >= buffer.length) { + rezize(); + } + final int forCopy = size - pos; + if (forCopy > 0) { + System.arraycopy(buffer, pos, buffer, pos + 1, forCopy); + } + buffer[pos++] = (byte) b; + size++; + } + + public int goRight() { + if (pos < size) { + return buffer[pos++] & 0xFF; + } + return -1; + } + + public boolean goLeft() { + if (pos > 0) { + pos--; + return true; + } + return false; + } + + public void delete() { + if (pos < size) { + final int forCopy = size - pos; + System.arraycopy(buffer, pos + 1, buffer, pos, forCopy); + size--; + } + } + + public boolean backSpace() { + if (pos > 0 && size > 0) { + final int forCopy = size - pos; + System.arraycopy(buffer, pos, buffer, pos - 1, forCopy); + size--; + pos--; + return true; + } + return false; + } + + public void delAll() { + pos = 0; + size = 0; + } + + public byte[] getCurrentData() { + byte[] res = new byte[size]; + System.arraycopy(buffer, 0, res, 0, size); + pos = 0; + size = 0; + return res; + } + + public void set(byte[] newData) { + pos = 0; + size = 0; + if (newData != null) { + for (byte data : newData) { + insert(data); + } + } + } + + public int getPos() { + return pos; + } + + public byte[] copyCurrentData() { + byte[] res = new byte[size]; + System.arraycopy(buffer, 0, res, 0, size); + return res; + } + + public int getCurrentChar() { + if (pos < size) { + return buffer[pos] & 0xFF; + } else { + return -1; + } + } + + public int getSize() { + return size; + } + + public int resetPos() { + int res = pos; + pos = 0; + return res; + } + + public void replace(int b) { + if (pos == size) { + insert(b); + } else { + buffer[pos++] = (byte) b; + } + } } diff --git a/bundles/org.eclipse.equinox.console/src/org/eclipse/equinox/console/common/terminal/ANSITerminalTypeMappings.java b/bundles/org.eclipse.equinox.console/src/org/eclipse/equinox/console/common/terminal/ANSITerminalTypeMappings.java index d4b129345..989159f57 100755 --- a/bundles/org.eclipse.equinox.console/src/org/eclipse/equinox/console/common/terminal/ANSITerminalTypeMappings.java +++ b/bundles/org.eclipse.equinox.console/src/org/eclipse/equinox/console/common/terminal/ANSITerminalTypeMappings.java @@ -21,17 +21,17 @@ public class ANSITerminalTypeMappings extends TerminalTypeMappings { public ANSITerminalTypeMappings() { super(); - BACKSPACE = 8; - DEL = 127; + BACKSPACE = 8; + DEL = 127; } @Override public void setKeypadMappings() { escapesToKey.put("[1~", KEYS.HOME); //$NON-NLS-1$ - escapesToKey.put("[4~", KEYS.END); //$NON-NLS-1$ - escapesToKey.put("[5~", KEYS.PGUP); //$NON-NLS-1$ - escapesToKey.put("[6~", KEYS.PGDN); //$NON-NLS-1$ - escapesToKey.put("[2~", KEYS.INS); //$NON-NLS-1$ - escapesToKey.put("[3~", KEYS.DEL); //$NON-NLS-1$ + escapesToKey.put("[4~", KEYS.END); //$NON-NLS-1$ + escapesToKey.put("[5~", KEYS.PGUP); //$NON-NLS-1$ + escapesToKey.put("[6~", KEYS.PGDN); //$NON-NLS-1$ + escapesToKey.put("[2~", KEYS.INS); //$NON-NLS-1$ + escapesToKey.put("[3~", KEYS.DEL); //$NON-NLS-1$ } } diff --git a/bundles/org.eclipse.equinox.console/src/org/eclipse/equinox/console/common/terminal/TerminalTypeMappings.java b/bundles/org.eclipse.equinox.console/src/org/eclipse/equinox/console/common/terminal/TerminalTypeMappings.java index e8b97cd33..a95d4153f 100755 --- a/bundles/org.eclipse.equinox.console/src/org/eclipse/equinox/console/common/terminal/TerminalTypeMappings.java +++ b/bundles/org.eclipse.equinox.console/src/org/eclipse/equinox/console/common/terminal/TerminalTypeMappings.java @@ -31,13 +31,13 @@ public abstract class TerminalTypeMappings { public TerminalTypeMappings() { escapesToKey = new HashMap<>(); - escapesToKey.put("[A", KEYS.UP); //$NON-NLS-1$ - escapesToKey.put("[B", KEYS.DOWN); //$NON-NLS-1$ - escapesToKey.put("[C", KEYS.RIGHT); //$NON-NLS-1$ - escapesToKey.put("[D", KEYS.LEFT); //$NON-NLS-1$ - escapesToKey.put("[G", KEYS.CENTER); //$NON-NLS-1$ - setKeypadMappings(); - createEscapes(); + escapesToKey.put("[A", KEYS.UP); //$NON-NLS-1$ + escapesToKey.put("[B", KEYS.DOWN); //$NON-NLS-1$ + escapesToKey.put("[C", KEYS.RIGHT); //$NON-NLS-1$ + escapesToKey.put("[D", KEYS.LEFT); //$NON-NLS-1$ + escapesToKey.put("[G", KEYS.CENTER); //$NON-NLS-1$ + setKeypadMappings(); + createEscapes(); } public Map<String, KEYS> getEscapesToKey() { @@ -45,13 +45,13 @@ public abstract class TerminalTypeMappings { } public String[] getEscapes() { - if (escapes != null) { - String[] copy = new String[escapes.length]; - System.arraycopy(escapes, 0, copy, 0, escapes.length); - return copy; - } else { - return null; - } + if (escapes != null) { + String[] copy = new String[escapes.length]; + System.arraycopy(escapes, 0, copy, 0, escapes.length); + return copy; + } else { + return null; + } } public byte getBackspace() { @@ -66,9 +66,9 @@ public abstract class TerminalTypeMappings { private void createEscapes() { escapes = new String[escapesToKey.size()]; - Object[] temp = escapesToKey.keySet().toArray(); - for (int i = 0; i < escapes.length; i++) { - escapes[i] = (String) temp[i]; - } + Object[] temp = escapesToKey.keySet().toArray(); + for (int i = 0; i < escapes.length; i++) { + escapes[i] = (String) temp[i]; + } } } diff --git a/bundles/org.eclipse.equinox.console/src/org/eclipse/equinox/console/common/terminal/VT100TerminalTypeMappings.java b/bundles/org.eclipse.equinox.console/src/org/eclipse/equinox/console/common/terminal/VT100TerminalTypeMappings.java index 14490fb64..5bc577a56 100755 --- a/bundles/org.eclipse.equinox.console/src/org/eclipse/equinox/console/common/terminal/VT100TerminalTypeMappings.java +++ b/bundles/org.eclipse.equinox.console/src/org/eclipse/equinox/console/common/terminal/VT100TerminalTypeMappings.java @@ -20,17 +20,17 @@ public class VT100TerminalTypeMappings extends TerminalTypeMappings { public VT100TerminalTypeMappings() { super(); - BACKSPACE = 127; - DEL = -1; + BACKSPACE = 127; + DEL = -1; } @Override public void setKeypadMappings() { escapesToKey.put("[H", KEYS.HOME); //$NON-NLS-1$ - escapesToKey.put("[4~", KEYS.END); //$NON-NLS-1$ - escapesToKey.put("[5~", KEYS.PGUP); //$NON-NLS-1$ - escapesToKey.put("[6~", KEYS.PGDN); //$NON-NLS-1$ - escapesToKey.put("[2~", KEYS.INS); //$NON-NLS-1$ - escapesToKey.put("[3~", KEYS.DEL); //$NON-NLS-1$ + escapesToKey.put("[4~", KEYS.END); //$NON-NLS-1$ + escapesToKey.put("[5~", KEYS.PGUP); //$NON-NLS-1$ + escapesToKey.put("[6~", KEYS.PGDN); //$NON-NLS-1$ + escapesToKey.put("[2~", KEYS.INS); //$NON-NLS-1$ + escapesToKey.put("[3~", KEYS.DEL); //$NON-NLS-1$ } } diff --git a/bundles/org.eclipse.equinox.console/src/org/eclipse/equinox/console/common/terminal/VT320TerminalTypeMappings.java b/bundles/org.eclipse.equinox.console/src/org/eclipse/equinox/console/common/terminal/VT320TerminalTypeMappings.java index 85954248e..285f85c2e 100755 --- a/bundles/org.eclipse.equinox.console/src/org/eclipse/equinox/console/common/terminal/VT320TerminalTypeMappings.java +++ b/bundles/org.eclipse.equinox.console/src/org/eclipse/equinox/console/common/terminal/VT320TerminalTypeMappings.java @@ -20,18 +20,18 @@ public class VT320TerminalTypeMappings extends TerminalTypeMappings { public VT320TerminalTypeMappings() { super(); - BACKSPACE = 8; - DEL = 127; + BACKSPACE = 8; + DEL = 127; } @Override public void setKeypadMappings() { escapesToKey.put("[H", KEYS.HOME); escapesToKey.put("[F", KEYS.END); - escapesToKey.put("[5~", KEYS.PGUP); //$NON-NLS-1$ - escapesToKey.put("[6~", KEYS.PGDN); //$NON-NLS-1$ - escapesToKey.put("[2~", KEYS.INS); //$NON-NLS-1$ - escapesToKey.put("[3~", KEYS.DEL); //$NON-NLS-1$ + escapesToKey.put("[5~", KEYS.PGUP); //$NON-NLS-1$ + escapesToKey.put("[6~", KEYS.PGDN); //$NON-NLS-1$ + escapesToKey.put("[2~", KEYS.INS); //$NON-NLS-1$ + escapesToKey.put("[3~", KEYS.DEL); //$NON-NLS-1$ } } diff --git a/bundles/org.eclipse.equinox.console/src/org/eclipse/equinox/console/completion/CompletionHandler.java b/bundles/org.eclipse.equinox.console/src/org/eclipse/equinox/console/completion/CompletionHandler.java index 6af4a6574..fd5205ca2 100755 --- a/bundles/org.eclipse.equinox.console/src/org/eclipse/equinox/console/completion/CompletionHandler.java +++ b/bundles/org.eclipse.equinox.console/src/org/eclipse/equinox/console/completion/CompletionHandler.java @@ -48,22 +48,22 @@ public class CompletionHandler { } public Map<String, Integer> getCandidates(byte[] buf, int cursor) { - String currentInput = new String(buf); - String currentToken = CommandLineParser.getCurrentToken(currentInput, cursor); - if (currentToken == null){ - return new HashMap<>(); - } - if (currentToken.contains(FILE) == true) { - completers.add(new FileNamesCompleter()); - }else{ - if ((cursor - currentToken.length() > 0) && (buf[cursor - currentToken.length() - 1] == VARIABLE_PREFIX)){ - completers.add(new VariableNamesCompleter(session)); - }else { - completers.add(new CommandNamesCompleter(context, session)); - completers.add(new FileNamesCompleter()); - } - } - lookupCustomCompleters(); + String currentInput = new String(buf); + String currentToken = CommandLineParser.getCurrentToken(currentInput, cursor); + if (currentToken == null){ + return new HashMap<>(); + } + if (currentToken.contains(FILE) == true) { + completers.add(new FileNamesCompleter()); + }else{ + if ((cursor - currentToken.length() > 0) && (buf[cursor - currentToken.length() - 1] == VARIABLE_PREFIX)){ + completers.add(new VariableNamesCompleter(session)); + }else { + completers.add(new CommandNamesCompleter(context, session)); + completers.add(new FileNamesCompleter()); + } + } + lookupCustomCompleters(); Map<String, Integer> candidates = new TreeMap<>(); for (Completer completer : completers) { candidates.putAll(completer.getCandidates(currentInput, cursor)); diff --git a/bundles/org.eclipse.equinox.console/src/org/eclipse/equinox/console/telnet/TelnetCommand.java b/bundles/org.eclipse.equinox.console/src/org/eclipse/equinox/console/telnet/TelnetCommand.java index 05ae84f7c..b31aab11b 100755 --- a/bundles/org.eclipse.equinox.console/src/org/eclipse/equinox/console/telnet/TelnetCommand.java +++ b/bundles/org.eclipse.equinox.console/src/org/eclipse/equinox/console/telnet/TelnetCommand.java @@ -35,65 +35,65 @@ import org.osgi.service.cm.ManagedService; public class TelnetCommand { private String defaultHost = null; - private int defaultPort; - private List<CommandProcessor> processors = new ArrayList<>(); - private final BundleContext context; - private String host = null; - private int port; - private TelnetServer telnetServer = null; - private ServiceRegistration<?> configuratorRegistration; - private boolean isEnabled = false; - - private static final String HOST = "host"; - private static final String PORT = "port"; - private static final String USE_CONFIG_ADMIN_PROP = "osgi.console.useConfigAdmin"; - private static final String TELNET_PID = "osgi.console.telnet"; - private static final String CONSOLE_PROP = "osgi.console"; - private static final String ENABLED = "enabled"; - private final Object lock = new Object(); + private int defaultPort; + private List<CommandProcessor> processors = new ArrayList<>(); + private final BundleContext context; + private String host = null; + private int port; + private TelnetServer telnetServer = null; + private ServiceRegistration<?> configuratorRegistration; + private boolean isEnabled = false; + + private static final String HOST = "host"; + private static final String PORT = "port"; + private static final String USE_CONFIG_ADMIN_PROP = "osgi.console.useConfigAdmin"; + private static final String TELNET_PID = "osgi.console.telnet"; + private static final String CONSOLE_PROP = "osgi.console"; + private static final String ENABLED = "enabled"; + private final Object lock = new Object(); - public TelnetCommand(CommandProcessor processor, BundleContext context) - { - processors.add(processor); - this.context = context; - if ("true".equals(context.getProperty(USE_CONFIG_ADMIN_PROP))) { - Dictionary<String, String> telnetProperties = new Hashtable<>(); - telnetProperties.put(Constants.SERVICE_PID, TELNET_PID); - try { - synchronized (lock) { - configuratorRegistration = context.registerService(ManagedService.class.getName(), new TelnetConfigurator(), telnetProperties); - } - } catch (NoClassDefFoundError e) { - System.out.println("Configuration Admin not available!"); - return; - } - } else { - parseHostAndPort(); - } - } - - private void parseHostAndPort() { - String telnetPort = null; - String consolePropValue = context.getProperty(CONSOLE_PROP); - if(consolePropValue != null) { - int index = consolePropValue.lastIndexOf(':'); - if (index > -1) { - defaultHost = consolePropValue.substring(0, index); - } - telnetPort = consolePropValue.substring(index + 1); - isEnabled = true; - } - if (telnetPort != null && !"".equals(telnetPort)) { - try { - defaultPort = Integer.parseInt(telnetPort); + public TelnetCommand(CommandProcessor processor, BundleContext context) + { + processors.add(processor); + this.context = context; + if ("true".equals(context.getProperty(USE_CONFIG_ADMIN_PROP))) { + Dictionary<String, String> telnetProperties = new Hashtable<>(); + telnetProperties.put(Constants.SERVICE_PID, TELNET_PID); + try { + synchronized (lock) { + configuratorRegistration = context.registerService(ManagedService.class.getName(), new TelnetConfigurator(), telnetProperties); + } + } catch (NoClassDefFoundError e) { + System.out.println("Configuration Admin not available!"); + return; + } + } else { + parseHostAndPort(); + } + } + + private void parseHostAndPort() { + String telnetPort = null; + String consolePropValue = context.getProperty(CONSOLE_PROP); + if(consolePropValue != null) { + int index = consolePropValue.lastIndexOf(':'); + if (index > -1) { + defaultHost = consolePropValue.substring(0, index); + } + telnetPort = consolePropValue.substring(index + 1); + isEnabled = true; + } + if (telnetPort != null && !"".equals(telnetPort)) { + try { + defaultPort = Integer.parseInt(telnetPort); } catch (NumberFormatException e) { // do nothing } - } - } - - public synchronized void startService() { - Dictionary<String, Object> properties = new Hashtable<>(); + } + } + + public synchronized void startService() { + Dictionary<String, Object> properties = new Hashtable<>(); properties.put("osgi.command.scope", "equinox"); properties.put("osgi.command.function", new String[] {"telnet"}); if ((port > 0 || defaultPort > 0) && isEnabled == true) { @@ -105,118 +105,118 @@ public class TelnetCommand { } } context.registerService(TelnetCommand.class.getName(), this, properties); - } + } - @Descriptor("start/stop a telnet server") - public synchronized void telnet(String[] arguments) throws Exception - { - String command = null; - int newPort = 0; - String newHost = null; - - for(int i = 0; i < arguments.length; i++) { - if("-?".equals(arguments[i]) || "-help".equals(arguments[i])) { - printHelp(); - return; - } else if("start".equals(arguments[i])) { - command = "start"; - } else if ("stop".equals(arguments[i])) { - command = "stop"; - } else if ("-port".equals(arguments[i]) && (arguments.length > i + 1)) { - i++; - newPort = Integer.parseInt(arguments[i]); - } else if ("-host".equals(arguments[i]) && (arguments.length > i + 1)) { - i++; - newHost = arguments[i]; - } else { - throw new Exception("Unrecognized telnet command/option " + arguments[i]); - } - } - - if (command == null) { - throw new Exception("No telnet command specified"); - } - - if (newPort != 0) { - port = newPort; - } else if (port == 0) { - port = defaultPort; - } - - if (port == 0) { - throw new Exception("No telnet port specified"); - } - - if (newHost != null) { - host = newHost; - } else { - host = defaultHost; - } + @Descriptor("start/stop a telnet server") + public synchronized void telnet(String[] arguments) throws Exception + { + String command = null; + int newPort = 0; + String newHost = null; + + for(int i = 0; i < arguments.length; i++) { + if("-?".equals(arguments[i]) || "-help".equals(arguments[i])) { + printHelp(); + return; + } else if("start".equals(arguments[i])) { + command = "start"; + } else if ("stop".equals(arguments[i])) { + command = "stop"; + } else if ("-port".equals(arguments[i]) && (arguments.length > i + 1)) { + i++; + newPort = Integer.parseInt(arguments[i]); + } else if ("-host".equals(arguments[i]) && (arguments.length > i + 1)) { + i++; + newHost = arguments[i]; + } else { + throw new Exception("Unrecognized telnet command/option " + arguments[i]); + } + } + + if (command == null) { + throw new Exception("No telnet command specified"); + } + + if (newPort != 0) { + port = newPort; + } else if (port == 0) { + port = defaultPort; + } + + if (port == 0) { + throw new Exception("No telnet port specified"); + } + + if (newHost != null) { + host = newHost; + } else { + host = defaultHost; + } - if ("start".equals(command)) { - if (telnetServer != null) { - throw new IllegalStateException("telnet is already running on port " + port); - } - - try { + if ("start".equals(command)) { + if (telnetServer != null) { + throw new IllegalStateException("telnet is already running on port " + port); + } + + try { telnetServer = new TelnetServer(context, processors, host, port); } catch (BindException e) { throw new Exception("Port " + port + " already in use"); } - telnetServer.setName("equinox telnet"); - telnetServer.start(); - } else if ("stop".equals(command)) { - if (telnetServer == null) { - System.out.println("telnet is not running."); - return; - } - - telnetServer.stopTelnetServer(); - telnetServer = null; - } - } - - public synchronized void addCommandProcessor(CommandProcessor processor) { - processors.add(processor); - if (telnetServer != null) { - telnetServer.addCommandProcessor(processor); - } - } - - public synchronized void removeCommandProcessor(CommandProcessor processor) { - processors.remove(processor); - if (telnetServer != null) { - telnetServer.removeCommandProcessor(processor); - } - } - - private void printHelp() { - StringBuilder help = new StringBuilder(); - help.append("telnet - start simple telnet server"); - help.append("\n"); - help.append("Usage: telnet start | stop [-port port] [-host host]"); - help.append("\n"); - help.append("\t"); - help.append("-port"); - help.append("\t"); - help.append("listen port (default="); - help.append(defaultPort); - help.append(")"); - help.append("\n"); - help.append("\t"); - help.append("-host"); - help.append("\t"); - help.append("local host address to listen on (default is none - listen on all network interfaces)"); - help.append("\n"); - help.append("\t"); - help.append("-?, -help"); - help.append("\t"); - help.append("show help"); - System.out.println(help.toString()); - } - - class TelnetConfigurator implements ManagedService { + telnetServer.setName("equinox telnet"); + telnetServer.start(); + } else if ("stop".equals(command)) { + if (telnetServer == null) { + System.out.println("telnet is not running."); + return; + } + + telnetServer.stopTelnetServer(); + telnetServer = null; + } + } + + public synchronized void addCommandProcessor(CommandProcessor processor) { + processors.add(processor); + if (telnetServer != null) { + telnetServer.addCommandProcessor(processor); + } + } + + public synchronized void removeCommandProcessor(CommandProcessor processor) { + processors.remove(processor); + if (telnetServer != null) { + telnetServer.removeCommandProcessor(processor); + } + } + + private void printHelp() { + StringBuilder help = new StringBuilder(); + help.append("telnet - start simple telnet server"); + help.append("\n"); + help.append("Usage: telnet start | stop [-port port] [-host host]"); + help.append("\n"); + help.append("\t"); + help.append("-port"); + help.append("\t"); + help.append("listen port (default="); + help.append(defaultPort); + help.append(")"); + help.append("\n"); + help.append("\t"); + help.append("-host"); + help.append("\t"); + help.append("local host address to listen on (default is none - listen on all network interfaces)"); + help.append("\n"); + help.append("\t"); + help.append("-?, -help"); + help.append("\t"); + help.append("show help"); + System.out.println(help.toString()); + } + + class TelnetConfigurator implements ManagedService { private Dictionary<String, Object> properties; @Override public synchronized void updated(Dictionary<String, ?> props) throws ConfigurationException { @@ -248,6 +248,6 @@ public class TelnetCommand { } } } - - } + + } } diff --git a/bundles/org.eclipse.equinox.console/src/org/eclipse/equinox/console/telnet/TelnetConnection.java b/bundles/org.eclipse.equinox.console/src/org/eclipse/equinox/console/telnet/TelnetConnection.java index 8225970ed..aa5a8293e 100755 --- a/bundles/org.eclipse.equinox.console/src/org/eclipse/equinox/console/telnet/TelnetConnection.java +++ b/bundles/org.eclipse.equinox.console/src/org/eclipse/equinox/console/telnet/TelnetConnection.java @@ -37,14 +37,14 @@ public class TelnetConnection extends Thread implements Closeable { private CommandProcessor processor; private BundleContext context; protected boolean isTelnetNegotiationFinished = false; - private Callback callback; - private static final long TIMEOUT = 1000; - private static final long NEGOTIATION_TIMEOUT = 60000; - private static final String PROMPT = "prompt"; - private static final String OSGI_PROMPT = "osgi> "; - private static final String SCOPE = "SCOPE"; - private static final String EQUINOX_SCOPE = "equinox:*"; - private static final String CLOSEABLE = "CLOSEABLE"; + private Callback callback; + private static final long TIMEOUT = 1000; + private static final long NEGOTIATION_TIMEOUT = 60000; + private static final String PROMPT = "prompt"; + private static final String OSGI_PROMPT = "osgi> "; + private static final String SCOPE = "SCOPE"; + private static final String EQUINOX_SCOPE = "equinox:*"; + private static final String CLOSEABLE = "CLOSEABLE"; public TelnetConnection (Socket socket, CommandProcessor processor, BundleContext context) { this.socket = socket; @@ -78,35 +78,35 @@ public class TelnetConnection extends Thread implements Closeable { ConsoleInputStream inp = new ConsoleInputStream(); - ConsoleInputHandler consoleInputHandler = new ConsoleInputHandler(in, inp, out); - consoleInputHandler.getScanner().setBackspace(telnetInputHandler.getScanner().getBackspace()); - consoleInputHandler.getScanner().setDel(telnetInputHandler.getScanner().getDel()); - consoleInputHandler.getScanner().setCurrentEscapesToKey(telnetInputHandler.getScanner().getCurrentEscapesToKey()); - consoleInputHandler.getScanner().setEscapes(telnetInputHandler.getScanner().getEscapes()); - ((ConsoleInputScanner)consoleInputHandler.getScanner()).setContext(context); - - consoleInputHandler.start(); - - session = processor.createSession(inp, output, output); - session.put(SCOPE, EQUINOX_SCOPE); - session.put(PROMPT, OSGI_PROMPT); - // Store this closeable object in the session, so that the disconnect command can close it - session.put(CLOSEABLE, this); - ((ConsoleInputScanner)consoleInputHandler.getScanner()).setSession(session); - + ConsoleInputHandler consoleInputHandler = new ConsoleInputHandler(in, inp, out); + consoleInputHandler.getScanner().setBackspace(telnetInputHandler.getScanner().getBackspace()); + consoleInputHandler.getScanner().setDel(telnetInputHandler.getScanner().getDel()); + consoleInputHandler.getScanner().setCurrentEscapesToKey(telnetInputHandler.getScanner().getCurrentEscapesToKey()); + consoleInputHandler.getScanner().setEscapes(telnetInputHandler.getScanner().getEscapes()); + ((ConsoleInputScanner)consoleInputHandler.getScanner()).setContext(context); + + consoleInputHandler.start(); + + session = processor.createSession(inp, output, output); + session.put(SCOPE, EQUINOX_SCOPE); + session.put(PROMPT, OSGI_PROMPT); + // Store this closeable object in the session, so that the disconnect command can close it + session.put(CLOSEABLE, this); + ((ConsoleInputScanner)consoleInputHandler.getScanner()).setSession(session); + try { - session.execute("gosh --login --noshutdown"); - } catch (Exception e) { - e.printStackTrace(); - } finally { - session.close(); - try { - socket.close(); - } - catch (IOException e) { - // do nothing - } - } + session.execute("gosh --login --noshutdown"); + } catch (Exception e) { + e.printStackTrace(); + } finally { + session.close(); + try { + socket.close(); + } + catch (IOException e) { + // do nothing + } + } } catch (IOException e) { e.printStackTrace(); } diff --git a/bundles/org.eclipse.equinox.console/src/org/eclipse/equinox/console/telnet/TelnetInputHandler.java b/bundles/org.eclipse.equinox.console/src/org/eclipse/equinox/console/telnet/TelnetInputHandler.java index d4a74d7d6..6bfce4765 100755 --- a/bundles/org.eclipse.equinox.console/src/org/eclipse/equinox/console/telnet/TelnetInputHandler.java +++ b/bundles/org.eclipse.equinox.console/src/org/eclipse/equinox/console/telnet/TelnetInputHandler.java @@ -25,8 +25,8 @@ import org.eclipse.equinox.console.common.InputHandler; */ public class TelnetInputHandler extends InputHandler { - public TelnetInputHandler(InputStream input, ConsoleInputStream in, ConsoleOutputStream out, Callback callback) { - super(input, in, out); - inputScanner = new TelnetInputScanner(in, out, callback); - } + public TelnetInputHandler(InputStream input, ConsoleInputStream in, ConsoleOutputStream out, Callback callback) { + super(input, in, out); + inputScanner = new TelnetInputScanner(in, out, callback); + } } diff --git a/bundles/org.eclipse.equinox.console/src/org/eclipse/equinox/console/telnet/TelnetInputScanner.java b/bundles/org.eclipse.equinox.console/src/org/eclipse/equinox/console/telnet/TelnetInputScanner.java index 8f875f3d0..b285d8159 100755 --- a/bundles/org.eclipse.equinox.console/src/org/eclipse/equinox/console/telnet/TelnetInputScanner.java +++ b/bundles/org.eclipse.equinox.console/src/org/eclipse/equinox/console/telnet/TelnetInputScanner.java @@ -37,134 +37,134 @@ import java.util.Set; */ public class TelnetInputScanner extends Scanner { - private boolean isCommand = false; - private boolean isReadingTtype = false; - private boolean shouldFinish = false; - private boolean tTypeNegotiationStarted = false; - private int lastRead = -1; - private ArrayList<Integer> currentTerminalType = new ArrayList<>(); - private ArrayList<Integer> lastTerminalType = null; - private Set<String> supportedTerminalTypes = new HashSet<>(); - private Callback callback; + private boolean isCommand = false; + private boolean isReadingTtype = false; + private boolean shouldFinish = false; + private boolean tTypeNegotiationStarted = false; + private int lastRead = -1; + private ArrayList<Integer> currentTerminalType = new ArrayList<>(); + private ArrayList<Integer> lastTerminalType = null; + private Set<String> supportedTerminalTypes = new HashSet<>(); + private Callback callback; - public TelnetInputScanner(ConsoleInputStream toShell, ConsoleOutputStream toTelnet, Callback callback) { - super(toShell, toTelnet); - initializeSupportedTerminalTypes(); - TerminalTypeMappings currentMapping = supportedEscapeSequences.get(DEFAULT_TTYPE); - currentEscapesToKey = currentMapping.getEscapesToKey(); - escapes = currentMapping.getEscapes(); - setBackspace(currentMapping.getBackspace()); - setDel(currentMapping.getDel()); - this.callback = callback; - } - - private void initializeSupportedTerminalTypes() { - supportedTerminalTypes.add("ANSI"); - supportedTerminalTypes.add("VT100"); - supportedTerminalTypes.add("VT220"); - supportedTerminalTypes.add("VT320"); - supportedTerminalTypes.add("XTERM"); - supportedTerminalTypes.add("SCO"); - } + public TelnetInputScanner(ConsoleInputStream toShell, ConsoleOutputStream toTelnet, Callback callback) { + super(toShell, toTelnet); + initializeSupportedTerminalTypes(); + TerminalTypeMappings currentMapping = supportedEscapeSequences.get(DEFAULT_TTYPE); + currentEscapesToKey = currentMapping.getEscapesToKey(); + escapes = currentMapping.getEscapes(); + setBackspace(currentMapping.getBackspace()); + setDel(currentMapping.getDel()); + this.callback = callback; + } + + private void initializeSupportedTerminalTypes() { + supportedTerminalTypes.add("ANSI"); + supportedTerminalTypes.add("VT100"); + supportedTerminalTypes.add("VT220"); + supportedTerminalTypes.add("VT320"); + supportedTerminalTypes.add("XTERM"); + supportedTerminalTypes.add("SCO"); + } - @Override + @Override public void scan(int b) throws IOException { - b &= 0xFF; + b &= 0xFF; - if (isEsc) { - scanEsc(b); - } else if (isCommand) { - scanCommand(b); - } else if (b == IAC) { - startCommand(); - } else { - switch (b) { - case ESC: - startEsc(); - toShell.add(new byte[]{(byte) b}); - break; - default: - if (b >= SPACE && b < MAX_CHAR) { - echo((byte) b); - flush(); - } - toShell.add(new byte[]{(byte) b}); - } + if (isEsc) { + scanEsc(b); + } else if (isCommand) { + scanCommand(b); + } else if (b == IAC) { + startCommand(); + } else { + switch (b) { + case ESC: + startEsc(); + toShell.add(new byte[]{(byte) b}); + break; + default: + if (b >= SPACE && b < MAX_CHAR) { + echo((byte) b); + flush(); + } + toShell.add(new byte[]{(byte) b}); + } - } - lastRead = b; - } + } + lastRead = b; + } - /* Telnet command codes are described in RFC 854, TELNET PROTOCOL SPECIFICATION - * available at http://www.ietf.org/rfc/rfc854.txt - * - * Telnet terminal type negotiation option is described in RFC 1091, Telnet Terminal-Type Option - * available at http://www.ietf.org/rfc/rfc1091.txt - */ - private static final int SE = 240; - private static final int EC = 247; - private static final int EL = 248; - private static final int SB = 250; - private static final int WILL = 251; - private static final int WILL_NOT = 252; - private static final int DO = 253; - private static final int DO_NOT = 254; - private static final int TTYPE = 24; - private static final int SEND = 1; - private static final int IAC = 255; - private static final int IS = 0; + /* Telnet command codes are described in RFC 854, TELNET PROTOCOL SPECIFICATION + * available at http://www.ietf.org/rfc/rfc854.txt + * + * Telnet terminal type negotiation option is described in RFC 1091, Telnet Terminal-Type Option + * available at http://www.ietf.org/rfc/rfc1091.txt + */ + private static final int SE = 240; + private static final int EC = 247; + private static final int EL = 248; + private static final int SB = 250; + private static final int WILL = 251; + private static final int WILL_NOT = 252; + private static final int DO = 253; + private static final int DO_NOT = 254; + private static final int TTYPE = 24; + private static final int SEND = 1; + private static final int IAC = 255; + private static final int IS = 0; - private boolean isNegotiation; - private boolean isWill; - - private byte[] tTypeRequest = {(byte)IAC, (byte)SB, (byte)TTYPE, (byte)SEND, (byte)IAC, (byte)SE}; + private boolean isNegotiation; + private boolean isWill; + + private byte[] tTypeRequest = {(byte)IAC, (byte)SB, (byte)TTYPE, (byte)SEND, (byte)IAC, (byte)SE}; - private void scanCommand(final int b) throws IOException { - if (isNegotiation) { - scanNegotiation(b); - } else if (isWill) { - isWill = false; - isCommand = false; - if(b == TTYPE && tTypeNegotiationStarted == false) { - sendRequest(); - } - } else { - switch (b) { - case WILL: - isWill = true; - break; - case WILL_NOT: - break; - case DO: - break; - case DO_NOT: - break; - case SB: - isNegotiation = true; - break; - case EC: - eraseChar(); - isCommand = false; - break; - case EL: - default: - isCommand = false; - break; - } - } - } + private void scanCommand(final int b) throws IOException { + if (isNegotiation) { + scanNegotiation(b); + } else if (isWill) { + isWill = false; + isCommand = false; + if(b == TTYPE && tTypeNegotiationStarted == false) { + sendRequest(); + } + } else { + switch (b) { + case WILL: + isWill = true; + break; + case WILL_NOT: + break; + case DO: + break; + case DO_NOT: + break; + case SB: + isNegotiation = true; + break; + case EC: + eraseChar(); + isCommand = false; + break; + case EL: + default: + isCommand = false; + break; + } + } + } - private void scanNegotiation(final int b) { - if (lastRead == SB && b == TTYPE) { - isReadingTtype = true; - } else if (b == IS) { - - } else if (b == IAC) { - - } else if (b == SE) { - isNegotiation = false; - isCommand = false; - if (isReadingTtype == true) { + private void scanNegotiation(final int b) { + if (lastRead == SB && b == TTYPE) { + isReadingTtype = true; + } else if (b == IS) { + + } else if (b == IAC) { + + } else if (b == SE) { + isNegotiation = false; + isCommand = false; + if (isReadingTtype == true) { isReadingTtype = false; if (shouldFinish == true) { setCurrentTerminalType(); @@ -186,66 +186,66 @@ public class TelnetInputScanner extends Scanner { sendRequest(); } } - } else if (isReadingTtype == true){ - currentTerminalType.add(b); - } - } - - private boolean isTerminalTypeSupported() { - byte[] tmp = new byte[currentTerminalType.size()]; - int idx = 0; - for(Integer i : currentTerminalType) { - tmp[idx] = i.byteValue(); - idx++; - } - String tType = new String(tmp); - - for(String terminal : supportedTerminalTypes) { - if(tType.toUpperCase().contains(terminal)) { - return true; - } - } - - return false; - } - - private boolean isLast() { - if(currentTerminalType.equals(lastTerminalType)) { - return true; - } else { - return false; - } - } - - private void setCurrentTerminalType() { - byte[] tmp = new byte[currentTerminalType.size()]; - int idx = 0; - for(Integer i : currentTerminalType) { - tmp[idx] = i.byteValue(); - idx++; - } - String tType = new String(tmp); - String term = null; - for(String terminal : supportedTerminalTypes) { - if(tType.toUpperCase().contains(terminal)) { - term = terminal; - } - } - TerminalTypeMappings currentMapping = supportedEscapeSequences.get(term); - if(currentMapping == null) { - currentMapping = supportedEscapeSequences.get(DEFAULT_TTYPE); - } - currentEscapesToKey = currentMapping.getEscapesToKey(); - escapes = currentMapping.getEscapes(); - setBackspace(currentMapping.getBackspace()); - setDel(currentMapping.getDel()); - if(callback != null) { - callback.finished(); - } - } - - private void sendRequest() { - try { + } else if (isReadingTtype == true){ + currentTerminalType.add(b); + } + } + + private boolean isTerminalTypeSupported() { + byte[] tmp = new byte[currentTerminalType.size()]; + int idx = 0; + for(Integer i : currentTerminalType) { + tmp[idx] = i.byteValue(); + idx++; + } + String tType = new String(tmp); + + for(String terminal : supportedTerminalTypes) { + if(tType.toUpperCase().contains(terminal)) { + return true; + } + } + + return false; + } + + private boolean isLast() { + if(currentTerminalType.equals(lastTerminalType)) { + return true; + } else { + return false; + } + } + + private void setCurrentTerminalType() { + byte[] tmp = new byte[currentTerminalType.size()]; + int idx = 0; + for(Integer i : currentTerminalType) { + tmp[idx] = i.byteValue(); + idx++; + } + String tType = new String(tmp); + String term = null; + for(String terminal : supportedTerminalTypes) { + if(tType.toUpperCase().contains(terminal)) { + term = terminal; + } + } + TerminalTypeMappings currentMapping = supportedEscapeSequences.get(term); + if(currentMapping == null) { + currentMapping = supportedEscapeSequences.get(DEFAULT_TTYPE); + } + currentEscapesToKey = currentMapping.getEscapesToKey(); + escapes = currentMapping.getEscapes(); + setBackspace(currentMapping.getBackspace()); + setDel(currentMapping.getDel()); + if(callback != null) { + callback.finished(); + } + } + + private void sendRequest() { + try { toTelnet.write(tTypeRequest); toTelnet.flush(); if(tTypeNegotiationStarted == false) { @@ -255,32 +255,32 @@ public class TelnetInputScanner extends Scanner { e.printStackTrace(); } - } + } - private void startCommand() { - isCommand = true; - isNegotiation = false; - isWill = false; - } + private void startCommand() { + isCommand = true; + isNegotiation = false; + isWill = false; + } - private void eraseChar() throws IOException { - toShell.add(new byte[]{BS}); - } + private void eraseChar() throws IOException { + toShell.add(new byte[]{BS}); + } - @Override + @Override protected void scanEsc(int b) throws IOException { - esc += (char) b; - toShell.add(new byte[]{(byte) b}); - KEYS key = checkEscape(esc); - if (key == KEYS.UNFINISHED) { - return; - } - if (key == KEYS.UNKNOWN) { - isEsc = false; - scan(b); - return; - } - isEsc = false; - } + esc += (char) b; + toShell.add(new byte[]{(byte) b}); + KEYS key = checkEscape(esc); + if (key == KEYS.UNFINISHED) { + return; + } + if (key == KEYS.UNKNOWN) { + isEsc = false; + scan(b); + return; + } + isEsc = false; + } } diff --git a/bundles/org.eclipse.equinox.console/src/org/eclipse/equinox/console/telnet/TelnetOutputStream.java b/bundles/org.eclipse.equinox.console/src/org/eclipse/equinox/console/telnet/TelnetOutputStream.java index 77dad6047..e6dc0908f 100755 --- a/bundles/org.eclipse.equinox.console/src/org/eclipse/equinox/console/telnet/TelnetOutputStream.java +++ b/bundles/org.eclipse.equinox.console/src/org/eclipse/equinox/console/telnet/TelnetOutputStream.java @@ -24,21 +24,21 @@ import java.io.OutputStream; */ public class TelnetOutputStream extends ConsoleOutputStream { - static final byte[] autoMessage = new byte[]{(byte) 255, (byte) 251, (byte) 1, // IAC WILL ECHO - (byte) 255, (byte) 251, (byte) 3, // IAC WILL SUPPRESS GO_AHEAD - (byte) 255, (byte) 253, (byte) 31, // IAC DO NAWS - (byte) 255, (byte) 253, (byte) 24}; // IAC DO TTYPE - - public TelnetOutputStream(OutputStream out) { - super(out); - } + static final byte[] autoMessage = new byte[]{(byte) 255, (byte) 251, (byte) 1, // IAC WILL ECHO + (byte) 255, (byte) 251, (byte) 3, // IAC WILL SUPPRESS GO_AHEAD + (byte) 255, (byte) 253, (byte) 31, // IAC DO NAWS + (byte) 255, (byte) 253, (byte) 24}; // IAC DO TTYPE + + public TelnetOutputStream(OutputStream out) { + super(out); + } - /** - * Sends the options which a server wants to negotiate with a telnet client. - */ - public synchronized void autoSend() throws IOException { - write(autoMessage); - flush(); - } + /** + * Sends the options which a server wants to negotiate with a telnet client. + */ + public synchronized void autoSend() throws IOException { + write(autoMessage); + flush(); + } } diff --git a/bundles/org.eclipse.equinox.console/src/org/eclipse/equinox/console/telnet/TelnetServer.java b/bundles/org.eclipse.equinox.console/src/org/eclipse/equinox/console/telnet/TelnetServer.java index ddcdbe1d2..22cbbcdf1 100755 --- a/bundles/org.eclipse.equinox.console/src/org/eclipse/equinox/console/telnet/TelnetServer.java +++ b/bundles/org.eclipse.equinox.console/src/org/eclipse/equinox/console/telnet/TelnetServer.java @@ -35,57 +35,57 @@ import org.osgi.framework.BundleContext; public class TelnetServer extends Thread { private ServerSocket server; - private boolean isRunning = true; - private List<CommandProcessor> processors = null; - private BundleContext context; - private List<Socket> sockets = new ArrayList<>(); - private Map<CommandProcessor, List<TelnetConnection>> processorToConnectionsMapping = new HashMap<>(); - - public TelnetServer(BundleContext context, List<CommandProcessor> processors, String host, int port) throws IOException { - this.context = context; - this.processors = processors; - if(host != null) { - server = new ServerSocket(port, 0, InetAddress.getByName(host)); - } else { - server = new ServerSocket(port); - } - } - + private boolean isRunning = true; + private List<CommandProcessor> processors = null; + private BundleContext context; + private List<Socket> sockets = new ArrayList<>(); + private Map<CommandProcessor, List<TelnetConnection>> processorToConnectionsMapping = new HashMap<>(); + + public TelnetServer(BundleContext context, List<CommandProcessor> processors, String host, int port) throws IOException { + this.context = context; + this.processors = processors; + if(host != null) { + server = new ServerSocket(port, 0, InetAddress.getByName(host)); + } else { + server = new ServerSocket(port); + } + } + @Override public void run() - { - try - { - while (isRunning) - { - final Socket socket = server.accept(); - sockets.add(socket); - for (CommandProcessor processor : processors) { - TelnetConnection telnetConnection = new TelnetConnection(socket, processor, context); - List<TelnetConnection> telnetConnections = processorToConnectionsMapping.get(processor); - if (telnetConnections == null) { - telnetConnections = new ArrayList<>(); - processorToConnectionsMapping.put(processor, telnetConnections); - } - telnetConnections.add(telnetConnection); - telnetConnection.start(); - } - } - } catch (IOException e) { - if (isRunning == true) { - e.printStackTrace(); - } - } finally { - isRunning = false; - try { - if (server != null) { - server.close(); - } - } catch (IOException e){ - // do nothing - } - } - } + { + try + { + while (isRunning) + { + final Socket socket = server.accept(); + sockets.add(socket); + for (CommandProcessor processor : processors) { + TelnetConnection telnetConnection = new TelnetConnection(socket, processor, context); + List<TelnetConnection> telnetConnections = processorToConnectionsMapping.get(processor); + if (telnetConnections == null) { + telnetConnections = new ArrayList<>(); + processorToConnectionsMapping.put(processor, telnetConnections); + } + telnetConnections.add(telnetConnection); + telnetConnection.start(); + } + } + } catch (IOException e) { + if (isRunning == true) { + e.printStackTrace(); + } + } finally { + isRunning = false; + try { + if (server != null) { + server.close(); + } + } catch (IOException e){ + // do nothing + } + } + } public synchronized void addCommandProcessor(CommandProcessor processor) { processors.add(processor); @@ -113,19 +113,19 @@ public class TelnetServer extends Thread { public synchronized void stopTelnetServer() { isRunning = false; try { - if (server != null) { - server.close(); - } - } catch (IOException e){ - // do nothing - } - - for(List<TelnetConnection> telnetConnections : processorToConnectionsMapping.values()) { - for (TelnetConnection telnetConnection : telnetConnections) { - telnetConnection.close(); - } - } - + if (server != null) { + server.close(); + } + } catch (IOException e){ + // do nothing + } + + for(List<TelnetConnection> telnetConnections : processorToConnectionsMapping.values()) { + for (TelnetConnection telnetConnection : telnetConnections) { + telnetConnection.close(); + } + } + this.interrupt(); } } diff --git a/bundles/org.eclipse.equinox.http.servlet.tests/bundles_src/tb1/org/eclipse/equinox/http/servlet/tests/tb1/TestServlet10.java b/bundles/org.eclipse.equinox.http.servlet.tests/bundles_src/tb1/org/eclipse/equinox/http/servlet/tests/tb1/TestServlet10.java index 8466b4192..e35a4c975 100644 --- a/bundles/org.eclipse.equinox.http.servlet.tests/bundles_src/tb1/org/eclipse/equinox/http/servlet/tests/tb1/TestServlet10.java +++ b/bundles/org.eclipse.equinox.http.servlet.tests/bundles_src/tb1/org/eclipse/equinox/http/servlet/tests/tb1/TestServlet10.java @@ -43,12 +43,12 @@ public class TestServlet10 extends AbstractTestServlet { OutputStream out = response.getOutputStream(); try { - byte[] buffer = new byte[2048]; - int bytesRead; + byte[] buffer = new byte[2048]; + int bytesRead; - while ((bytesRead = in.read(buffer)) != -1) { - out.write(buffer, 0, bytesRead); - } + while ((bytesRead = in.read(buffer)) != -1) { + out.write(buffer, 0, bytesRead); + } } finally { out.close(); diff --git a/bundles/org.eclipse.equinox.http.servlet.tests/bundles_src/tb1/org/eclipse/equinox/http/servlet/tests/tb1/TestServlet11.java b/bundles/org.eclipse.equinox.http.servlet.tests/bundles_src/tb1/org/eclipse/equinox/http/servlet/tests/tb1/TestServlet11.java index ccb82fc93..979e749f3 100644 --- a/bundles/org.eclipse.equinox.http.servlet.tests/bundles_src/tb1/org/eclipse/equinox/http/servlet/tests/tb1/TestServlet11.java +++ b/bundles/org.eclipse.equinox.http.servlet.tests/bundles_src/tb1/org/eclipse/equinox/http/servlet/tests/tb1/TestServlet11.java @@ -45,12 +45,12 @@ public class TestServlet11 extends AbstractTestServlet { OutputStream out = response.getOutputStream(); try { - byte[] buffer = new byte[2048]; - int bytesRead; + byte[] buffer = new byte[2048]; + int bytesRead; - while ((bytesRead = in.read(buffer)) != -1) { - out.write(buffer, 0, bytesRead); - } + while ((bytesRead = in.read(buffer)) != -1) { + out.write(buffer, 0, bytesRead); + } } finally { out.close(); diff --git a/bundles/org.eclipse.equinox.http.servlet.tests/src/org/eclipse/equinox/http/servlet/tests/DispatchingTest.java b/bundles/org.eclipse.equinox.http.servlet.tests/src/org/eclipse/equinox/http/servlet/tests/DispatchingTest.java index e0b2fcb14..5f8afd896 100644 --- a/bundles/org.eclipse.equinox.http.servlet.tests/src/org/eclipse/equinox/http/servlet/tests/DispatchingTest.java +++ b/bundles/org.eclipse.equinox.http.servlet.tests/src/org/eclipse/equinox/http/servlet/tests/DispatchingTest.java @@ -1439,8 +1439,8 @@ public class DispatchingTest extends BaseTest { protected void service(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { - response.setContentType("text/event-stream"); - response.setCharacterEncoding("UTF-8"); + response.setContentType("text/event-stream"); + response.setCharacterEncoding("UTF-8"); try (ServletOutputStream out = response.getOutputStream()) { for (int i = 1; i <= 10; ++i) { @@ -1515,8 +1515,8 @@ public class DispatchingTest extends BaseTest { protected void service(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { - response.setContentType("text/event-stream"); - response.setCharacterEncoding("UTF-8"); + response.setContentType("text/event-stream"); + response.setCharacterEncoding("UTF-8"); try (PrintWriter writer = response.getWriter()) { for (int i = 1; i <= 10; ++i) { diff --git a/bundles/org.eclipse.equinox.http.servlet.tests/src/org/eclipse/equinox/http/servlet/tests/util/ServletRequestAdvisor.java b/bundles/org.eclipse.equinox.http.servlet.tests/src/org/eclipse/equinox/http/servlet/tests/util/ServletRequestAdvisor.java index a5f82a12b..49451a6e4 100644 --- a/bundles/org.eclipse.equinox.http.servlet.tests/src/org/eclipse/equinox/http/servlet/tests/util/ServletRequestAdvisor.java +++ b/bundles/org.eclipse.equinox.http.servlet.tests/src/org/eclipse/equinox/http/servlet/tests/util/ServletRequestAdvisor.java @@ -135,15 +135,15 @@ public class ServletRequestAdvisor extends Object { HttpsURLConnection httpsConn = (HttpsURLConnection)url.openConnection(); httpsConn.setSSLSocketFactory(sslContext.getSocketFactory()); - httpsConn.setRequestMethod("GET"); - httpsConn.setDoOutput(false); - httpsConn.setDoInput(true); - httpsConn.setConnectTimeout(150 * 1000); - httpsConn.setReadTimeout(150 * 1000); - httpsConn.connect(); - - assertEquals("Request to the url " + spec + " was not successful", 200 , httpsConn.getResponseCode()); - InputStream stream = httpsConn.getInputStream(); + httpsConn.setRequestMethod("GET"); + httpsConn.setDoOutput(false); + httpsConn.setDoInput(true); + httpsConn.setConnectTimeout(150 * 1000); + httpsConn.setReadTimeout(150 * 1000); + httpsConn.connect(); + + assertEquals("Request to the url " + spec + " was not successful", 200 , httpsConn.getResponseCode()); + InputStream stream = httpsConn.getInputStream(); try { return drain(stream); } finally { @@ -153,41 +153,41 @@ public class ServletRequestAdvisor extends Object { private void initializeSSLContext(SSLContext sslContext, String ksPath, String ksPassword) throws Exception { KeyManager keyManagers[] = null; - if (ksPath != null) { - KeyManagerFactory kmFactory = KeyManagerFactory.getInstance(KeyManagerFactory.getDefaultAlgorithm()); - File ksFile = new File(ksPath); - KeyStore keyStore = KeyStore.getInstance("JKS"); - - try(InputStream ksStream = new FileInputStream(ksFile)){ - keyStore.load(ksStream, ksPassword.toCharArray()); - kmFactory.init(keyStore, ksPassword.toCharArray()); - keyManagers = kmFactory.getKeyManagers(); - } - } - - TrustManager[] trustManagers = getTrustManager(); - - sslContext.init(keyManagers, trustManagers, null); + if (ksPath != null) { + KeyManagerFactory kmFactory = KeyManagerFactory.getInstance(KeyManagerFactory.getDefaultAlgorithm()); + File ksFile = new File(ksPath); + KeyStore keyStore = KeyStore.getInstance("JKS"); + + try(InputStream ksStream = new FileInputStream(ksFile)){ + keyStore.load(ksStream, ksPassword.toCharArray()); + kmFactory.init(keyStore, ksPassword.toCharArray()); + keyManagers = kmFactory.getKeyManagers(); + } + } + + TrustManager[] trustManagers = getTrustManager(); + + sslContext.init(keyManagers, trustManagers, null); } private TrustManager[] getTrustManager() { TrustManager[] trustAllCerts = new TrustManager[] { new X509TrustManager() { - @Override - public java.security.cert.X509Certificate[] getAcceptedIssuers() { - return null; - } + @Override + public java.security.cert.X509Certificate[] getAcceptedIssuers() { + return null; + } - @Override - public void checkClientTrusted( - java.security.cert.X509Certificate[] certs, String authType) {} + @Override + public void checkClientTrusted( + java.security.cert.X509Certificate[] certs, String authType) {} - @Override - public void checkServerTrusted( - java.security.cert.X509Certificate[] certs, String authType) {} - } }; + @Override + public void checkServerTrusted( + java.security.cert.X509Certificate[] certs, String authType) {} + } }; - return trustAllCerts; + return trustAllCerts; } public Map<String, List<String>> request(String value, Map<String, List<String>> headers) throws IOException { diff --git a/bundles/org.eclipse.equinox.http.servlet/src/org/eclipse/equinox/http/servlet/internal/multipart/MultipartSupportPart.java b/bundles/org.eclipse.equinox.http.servlet/src/org/eclipse/equinox/http/servlet/internal/multipart/MultipartSupportPart.java index dd60116a3..a0b3c2624 100644 --- a/bundles/org.eclipse.equinox.http.servlet/src/org/eclipse/equinox/http/servlet/internal/multipart/MultipartSupportPart.java +++ b/bundles/org.eclipse.equinox.http.servlet/src/org/eclipse/equinox/http/servlet/internal/multipart/MultipartSupportPart.java @@ -97,9 +97,9 @@ public class MultipartSupportPart implements Part { public IteratorCollection(Iterator<String> iterator) { this.collection = new ArrayList<String>(); - while (iterator.hasNext()) { - collection.add(iterator.next()); - } + while (iterator.hasNext()) { + collection.add(iterator.next()); + } } @Override diff --git a/bundles/org.eclipse.equinox.http.servlet/src/org/eclipse/equinox/http/servlet/internal/util/HttpStatus.java b/bundles/org.eclipse.equinox.http.servlet/src/org/eclipse/equinox/http/servlet/internal/util/HttpStatus.java index 5db5d3e08..ca6639640 100644 --- a/bundles/org.eclipse.equinox.http.servlet/src/org/eclipse/equinox/http/servlet/internal/util/HttpStatus.java +++ b/bundles/org.eclipse.equinox.http.servlet/src/org/eclipse/equinox/http/servlet/internal/util/HttpStatus.java @@ -22,152 +22,152 @@ public enum HttpStatus { UNKNOWN_STATUS(-1, "Unknown Status", ""), //$NON-NLS-1$ //$NON-NLS-2$ - CONTINUE(100, "Continue", "RFC7231"), //$NON-NLS-1$ //$NON-NLS-2$ + CONTINUE(100, "Continue", "RFC7231"), //$NON-NLS-1$ //$NON-NLS-2$ - SWITCHING_PROTOCOLS(101, "Switching Protocols", "RFC7231"), //$NON-NLS-1$ //$NON-NLS-2$ + SWITCHING_PROTOCOLS(101, "Switching Protocols", "RFC7231"), //$NON-NLS-1$ //$NON-NLS-2$ - PROCESSING(102, "Processing", "RFC2518"), //$NON-NLS-1$ //$NON-NLS-2$ + PROCESSING(102, "Processing", "RFC2518"), //$NON-NLS-1$ //$NON-NLS-2$ - EARLY_HINTS(103, "Early Hints", "RFC8297"), //$NON-NLS-1$ //$NON-NLS-2$ + EARLY_HINTS(103, "Early Hints", "RFC8297"), //$NON-NLS-1$ //$NON-NLS-2$ - OK(200, "OK", "RFC7231"), //$NON-NLS-1$ //$NON-NLS-2$ + OK(200, "OK", "RFC7231"), //$NON-NLS-1$ //$NON-NLS-2$ - CREATED(201, "Created", "RFC7231"), //$NON-NLS-1$ //$NON-NLS-2$ + CREATED(201, "Created", "RFC7231"), //$NON-NLS-1$ //$NON-NLS-2$ - ACCEPTED(202, "Accepted", "RFC7231"), //$NON-NLS-1$ //$NON-NLS-2$ + ACCEPTED(202, "Accepted", "RFC7231"), //$NON-NLS-1$ //$NON-NLS-2$ - NON_AUTHORITATIVE_INFORMATION(203, "Non Authoritative Information", "RFC7231"), //$NON-NLS-1$ //$NON-NLS-2$ + NON_AUTHORITATIVE_INFORMATION(203, "Non Authoritative Information", "RFC7231"), //$NON-NLS-1$ //$NON-NLS-2$ - NO_CONTENT(204, "No Content", "RFC7231"), //$NON-NLS-1$ //$NON-NLS-2$ + NO_CONTENT(204, "No Content", "RFC7231"), //$NON-NLS-1$ //$NON-NLS-2$ - RESET_CONTENT(205, "Reset Content", "RFC7231"), //$NON-NLS-1$ //$NON-NLS-2$ + RESET_CONTENT(205, "Reset Content", "RFC7231"), //$NON-NLS-1$ //$NON-NLS-2$ - PARTIAL_CONTENT(206, "Partial Content", "RFC7233"), //$NON-NLS-1$ //$NON-NLS-2$ - /** )*/ - MULTI_STATUS(207, "Partial Update OK", "RFC4918"), //$NON-NLS-1$ //$NON-NLS-2$ + PARTIAL_CONTENT(206, "Partial Content", "RFC7233"), //$NON-NLS-1$ //$NON-NLS-2$ + /** )*/ + MULTI_STATUS(207, "Partial Update OK", "RFC4918"), //$NON-NLS-1$ //$NON-NLS-2$ - ALREADY_REPORTED(208, "Already Reported", "RFC5842"), //$NON-NLS-1$ //$NON-NLS-2$ + ALREADY_REPORTED(208, "Already Reported", "RFC5842"), //$NON-NLS-1$ //$NON-NLS-2$ - IM_USED(226, "IM Used", "RFC3229"), //$NON-NLS-1$ //$NON-NLS-2$ + IM_USED(226, "IM Used", "RFC3229"), //$NON-NLS-1$ //$NON-NLS-2$ - MULTIPLE_CHOICES(300, "Multiple Choices", "RFC7231"), //$NON-NLS-1$ //$NON-NLS-2$ + MULTIPLE_CHOICES(300, "Multiple Choices", "RFC7231"), //$NON-NLS-1$ //$NON-NLS-2$ - MOVED_PERMANENTLY(301, "Moved Permanently", "RFC7231"), //$NON-NLS-1$ //$NON-NLS-2$ + MOVED_PERMANENTLY(301, "Moved Permanently", "RFC7231"), //$NON-NLS-1$ //$NON-NLS-2$ - MOVED_TEMPORARILY(302, "Found", "RFC7231"), //$NON-NLS-1$ //$NON-NLS-2$ + MOVED_TEMPORARILY(302, "Found", "RFC7231"), //$NON-NLS-1$ //$NON-NLS-2$ - SEE_OTHER(303, "See Other", "RFC7231"), //$NON-NLS-1$ //$NON-NLS-2$ + SEE_OTHER(303, "See Other", "RFC7231"), //$NON-NLS-1$ //$NON-NLS-2$ - NOT_MODIFIED(304, "Not Modified", "RFC7232"), //$NON-NLS-1$ //$NON-NLS-2$ + NOT_MODIFIED(304, "Not Modified", "RFC7232"), //$NON-NLS-1$ //$NON-NLS-2$ - USE_PROXY(305, "Use Proxy", "RFC7231"), //$NON-NLS-1$ //$NON-NLS-2$ + USE_PROXY(305, "Use Proxy", "RFC7231"), //$NON-NLS-1$ //$NON-NLS-2$ - TEMPORARY_REDIRECT(307, "Temporary Redirect", "RFC7231"), //$NON-NLS-1$ //$NON-NLS-2$ + TEMPORARY_REDIRECT(307, "Temporary Redirect", "RFC7231"), //$NON-NLS-1$ //$NON-NLS-2$ - PERMANENT_REDIRECT(308, "Permanent Redirect", "RFC7538"), //$NON-NLS-1$ //$NON-NLS-2$ + PERMANENT_REDIRECT(308, "Permanent Redirect", "RFC7538"), //$NON-NLS-1$ //$NON-NLS-2$ - BAD_REQUEST(400, "Bad Request", "RFC7231"), //$NON-NLS-1$ //$NON-NLS-2$ + BAD_REQUEST(400, "Bad Request", "RFC7231"), //$NON-NLS-1$ //$NON-NLS-2$ - UNAUTHORIZED(401, "Unauthorized", "RFC7235"), //$NON-NLS-1$ //$NON-NLS-2$ + UNAUTHORIZED(401, "Unauthorized", "RFC7235"), //$NON-NLS-1$ //$NON-NLS-2$ - PAYMENT_REQUIRED(402, "Payment Required", "RFC7231"), //$NON-NLS-1$ //$NON-NLS-2$ + PAYMENT_REQUIRED(402, "Payment Required", "RFC7231"), //$NON-NLS-1$ //$NON-NLS-2$ - FORBIDDEN(403, "Forbidden", "RFC7231"), //$NON-NLS-1$ //$NON-NLS-2$ + FORBIDDEN(403, "Forbidden", "RFC7231"), //$NON-NLS-1$ //$NON-NLS-2$ - NOT_FOUND(404, "Not Found", "RFC7231"), //$NON-NLS-1$ //$NON-NLS-2$ + NOT_FOUND(404, "Not Found", "RFC7231"), //$NON-NLS-1$ //$NON-NLS-2$ - METHOD_NOT_ALLOWED(405, "Method Not Allowed", "RFC7231"), //$NON-NLS-1$ //$NON-NLS-2$ + METHOD_NOT_ALLOWED(405, "Method Not Allowed", "RFC7231"), //$NON-NLS-1$ //$NON-NLS-2$ - NOT_ACCEPTABLE(406, "Not Acceptable", "RFC7231"), //$NON-NLS-1$ //$NON-NLS-2$ + NOT_ACCEPTABLE(406, "Not Acceptable", "RFC7231"), //$NON-NLS-1$ //$NON-NLS-2$ - PROXY_AUTHENTICATION_REQUIRED(407, "Proxy Authentication Required", "RFC7235"), //$NON-NLS-1$ //$NON-NLS-2$ + PROXY_AUTHENTICATION_REQUIRED(407, "Proxy Authentication Required", "RFC7235"), //$NON-NLS-1$ //$NON-NLS-2$ - REQUEST_TIMEOUT(408, "Request Timeout", "RFC7231"), //$NON-NLS-1$ //$NON-NLS-2$ + REQUEST_TIMEOUT(408, "Request Timeout", "RFC7231"), //$NON-NLS-1$ //$NON-NLS-2$ - CONFLICT(409, "Conflict", "RFC7231"), //$NON-NLS-1$ //$NON-NLS-2$ + CONFLICT(409, "Conflict", "RFC7231"), //$NON-NLS-1$ //$NON-NLS-2$ - GONE(410, "Gone", "RFC7231"), //$NON-NLS-1$ //$NON-NLS-2$ + GONE(410, "Gone", "RFC7231"), //$NON-NLS-1$ //$NON-NLS-2$ - LENGTH_REQUIRED(411, "Length Required", "RFC7231"), //$NON-NLS-1$ //$NON-NLS-2$ + LENGTH_REQUIRED(411, "Length Required", "RFC7231"), //$NON-NLS-1$ //$NON-NLS-2$ - PRECONDITION_FAILED(412, "Precondition Failed", "RFC7232"), //$NON-NLS-1$ //$NON-NLS-2$ + PRECONDITION_FAILED(412, "Precondition Failed", "RFC7232"), //$NON-NLS-1$ //$NON-NLS-2$ - PAYLOAD_TOO_LARGE(413, "Payload Too Large", "RFC7231"), //$NON-NLS-1$ //$NON-NLS-2$ + PAYLOAD_TOO_LARGE(413, "Payload Too Large", "RFC7231"), //$NON-NLS-1$ //$NON-NLS-2$ - URI_TOO_LONG(414, "URI Too Long", "RFC7231"), //$NON-NLS-1$ //$NON-NLS-2$ + URI_TOO_LONG(414, "URI Too Long", "RFC7231"), //$NON-NLS-1$ //$NON-NLS-2$ - UNSUPPORTED_MEDIA_TYPE(415, "Unsupported Media Type", "RFC7231"), //$NON-NLS-1$ //$NON-NLS-2$ + UNSUPPORTED_MEDIA_TYPE(415, "Unsupported Media Type", "RFC7231"), //$NON-NLS-1$ //$NON-NLS-2$ - RANGE_NOT_SATISFIABLE(416, "Range Not Satisfiable", "RFC7233"), //$NON-NLS-1$ //$NON-NLS-2$ + RANGE_NOT_SATISFIABLE(416, "Range Not Satisfiable", "RFC7233"), //$NON-NLS-1$ //$NON-NLS-2$ - EXPECTATION_FAILED(417, "Expectation Failed", "RFC7231"), //$NON-NLS-1$ //$NON-NLS-2$ + EXPECTATION_FAILED(417, "Expectation Failed", "RFC7231"), //$NON-NLS-1$ //$NON-NLS-2$ - MISDIRECTED_REQUEST(421, "Misdirected Request", "RFC7540"), //$NON-NLS-1$ //$NON-NLS-2$ + MISDIRECTED_REQUEST(421, "Misdirected Request", "RFC7540"), //$NON-NLS-1$ //$NON-NLS-2$ - UNPROCESSABLE_ENTITY(422, "Unprocessable Entity", "RFC4918"), //$NON-NLS-1$ //$NON-NLS-2$ + UNPROCESSABLE_ENTITY(422, "Unprocessable Entity", "RFC4918"), //$NON-NLS-1$ //$NON-NLS-2$ - LOCKED(423, "Locked", "RFC4918"), //$NON-NLS-1$ //$NON-NLS-2$ + LOCKED(423, "Locked", "RFC4918"), //$NON-NLS-1$ //$NON-NLS-2$ - FAILED_DEPENDENCY(424, "Failed Dependency", "RFC4918"), //$NON-NLS-1$ //$NON-NLS-2$ + FAILED_DEPENDENCY(424, "Failed Dependency", "RFC4918"), //$NON-NLS-1$ //$NON-NLS-2$ - PRECONDITION_REQUIRED(428, "Precondition Required", "RFC6585"), //$NON-NLS-1$ //$NON-NLS-2$ + PRECONDITION_REQUIRED(428, "Precondition Required", "RFC6585"), //$NON-NLS-1$ //$NON-NLS-2$ - TOO_MANY_REQUESTS(429, "Too Many Requests", "RFC6585"), //$NON-NLS-1$ //$NON-NLS-2$ + TOO_MANY_REQUESTS(429, "Too Many Requests", "RFC6585"), //$NON-NLS-1$ //$NON-NLS-2$ - REQUEST_HEADER_FIELDS_TOO_LARGE(431, "Request Header Fields Too Large", "RFC6585"), //$NON-NLS-1$ //$NON-NLS-2$ + REQUEST_HEADER_FIELDS_TOO_LARGE(431, "Request Header Fields Too Large", "RFC6585"), //$NON-NLS-1$ //$NON-NLS-2$ - UNAVAILABLE_FOR_LEGAL_REASONS(451, "Unavailable For Legal Reasons", "RFC7725"), //$NON-NLS-1$ //$NON-NLS-2$ + UNAVAILABLE_FOR_LEGAL_REASONS(451, "Unavailable For Legal Reasons", "RFC7725"), //$NON-NLS-1$ //$NON-NLS-2$ - INTERNAL_SERVER_ERROR(500, "Internal Server Error", "RFC7231"), //$NON-NLS-1$ //$NON-NLS-2$ + INTERNAL_SERVER_ERROR(500, "Internal Server Error", "RFC7231"), //$NON-NLS-1$ //$NON-NLS-2$ - NOT_IMPLEMENTED(501, "Not Implemented", "RFC7231"), //$NON-NLS-1$ //$NON-NLS-2$ + NOT_IMPLEMENTED(501, "Not Implemented", "RFC7231"), //$NON-NLS-1$ //$NON-NLS-2$ - BAD_GATEWAY(502, "Bad Gateway", "RFC7231"), //$NON-NLS-1$ //$NON-NLS-2$ + BAD_GATEWAY(502, "Bad Gateway", "RFC7231"), //$NON-NLS-1$ //$NON-NLS-2$ - SERVICE_UNAVAILABLE(503, "Service Unavailable", "RFC7231"), //$NON-NLS-1$ //$NON-NLS-2$ + SERVICE_UNAVAILABLE(503, "Service Unavailable", "RFC7231"), //$NON-NLS-1$ //$NON-NLS-2$ - GATEWAY_TIMEOUT(504, "Gateway Timeout", "RFC7231"), //$NON-NLS-1$ //$NON-NLS-2$ + GATEWAY_TIMEOUT(504, "Gateway Timeout", "RFC7231"), //$NON-NLS-1$ //$NON-NLS-2$ - HTTP_VERSION_NOT_SUPPORTED(505, "HTTP Version Not Supported", "RFC7231"), //$NON-NLS-1$ //$NON-NLS-2$ + HTTP_VERSION_NOT_SUPPORTED(505, "HTTP Version Not Supported", "RFC7231"), //$NON-NLS-1$ //$NON-NLS-2$ - VARIANT_ALSO_NEGOTIATES(506, "Variant Also Negotiates", "RFC2295"), //$NON-NLS-1$ //$NON-NLS-2$ + VARIANT_ALSO_NEGOTIATES(506, "Variant Also Negotiates", "RFC2295"), //$NON-NLS-1$ //$NON-NLS-2$ - INSUFFICIENT_STORAGE(507, "Insufficient Storage", "RFC4918"), //$NON-NLS-1$ //$NON-NLS-2$ + INSUFFICIENT_STORAGE(507, "Insufficient Storage", "RFC4918"), //$NON-NLS-1$ //$NON-NLS-2$ - LOOP_DETECTED(508, "Loop Detected", "RFC5842"), //$NON-NLS-1$ //$NON-NLS-2$ + LOOP_DETECTED(508, "Loop Detected", "RFC5842"), //$NON-NLS-1$ //$NON-NLS-2$ - NOT_EXTENDED(510, "Not Extended", "RFC2774"), //$NON-NLS-1$ //$NON-NLS-2$ + NOT_EXTENDED(510, "Not Extended", "RFC2774"), //$NON-NLS-1$ //$NON-NLS-2$ - NETWORK_AUTHENTICATION_REQUIRED(511, "Network Authentication Required", "RFC6585"); //$NON-NLS-1$ //$NON-NLS-2$ + NETWORK_AUTHENTICATION_REQUIRED(511, "Network Authentication Required", "RFC6585"); //$NON-NLS-1$ //$NON-NLS-2$ private HttpStatus(int value, String description, String reference) { - this.value = value; - this.description = description; - this.reference = reference; + this.value = value; + this.description = description; + this.reference = reference; } public String description() { return description; } - public String reference() { - return reference; - } - - public int value() { - return value; - } - - private final int value; - private final String description; - private final String reference; - - public static HttpStatus of(int value) { - for (HttpStatus v : HttpStatus.values()) { - if (v.value == value) { - return v; - } - } - return UNKNOWN_STATUS; - } + public String reference() { + return reference; + } + + public int value() { + return value; + } + + private final int value; + private final String description; + private final String reference; + + public static HttpStatus of(int value) { + for (HttpStatus v : HttpStatus.values()) { + if (v.value == value) { + return v; + } + } + return UNKNOWN_STATUS; + } } diff --git a/bundles/org.eclipse.equinox.http.servlet/src/org/eclipse/equinox/http/servlet/internal/util/ServiceReferenceMap.java b/bundles/org.eclipse.equinox.http.servlet/src/org/eclipse/equinox/http/servlet/internal/util/ServiceReferenceMap.java index 7b7cdd594..5f8419dec 100644 --- a/bundles/org.eclipse.equinox.http.servlet/src/org/eclipse/equinox/http/servlet/internal/util/ServiceReferenceMap.java +++ b/bundles/org.eclipse.equinox.http.servlet/src/org/eclipse/equinox/http/servlet/internal/util/ServiceReferenceMap.java @@ -23,15 +23,15 @@ import org.osgi.framework.ServiceReference; public class ServiceReferenceMap extends AbstractMap<String, Object> { public ServiceReferenceMap(ServiceReference<?> serviceReference) { - String[] propertyKeys = serviceReference.getPropertyKeys(); + String[] propertyKeys = serviceReference.getPropertyKeys(); - entries = new HashSet<Map.Entry<String,Object>>(propertyKeys.length); + entries = new HashSet<Map.Entry<String,Object>>(propertyKeys.length); - for (String key : propertyKeys) { - Map.Entry<String,Object> entry = new ReferenceEntry( - key, serviceReference.getProperty(key)); + for (String key : propertyKeys) { + Map.Entry<String,Object> entry = new ReferenceEntry( + key, serviceReference.getProperty(key)); - entries.add(entry); + entries.add(entry); } } diff --git a/bundles/org.eclipse.equinox.metatype/src/org/eclipse/equinox/metatype/impl/MetaTypeProviderTracker.java b/bundles/org.eclipse.equinox.metatype/src/org/eclipse/equinox/metatype/impl/MetaTypeProviderTracker.java index baaa8f890..a8fc0d8fa 100644 --- a/bundles/org.eclipse.equinox.metatype/src/org/eclipse/equinox/metatype/impl/MetaTypeProviderTracker.java +++ b/bundles/org.eclipse.equinox.metatype/src/org/eclipse/equinox/metatype/impl/MetaTypeProviderTracker.java @@ -272,22 +272,22 @@ public class MetaTypeProviderTracker implements EquinoxMetaTypeInformation { return ad.getDefaultValue(); } - @Override + @Override public Map<String, String> getExtensionAttributes(String schema) { return Collections.<String, String> emptyMap(); } - @Override + @Override public Set<String> getExtensionUris() { return Collections.<String> emptySet(); } - @Override + @Override public String getMax() { return null; } - @Override + @Override public String getMin() { return null; } diff --git a/bundles/org.eclipse.equinox.preferences/src/org/eclipse/core/internal/preferences/DefaultPreferences.java b/bundles/org.eclipse.equinox.preferences/src/org/eclipse/core/internal/preferences/DefaultPreferences.java index b2b0daa4e..bf36e9dfa 100644 --- a/bundles/org.eclipse.equinox.preferences/src/org/eclipse/core/internal/preferences/DefaultPreferences.java +++ b/bundles/org.eclipse.equinox.preferences/src/org/eclipse/core/internal/preferences/DefaultPreferences.java @@ -372,7 +372,7 @@ public class DefaultPreferences extends EclipsePreferences { e.printStackTrace(); } } - finally { + finally { if (input != null) try { input.close(); diff --git a/bundles/org.eclipse.equinox.preferences/src/org/eclipse/core/internal/preferences/PreferencesService.java b/bundles/org.eclipse.equinox.preferences/src/org/eclipse/core/internal/preferences/PreferencesService.java index 7a114ccc1..b374bb9ca 100644 --- a/bundles/org.eclipse.equinox.preferences/src/org/eclipse/core/internal/preferences/PreferencesService.java +++ b/bundles/org.eclipse.equinox.preferences/src/org/eclipse/core/internal/preferences/PreferencesService.java @@ -1129,11 +1129,11 @@ public class PreferencesService implements IPreferencesService { } /* - * Set the default search order to use when there is nothing else set. Clients should not - * call this method because it is in an internal class and has been created solely for use by - * the org.eclipse.core.resources bundle in response to this bug: - * https://bugs.eclipse.org/330320 - */ + * Set the default search order to use when there is nothing else set. Clients should not + * call this method because it is in an internal class and has been created solely for use by + * the org.eclipse.core.resources bundle in response to this bug: + * https://bugs.eclipse.org/330320 + */ public void setDefaultDefaultLookupOrder(String[] order) { // shouldn't happen but let's protect against an NPE. if (order == null) diff --git a/bundles/org.eclipse.equinox.preferences/src/org/osgi/service/prefs/BackingStoreException.java b/bundles/org.eclipse.equinox.preferences/src/org/osgi/service/prefs/BackingStoreException.java index 57352a14a..71bf236ba 100644 --- a/bundles/org.eclipse.equinox.preferences/src/org/osgi/service/prefs/BackingStoreException.java +++ b/bundles/org.eclipse.equinox.preferences/src/org/osgi/service/prefs/BackingStoreException.java @@ -22,7 +22,7 @@ package org.osgi.service.prefs; * @version $Id$ */ public class BackingStoreException extends Exception { - static final long serialVersionUID = -1415637364122829574L; + static final long serialVersionUID = -1415637364122829574L; /** * Constructs a {@code BackingStoreException} with the specified detail diff --git a/bundles/org.eclipse.equinox.security.linux.x86_64/src/org/eclipse/equinox/internal/security/linux/LinuxPasswordProvider.java b/bundles/org.eclipse.equinox.security.linux.x86_64/src/org/eclipse/equinox/internal/security/linux/LinuxPasswordProvider.java index ab79aac8c..8384935e2 100644 --- a/bundles/org.eclipse.equinox.security.linux.x86_64/src/org/eclipse/equinox/internal/security/linux/LinuxPasswordProvider.java +++ b/bundles/org.eclipse.equinox.security.linux.x86_64/src/org/eclipse/equinox/internal/security/linux/LinuxPasswordProvider.java @@ -27,62 +27,62 @@ import org.eclipse.equinox.security.storage.provider.PasswordProvider; public class LinuxPasswordProvider extends PasswordProvider implements IValidatingPasswordProvider { - /** - * The length of the randomly generated password in bytes - */ - private static final int PASSWORD_LENGTH = 64; - - private native String getMasterPassword() throws SecurityException; - - private native void saveMasterPassword(String password) throws SecurityException; - - private native boolean canUnlock() throws SecurityException; - - static { - System.loadLibrary("keystorelinuxnative"); //$NON-NLS-1$ - } - - @Override - public PBEKeySpec getPassword(IPreferencesContainer container, int passwordType) { - - boolean newPassword = (passwordType & CREATE_NEW_PASSWORD) != 0; - boolean passwordChange = (passwordType & PASSWORD_CHANGE) != 0; - - if (!newPassword && !passwordChange) { - try { - return new PBEKeySpec(getMasterPassword().toCharArray()); - } catch (SecurityException e) { - AuthPlugin.getDefault().logError(LinuxPasswordProviderMessages.getMasterPasswordError, e); - return null; - } - } - - byte[] rawPassword = new byte[PASSWORD_LENGTH]; - SecureRandom random = new SecureRandom(); - random.setSeed(System.currentTimeMillis()); - random.nextBytes(rawPassword); - String newPasswordString = Base64.encode(rawPassword); - - // add info message in the log - AuthPlugin.getDefault().logMessage(LinuxPasswordProviderMessages.newMasterPasswordGenerated); - - try { - saveMasterPassword(newPasswordString); - return new PBEKeySpec(newPasswordString.toCharArray()); - } catch (SecurityException e) { - AuthPlugin.getDefault().logError(LinuxPasswordProviderMessages.saveMasterPasswordError, e); - return null; - } - } - - - @Override - public boolean isValid() { - try { - return canUnlock(); + /** + * The length of the randomly generated password in bytes + */ + private static final int PASSWORD_LENGTH = 64; + + private native String getMasterPassword() throws SecurityException; + + private native void saveMasterPassword(String password) throws SecurityException; + + private native boolean canUnlock() throws SecurityException; + + static { + System.loadLibrary("keystorelinuxnative"); //$NON-NLS-1$ + } + + @Override + public PBEKeySpec getPassword(IPreferencesContainer container, int passwordType) { + + boolean newPassword = (passwordType & CREATE_NEW_PASSWORD) != 0; + boolean passwordChange = (passwordType & PASSWORD_CHANGE) != 0; + + if (!newPassword && !passwordChange) { + try { + return new PBEKeySpec(getMasterPassword().toCharArray()); + } catch (SecurityException e) { + AuthPlugin.getDefault().logError(LinuxPasswordProviderMessages.getMasterPasswordError, e); + return null; + } + } + + byte[] rawPassword = new byte[PASSWORD_LENGTH]; + SecureRandom random = new SecureRandom(); + random.setSeed(System.currentTimeMillis()); + random.nextBytes(rawPassword); + String newPasswordString = Base64.encode(rawPassword); + + // add info message in the log + AuthPlugin.getDefault().logMessage(LinuxPasswordProviderMessages.newMasterPasswordGenerated); + + try { + saveMasterPassword(newPasswordString); + return new PBEKeySpec(newPasswordString.toCharArray()); + } catch (SecurityException e) { + AuthPlugin.getDefault().logError(LinuxPasswordProviderMessages.saveMasterPasswordError, e); + return null; + } + } + + + @Override + public boolean isValid() { + try { + return canUnlock(); } catch (SecurityException e) { - return false; + return false; + } } - } } diff --git a/bundles/org.eclipse.equinox.security.linux.x86_64/src/org/eclipse/equinox/internal/security/linux/nls/LinuxPasswordProviderMessages.java b/bundles/org.eclipse.equinox.security.linux.x86_64/src/org/eclipse/equinox/internal/security/linux/nls/LinuxPasswordProviderMessages.java index b19086ca9..0dbbd1df5 100644 --- a/bundles/org.eclipse.equinox.security.linux.x86_64/src/org/eclipse/equinox/internal/security/linux/nls/LinuxPasswordProviderMessages.java +++ b/bundles/org.eclipse.equinox.security.linux.x86_64/src/org/eclipse/equinox/internal/security/linux/nls/LinuxPasswordProviderMessages.java @@ -17,18 +17,18 @@ import org.eclipse.osgi.util.NLS; public class LinuxPasswordProviderMessages extends NLS { - private static final String BUNDLE_NAME = "org.eclipse.equinox.internal.security.linux.nls.messages"; //$NON-NLS-1$ + private static final String BUNDLE_NAME = "org.eclipse.equinox.internal.security.linux.nls.messages"; //$NON-NLS-1$ - public static String getMasterPasswordError; - public static String saveMasterPasswordError; - public static String newMasterPasswordGenerated; + public static String getMasterPasswordError; + public static String saveMasterPasswordError; + public static String newMasterPasswordGenerated; - static { - // load message values from bundle file - reloadMessages(); - } + static { + // load message values from bundle file + reloadMessages(); + } - public static void reloadMessages() { - NLS.initializeMessages(BUNDLE_NAME, LinuxPasswordProviderMessages.class); - } + public static void reloadMessages() { + NLS.initializeMessages(BUNDLE_NAME, LinuxPasswordProviderMessages.class); + } } diff --git a/bundles/org.eclipse.equinox.security.macosx/keystoreNative/src/keystoreNative.java b/bundles/org.eclipse.equinox.security.macosx/keystoreNative/src/keystoreNative.java index a13e4c3e9..5487c792e 100644 --- a/bundles/org.eclipse.equinox.security.macosx/keystoreNative/src/keystoreNative.java +++ b/bundles/org.eclipse.equinox.security.macosx/keystoreNative/src/keystoreNative.java @@ -15,33 +15,33 @@ import java.util.*; public class keystoreNative { - static { - // Ensure native JNI library is loaded - System.loadLibrary("keyfile://localhost/Users/kim/keystoreNative/src/keystoreNative.javastoreNative"); - } + static { + // Ensure native JNI library is loaded + System.loadLibrary("keyfile://localhost/Users/kim/keystoreNative/src/keystoreNative.javastoreNative"); + } - public keystoreNative() { - System.out.println("Instance created"); - } + public keystoreNative() { + System.out.println("Instance created"); + } - private native String getPassword(String serviceName, String accountName); + private native String getPassword(String serviceName, String accountName); private native void setPassword(String serviceName, String accountName, String password); - public static void main (String args[]) { - // insert code here... - System.out.println("Started application"); - System.out.println("java.library.path = " + System.getProperty("java.library.path")); - keystoreNative newjni = new keystoreNative(); + public static void main (String args[]) { + // insert code here... + System.out.println("Started application"); + System.out.println("java.library.path = " + System.getProperty("java.library.path")); + keystoreNative newjni = new keystoreNative(); String password = "abby" + System.currentTimeMillis(); System.out.println("Trying to set password to: " + password); try { newjni.setPassword("org.eclipse.sdk", "kim", password); - String result = newjni.getPassword("org.eclipse.sdk", "kim"); - System.out.println("Finished application. Answer is " + result); + String result = newjni.getPassword("org.eclipse.sdk", "kim"); + System.out.println("Finished application. Answer is " + result); } catch (SecurityException e) { e.printStackTrace(); } - } + } } |