repo_name stringlengths 7 104 | file_path stringlengths 13 198 | context stringlengths 67 7.15k | import_statement stringlengths 16 4.43k | code stringlengths 40 6.98k | prompt stringlengths 227 8.27k | next_line stringlengths 8 795 |
|---|---|---|---|---|---|---|
eskatos/asadmin | asadmin-maven-plugin/src/main/java/org/n0pe/mojo/asadmin/StartClusterMojo.java | // Path: asadmin-java/src/main/java/org/n0pe/asadmin/AsAdminCmdList.java
// public class AsAdminCmdList
// extends ArrayList<IAsAdminCmd>
// {
//
// private static final long serialVersionUID = 1L;
//
// public AsAdminCmdList()
// {
// super();
// }
//
// }
//
// Path: asadmin-java/src/main/java/org/n0pe/asadmin/commands/Cluster.java
// public class Cluster
// extends AbstractAsAdminCmd
// {
//
// public static final String START = "start-cluster";
// public static final String STOP = "stop-cluster";
// private Boolean start = null;
// private String cluster;
//
// public Cluster( String cluster )
// {
// this.cluster = cluster;
// }
//
// public Cluster start()
// {
// start = Boolean.TRUE;
// return this;
// }
//
// public Cluster stop()
// {
// start = Boolean.FALSE;
// return this;
// }
//
// public boolean needCredentials()
// {
// return true;
// }
//
// public String getActionCommand()
// {
// if( start == null )
// {
// throw new IllegalStateException();
// }
// return start.booleanValue()
// ? START
// : STOP;
// }
//
// public String[] getParameters()
// {
// if( start == null )
// {
// throw new IllegalStateException();
// }
// return new String[]
// {
// cluster
// };
// }
//
// }
| import org.n0pe.asadmin.commands.Cluster;
import org.n0pe.asadmin.AsAdminCmdList;
| /*
* Copyright (c) 2011, J. Francis.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
*/
package org.n0pe.mojo.asadmin;
/**
* @goal start-cluster
* @description AsAdmin start-cluster mojo
*/
public class StartClusterMojo
extends AbstractAsadminMojo
{
@Override
protected AsAdminCmdList getAsCommandList()
{
getLog().info( "Starting cluster: " + cluster );
final AsAdminCmdList list = new AsAdminCmdList();
| // Path: asadmin-java/src/main/java/org/n0pe/asadmin/AsAdminCmdList.java
// public class AsAdminCmdList
// extends ArrayList<IAsAdminCmd>
// {
//
// private static final long serialVersionUID = 1L;
//
// public AsAdminCmdList()
// {
// super();
// }
//
// }
//
// Path: asadmin-java/src/main/java/org/n0pe/asadmin/commands/Cluster.java
// public class Cluster
// extends AbstractAsAdminCmd
// {
//
// public static final String START = "start-cluster";
// public static final String STOP = "stop-cluster";
// private Boolean start = null;
// private String cluster;
//
// public Cluster( String cluster )
// {
// this.cluster = cluster;
// }
//
// public Cluster start()
// {
// start = Boolean.TRUE;
// return this;
// }
//
// public Cluster stop()
// {
// start = Boolean.FALSE;
// return this;
// }
//
// public boolean needCredentials()
// {
// return true;
// }
//
// public String getActionCommand()
// {
// if( start == null )
// {
// throw new IllegalStateException();
// }
// return start.booleanValue()
// ? START
// : STOP;
// }
//
// public String[] getParameters()
// {
// if( start == null )
// {
// throw new IllegalStateException();
// }
// return new String[]
// {
// cluster
// };
// }
//
// }
// Path: asadmin-maven-plugin/src/main/java/org/n0pe/mojo/asadmin/StartClusterMojo.java
import org.n0pe.asadmin.commands.Cluster;
import org.n0pe.asadmin.AsAdminCmdList;
/*
* Copyright (c) 2011, J. Francis.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
*/
package org.n0pe.mojo.asadmin;
/**
* @goal start-cluster
* @description AsAdmin start-cluster mojo
*/
public class StartClusterMojo
extends AbstractAsadminMojo
{
@Override
protected AsAdminCmdList getAsCommandList()
{
getLog().info( "Starting cluster: " + cluster );
final AsAdminCmdList list = new AsAdminCmdList();
| Cluster clusterCmd = new Cluster( cluster ).start();
|
eskatos/asadmin | asadmin-maven-plugin/src/main/java/org/n0pe/mojo/asadmin/StopDatabaseMojo.java | // Path: asadmin-java/src/main/java/org/n0pe/asadmin/AsAdminCmdList.java
// public class AsAdminCmdList
// extends ArrayList<IAsAdminCmd>
// {
//
// private static final long serialVersionUID = 1L;
//
// public AsAdminCmdList()
// {
// super();
// }
//
// }
//
// Path: asadmin-java/src/main/java/org/n0pe/asadmin/commands/Database.java
// public class Database
// extends AbstractAsAdminCmd
// {
//
// public static final String START = "start-database";
// public static final String STOP = "stop-database";
// public static final String DB_HOST = "--dbhost";
// public static final String DB_PORT = "--dbport";
// private Boolean start = null;
// private String dbHost;
// private String dbPort;
//
// /**
// * Database CTOR.
// */
// public Database()
// {
// }
//
// public Database( String dbHost, String dbPort )
// {
// this.dbHost = dbHost;
// this.dbPort = dbPort;
// }
//
// public Database setDbHost( String dbHost )
// {
// this.dbHost = dbHost;
// return this;
// }
//
// public Database setDbPort( String dbPort )
// {
// this.dbPort = dbPort;
// return this;
// }
//
// public Database start()
// {
// start = Boolean.TRUE;
// return this;
// }
//
// public Database stop()
// {
// start = Boolean.FALSE;
// return this;
// }
//
// public boolean needCredentials()
// {
// return false;
// }
//
// public String getActionCommand()
// {
// if( start == null )
// {
// throw new IllegalStateException();
// }
// return start.booleanValue()
// ? START
// : STOP;
// }
//
// public String[] getParameters()
// {
// final List<String> params = new ArrayList<String>();
// if( isSet( dbHost ) )
// {
// params.add( DB_HOST );
// params.add( dbHost );
// }
// if( isSet( dbPort ) )
// {
// params.add( DB_PORT );
// params.add( dbPort );
// }
// return params.toArray( new String[ 0 ] );
// }
//
// private final boolean isSet( String str )
// {
// return str != null && str.trim().length() > 0;
// }
//
// }
| import org.n0pe.asadmin.AsAdminCmdList;
import org.n0pe.asadmin.commands.Database;
| /*
* Copyright (c) 2010, Paul Merlin.
* Copyright (c) 2011, Marenz.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
*/
package org.n0pe.mojo.asadmin;
/**
* @goal stop-database
* @description AsAdmin stop-database mojo
*/
public class StopDatabaseMojo
extends AbstractAsadminMojo
{
@Override
| // Path: asadmin-java/src/main/java/org/n0pe/asadmin/AsAdminCmdList.java
// public class AsAdminCmdList
// extends ArrayList<IAsAdminCmd>
// {
//
// private static final long serialVersionUID = 1L;
//
// public AsAdminCmdList()
// {
// super();
// }
//
// }
//
// Path: asadmin-java/src/main/java/org/n0pe/asadmin/commands/Database.java
// public class Database
// extends AbstractAsAdminCmd
// {
//
// public static final String START = "start-database";
// public static final String STOP = "stop-database";
// public static final String DB_HOST = "--dbhost";
// public static final String DB_PORT = "--dbport";
// private Boolean start = null;
// private String dbHost;
// private String dbPort;
//
// /**
// * Database CTOR.
// */
// public Database()
// {
// }
//
// public Database( String dbHost, String dbPort )
// {
// this.dbHost = dbHost;
// this.dbPort = dbPort;
// }
//
// public Database setDbHost( String dbHost )
// {
// this.dbHost = dbHost;
// return this;
// }
//
// public Database setDbPort( String dbPort )
// {
// this.dbPort = dbPort;
// return this;
// }
//
// public Database start()
// {
// start = Boolean.TRUE;
// return this;
// }
//
// public Database stop()
// {
// start = Boolean.FALSE;
// return this;
// }
//
// public boolean needCredentials()
// {
// return false;
// }
//
// public String getActionCommand()
// {
// if( start == null )
// {
// throw new IllegalStateException();
// }
// return start.booleanValue()
// ? START
// : STOP;
// }
//
// public String[] getParameters()
// {
// final List<String> params = new ArrayList<String>();
// if( isSet( dbHost ) )
// {
// params.add( DB_HOST );
// params.add( dbHost );
// }
// if( isSet( dbPort ) )
// {
// params.add( DB_PORT );
// params.add( dbPort );
// }
// return params.toArray( new String[ 0 ] );
// }
//
// private final boolean isSet( String str )
// {
// return str != null && str.trim().length() > 0;
// }
//
// }
// Path: asadmin-maven-plugin/src/main/java/org/n0pe/mojo/asadmin/StopDatabaseMojo.java
import org.n0pe.asadmin.AsAdminCmdList;
import org.n0pe.asadmin.commands.Database;
/*
* Copyright (c) 2010, Paul Merlin.
* Copyright (c) 2011, Marenz.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
*/
package org.n0pe.mojo.asadmin;
/**
* @goal stop-database
* @description AsAdmin stop-database mojo
*/
public class StopDatabaseMojo
extends AbstractAsadminMojo
{
@Override
| protected AsAdminCmdList getAsCommandList()
|
eskatos/asadmin | asadmin-maven-plugin/src/main/java/org/n0pe/mojo/asadmin/StopDatabaseMojo.java | // Path: asadmin-java/src/main/java/org/n0pe/asadmin/AsAdminCmdList.java
// public class AsAdminCmdList
// extends ArrayList<IAsAdminCmd>
// {
//
// private static final long serialVersionUID = 1L;
//
// public AsAdminCmdList()
// {
// super();
// }
//
// }
//
// Path: asadmin-java/src/main/java/org/n0pe/asadmin/commands/Database.java
// public class Database
// extends AbstractAsAdminCmd
// {
//
// public static final String START = "start-database";
// public static final String STOP = "stop-database";
// public static final String DB_HOST = "--dbhost";
// public static final String DB_PORT = "--dbport";
// private Boolean start = null;
// private String dbHost;
// private String dbPort;
//
// /**
// * Database CTOR.
// */
// public Database()
// {
// }
//
// public Database( String dbHost, String dbPort )
// {
// this.dbHost = dbHost;
// this.dbPort = dbPort;
// }
//
// public Database setDbHost( String dbHost )
// {
// this.dbHost = dbHost;
// return this;
// }
//
// public Database setDbPort( String dbPort )
// {
// this.dbPort = dbPort;
// return this;
// }
//
// public Database start()
// {
// start = Boolean.TRUE;
// return this;
// }
//
// public Database stop()
// {
// start = Boolean.FALSE;
// return this;
// }
//
// public boolean needCredentials()
// {
// return false;
// }
//
// public String getActionCommand()
// {
// if( start == null )
// {
// throw new IllegalStateException();
// }
// return start.booleanValue()
// ? START
// : STOP;
// }
//
// public String[] getParameters()
// {
// final List<String> params = new ArrayList<String>();
// if( isSet( dbHost ) )
// {
// params.add( DB_HOST );
// params.add( dbHost );
// }
// if( isSet( dbPort ) )
// {
// params.add( DB_PORT );
// params.add( dbPort );
// }
// return params.toArray( new String[ 0 ] );
// }
//
// private final boolean isSet( String str )
// {
// return str != null && str.trim().length() > 0;
// }
//
// }
| import org.n0pe.asadmin.AsAdminCmdList;
import org.n0pe.asadmin.commands.Database;
| /*
* Copyright (c) 2010, Paul Merlin.
* Copyright (c) 2011, Marenz.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
*/
package org.n0pe.mojo.asadmin;
/**
* @goal stop-database
* @description AsAdmin stop-database mojo
*/
public class StopDatabaseMojo
extends AbstractAsadminMojo
{
@Override
protected AsAdminCmdList getAsCommandList()
{
getLog().info( "Stopping database" );
final AsAdminCmdList list = new AsAdminCmdList();
| // Path: asadmin-java/src/main/java/org/n0pe/asadmin/AsAdminCmdList.java
// public class AsAdminCmdList
// extends ArrayList<IAsAdminCmd>
// {
//
// private static final long serialVersionUID = 1L;
//
// public AsAdminCmdList()
// {
// super();
// }
//
// }
//
// Path: asadmin-java/src/main/java/org/n0pe/asadmin/commands/Database.java
// public class Database
// extends AbstractAsAdminCmd
// {
//
// public static final String START = "start-database";
// public static final String STOP = "stop-database";
// public static final String DB_HOST = "--dbhost";
// public static final String DB_PORT = "--dbport";
// private Boolean start = null;
// private String dbHost;
// private String dbPort;
//
// /**
// * Database CTOR.
// */
// public Database()
// {
// }
//
// public Database( String dbHost, String dbPort )
// {
// this.dbHost = dbHost;
// this.dbPort = dbPort;
// }
//
// public Database setDbHost( String dbHost )
// {
// this.dbHost = dbHost;
// return this;
// }
//
// public Database setDbPort( String dbPort )
// {
// this.dbPort = dbPort;
// return this;
// }
//
// public Database start()
// {
// start = Boolean.TRUE;
// return this;
// }
//
// public Database stop()
// {
// start = Boolean.FALSE;
// return this;
// }
//
// public boolean needCredentials()
// {
// return false;
// }
//
// public String getActionCommand()
// {
// if( start == null )
// {
// throw new IllegalStateException();
// }
// return start.booleanValue()
// ? START
// : STOP;
// }
//
// public String[] getParameters()
// {
// final List<String> params = new ArrayList<String>();
// if( isSet( dbHost ) )
// {
// params.add( DB_HOST );
// params.add( dbHost );
// }
// if( isSet( dbPort ) )
// {
// params.add( DB_PORT );
// params.add( dbPort );
// }
// return params.toArray( new String[ 0 ] );
// }
//
// private final boolean isSet( String str )
// {
// return str != null && str.trim().length() > 0;
// }
//
// }
// Path: asadmin-maven-plugin/src/main/java/org/n0pe/mojo/asadmin/StopDatabaseMojo.java
import org.n0pe.asadmin.AsAdminCmdList;
import org.n0pe.asadmin.commands.Database;
/*
* Copyright (c) 2010, Paul Merlin.
* Copyright (c) 2011, Marenz.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
*/
package org.n0pe.mojo.asadmin;
/**
* @goal stop-database
* @description AsAdmin stop-database mojo
*/
public class StopDatabaseMojo
extends AbstractAsadminMojo
{
@Override
protected AsAdminCmdList getAsCommandList()
{
getLog().info( "Stopping database" );
final AsAdminCmdList list = new AsAdminCmdList();
| list.add( new Database( dbHost, dbPort ).stop() );
|
eskatos/asadmin | asadmin-java/src/main/java/org/n0pe/asadmin/commands/ListFileUsers.java | // Path: asadmin-java/src/main/java/org/n0pe/asadmin/AbstractAsAdminCmd.java
// public abstract class AbstractAsAdminCmd
// implements IAsAdminCmd
// {
//
// public static final String[] EMPTY_ARRAY = new String[ 0 ];
// private final StringBuilder stdoutBuilder = new StringBuilder();
// private final StringBuilder stderrBuilder = new StringBuilder();
// private Pattern okayErrorPattern = null;
// private Pattern okayStdOutPattern = null;
//
// @Override
// public final Reader getStandardOutput()
// {
// return new CharSequenceReader( stdoutBuilder );
// }
//
// @Override
// public final Reader getErrorOutput()
// {
// return new CharSequenceReader( stderrBuilder );
// }
//
// @Override
// public boolean failOnNonZeroExit()
// {
// if( okayErrorPattern == null )
// {
// if( okayStdOutPattern == null )
// {
// return true;
// }
// else
// {
// return !okayStdOutPattern.matcher( stdoutBuilder.toString() ).matches();
// }
// }
// else
// {
// boolean stderrorNotOK = !okayErrorPattern.matcher( stderrBuilder.toString() ).matches();
// if( okayStdOutPattern == null )
// {
// return stderrorNotOK;
// }
// else
// {
// return !okayStdOutPattern.matcher( stdoutBuilder.toString() ).matches();
// }
//
// }
// }
//
// @Override
// public void setOkayErrorPattern( Pattern pattern )
// {
// this.okayErrorPattern = pattern;
// }
//
// @Override
// public void setOkayStdOutPattern( Pattern pattern )
// {
// this.okayStdOutPattern = pattern;
// }
//
// public String handlePasswordFile( String configuredPasswordFile )
// throws AsAdminException
// {
// return configuredPasswordFile;
// }
//
// final void appendStandardOutputLine( String line )
// {
// //System.out.println("Out: " + line);
// stdoutBuilder.append( line ).append( "\n" );
// }
//
// final void appendErrorOutputLine( String line )
// {
// //System.err.println("Err: " + line);
// stderrBuilder.append( line ).append( "\n" );
// }
//
// }
//
// Path: asadmin-java/src/main/java/org/n0pe/asadmin/AsAdminException.java
// public class AsAdminException
// extends NestableException
// {
//
// private static final long serialVersionUID = 1L;
//
// public AsAdminException()
// {
// }
//
// public AsAdminException( final String message )
// {
// super( message );
// }
//
// public AsAdminException( final String message, Throwable cause )
// {
// super( message, cause );
// }
//
// }
| import java.io.BufferedReader;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import org.n0pe.asadmin.AbstractAsAdminCmd;
import org.n0pe.asadmin.AsAdminException; | /*
* Copyright (c) 2010, Christophe Souvignier.
* Copyright (c) 2010, Paul Merlin.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
*/
package org.n0pe.asadmin.commands;
public class ListFileUsers
extends AbstractAsAdminCmd
{
public static final String LIST_FILE_USER = "list-file-users";
@Override
public boolean needCredentials()
{
return true;
}
@Override
public String getActionCommand()
{
return LIST_FILE_USER;
}
@Override
public String[] getParameters()
{
return new String[]
{
};
}
public List<String> getUsers() | // Path: asadmin-java/src/main/java/org/n0pe/asadmin/AbstractAsAdminCmd.java
// public abstract class AbstractAsAdminCmd
// implements IAsAdminCmd
// {
//
// public static final String[] EMPTY_ARRAY = new String[ 0 ];
// private final StringBuilder stdoutBuilder = new StringBuilder();
// private final StringBuilder stderrBuilder = new StringBuilder();
// private Pattern okayErrorPattern = null;
// private Pattern okayStdOutPattern = null;
//
// @Override
// public final Reader getStandardOutput()
// {
// return new CharSequenceReader( stdoutBuilder );
// }
//
// @Override
// public final Reader getErrorOutput()
// {
// return new CharSequenceReader( stderrBuilder );
// }
//
// @Override
// public boolean failOnNonZeroExit()
// {
// if( okayErrorPattern == null )
// {
// if( okayStdOutPattern == null )
// {
// return true;
// }
// else
// {
// return !okayStdOutPattern.matcher( stdoutBuilder.toString() ).matches();
// }
// }
// else
// {
// boolean stderrorNotOK = !okayErrorPattern.matcher( stderrBuilder.toString() ).matches();
// if( okayStdOutPattern == null )
// {
// return stderrorNotOK;
// }
// else
// {
// return !okayStdOutPattern.matcher( stdoutBuilder.toString() ).matches();
// }
//
// }
// }
//
// @Override
// public void setOkayErrorPattern( Pattern pattern )
// {
// this.okayErrorPattern = pattern;
// }
//
// @Override
// public void setOkayStdOutPattern( Pattern pattern )
// {
// this.okayStdOutPattern = pattern;
// }
//
// public String handlePasswordFile( String configuredPasswordFile )
// throws AsAdminException
// {
// return configuredPasswordFile;
// }
//
// final void appendStandardOutputLine( String line )
// {
// //System.out.println("Out: " + line);
// stdoutBuilder.append( line ).append( "\n" );
// }
//
// final void appendErrorOutputLine( String line )
// {
// //System.err.println("Err: " + line);
// stderrBuilder.append( line ).append( "\n" );
// }
//
// }
//
// Path: asadmin-java/src/main/java/org/n0pe/asadmin/AsAdminException.java
// public class AsAdminException
// extends NestableException
// {
//
// private static final long serialVersionUID = 1L;
//
// public AsAdminException()
// {
// }
//
// public AsAdminException( final String message )
// {
// super( message );
// }
//
// public AsAdminException( final String message, Throwable cause )
// {
// super( message, cause );
// }
//
// }
// Path: asadmin-java/src/main/java/org/n0pe/asadmin/commands/ListFileUsers.java
import java.io.BufferedReader;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import org.n0pe.asadmin.AbstractAsAdminCmd;
import org.n0pe.asadmin.AsAdminException;
/*
* Copyright (c) 2010, Christophe Souvignier.
* Copyright (c) 2010, Paul Merlin.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
*/
package org.n0pe.asadmin.commands;
public class ListFileUsers
extends AbstractAsAdminCmd
{
public static final String LIST_FILE_USER = "list-file-users";
@Override
public boolean needCredentials()
{
return true;
}
@Override
public String getActionCommand()
{
return LIST_FILE_USER;
}
@Override
public String[] getParameters()
{
return new String[]
{
};
}
public List<String> getUsers() | throws AsAdminException |
eskatos/asadmin | asadmin-maven-plugin/src/main/java/org/n0pe/mojo/asadmin/DeleteFileUserMojo.java | // Path: asadmin-java/src/main/java/org/n0pe/asadmin/AsAdminCmdList.java
// public class AsAdminCmdList
// extends ArrayList<IAsAdminCmd>
// {
//
// private static final long serialVersionUID = 1L;
//
// public AsAdminCmdList()
// {
// super();
// }
//
// }
//
// Path: asadmin-java/src/main/java/org/n0pe/asadmin/commands/DeleteFileUser.java
// public class DeleteFileUser
// extends AbstractAsAdminCmd
// {
//
// public static final String DELETE_FILE_USER = "delete-file-user";
// private String userName;
//
// /**
// * DeleteFileUser default constructor.
// */
// private DeleteFileUser()
// {
// }
//
// public DeleteFileUser( String userName )
// {
// this.userName = userName;
// }
//
// @Override
// public boolean needCredentials()
// {
// return true;
// }
//
// @Override
// public String getActionCommand()
// {
// if( userName == null )
// {
// throw new IllegalStateException();
// }
// return DELETE_FILE_USER;
// }
//
// @Override
// public String[] getParameters()
// {
// final String[] params;
// params = new String[]
// {
// userName
// };
// return params;
// }
//
// }
| import org.apache.maven.plugin.MojoFailureException;
import org.n0pe.asadmin.AsAdminCmdList;
import org.n0pe.asadmin.commands.DeleteFileUser;
import org.apache.maven.plugin.MojoExecutionException; | /*
* Copyright (c) 2010, Paul Merlin.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
*/
package org.n0pe.mojo.asadmin;
/**
* @goal delete-file-user
*/
public class DeleteFileUserMojo
extends AbstractAsadminMojo
{
/**
* @parameter
* @required
*/
private String userName;
@Override | // Path: asadmin-java/src/main/java/org/n0pe/asadmin/AsAdminCmdList.java
// public class AsAdminCmdList
// extends ArrayList<IAsAdminCmd>
// {
//
// private static final long serialVersionUID = 1L;
//
// public AsAdminCmdList()
// {
// super();
// }
//
// }
//
// Path: asadmin-java/src/main/java/org/n0pe/asadmin/commands/DeleteFileUser.java
// public class DeleteFileUser
// extends AbstractAsAdminCmd
// {
//
// public static final String DELETE_FILE_USER = "delete-file-user";
// private String userName;
//
// /**
// * DeleteFileUser default constructor.
// */
// private DeleteFileUser()
// {
// }
//
// public DeleteFileUser( String userName )
// {
// this.userName = userName;
// }
//
// @Override
// public boolean needCredentials()
// {
// return true;
// }
//
// @Override
// public String getActionCommand()
// {
// if( userName == null )
// {
// throw new IllegalStateException();
// }
// return DELETE_FILE_USER;
// }
//
// @Override
// public String[] getParameters()
// {
// final String[] params;
// params = new String[]
// {
// userName
// };
// return params;
// }
//
// }
// Path: asadmin-maven-plugin/src/main/java/org/n0pe/mojo/asadmin/DeleteFileUserMojo.java
import org.apache.maven.plugin.MojoFailureException;
import org.n0pe.asadmin.AsAdminCmdList;
import org.n0pe.asadmin.commands.DeleteFileUser;
import org.apache.maven.plugin.MojoExecutionException;
/*
* Copyright (c) 2010, Paul Merlin.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
*/
package org.n0pe.mojo.asadmin;
/**
* @goal delete-file-user
*/
public class DeleteFileUserMojo
extends AbstractAsadminMojo
{
/**
* @parameter
* @required
*/
private String userName;
@Override | protected AsAdminCmdList getAsCommandList() |
eskatos/asadmin | asadmin-maven-plugin/src/main/java/org/n0pe/mojo/asadmin/DeleteFileUserMojo.java | // Path: asadmin-java/src/main/java/org/n0pe/asadmin/AsAdminCmdList.java
// public class AsAdminCmdList
// extends ArrayList<IAsAdminCmd>
// {
//
// private static final long serialVersionUID = 1L;
//
// public AsAdminCmdList()
// {
// super();
// }
//
// }
//
// Path: asadmin-java/src/main/java/org/n0pe/asadmin/commands/DeleteFileUser.java
// public class DeleteFileUser
// extends AbstractAsAdminCmd
// {
//
// public static final String DELETE_FILE_USER = "delete-file-user";
// private String userName;
//
// /**
// * DeleteFileUser default constructor.
// */
// private DeleteFileUser()
// {
// }
//
// public DeleteFileUser( String userName )
// {
// this.userName = userName;
// }
//
// @Override
// public boolean needCredentials()
// {
// return true;
// }
//
// @Override
// public String getActionCommand()
// {
// if( userName == null )
// {
// throw new IllegalStateException();
// }
// return DELETE_FILE_USER;
// }
//
// @Override
// public String[] getParameters()
// {
// final String[] params;
// params = new String[]
// {
// userName
// };
// return params;
// }
//
// }
| import org.apache.maven.plugin.MojoFailureException;
import org.n0pe.asadmin.AsAdminCmdList;
import org.n0pe.asadmin.commands.DeleteFileUser;
import org.apache.maven.plugin.MojoExecutionException; | /*
* Copyright (c) 2010, Paul Merlin.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
*/
package org.n0pe.mojo.asadmin;
/**
* @goal delete-file-user
*/
public class DeleteFileUserMojo
extends AbstractAsadminMojo
{
/**
* @parameter
* @required
*/
private String userName;
@Override
protected AsAdminCmdList getAsCommandList()
throws MojoExecutionException, MojoFailureException
{
getLog().info( "Delete file user: " + userName );
AsAdminCmdList cmdList = new AsAdminCmdList(); | // Path: asadmin-java/src/main/java/org/n0pe/asadmin/AsAdminCmdList.java
// public class AsAdminCmdList
// extends ArrayList<IAsAdminCmd>
// {
//
// private static final long serialVersionUID = 1L;
//
// public AsAdminCmdList()
// {
// super();
// }
//
// }
//
// Path: asadmin-java/src/main/java/org/n0pe/asadmin/commands/DeleteFileUser.java
// public class DeleteFileUser
// extends AbstractAsAdminCmd
// {
//
// public static final String DELETE_FILE_USER = "delete-file-user";
// private String userName;
//
// /**
// * DeleteFileUser default constructor.
// */
// private DeleteFileUser()
// {
// }
//
// public DeleteFileUser( String userName )
// {
// this.userName = userName;
// }
//
// @Override
// public boolean needCredentials()
// {
// return true;
// }
//
// @Override
// public String getActionCommand()
// {
// if( userName == null )
// {
// throw new IllegalStateException();
// }
// return DELETE_FILE_USER;
// }
//
// @Override
// public String[] getParameters()
// {
// final String[] params;
// params = new String[]
// {
// userName
// };
// return params;
// }
//
// }
// Path: asadmin-maven-plugin/src/main/java/org/n0pe/mojo/asadmin/DeleteFileUserMojo.java
import org.apache.maven.plugin.MojoFailureException;
import org.n0pe.asadmin.AsAdminCmdList;
import org.n0pe.asadmin.commands.DeleteFileUser;
import org.apache.maven.plugin.MojoExecutionException;
/*
* Copyright (c) 2010, Paul Merlin.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
*/
package org.n0pe.mojo.asadmin;
/**
* @goal delete-file-user
*/
public class DeleteFileUserMojo
extends AbstractAsadminMojo
{
/**
* @parameter
* @required
*/
private String userName;
@Override
protected AsAdminCmdList getAsCommandList()
throws MojoExecutionException, MojoFailureException
{
getLog().info( "Delete file user: " + userName );
AsAdminCmdList cmdList = new AsAdminCmdList(); | cmdList.add( new DeleteFileUser( userName ) ); |
eskatos/asadmin | asadmin-java/src/main/java/org/n0pe/asadmin/commands/CreateAuthRealm.java | // Path: asadmin-java/src/main/java/org/n0pe/asadmin/AbstractAsAdminCmd.java
// public abstract class AbstractAsAdminCmd
// implements IAsAdminCmd
// {
//
// public static final String[] EMPTY_ARRAY = new String[ 0 ];
// private final StringBuilder stdoutBuilder = new StringBuilder();
// private final StringBuilder stderrBuilder = new StringBuilder();
// private Pattern okayErrorPattern = null;
// private Pattern okayStdOutPattern = null;
//
// @Override
// public final Reader getStandardOutput()
// {
// return new CharSequenceReader( stdoutBuilder );
// }
//
// @Override
// public final Reader getErrorOutput()
// {
// return new CharSequenceReader( stderrBuilder );
// }
//
// @Override
// public boolean failOnNonZeroExit()
// {
// if( okayErrorPattern == null )
// {
// if( okayStdOutPattern == null )
// {
// return true;
// }
// else
// {
// return !okayStdOutPattern.matcher( stdoutBuilder.toString() ).matches();
// }
// }
// else
// {
// boolean stderrorNotOK = !okayErrorPattern.matcher( stderrBuilder.toString() ).matches();
// if( okayStdOutPattern == null )
// {
// return stderrorNotOK;
// }
// else
// {
// return !okayStdOutPattern.matcher( stdoutBuilder.toString() ).matches();
// }
//
// }
// }
//
// @Override
// public void setOkayErrorPattern( Pattern pattern )
// {
// this.okayErrorPattern = pattern;
// }
//
// @Override
// public void setOkayStdOutPattern( Pattern pattern )
// {
// this.okayStdOutPattern = pattern;
// }
//
// public String handlePasswordFile( String configuredPasswordFile )
// throws AsAdminException
// {
// return configuredPasswordFile;
// }
//
// final void appendStandardOutputLine( String line )
// {
// //System.out.println("Out: " + line);
// stdoutBuilder.append( line ).append( "\n" );
// }
//
// final void appendErrorOutputLine( String line )
// {
// //System.err.println("Err: " + line);
// stderrBuilder.append( line ).append( "\n" );
// }
//
// }
//
// Path: asadmin-java/src/main/java/org/n0pe/asadmin/Util.java
// public final class Util
// {
//
// public static String quoteCommandArgument( String s )
// {
// return new StringBuilder( s.length() + 2 ).append( "\"" ).append( s ).append( "\"" ).toString();
// }
//
// private Util()
// {
// }
//
// }
| import java.io.StringWriter;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;
import org.apache.commons.lang.StringUtils;
import org.n0pe.asadmin.AbstractAsAdminCmd;
import org.n0pe.asadmin.Util; | properties = new HashMap();
}
properties.put( key, value );
return this;
}
public boolean needCredentials()
{
return true;
}
public String getActionCommand()
{
return "create-auth-realm";
}
public String[] getParameters()
{
if( StringUtils.isEmpty( className ) )
{
throw new IllegalStateException();
}
final String[] params;
if( properties != null && !properties.isEmpty() )
{
final StringWriter sw = new StringWriter();
String key;
for( final Iterator it = properties.keySet().iterator(); it.hasNext(); )
{
key = (String) it.next(); | // Path: asadmin-java/src/main/java/org/n0pe/asadmin/AbstractAsAdminCmd.java
// public abstract class AbstractAsAdminCmd
// implements IAsAdminCmd
// {
//
// public static final String[] EMPTY_ARRAY = new String[ 0 ];
// private final StringBuilder stdoutBuilder = new StringBuilder();
// private final StringBuilder stderrBuilder = new StringBuilder();
// private Pattern okayErrorPattern = null;
// private Pattern okayStdOutPattern = null;
//
// @Override
// public final Reader getStandardOutput()
// {
// return new CharSequenceReader( stdoutBuilder );
// }
//
// @Override
// public final Reader getErrorOutput()
// {
// return new CharSequenceReader( stderrBuilder );
// }
//
// @Override
// public boolean failOnNonZeroExit()
// {
// if( okayErrorPattern == null )
// {
// if( okayStdOutPattern == null )
// {
// return true;
// }
// else
// {
// return !okayStdOutPattern.matcher( stdoutBuilder.toString() ).matches();
// }
// }
// else
// {
// boolean stderrorNotOK = !okayErrorPattern.matcher( stderrBuilder.toString() ).matches();
// if( okayStdOutPattern == null )
// {
// return stderrorNotOK;
// }
// else
// {
// return !okayStdOutPattern.matcher( stdoutBuilder.toString() ).matches();
// }
//
// }
// }
//
// @Override
// public void setOkayErrorPattern( Pattern pattern )
// {
// this.okayErrorPattern = pattern;
// }
//
// @Override
// public void setOkayStdOutPattern( Pattern pattern )
// {
// this.okayStdOutPattern = pattern;
// }
//
// public String handlePasswordFile( String configuredPasswordFile )
// throws AsAdminException
// {
// return configuredPasswordFile;
// }
//
// final void appendStandardOutputLine( String line )
// {
// //System.out.println("Out: " + line);
// stdoutBuilder.append( line ).append( "\n" );
// }
//
// final void appendErrorOutputLine( String line )
// {
// //System.err.println("Err: " + line);
// stderrBuilder.append( line ).append( "\n" );
// }
//
// }
//
// Path: asadmin-java/src/main/java/org/n0pe/asadmin/Util.java
// public final class Util
// {
//
// public static String quoteCommandArgument( String s )
// {
// return new StringBuilder( s.length() + 2 ).append( "\"" ).append( s ).append( "\"" ).toString();
// }
//
// private Util()
// {
// }
//
// }
// Path: asadmin-java/src/main/java/org/n0pe/asadmin/commands/CreateAuthRealm.java
import java.io.StringWriter;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;
import org.apache.commons.lang.StringUtils;
import org.n0pe.asadmin.AbstractAsAdminCmd;
import org.n0pe.asadmin.Util;
properties = new HashMap();
}
properties.put( key, value );
return this;
}
public boolean needCredentials()
{
return true;
}
public String getActionCommand()
{
return "create-auth-realm";
}
public String[] getParameters()
{
if( StringUtils.isEmpty( className ) )
{
throw new IllegalStateException();
}
final String[] params;
if( properties != null && !properties.isEmpty() )
{
final StringWriter sw = new StringWriter();
String key;
for( final Iterator it = properties.keySet().iterator(); it.hasNext(); )
{
key = (String) it.next(); | sw.append( key ).append( "=" ).append( Util.quoteCommandArgument( (String) properties.get( key ) ) ); |
eskatos/asadmin | asadmin-maven-plugin/src/main/java/org/n0pe/mojo/asadmin/DeleteJdbcResourceMojo.java | // Path: asadmin-java/src/main/java/org/n0pe/asadmin/AsAdminCmdList.java
// public class AsAdminCmdList
// extends ArrayList<IAsAdminCmd>
// {
//
// private static final long serialVersionUID = 1L;
//
// public AsAdminCmdList()
// {
// super();
// }
//
// }
//
// Path: asadmin-java/src/main/java/org/n0pe/asadmin/commands/DeleteJdbcResource.java
// public class DeleteJdbcResource
// extends AbstractAsAdminCmd
// {
//
// public static final String JDBC = "delete-jdbc-resource";
// private String resourceName;
//
// private DeleteJdbcResource()
// {
// }
//
// public DeleteJdbcResource( String resourceName )
// {
// this.resourceName = resourceName;
// }
//
// public boolean needCredentials()
// {
// return true;
// }
//
// public String getActionCommand()
// {
// if( resourceName == null )
// {
// throw new IllegalStateException();
// }
// return JDBC;
// }
//
// public String[] getParameters()
// {
// return new String[]
// {
// resourceName
// };
// }
//
// }
| import org.apache.maven.plugin.MojoExecutionException;
import org.apache.maven.plugin.MojoFailureException;
import org.n0pe.asadmin.AsAdminCmdList;
import org.n0pe.asadmin.commands.DeleteJdbcResource; | /*
* Copyright (c) 2010, Christophe Souvignier.
* Copyright (c) 2010, Paul Merlin.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
*/
package org.n0pe.mojo.asadmin;
/**
* @goal delete-jdbc-resource
*/
public class DeleteJdbcResourceMojo
extends AbstractAsadminMojo
{
/**
* @parameter
* @required
*/
private String resourceName;
@Override | // Path: asadmin-java/src/main/java/org/n0pe/asadmin/AsAdminCmdList.java
// public class AsAdminCmdList
// extends ArrayList<IAsAdminCmd>
// {
//
// private static final long serialVersionUID = 1L;
//
// public AsAdminCmdList()
// {
// super();
// }
//
// }
//
// Path: asadmin-java/src/main/java/org/n0pe/asadmin/commands/DeleteJdbcResource.java
// public class DeleteJdbcResource
// extends AbstractAsAdminCmd
// {
//
// public static final String JDBC = "delete-jdbc-resource";
// private String resourceName;
//
// private DeleteJdbcResource()
// {
// }
//
// public DeleteJdbcResource( String resourceName )
// {
// this.resourceName = resourceName;
// }
//
// public boolean needCredentials()
// {
// return true;
// }
//
// public String getActionCommand()
// {
// if( resourceName == null )
// {
// throw new IllegalStateException();
// }
// return JDBC;
// }
//
// public String[] getParameters()
// {
// return new String[]
// {
// resourceName
// };
// }
//
// }
// Path: asadmin-maven-plugin/src/main/java/org/n0pe/mojo/asadmin/DeleteJdbcResourceMojo.java
import org.apache.maven.plugin.MojoExecutionException;
import org.apache.maven.plugin.MojoFailureException;
import org.n0pe.asadmin.AsAdminCmdList;
import org.n0pe.asadmin.commands.DeleteJdbcResource;
/*
* Copyright (c) 2010, Christophe Souvignier.
* Copyright (c) 2010, Paul Merlin.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
*/
package org.n0pe.mojo.asadmin;
/**
* @goal delete-jdbc-resource
*/
public class DeleteJdbcResourceMojo
extends AbstractAsadminMojo
{
/**
* @parameter
* @required
*/
private String resourceName;
@Override | protected AsAdminCmdList getAsCommandList() |
eskatos/asadmin | asadmin-maven-plugin/src/main/java/org/n0pe/mojo/asadmin/DeleteJdbcResourceMojo.java | // Path: asadmin-java/src/main/java/org/n0pe/asadmin/AsAdminCmdList.java
// public class AsAdminCmdList
// extends ArrayList<IAsAdminCmd>
// {
//
// private static final long serialVersionUID = 1L;
//
// public AsAdminCmdList()
// {
// super();
// }
//
// }
//
// Path: asadmin-java/src/main/java/org/n0pe/asadmin/commands/DeleteJdbcResource.java
// public class DeleteJdbcResource
// extends AbstractAsAdminCmd
// {
//
// public static final String JDBC = "delete-jdbc-resource";
// private String resourceName;
//
// private DeleteJdbcResource()
// {
// }
//
// public DeleteJdbcResource( String resourceName )
// {
// this.resourceName = resourceName;
// }
//
// public boolean needCredentials()
// {
// return true;
// }
//
// public String getActionCommand()
// {
// if( resourceName == null )
// {
// throw new IllegalStateException();
// }
// return JDBC;
// }
//
// public String[] getParameters()
// {
// return new String[]
// {
// resourceName
// };
// }
//
// }
| import org.apache.maven.plugin.MojoExecutionException;
import org.apache.maven.plugin.MojoFailureException;
import org.n0pe.asadmin.AsAdminCmdList;
import org.n0pe.asadmin.commands.DeleteJdbcResource; | /*
* Copyright (c) 2010, Christophe Souvignier.
* Copyright (c) 2010, Paul Merlin.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
*/
package org.n0pe.mojo.asadmin;
/**
* @goal delete-jdbc-resource
*/
public class DeleteJdbcResourceMojo
extends AbstractAsadminMojo
{
/**
* @parameter
* @required
*/
private String resourceName;
@Override
protected AsAdminCmdList getAsCommandList()
throws MojoExecutionException, MojoFailureException
{
getLog().info( "Delete jdbc resource: " + resourceName );
final AsAdminCmdList list = new AsAdminCmdList(); | // Path: asadmin-java/src/main/java/org/n0pe/asadmin/AsAdminCmdList.java
// public class AsAdminCmdList
// extends ArrayList<IAsAdminCmd>
// {
//
// private static final long serialVersionUID = 1L;
//
// public AsAdminCmdList()
// {
// super();
// }
//
// }
//
// Path: asadmin-java/src/main/java/org/n0pe/asadmin/commands/DeleteJdbcResource.java
// public class DeleteJdbcResource
// extends AbstractAsAdminCmd
// {
//
// public static final String JDBC = "delete-jdbc-resource";
// private String resourceName;
//
// private DeleteJdbcResource()
// {
// }
//
// public DeleteJdbcResource( String resourceName )
// {
// this.resourceName = resourceName;
// }
//
// public boolean needCredentials()
// {
// return true;
// }
//
// public String getActionCommand()
// {
// if( resourceName == null )
// {
// throw new IllegalStateException();
// }
// return JDBC;
// }
//
// public String[] getParameters()
// {
// return new String[]
// {
// resourceName
// };
// }
//
// }
// Path: asadmin-maven-plugin/src/main/java/org/n0pe/mojo/asadmin/DeleteJdbcResourceMojo.java
import org.apache.maven.plugin.MojoExecutionException;
import org.apache.maven.plugin.MojoFailureException;
import org.n0pe.asadmin.AsAdminCmdList;
import org.n0pe.asadmin.commands.DeleteJdbcResource;
/*
* Copyright (c) 2010, Christophe Souvignier.
* Copyright (c) 2010, Paul Merlin.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
*/
package org.n0pe.mojo.asadmin;
/**
* @goal delete-jdbc-resource
*/
public class DeleteJdbcResourceMojo
extends AbstractAsadminMojo
{
/**
* @parameter
* @required
*/
private String resourceName;
@Override
protected AsAdminCmdList getAsCommandList()
throws MojoExecutionException, MojoFailureException
{
getLog().info( "Delete jdbc resource: " + resourceName );
final AsAdminCmdList list = new AsAdminCmdList(); | final DeleteJdbcResource cmd = new DeleteJdbcResource( resourceName ); |
eskatos/asadmin | asadmin-maven-plugin/src/main/java/org/n0pe/mojo/asadmin/GetHealthMojo.java | // Path: asadmin-java/src/main/java/org/n0pe/asadmin/AsAdminCmdList.java
// public class AsAdminCmdList
// extends ArrayList<IAsAdminCmd>
// {
//
// private static final long serialVersionUID = 1L;
//
// public AsAdminCmdList()
// {
// super();
// }
//
// }
//
// Path: asadmin-java/src/main/java/org/n0pe/asadmin/IAsAdminConfig.java
// public interface IAsAdminConfig
// {
//
// /**
// * @return A map of environment to use when forking the asadmin process.
// */
// Map<String, String> getEnvironmentVariables();
//
// /**
// * @return The glassfish home path.
// */
// String getGlassfishHome();
//
// /**
// * @return The username to use with asadmin.
// */
// String getUser();
//
// /**
// * @return The file where credentials are stored.
// */
// String getPasswordFile();
//
// /**
// * @return The glassfish host.
// */
// String getHost();
//
// /**
// * @return The glassfish port.
// */
// String getPort();
//
// /**
// * @return True if gf admin connection is secure.
// */
// boolean isSecure();
//
// }
//
// Path: asadmin-java/src/main/java/org/n0pe/asadmin/commands/GetHealth.java
// public class GetHealth
// extends AbstractAsAdminCmd
// {
//
// private String clusterName = null;
//
// public String getClusterName()
// {
// return clusterName;
// }
//
// public void setClusterName( String clusterName )
// {
// this.clusterName = clusterName;
// }
//
// @Override
// public boolean needCredentials()
// {
// return true;
// }
//
// @Override
// public String getActionCommand()
// {
// return "get-health";
// }
//
// @Override
// public String[] getParameters()
// {
// if( clusterName == null )
// {
// return EMPTY_ARRAY;
// }
// else
// {
// return new String[]
// {
// clusterName
// };
// }
// }
//
// }
| import org.apache.maven.plugin.MojoExecutionException;
import org.apache.maven.plugin.MojoFailureException;
import org.n0pe.asadmin.AsAdminCmdList;
import org.n0pe.asadmin.IAsAdminConfig;
import org.n0pe.asadmin.commands.GetHealth;
| /*
* Copyright (c) 2011, J.Francis.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
*/
package org.n0pe.mojo.asadmin;
/**
* @goal get-health
* @description AsAdmin get-health mojo
*/
public class GetHealthMojo
extends AbstractAsadminMojo
| // Path: asadmin-java/src/main/java/org/n0pe/asadmin/AsAdminCmdList.java
// public class AsAdminCmdList
// extends ArrayList<IAsAdminCmd>
// {
//
// private static final long serialVersionUID = 1L;
//
// public AsAdminCmdList()
// {
// super();
// }
//
// }
//
// Path: asadmin-java/src/main/java/org/n0pe/asadmin/IAsAdminConfig.java
// public interface IAsAdminConfig
// {
//
// /**
// * @return A map of environment to use when forking the asadmin process.
// */
// Map<String, String> getEnvironmentVariables();
//
// /**
// * @return The glassfish home path.
// */
// String getGlassfishHome();
//
// /**
// * @return The username to use with asadmin.
// */
// String getUser();
//
// /**
// * @return The file where credentials are stored.
// */
// String getPasswordFile();
//
// /**
// * @return The glassfish host.
// */
// String getHost();
//
// /**
// * @return The glassfish port.
// */
// String getPort();
//
// /**
// * @return True if gf admin connection is secure.
// */
// boolean isSecure();
//
// }
//
// Path: asadmin-java/src/main/java/org/n0pe/asadmin/commands/GetHealth.java
// public class GetHealth
// extends AbstractAsAdminCmd
// {
//
// private String clusterName = null;
//
// public String getClusterName()
// {
// return clusterName;
// }
//
// public void setClusterName( String clusterName )
// {
// this.clusterName = clusterName;
// }
//
// @Override
// public boolean needCredentials()
// {
// return true;
// }
//
// @Override
// public String getActionCommand()
// {
// return "get-health";
// }
//
// @Override
// public String[] getParameters()
// {
// if( clusterName == null )
// {
// return EMPTY_ARRAY;
// }
// else
// {
// return new String[]
// {
// clusterName
// };
// }
// }
//
// }
// Path: asadmin-maven-plugin/src/main/java/org/n0pe/mojo/asadmin/GetHealthMojo.java
import org.apache.maven.plugin.MojoExecutionException;
import org.apache.maven.plugin.MojoFailureException;
import org.n0pe.asadmin.AsAdminCmdList;
import org.n0pe.asadmin.IAsAdminConfig;
import org.n0pe.asadmin.commands.GetHealth;
/*
* Copyright (c) 2011, J.Francis.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
*/
package org.n0pe.mojo.asadmin;
/**
* @goal get-health
* @description AsAdmin get-health mojo
*/
public class GetHealthMojo
extends AbstractAsadminMojo
| implements IAsAdminConfig
|
eskatos/asadmin | asadmin-maven-plugin/src/main/java/org/n0pe/mojo/asadmin/GetHealthMojo.java | // Path: asadmin-java/src/main/java/org/n0pe/asadmin/AsAdminCmdList.java
// public class AsAdminCmdList
// extends ArrayList<IAsAdminCmd>
// {
//
// private static final long serialVersionUID = 1L;
//
// public AsAdminCmdList()
// {
// super();
// }
//
// }
//
// Path: asadmin-java/src/main/java/org/n0pe/asadmin/IAsAdminConfig.java
// public interface IAsAdminConfig
// {
//
// /**
// * @return A map of environment to use when forking the asadmin process.
// */
// Map<String, String> getEnvironmentVariables();
//
// /**
// * @return The glassfish home path.
// */
// String getGlassfishHome();
//
// /**
// * @return The username to use with asadmin.
// */
// String getUser();
//
// /**
// * @return The file where credentials are stored.
// */
// String getPasswordFile();
//
// /**
// * @return The glassfish host.
// */
// String getHost();
//
// /**
// * @return The glassfish port.
// */
// String getPort();
//
// /**
// * @return True if gf admin connection is secure.
// */
// boolean isSecure();
//
// }
//
// Path: asadmin-java/src/main/java/org/n0pe/asadmin/commands/GetHealth.java
// public class GetHealth
// extends AbstractAsAdminCmd
// {
//
// private String clusterName = null;
//
// public String getClusterName()
// {
// return clusterName;
// }
//
// public void setClusterName( String clusterName )
// {
// this.clusterName = clusterName;
// }
//
// @Override
// public boolean needCredentials()
// {
// return true;
// }
//
// @Override
// public String getActionCommand()
// {
// return "get-health";
// }
//
// @Override
// public String[] getParameters()
// {
// if( clusterName == null )
// {
// return EMPTY_ARRAY;
// }
// else
// {
// return new String[]
// {
// clusterName
// };
// }
// }
//
// }
| import org.apache.maven.plugin.MojoExecutionException;
import org.apache.maven.plugin.MojoFailureException;
import org.n0pe.asadmin.AsAdminCmdList;
import org.n0pe.asadmin.IAsAdminConfig;
import org.n0pe.asadmin.commands.GetHealth;
| /*
* Copyright (c) 2011, J.Francis.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
*/
package org.n0pe.mojo.asadmin;
/**
* @goal get-health
* @description AsAdmin get-health mojo
*/
public class GetHealthMojo
extends AbstractAsadminMojo
implements IAsAdminConfig
{
@Override
| // Path: asadmin-java/src/main/java/org/n0pe/asadmin/AsAdminCmdList.java
// public class AsAdminCmdList
// extends ArrayList<IAsAdminCmd>
// {
//
// private static final long serialVersionUID = 1L;
//
// public AsAdminCmdList()
// {
// super();
// }
//
// }
//
// Path: asadmin-java/src/main/java/org/n0pe/asadmin/IAsAdminConfig.java
// public interface IAsAdminConfig
// {
//
// /**
// * @return A map of environment to use when forking the asadmin process.
// */
// Map<String, String> getEnvironmentVariables();
//
// /**
// * @return The glassfish home path.
// */
// String getGlassfishHome();
//
// /**
// * @return The username to use with asadmin.
// */
// String getUser();
//
// /**
// * @return The file where credentials are stored.
// */
// String getPasswordFile();
//
// /**
// * @return The glassfish host.
// */
// String getHost();
//
// /**
// * @return The glassfish port.
// */
// String getPort();
//
// /**
// * @return True if gf admin connection is secure.
// */
// boolean isSecure();
//
// }
//
// Path: asadmin-java/src/main/java/org/n0pe/asadmin/commands/GetHealth.java
// public class GetHealth
// extends AbstractAsAdminCmd
// {
//
// private String clusterName = null;
//
// public String getClusterName()
// {
// return clusterName;
// }
//
// public void setClusterName( String clusterName )
// {
// this.clusterName = clusterName;
// }
//
// @Override
// public boolean needCredentials()
// {
// return true;
// }
//
// @Override
// public String getActionCommand()
// {
// return "get-health";
// }
//
// @Override
// public String[] getParameters()
// {
// if( clusterName == null )
// {
// return EMPTY_ARRAY;
// }
// else
// {
// return new String[]
// {
// clusterName
// };
// }
// }
//
// }
// Path: asadmin-maven-plugin/src/main/java/org/n0pe/mojo/asadmin/GetHealthMojo.java
import org.apache.maven.plugin.MojoExecutionException;
import org.apache.maven.plugin.MojoFailureException;
import org.n0pe.asadmin.AsAdminCmdList;
import org.n0pe.asadmin.IAsAdminConfig;
import org.n0pe.asadmin.commands.GetHealth;
/*
* Copyright (c) 2011, J.Francis.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
*/
package org.n0pe.mojo.asadmin;
/**
* @goal get-health
* @description AsAdmin get-health mojo
*/
public class GetHealthMojo
extends AbstractAsadminMojo
implements IAsAdminConfig
{
@Override
| protected AsAdminCmdList getAsCommandList()
|
eskatos/asadmin | asadmin-maven-plugin/src/main/java/org/n0pe/mojo/asadmin/GetHealthMojo.java | // Path: asadmin-java/src/main/java/org/n0pe/asadmin/AsAdminCmdList.java
// public class AsAdminCmdList
// extends ArrayList<IAsAdminCmd>
// {
//
// private static final long serialVersionUID = 1L;
//
// public AsAdminCmdList()
// {
// super();
// }
//
// }
//
// Path: asadmin-java/src/main/java/org/n0pe/asadmin/IAsAdminConfig.java
// public interface IAsAdminConfig
// {
//
// /**
// * @return A map of environment to use when forking the asadmin process.
// */
// Map<String, String> getEnvironmentVariables();
//
// /**
// * @return The glassfish home path.
// */
// String getGlassfishHome();
//
// /**
// * @return The username to use with asadmin.
// */
// String getUser();
//
// /**
// * @return The file where credentials are stored.
// */
// String getPasswordFile();
//
// /**
// * @return The glassfish host.
// */
// String getHost();
//
// /**
// * @return The glassfish port.
// */
// String getPort();
//
// /**
// * @return True if gf admin connection is secure.
// */
// boolean isSecure();
//
// }
//
// Path: asadmin-java/src/main/java/org/n0pe/asadmin/commands/GetHealth.java
// public class GetHealth
// extends AbstractAsAdminCmd
// {
//
// private String clusterName = null;
//
// public String getClusterName()
// {
// return clusterName;
// }
//
// public void setClusterName( String clusterName )
// {
// this.clusterName = clusterName;
// }
//
// @Override
// public boolean needCredentials()
// {
// return true;
// }
//
// @Override
// public String getActionCommand()
// {
// return "get-health";
// }
//
// @Override
// public String[] getParameters()
// {
// if( clusterName == null )
// {
// return EMPTY_ARRAY;
// }
// else
// {
// return new String[]
// {
// clusterName
// };
// }
// }
//
// }
| import org.apache.maven.plugin.MojoExecutionException;
import org.apache.maven.plugin.MojoFailureException;
import org.n0pe.asadmin.AsAdminCmdList;
import org.n0pe.asadmin.IAsAdminConfig;
import org.n0pe.asadmin.commands.GetHealth;
| /*
* Copyright (c) 2011, J.Francis.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
*/
package org.n0pe.mojo.asadmin;
/**
* @goal get-health
* @description AsAdmin get-health mojo
*/
public class GetHealthMojo
extends AbstractAsadminMojo
implements IAsAdminConfig
{
@Override
protected AsAdminCmdList getAsCommandList()
throws MojoExecutionException,
MojoFailureException
{
getLog().info( "Checking health of cluster " + cluster );
final AsAdminCmdList list = new AsAdminCmdList();
| // Path: asadmin-java/src/main/java/org/n0pe/asadmin/AsAdminCmdList.java
// public class AsAdminCmdList
// extends ArrayList<IAsAdminCmd>
// {
//
// private static final long serialVersionUID = 1L;
//
// public AsAdminCmdList()
// {
// super();
// }
//
// }
//
// Path: asadmin-java/src/main/java/org/n0pe/asadmin/IAsAdminConfig.java
// public interface IAsAdminConfig
// {
//
// /**
// * @return A map of environment to use when forking the asadmin process.
// */
// Map<String, String> getEnvironmentVariables();
//
// /**
// * @return The glassfish home path.
// */
// String getGlassfishHome();
//
// /**
// * @return The username to use with asadmin.
// */
// String getUser();
//
// /**
// * @return The file where credentials are stored.
// */
// String getPasswordFile();
//
// /**
// * @return The glassfish host.
// */
// String getHost();
//
// /**
// * @return The glassfish port.
// */
// String getPort();
//
// /**
// * @return True if gf admin connection is secure.
// */
// boolean isSecure();
//
// }
//
// Path: asadmin-java/src/main/java/org/n0pe/asadmin/commands/GetHealth.java
// public class GetHealth
// extends AbstractAsAdminCmd
// {
//
// private String clusterName = null;
//
// public String getClusterName()
// {
// return clusterName;
// }
//
// public void setClusterName( String clusterName )
// {
// this.clusterName = clusterName;
// }
//
// @Override
// public boolean needCredentials()
// {
// return true;
// }
//
// @Override
// public String getActionCommand()
// {
// return "get-health";
// }
//
// @Override
// public String[] getParameters()
// {
// if( clusterName == null )
// {
// return EMPTY_ARRAY;
// }
// else
// {
// return new String[]
// {
// clusterName
// };
// }
// }
//
// }
// Path: asadmin-maven-plugin/src/main/java/org/n0pe/mojo/asadmin/GetHealthMojo.java
import org.apache.maven.plugin.MojoExecutionException;
import org.apache.maven.plugin.MojoFailureException;
import org.n0pe.asadmin.AsAdminCmdList;
import org.n0pe.asadmin.IAsAdminConfig;
import org.n0pe.asadmin.commands.GetHealth;
/*
* Copyright (c) 2011, J.Francis.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
*/
package org.n0pe.mojo.asadmin;
/**
* @goal get-health
* @description AsAdmin get-health mojo
*/
public class GetHealthMojo
extends AbstractAsadminMojo
implements IAsAdminConfig
{
@Override
protected AsAdminCmdList getAsCommandList()
throws MojoExecutionException,
MojoFailureException
{
getLog().info( "Checking health of cluster " + cluster );
final AsAdminCmdList list = new AsAdminCmdList();
| GetHealth healthCmd = new GetHealth();
|
eskatos/asadmin | asadmin-maven-plugin/src/main/java/org/n0pe/mojo/asadmin/CreateFileUserMojo.java | // Path: asadmin-java/src/main/java/org/n0pe/asadmin/AsAdminCmdList.java
// public class AsAdminCmdList
// extends ArrayList<IAsAdminCmd>
// {
//
// private static final long serialVersionUID = 1L;
//
// public AsAdminCmdList()
// {
// super();
// }
//
// }
//
// Path: asadmin-java/src/main/java/org/n0pe/asadmin/commands/CreateFileUser.java
// public class CreateFileUser
// extends AbstractAsAdminCmd
// {
//
// public static final String CREATE_FILE_USER = "create-file-user";
// public static final String GROUPS = "--groups";
// private String userName;
// private char[] password;
// private String group;
//
// private CreateFileUser()
// {
// }
//
// public CreateFileUser( String userName )
// {
// this.userName = userName;
// }
//
// public CreateFileUser withPassword( char[] password )
// {
// this.password = password;
// return this;
// }
//
// public CreateFileUser withGroup( String group )
// {
// this.group = group;
// return this;
// }
//
// @Override
// public boolean needCredentials()
// {
// return true;
// }
//
// @Override
// public String getActionCommand()
// {
// if( userName == null )
// {
// throw new IllegalStateException();
// }
// return CREATE_FILE_USER;
// }
//
// @Override
// public String[] getParameters()
// {
// final String[] params;
// params = new String[]
// {
// GROUPS, group, userName
// };
// return params;
// }
//
// @Override
// public String handlePasswordFile( String configuredPasswordFile )
// throws AsAdminException
// {
// try
// {
// File passwordTempFile = File.createTempFile( "asadmin-create-file-user", ".pwd" );
// passwordTempFile.deleteOnExit();
// FileUtils.copyFile( new File( configuredPasswordFile ), passwordTempFile );
// BufferedWriter out = new BufferedWriter( new FileWriter( passwordTempFile ) );
// out.write( "AS_ADMIN_USERPASSWORD=" + new String( password ) );
// out.close();
// return passwordTempFile.getAbsolutePath();
// }
// catch( IOException ex )
// {
// throw new AsAdminException( "Unable to handle password file for CreateFileUser command", ex );
// }
// }
//
// }
| import org.apache.maven.plugin.MojoFailureException;
import org.n0pe.asadmin.AsAdminCmdList;
import org.n0pe.asadmin.commands.CreateFileUser;
import org.apache.maven.plugin.MojoExecutionException; | /*
* Copyright (c) 2010, Paul Merlin.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
*/
package org.n0pe.mojo.asadmin;
/**
* @goal create-file-user
*/
public class CreateFileUserMojo
extends AbstractAsadminMojo
{
/**
* @parameter
* @required
*/
private String userName;
/**
* @parameter
* @required
*/
private String userPassword;
/**
* @parameter
* @required
*/
private String group;
@Override | // Path: asadmin-java/src/main/java/org/n0pe/asadmin/AsAdminCmdList.java
// public class AsAdminCmdList
// extends ArrayList<IAsAdminCmd>
// {
//
// private static final long serialVersionUID = 1L;
//
// public AsAdminCmdList()
// {
// super();
// }
//
// }
//
// Path: asadmin-java/src/main/java/org/n0pe/asadmin/commands/CreateFileUser.java
// public class CreateFileUser
// extends AbstractAsAdminCmd
// {
//
// public static final String CREATE_FILE_USER = "create-file-user";
// public static final String GROUPS = "--groups";
// private String userName;
// private char[] password;
// private String group;
//
// private CreateFileUser()
// {
// }
//
// public CreateFileUser( String userName )
// {
// this.userName = userName;
// }
//
// public CreateFileUser withPassword( char[] password )
// {
// this.password = password;
// return this;
// }
//
// public CreateFileUser withGroup( String group )
// {
// this.group = group;
// return this;
// }
//
// @Override
// public boolean needCredentials()
// {
// return true;
// }
//
// @Override
// public String getActionCommand()
// {
// if( userName == null )
// {
// throw new IllegalStateException();
// }
// return CREATE_FILE_USER;
// }
//
// @Override
// public String[] getParameters()
// {
// final String[] params;
// params = new String[]
// {
// GROUPS, group, userName
// };
// return params;
// }
//
// @Override
// public String handlePasswordFile( String configuredPasswordFile )
// throws AsAdminException
// {
// try
// {
// File passwordTempFile = File.createTempFile( "asadmin-create-file-user", ".pwd" );
// passwordTempFile.deleteOnExit();
// FileUtils.copyFile( new File( configuredPasswordFile ), passwordTempFile );
// BufferedWriter out = new BufferedWriter( new FileWriter( passwordTempFile ) );
// out.write( "AS_ADMIN_USERPASSWORD=" + new String( password ) );
// out.close();
// return passwordTempFile.getAbsolutePath();
// }
// catch( IOException ex )
// {
// throw new AsAdminException( "Unable to handle password file for CreateFileUser command", ex );
// }
// }
//
// }
// Path: asadmin-maven-plugin/src/main/java/org/n0pe/mojo/asadmin/CreateFileUserMojo.java
import org.apache.maven.plugin.MojoFailureException;
import org.n0pe.asadmin.AsAdminCmdList;
import org.n0pe.asadmin.commands.CreateFileUser;
import org.apache.maven.plugin.MojoExecutionException;
/*
* Copyright (c) 2010, Paul Merlin.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
*/
package org.n0pe.mojo.asadmin;
/**
* @goal create-file-user
*/
public class CreateFileUserMojo
extends AbstractAsadminMojo
{
/**
* @parameter
* @required
*/
private String userName;
/**
* @parameter
* @required
*/
private String userPassword;
/**
* @parameter
* @required
*/
private String group;
@Override | protected AsAdminCmdList getAsCommandList() |
eskatos/asadmin | asadmin-maven-plugin/src/main/java/org/n0pe/mojo/asadmin/CreateFileUserMojo.java | // Path: asadmin-java/src/main/java/org/n0pe/asadmin/AsAdminCmdList.java
// public class AsAdminCmdList
// extends ArrayList<IAsAdminCmd>
// {
//
// private static final long serialVersionUID = 1L;
//
// public AsAdminCmdList()
// {
// super();
// }
//
// }
//
// Path: asadmin-java/src/main/java/org/n0pe/asadmin/commands/CreateFileUser.java
// public class CreateFileUser
// extends AbstractAsAdminCmd
// {
//
// public static final String CREATE_FILE_USER = "create-file-user";
// public static final String GROUPS = "--groups";
// private String userName;
// private char[] password;
// private String group;
//
// private CreateFileUser()
// {
// }
//
// public CreateFileUser( String userName )
// {
// this.userName = userName;
// }
//
// public CreateFileUser withPassword( char[] password )
// {
// this.password = password;
// return this;
// }
//
// public CreateFileUser withGroup( String group )
// {
// this.group = group;
// return this;
// }
//
// @Override
// public boolean needCredentials()
// {
// return true;
// }
//
// @Override
// public String getActionCommand()
// {
// if( userName == null )
// {
// throw new IllegalStateException();
// }
// return CREATE_FILE_USER;
// }
//
// @Override
// public String[] getParameters()
// {
// final String[] params;
// params = new String[]
// {
// GROUPS, group, userName
// };
// return params;
// }
//
// @Override
// public String handlePasswordFile( String configuredPasswordFile )
// throws AsAdminException
// {
// try
// {
// File passwordTempFile = File.createTempFile( "asadmin-create-file-user", ".pwd" );
// passwordTempFile.deleteOnExit();
// FileUtils.copyFile( new File( configuredPasswordFile ), passwordTempFile );
// BufferedWriter out = new BufferedWriter( new FileWriter( passwordTempFile ) );
// out.write( "AS_ADMIN_USERPASSWORD=" + new String( password ) );
// out.close();
// return passwordTempFile.getAbsolutePath();
// }
// catch( IOException ex )
// {
// throw new AsAdminException( "Unable to handle password file for CreateFileUser command", ex );
// }
// }
//
// }
| import org.apache.maven.plugin.MojoFailureException;
import org.n0pe.asadmin.AsAdminCmdList;
import org.n0pe.asadmin.commands.CreateFileUser;
import org.apache.maven.plugin.MojoExecutionException; | /*
* Copyright (c) 2010, Paul Merlin.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
*/
package org.n0pe.mojo.asadmin;
/**
* @goal create-file-user
*/
public class CreateFileUserMojo
extends AbstractAsadminMojo
{
/**
* @parameter
* @required
*/
private String userName;
/**
* @parameter
* @required
*/
private String userPassword;
/**
* @parameter
* @required
*/
private String group;
@Override
protected AsAdminCmdList getAsCommandList()
throws MojoExecutionException, MojoFailureException
{
getLog().info( "Create file user: " + userName );
AsAdminCmdList cmdList = new AsAdminCmdList(); | // Path: asadmin-java/src/main/java/org/n0pe/asadmin/AsAdminCmdList.java
// public class AsAdminCmdList
// extends ArrayList<IAsAdminCmd>
// {
//
// private static final long serialVersionUID = 1L;
//
// public AsAdminCmdList()
// {
// super();
// }
//
// }
//
// Path: asadmin-java/src/main/java/org/n0pe/asadmin/commands/CreateFileUser.java
// public class CreateFileUser
// extends AbstractAsAdminCmd
// {
//
// public static final String CREATE_FILE_USER = "create-file-user";
// public static final String GROUPS = "--groups";
// private String userName;
// private char[] password;
// private String group;
//
// private CreateFileUser()
// {
// }
//
// public CreateFileUser( String userName )
// {
// this.userName = userName;
// }
//
// public CreateFileUser withPassword( char[] password )
// {
// this.password = password;
// return this;
// }
//
// public CreateFileUser withGroup( String group )
// {
// this.group = group;
// return this;
// }
//
// @Override
// public boolean needCredentials()
// {
// return true;
// }
//
// @Override
// public String getActionCommand()
// {
// if( userName == null )
// {
// throw new IllegalStateException();
// }
// return CREATE_FILE_USER;
// }
//
// @Override
// public String[] getParameters()
// {
// final String[] params;
// params = new String[]
// {
// GROUPS, group, userName
// };
// return params;
// }
//
// @Override
// public String handlePasswordFile( String configuredPasswordFile )
// throws AsAdminException
// {
// try
// {
// File passwordTempFile = File.createTempFile( "asadmin-create-file-user", ".pwd" );
// passwordTempFile.deleteOnExit();
// FileUtils.copyFile( new File( configuredPasswordFile ), passwordTempFile );
// BufferedWriter out = new BufferedWriter( new FileWriter( passwordTempFile ) );
// out.write( "AS_ADMIN_USERPASSWORD=" + new String( password ) );
// out.close();
// return passwordTempFile.getAbsolutePath();
// }
// catch( IOException ex )
// {
// throw new AsAdminException( "Unable to handle password file for CreateFileUser command", ex );
// }
// }
//
// }
// Path: asadmin-maven-plugin/src/main/java/org/n0pe/mojo/asadmin/CreateFileUserMojo.java
import org.apache.maven.plugin.MojoFailureException;
import org.n0pe.asadmin.AsAdminCmdList;
import org.n0pe.asadmin.commands.CreateFileUser;
import org.apache.maven.plugin.MojoExecutionException;
/*
* Copyright (c) 2010, Paul Merlin.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
*/
package org.n0pe.mojo.asadmin;
/**
* @goal create-file-user
*/
public class CreateFileUserMojo
extends AbstractAsadminMojo
{
/**
* @parameter
* @required
*/
private String userName;
/**
* @parameter
* @required
*/
private String userPassword;
/**
* @parameter
* @required
*/
private String group;
@Override
protected AsAdminCmdList getAsCommandList()
throws MojoExecutionException, MojoFailureException
{
getLog().info( "Create file user: " + userName );
AsAdminCmdList cmdList = new AsAdminCmdList(); | cmdList.add( new CreateFileUser( userName ).withGroup( group ).withPassword( userPassword.toCharArray() ) ); |
eskatos/asadmin | asadmin-maven-plugin/src/main/java/org/n0pe/mojo/asadmin/DeleteMessageSecurityProviderMojo.java | // Path: asadmin-java/src/main/java/org/n0pe/asadmin/AsAdminCmdList.java
// public class AsAdminCmdList
// extends ArrayList<IAsAdminCmd>
// {
//
// private static final long serialVersionUID = 1L;
//
// public AsAdminCmdList()
// {
// super();
// }
//
// }
//
// Path: asadmin-java/src/main/java/org/n0pe/asadmin/commands/DeleteMessageSecurityProvider.java
// public class DeleteMessageSecurityProvider
// extends AbstractAsAdminCmd
// {
//
// public static final String SECURITY_PROVIDER = "delete-message-security-provider";
// public static final String LAYER_OPT = "--layer";
// private String providerName;
// private String layer;
//
// private DeleteMessageSecurityProvider()
// {
// }
//
// public DeleteMessageSecurityProvider( String providerName )
// {
// this.providerName = providerName;
// }
//
// public DeleteMessageSecurityProvider withLayer( String layer )
// {
// this.layer = layer;
// return this;
// }
//
// public boolean needCredentials()
// {
// return true;
// }
//
// public String getActionCommand()
// {
// if( providerName == null )
// {
// throw new IllegalStateException();
// }
// return SECURITY_PROVIDER;
// }
//
// public String[] getParameters()
// {
// if( layer == null )
// {
// throw new IllegalStateException();
// }
// return new String[]
// {
// LAYER_OPT, layer, providerName
// };
// }
//
// }
| import org.apache.maven.plugin.MojoExecutionException;
import org.apache.maven.plugin.MojoFailureException;
import org.n0pe.asadmin.AsAdminCmdList;
import org.n0pe.asadmin.commands.DeleteMessageSecurityProvider; | /*
* Copyright (c) 2010, Christophe Souvignier.
* Copyright (c) 2010, Paul Merlin.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
*/
package org.n0pe.mojo.asadmin;
/**
* @goal delete-message-security-provider
*/
public class DeleteMessageSecurityProviderMojo
extends AbstractAsadminMojo
{
/**
* @parameter
* @required
*/
private String providerName;
/**
* @parameter default-value="SOAP"
* @required
*/
private String layer;
@Override | // Path: asadmin-java/src/main/java/org/n0pe/asadmin/AsAdminCmdList.java
// public class AsAdminCmdList
// extends ArrayList<IAsAdminCmd>
// {
//
// private static final long serialVersionUID = 1L;
//
// public AsAdminCmdList()
// {
// super();
// }
//
// }
//
// Path: asadmin-java/src/main/java/org/n0pe/asadmin/commands/DeleteMessageSecurityProvider.java
// public class DeleteMessageSecurityProvider
// extends AbstractAsAdminCmd
// {
//
// public static final String SECURITY_PROVIDER = "delete-message-security-provider";
// public static final String LAYER_OPT = "--layer";
// private String providerName;
// private String layer;
//
// private DeleteMessageSecurityProvider()
// {
// }
//
// public DeleteMessageSecurityProvider( String providerName )
// {
// this.providerName = providerName;
// }
//
// public DeleteMessageSecurityProvider withLayer( String layer )
// {
// this.layer = layer;
// return this;
// }
//
// public boolean needCredentials()
// {
// return true;
// }
//
// public String getActionCommand()
// {
// if( providerName == null )
// {
// throw new IllegalStateException();
// }
// return SECURITY_PROVIDER;
// }
//
// public String[] getParameters()
// {
// if( layer == null )
// {
// throw new IllegalStateException();
// }
// return new String[]
// {
// LAYER_OPT, layer, providerName
// };
// }
//
// }
// Path: asadmin-maven-plugin/src/main/java/org/n0pe/mojo/asadmin/DeleteMessageSecurityProviderMojo.java
import org.apache.maven.plugin.MojoExecutionException;
import org.apache.maven.plugin.MojoFailureException;
import org.n0pe.asadmin.AsAdminCmdList;
import org.n0pe.asadmin.commands.DeleteMessageSecurityProvider;
/*
* Copyright (c) 2010, Christophe Souvignier.
* Copyright (c) 2010, Paul Merlin.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
*/
package org.n0pe.mojo.asadmin;
/**
* @goal delete-message-security-provider
*/
public class DeleteMessageSecurityProviderMojo
extends AbstractAsadminMojo
{
/**
* @parameter
* @required
*/
private String providerName;
/**
* @parameter default-value="SOAP"
* @required
*/
private String layer;
@Override | protected AsAdminCmdList getAsCommandList() |
eskatos/asadmin | asadmin-maven-plugin/src/main/java/org/n0pe/mojo/asadmin/DeleteMessageSecurityProviderMojo.java | // Path: asadmin-java/src/main/java/org/n0pe/asadmin/AsAdminCmdList.java
// public class AsAdminCmdList
// extends ArrayList<IAsAdminCmd>
// {
//
// private static final long serialVersionUID = 1L;
//
// public AsAdminCmdList()
// {
// super();
// }
//
// }
//
// Path: asadmin-java/src/main/java/org/n0pe/asadmin/commands/DeleteMessageSecurityProvider.java
// public class DeleteMessageSecurityProvider
// extends AbstractAsAdminCmd
// {
//
// public static final String SECURITY_PROVIDER = "delete-message-security-provider";
// public static final String LAYER_OPT = "--layer";
// private String providerName;
// private String layer;
//
// private DeleteMessageSecurityProvider()
// {
// }
//
// public DeleteMessageSecurityProvider( String providerName )
// {
// this.providerName = providerName;
// }
//
// public DeleteMessageSecurityProvider withLayer( String layer )
// {
// this.layer = layer;
// return this;
// }
//
// public boolean needCredentials()
// {
// return true;
// }
//
// public String getActionCommand()
// {
// if( providerName == null )
// {
// throw new IllegalStateException();
// }
// return SECURITY_PROVIDER;
// }
//
// public String[] getParameters()
// {
// if( layer == null )
// {
// throw new IllegalStateException();
// }
// return new String[]
// {
// LAYER_OPT, layer, providerName
// };
// }
//
// }
| import org.apache.maven.plugin.MojoExecutionException;
import org.apache.maven.plugin.MojoFailureException;
import org.n0pe.asadmin.AsAdminCmdList;
import org.n0pe.asadmin.commands.DeleteMessageSecurityProvider; | /*
* Copyright (c) 2010, Christophe Souvignier.
* Copyright (c) 2010, Paul Merlin.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
*/
package org.n0pe.mojo.asadmin;
/**
* @goal delete-message-security-provider
*/
public class DeleteMessageSecurityProviderMojo
extends AbstractAsadminMojo
{
/**
* @parameter
* @required
*/
private String providerName;
/**
* @parameter default-value="SOAP"
* @required
*/
private String layer;
@Override
protected AsAdminCmdList getAsCommandList()
throws MojoExecutionException, MojoFailureException
{
getLog().info( "Deleting security provider: " + providerName );
final AsAdminCmdList list = new AsAdminCmdList(); | // Path: asadmin-java/src/main/java/org/n0pe/asadmin/AsAdminCmdList.java
// public class AsAdminCmdList
// extends ArrayList<IAsAdminCmd>
// {
//
// private static final long serialVersionUID = 1L;
//
// public AsAdminCmdList()
// {
// super();
// }
//
// }
//
// Path: asadmin-java/src/main/java/org/n0pe/asadmin/commands/DeleteMessageSecurityProvider.java
// public class DeleteMessageSecurityProvider
// extends AbstractAsAdminCmd
// {
//
// public static final String SECURITY_PROVIDER = "delete-message-security-provider";
// public static final String LAYER_OPT = "--layer";
// private String providerName;
// private String layer;
//
// private DeleteMessageSecurityProvider()
// {
// }
//
// public DeleteMessageSecurityProvider( String providerName )
// {
// this.providerName = providerName;
// }
//
// public DeleteMessageSecurityProvider withLayer( String layer )
// {
// this.layer = layer;
// return this;
// }
//
// public boolean needCredentials()
// {
// return true;
// }
//
// public String getActionCommand()
// {
// if( providerName == null )
// {
// throw new IllegalStateException();
// }
// return SECURITY_PROVIDER;
// }
//
// public String[] getParameters()
// {
// if( layer == null )
// {
// throw new IllegalStateException();
// }
// return new String[]
// {
// LAYER_OPT, layer, providerName
// };
// }
//
// }
// Path: asadmin-maven-plugin/src/main/java/org/n0pe/mojo/asadmin/DeleteMessageSecurityProviderMojo.java
import org.apache.maven.plugin.MojoExecutionException;
import org.apache.maven.plugin.MojoFailureException;
import org.n0pe.asadmin.AsAdminCmdList;
import org.n0pe.asadmin.commands.DeleteMessageSecurityProvider;
/*
* Copyright (c) 2010, Christophe Souvignier.
* Copyright (c) 2010, Paul Merlin.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
*/
package org.n0pe.mojo.asadmin;
/**
* @goal delete-message-security-provider
*/
public class DeleteMessageSecurityProviderMojo
extends AbstractAsadminMojo
{
/**
* @parameter
* @required
*/
private String providerName;
/**
* @parameter default-value="SOAP"
* @required
*/
private String layer;
@Override
protected AsAdminCmdList getAsCommandList()
throws MojoExecutionException, MojoFailureException
{
getLog().info( "Deleting security provider: " + providerName );
final AsAdminCmdList list = new AsAdminCmdList(); | final DeleteMessageSecurityProvider cmd = new DeleteMessageSecurityProvider( providerName ).withLayer( layer ); |
eskatos/asadmin | asadmin-maven-plugin/src/main/java/org/n0pe/mojo/asadmin/CreateJdbcConnectionPoolMojo.java | // Path: asadmin-java/src/main/java/org/n0pe/asadmin/AsAdminCmdList.java
// public class AsAdminCmdList
// extends ArrayList<IAsAdminCmd>
// {
//
// private static final long serialVersionUID = 1L;
//
// public AsAdminCmdList()
// {
// super();
// }
//
// }
//
// Path: asadmin-java/src/main/java/org/n0pe/asadmin/commands/CreateJdbcConnectionPool.java
// public class CreateJdbcConnectionPool
// extends AbstractAsAdminCmd
// {
//
// public static final String JDBC = "create-jdbc-connection-pool";
// public static final String DATA_SOURCE_OPT = "--datasourceclassname";
// public static final String RESTYPE_OPT = "--restype";
// public static final String PROPERTY_OPT = "--property";
// private String poolName;
// private String dataSource;
// private String restype;
// private Map properties;
//
// /**
// * CreateJdbcConnectionPool default constructor.
// */
// private CreateJdbcConnectionPool()
// {
// }
//
// public CreateJdbcConnectionPool( String poolName )
// {
// this.poolName = poolName;
// }
//
// public CreateJdbcConnectionPool withDataSource( String dataSource )
// {
// this.dataSource = dataSource;
// return this;
// }
//
// public CreateJdbcConnectionPool withRestype( String restype )
// {
// this.restype = restype;
// return this;
// }
//
// public CreateJdbcConnectionPool addProperty( String key, String value )
// {
// if( properties == null )
// {
// properties = new HashMap();
// }
// properties.put( key, value );
// return this;
// }
//
// public boolean needCredentials()
// {
// return true;
// }
//
// public String getActionCommand()
// {
// if( poolName == null )
// {
// throw new IllegalStateException();
// }
// return JDBC;
// }
//
// public String[] getParameters()
// {
// if( ( dataSource == null ) || ( restype == null ) )
// {
// throw new IllegalStateException();
// }
// final String[] params;
// if( properties != null && !properties.isEmpty() )
// {
// final StringBuffer sw = new StringBuffer();
// String key;
// for( final Iterator it = properties.keySet().iterator(); it.hasNext(); )
// {
// key = (String) it.next();
// sw.append( key ).append( "=" ).append( Util.quoteCommandArgument( (String) properties.get( key ) ) );
// if( it.hasNext() )
// {
// sw.append( ":" );
// }
// }
// params = new String[]
// {
// DATA_SOURCE_OPT, dataSource, RESTYPE_OPT, restype, PROPERTY_OPT, sw.toString(), poolName
// };
//
// }
// else
// {
// params = new String[]
// {
// DATA_SOURCE_OPT, dataSource, RESTYPE_OPT, restype, poolName
// };
// }
// return params;
// }
//
// }
| import java.util.Iterator;
import java.util.Map;
import org.apache.maven.plugin.MojoExecutionException;
import org.apache.maven.plugin.MojoFailureException;
import org.n0pe.asadmin.AsAdminCmdList;
import org.n0pe.asadmin.commands.CreateJdbcConnectionPool; | /*
* Copyright (c) 2010, Christophe Souvignier.
* Copyright (c) 2010, Paul Merlin.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
*/
package org.n0pe.mojo.asadmin;
/**
* @goal create-jdbc-connection-pool
*/
public class CreateJdbcConnectionPoolMojo
extends AbstractAsadminMojo
{
/**
* @parameter default-value="org.apache.derby.jdbc.ClientXADataSource"
* @required
*/
private String poolDataSource;
/**
* @parameter
* @required
*/
private String poolName;
/**
* @parameter default-value="javax.sql.XADataSource"
* @required
*/
private String restype;
/**
* @parameter
*/
private Map poolProperties;
@Override | // Path: asadmin-java/src/main/java/org/n0pe/asadmin/AsAdminCmdList.java
// public class AsAdminCmdList
// extends ArrayList<IAsAdminCmd>
// {
//
// private static final long serialVersionUID = 1L;
//
// public AsAdminCmdList()
// {
// super();
// }
//
// }
//
// Path: asadmin-java/src/main/java/org/n0pe/asadmin/commands/CreateJdbcConnectionPool.java
// public class CreateJdbcConnectionPool
// extends AbstractAsAdminCmd
// {
//
// public static final String JDBC = "create-jdbc-connection-pool";
// public static final String DATA_SOURCE_OPT = "--datasourceclassname";
// public static final String RESTYPE_OPT = "--restype";
// public static final String PROPERTY_OPT = "--property";
// private String poolName;
// private String dataSource;
// private String restype;
// private Map properties;
//
// /**
// * CreateJdbcConnectionPool default constructor.
// */
// private CreateJdbcConnectionPool()
// {
// }
//
// public CreateJdbcConnectionPool( String poolName )
// {
// this.poolName = poolName;
// }
//
// public CreateJdbcConnectionPool withDataSource( String dataSource )
// {
// this.dataSource = dataSource;
// return this;
// }
//
// public CreateJdbcConnectionPool withRestype( String restype )
// {
// this.restype = restype;
// return this;
// }
//
// public CreateJdbcConnectionPool addProperty( String key, String value )
// {
// if( properties == null )
// {
// properties = new HashMap();
// }
// properties.put( key, value );
// return this;
// }
//
// public boolean needCredentials()
// {
// return true;
// }
//
// public String getActionCommand()
// {
// if( poolName == null )
// {
// throw new IllegalStateException();
// }
// return JDBC;
// }
//
// public String[] getParameters()
// {
// if( ( dataSource == null ) || ( restype == null ) )
// {
// throw new IllegalStateException();
// }
// final String[] params;
// if( properties != null && !properties.isEmpty() )
// {
// final StringBuffer sw = new StringBuffer();
// String key;
// for( final Iterator it = properties.keySet().iterator(); it.hasNext(); )
// {
// key = (String) it.next();
// sw.append( key ).append( "=" ).append( Util.quoteCommandArgument( (String) properties.get( key ) ) );
// if( it.hasNext() )
// {
// sw.append( ":" );
// }
// }
// params = new String[]
// {
// DATA_SOURCE_OPT, dataSource, RESTYPE_OPT, restype, PROPERTY_OPT, sw.toString(), poolName
// };
//
// }
// else
// {
// params = new String[]
// {
// DATA_SOURCE_OPT, dataSource, RESTYPE_OPT, restype, poolName
// };
// }
// return params;
// }
//
// }
// Path: asadmin-maven-plugin/src/main/java/org/n0pe/mojo/asadmin/CreateJdbcConnectionPoolMojo.java
import java.util.Iterator;
import java.util.Map;
import org.apache.maven.plugin.MojoExecutionException;
import org.apache.maven.plugin.MojoFailureException;
import org.n0pe.asadmin.AsAdminCmdList;
import org.n0pe.asadmin.commands.CreateJdbcConnectionPool;
/*
* Copyright (c) 2010, Christophe Souvignier.
* Copyright (c) 2010, Paul Merlin.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
*/
package org.n0pe.mojo.asadmin;
/**
* @goal create-jdbc-connection-pool
*/
public class CreateJdbcConnectionPoolMojo
extends AbstractAsadminMojo
{
/**
* @parameter default-value="org.apache.derby.jdbc.ClientXADataSource"
* @required
*/
private String poolDataSource;
/**
* @parameter
* @required
*/
private String poolName;
/**
* @parameter default-value="javax.sql.XADataSource"
* @required
*/
private String restype;
/**
* @parameter
*/
private Map poolProperties;
@Override | protected AsAdminCmdList getAsCommandList() |
eskatos/asadmin | asadmin-maven-plugin/src/main/java/org/n0pe/mojo/asadmin/CreateJdbcConnectionPoolMojo.java | // Path: asadmin-java/src/main/java/org/n0pe/asadmin/AsAdminCmdList.java
// public class AsAdminCmdList
// extends ArrayList<IAsAdminCmd>
// {
//
// private static final long serialVersionUID = 1L;
//
// public AsAdminCmdList()
// {
// super();
// }
//
// }
//
// Path: asadmin-java/src/main/java/org/n0pe/asadmin/commands/CreateJdbcConnectionPool.java
// public class CreateJdbcConnectionPool
// extends AbstractAsAdminCmd
// {
//
// public static final String JDBC = "create-jdbc-connection-pool";
// public static final String DATA_SOURCE_OPT = "--datasourceclassname";
// public static final String RESTYPE_OPT = "--restype";
// public static final String PROPERTY_OPT = "--property";
// private String poolName;
// private String dataSource;
// private String restype;
// private Map properties;
//
// /**
// * CreateJdbcConnectionPool default constructor.
// */
// private CreateJdbcConnectionPool()
// {
// }
//
// public CreateJdbcConnectionPool( String poolName )
// {
// this.poolName = poolName;
// }
//
// public CreateJdbcConnectionPool withDataSource( String dataSource )
// {
// this.dataSource = dataSource;
// return this;
// }
//
// public CreateJdbcConnectionPool withRestype( String restype )
// {
// this.restype = restype;
// return this;
// }
//
// public CreateJdbcConnectionPool addProperty( String key, String value )
// {
// if( properties == null )
// {
// properties = new HashMap();
// }
// properties.put( key, value );
// return this;
// }
//
// public boolean needCredentials()
// {
// return true;
// }
//
// public String getActionCommand()
// {
// if( poolName == null )
// {
// throw new IllegalStateException();
// }
// return JDBC;
// }
//
// public String[] getParameters()
// {
// if( ( dataSource == null ) || ( restype == null ) )
// {
// throw new IllegalStateException();
// }
// final String[] params;
// if( properties != null && !properties.isEmpty() )
// {
// final StringBuffer sw = new StringBuffer();
// String key;
// for( final Iterator it = properties.keySet().iterator(); it.hasNext(); )
// {
// key = (String) it.next();
// sw.append( key ).append( "=" ).append( Util.quoteCommandArgument( (String) properties.get( key ) ) );
// if( it.hasNext() )
// {
// sw.append( ":" );
// }
// }
// params = new String[]
// {
// DATA_SOURCE_OPT, dataSource, RESTYPE_OPT, restype, PROPERTY_OPT, sw.toString(), poolName
// };
//
// }
// else
// {
// params = new String[]
// {
// DATA_SOURCE_OPT, dataSource, RESTYPE_OPT, restype, poolName
// };
// }
// return params;
// }
//
// }
| import java.util.Iterator;
import java.util.Map;
import org.apache.maven.plugin.MojoExecutionException;
import org.apache.maven.plugin.MojoFailureException;
import org.n0pe.asadmin.AsAdminCmdList;
import org.n0pe.asadmin.commands.CreateJdbcConnectionPool; | /*
* Copyright (c) 2010, Christophe Souvignier.
* Copyright (c) 2010, Paul Merlin.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
*/
package org.n0pe.mojo.asadmin;
/**
* @goal create-jdbc-connection-pool
*/
public class CreateJdbcConnectionPoolMojo
extends AbstractAsadminMojo
{
/**
* @parameter default-value="org.apache.derby.jdbc.ClientXADataSource"
* @required
*/
private String poolDataSource;
/**
* @parameter
* @required
*/
private String poolName;
/**
* @parameter default-value="javax.sql.XADataSource"
* @required
*/
private String restype;
/**
* @parameter
*/
private Map poolProperties;
@Override
protected AsAdminCmdList getAsCommandList()
throws MojoExecutionException, MojoFailureException
{
getLog().info( "Creating auth realm: " + poolName );
final AsAdminCmdList list = new AsAdminCmdList(); | // Path: asadmin-java/src/main/java/org/n0pe/asadmin/AsAdminCmdList.java
// public class AsAdminCmdList
// extends ArrayList<IAsAdminCmd>
// {
//
// private static final long serialVersionUID = 1L;
//
// public AsAdminCmdList()
// {
// super();
// }
//
// }
//
// Path: asadmin-java/src/main/java/org/n0pe/asadmin/commands/CreateJdbcConnectionPool.java
// public class CreateJdbcConnectionPool
// extends AbstractAsAdminCmd
// {
//
// public static final String JDBC = "create-jdbc-connection-pool";
// public static final String DATA_SOURCE_OPT = "--datasourceclassname";
// public static final String RESTYPE_OPT = "--restype";
// public static final String PROPERTY_OPT = "--property";
// private String poolName;
// private String dataSource;
// private String restype;
// private Map properties;
//
// /**
// * CreateJdbcConnectionPool default constructor.
// */
// private CreateJdbcConnectionPool()
// {
// }
//
// public CreateJdbcConnectionPool( String poolName )
// {
// this.poolName = poolName;
// }
//
// public CreateJdbcConnectionPool withDataSource( String dataSource )
// {
// this.dataSource = dataSource;
// return this;
// }
//
// public CreateJdbcConnectionPool withRestype( String restype )
// {
// this.restype = restype;
// return this;
// }
//
// public CreateJdbcConnectionPool addProperty( String key, String value )
// {
// if( properties == null )
// {
// properties = new HashMap();
// }
// properties.put( key, value );
// return this;
// }
//
// public boolean needCredentials()
// {
// return true;
// }
//
// public String getActionCommand()
// {
// if( poolName == null )
// {
// throw new IllegalStateException();
// }
// return JDBC;
// }
//
// public String[] getParameters()
// {
// if( ( dataSource == null ) || ( restype == null ) )
// {
// throw new IllegalStateException();
// }
// final String[] params;
// if( properties != null && !properties.isEmpty() )
// {
// final StringBuffer sw = new StringBuffer();
// String key;
// for( final Iterator it = properties.keySet().iterator(); it.hasNext(); )
// {
// key = (String) it.next();
// sw.append( key ).append( "=" ).append( Util.quoteCommandArgument( (String) properties.get( key ) ) );
// if( it.hasNext() )
// {
// sw.append( ":" );
// }
// }
// params = new String[]
// {
// DATA_SOURCE_OPT, dataSource, RESTYPE_OPT, restype, PROPERTY_OPT, sw.toString(), poolName
// };
//
// }
// else
// {
// params = new String[]
// {
// DATA_SOURCE_OPT, dataSource, RESTYPE_OPT, restype, poolName
// };
// }
// return params;
// }
//
// }
// Path: asadmin-maven-plugin/src/main/java/org/n0pe/mojo/asadmin/CreateJdbcConnectionPoolMojo.java
import java.util.Iterator;
import java.util.Map;
import org.apache.maven.plugin.MojoExecutionException;
import org.apache.maven.plugin.MojoFailureException;
import org.n0pe.asadmin.AsAdminCmdList;
import org.n0pe.asadmin.commands.CreateJdbcConnectionPool;
/*
* Copyright (c) 2010, Christophe Souvignier.
* Copyright (c) 2010, Paul Merlin.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
*/
package org.n0pe.mojo.asadmin;
/**
* @goal create-jdbc-connection-pool
*/
public class CreateJdbcConnectionPoolMojo
extends AbstractAsadminMojo
{
/**
* @parameter default-value="org.apache.derby.jdbc.ClientXADataSource"
* @required
*/
private String poolDataSource;
/**
* @parameter
* @required
*/
private String poolName;
/**
* @parameter default-value="javax.sql.XADataSource"
* @required
*/
private String restype;
/**
* @parameter
*/
private Map poolProperties;
@Override
protected AsAdminCmdList getAsCommandList()
throws MojoExecutionException, MojoFailureException
{
getLog().info( "Creating auth realm: " + poolName );
final AsAdminCmdList list = new AsAdminCmdList(); | final CreateJdbcConnectionPool cmd = new CreateJdbcConnectionPool( poolName ).withDataSource( poolDataSource ).withRestype( restype ); |
sunalong/JNIDemo | app/src/main/java/com/itcode/jnidemo/MainActivity.java | // Path: mylibrary/src/main/java/com/itcode/mylibrary/NativeEngine.java
// public class NativeEngine {
// /**
// * 用于将上下文传给 Cpp 层
// *
// * @param activity
// */
// public native void register(Activity activity);
//
// /**
// * 在 Cpp 中加密
// *
// * @param rawStr 原始字符
// * @return 加密后的字符
// */
// public native String encryptInCpp(String rawStr);
//
// /**
// * 在 Cpp 中解密
// *
// * @param cipherText 密文
// * @return 解密后的字符
// */
// public native String decryptInCpp(String cipherText);
//
// /**
// * 通过 cpp 请求网络获取机器配置
// *
// * @param deviceModel 手机设备名
// * @param timeout 超时时间
// * @return
// */
// public native boolean getDeviceInfo(String deviceModel, int timeout);
//
// // Used to load the 'native-lib' library on application startup.
// static {
// System.loadLibrary("native-lib");
// }
// }
| import android.os.Build;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.text.TextUtils;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;
import com.itcode.mylibrary.NativeEngine;
import org.xutils.view.annotation.ViewInject;
import org.xutils.x; | package com.itcode.jnidemo;
public class MainActivity extends AppCompatActivity implements View.OnClickListener {
@ViewInject(R.id.btnEncrypt)
private Button btnEncrypt;
@ViewInject(R.id.etRawStr)
private EditText etRawStr;
@ViewInject(R.id.etShowCipherText)
private EditText etShowCipherText;
@ViewInject(R.id.btnDecrypt)
private Button btnDecrypt;
@ViewInject(R.id.etdecrypt)
private EditText etdecrypt;
@ViewInject(R.id.etShowClearText)
private EditText etShowClearText;
@ViewInject(R.id.btnGetDeviceInfo)
private Button btnGetDeviceInfo;
@ViewInject(R.id.etDeviceModel)
private EditText etDeviceModel;
@ViewInject(R.id.etShowDeviceInfo)
private EditText etShowDeviceInfo; | // Path: mylibrary/src/main/java/com/itcode/mylibrary/NativeEngine.java
// public class NativeEngine {
// /**
// * 用于将上下文传给 Cpp 层
// *
// * @param activity
// */
// public native void register(Activity activity);
//
// /**
// * 在 Cpp 中加密
// *
// * @param rawStr 原始字符
// * @return 加密后的字符
// */
// public native String encryptInCpp(String rawStr);
//
// /**
// * 在 Cpp 中解密
// *
// * @param cipherText 密文
// * @return 解密后的字符
// */
// public native String decryptInCpp(String cipherText);
//
// /**
// * 通过 cpp 请求网络获取机器配置
// *
// * @param deviceModel 手机设备名
// * @param timeout 超时时间
// * @return
// */
// public native boolean getDeviceInfo(String deviceModel, int timeout);
//
// // Used to load the 'native-lib' library on application startup.
// static {
// System.loadLibrary("native-lib");
// }
// }
// Path: app/src/main/java/com/itcode/jnidemo/MainActivity.java
import android.os.Build;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.text.TextUtils;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;
import com.itcode.mylibrary.NativeEngine;
import org.xutils.view.annotation.ViewInject;
import org.xutils.x;
package com.itcode.jnidemo;
public class MainActivity extends AppCompatActivity implements View.OnClickListener {
@ViewInject(R.id.btnEncrypt)
private Button btnEncrypt;
@ViewInject(R.id.etRawStr)
private EditText etRawStr;
@ViewInject(R.id.etShowCipherText)
private EditText etShowCipherText;
@ViewInject(R.id.btnDecrypt)
private Button btnDecrypt;
@ViewInject(R.id.etdecrypt)
private EditText etdecrypt;
@ViewInject(R.id.etShowClearText)
private EditText etShowClearText;
@ViewInject(R.id.btnGetDeviceInfo)
private Button btnGetDeviceInfo;
@ViewInject(R.id.etDeviceModel)
private EditText etDeviceModel;
@ViewInject(R.id.etShowDeviceInfo)
private EditText etShowDeviceInfo; | NativeEngine nativeEngine; |
Niels-NTG/FTLAV | src/main/java/net/blerf/ftl/constants/FTLConstants.java | // Path: src/main/java/net/blerf/ftl/parser/SavedGameParser.java
// public enum CrewType {
// // TODO: Magic numbers.
// ANAEROBIC("anaerobic", 100),
// BATTLE ("battle", 150),
// CRYSTAL ("crystal", 120),
// ENERGY ("energy", 70),
// ENGI ("engi", 100),
// GHOST ("ghost", 50),
// HUMAN ("human", 100),
// MANTIS ("mantis", 100),
// ROCK ("rock", 150),
// SLUG ("slug", 100);
//
// // The following were introduced in FTL 1.5.4.
// // ANAEROBIC (when DLC is enabled)
//
// private String id;
// private int maxHealth;
// CrewType(String id, int maxHealth) {
// this.id = id;
// this.maxHealth = maxHealth;
// }
// public String getId() { return id; }
// public int getMaxHealth() { return maxHealth; }
// public String toString() { return id; }
//
// public static CrewType findById(String id) {
// for (CrewType race : values()) {
// if (race.getId().equals(id)) return race;
// }
// return null;
// }
//
// public static int getMaxHealth(String id) {
// CrewType race = CrewType.findById(id);
// if (race != null) return race.getMaxHealth();
// throw new RuntimeException("No max health known for crew race: "+ id);
// }
// }
| import net.blerf.ftl.parser.SavedGameParser.CrewType;
import java.util.List; | package net.blerf.ftl.constants;
public interface FTLConstants {
// ShipState constants.
int getMaxReservePoolCapacity();
// SystemState constants.
/**
* Returns the bonus system bars produced by a Battery system.
*
* @param batterySystemCapacity the capacity of the system itself (its level)
*/
int getBatteryPoolCapacity(int batterySystemCapacity);
int getMaxIonizedBars();
// CrewState constants.
| // Path: src/main/java/net/blerf/ftl/parser/SavedGameParser.java
// public enum CrewType {
// // TODO: Magic numbers.
// ANAEROBIC("anaerobic", 100),
// BATTLE ("battle", 150),
// CRYSTAL ("crystal", 120),
// ENERGY ("energy", 70),
// ENGI ("engi", 100),
// GHOST ("ghost", 50),
// HUMAN ("human", 100),
// MANTIS ("mantis", 100),
// ROCK ("rock", 150),
// SLUG ("slug", 100);
//
// // The following were introduced in FTL 1.5.4.
// // ANAEROBIC (when DLC is enabled)
//
// private String id;
// private int maxHealth;
// CrewType(String id, int maxHealth) {
// this.id = id;
// this.maxHealth = maxHealth;
// }
// public String getId() { return id; }
// public int getMaxHealth() { return maxHealth; }
// public String toString() { return id; }
//
// public static CrewType findById(String id) {
// for (CrewType race : values()) {
// if (race.getId().equals(id)) return race;
// }
// return null;
// }
//
// public static int getMaxHealth(String id) {
// CrewType race = CrewType.findById(id);
// if (race != null) return race.getMaxHealth();
// throw new RuntimeException("No max health known for crew race: "+ id);
// }
// }
// Path: src/main/java/net/blerf/ftl/constants/FTLConstants.java
import net.blerf.ftl.parser.SavedGameParser.CrewType;
import java.util.List;
package net.blerf.ftl.constants;
public interface FTLConstants {
// ShipState constants.
int getMaxReservePoolCapacity();
// SystemState constants.
/**
* Returns the bonus system bars produced by a Battery system.
*
* @param batterySystemCapacity the capacity of the system itself (its level)
*/
int getBatteryPoolCapacity(int batterySystemCapacity);
int getMaxIonizedBars();
// CrewState constants.
| List<CrewType> getCrewTypes(); |
Niels-NTG/FTLAV | src/main/java/net/blerf/ftl/xml/ShipBlueprint.java | // Path: src/main/java/net/blerf/ftl/parser/SavedGameParser.java
// public enum SystemType {
// // SystemType ids are tied to "img/icons/s_*_overlay.png" and store item ids.
// // TODO: Magic booleans.
// PILOT ("pilot", true),
// DOORS ("doors", true),
// SENSORS ("sensors", true),
// MEDBAY ("medbay", false),
// OXYGEN ("oxygen", false),
// SHIELDS ("shields", false),
// ENGINES ("engines", false),
// WEAPONS ("weapons", false),
// DRONE_CTRL("drones", false),
// TELEPORTER("teleporter", false),
// CLOAKING ("cloaking", false),
// ARTILLERY ("artillery", false),
// BATTERY ("battery", true),
// CLONEBAY ("clonebay", false),
// MIND ("mind", false),
// HACKING ("hacking", false);
//
// private String id;
// private boolean subsystem;
// SystemType(String id, boolean subsystem) {
// this.id = id;
// this.subsystem = subsystem;
// }
// public String getId() { return id; }
// public boolean isSubsystem() { return subsystem; }
// public String toString() { return id; }
//
// public static SystemType findById(String id) {
// for (SystemType s : values()) {
// if (s.getId().equals(id)) return s;
// }
// return null;
// }
// }
| import net.blerf.ftl.parser.SavedGameParser.SystemType;
import javax.xml.bind.annotation.*;
import java.util.ArrayList;
import java.util.List; |
public SystemRoom getCloakRoom() {
return cloakRoom;
}
public List<SystemRoom> getArtilleryRooms() {
return artilleryRooms;
}
public SystemRoom getCloneRoom() {
return cloneRoom;
}
public SystemRoom getHackRoom() {
return hackRoom;
}
public SystemRoom getMindRoom() {
return mindRoom;
}
public SystemRoom getBatteryRoom() {
return batteryRoom;
}
/**
* Returns SystemRooms, or null if not present.
*
* @return an array of SystemRooms, usually only containing one
*/ | // Path: src/main/java/net/blerf/ftl/parser/SavedGameParser.java
// public enum SystemType {
// // SystemType ids are tied to "img/icons/s_*_overlay.png" and store item ids.
// // TODO: Magic booleans.
// PILOT ("pilot", true),
// DOORS ("doors", true),
// SENSORS ("sensors", true),
// MEDBAY ("medbay", false),
// OXYGEN ("oxygen", false),
// SHIELDS ("shields", false),
// ENGINES ("engines", false),
// WEAPONS ("weapons", false),
// DRONE_CTRL("drones", false),
// TELEPORTER("teleporter", false),
// CLOAKING ("cloaking", false),
// ARTILLERY ("artillery", false),
// BATTERY ("battery", true),
// CLONEBAY ("clonebay", false),
// MIND ("mind", false),
// HACKING ("hacking", false);
//
// private String id;
// private boolean subsystem;
// SystemType(String id, boolean subsystem) {
// this.id = id;
// this.subsystem = subsystem;
// }
// public String getId() { return id; }
// public boolean isSubsystem() { return subsystem; }
// public String toString() { return id; }
//
// public static SystemType findById(String id) {
// for (SystemType s : values()) {
// if (s.getId().equals(id)) return s;
// }
// return null;
// }
// }
// Path: src/main/java/net/blerf/ftl/xml/ShipBlueprint.java
import net.blerf.ftl.parser.SavedGameParser.SystemType;
import javax.xml.bind.annotation.*;
import java.util.ArrayList;
import java.util.List;
public SystemRoom getCloakRoom() {
return cloakRoom;
}
public List<SystemRoom> getArtilleryRooms() {
return artilleryRooms;
}
public SystemRoom getCloneRoom() {
return cloneRoom;
}
public SystemRoom getHackRoom() {
return hackRoom;
}
public SystemRoom getMindRoom() {
return mindRoom;
}
public SystemRoom getBatteryRoom() {
return batteryRoom;
}
/**
* Returns SystemRooms, or null if not present.
*
* @return an array of SystemRooms, usually only containing one
*/ | public SystemList.SystemRoom[] getSystemRoom(SystemType systemType) { |
Gogolook-Inc/GogoMonkeyRun | UICompareRunner/com/james/uicomparerunner/ui/SocketFrame.java | // Path: UICompareRunner/com/james/uicomparerunner/ui/uiinterface/OnWindowCloseListener.java
// public interface OnWindowCloseListener {
// public void onWindowClosing(String... output);
// }
| import java.awt.BorderLayout;
import java.awt.event.WindowEvent;
import java.awt.event.WindowListener;
import javax.swing.JFrame;
import javax.swing.JTextPane;
import javax.swing.SwingUtilities;
import com.james.uicomparerunner.ui.uiinterface.OnWindowCloseListener; |
package com.james.uicomparerunner.ui;
public class SocketFrame extends JFrame {
private JTextPane devicePane;
| // Path: UICompareRunner/com/james/uicomparerunner/ui/uiinterface/OnWindowCloseListener.java
// public interface OnWindowCloseListener {
// public void onWindowClosing(String... output);
// }
// Path: UICompareRunner/com/james/uicomparerunner/ui/SocketFrame.java
import java.awt.BorderLayout;
import java.awt.event.WindowEvent;
import java.awt.event.WindowListener;
import javax.swing.JFrame;
import javax.swing.JTextPane;
import javax.swing.SwingUtilities;
import com.james.uicomparerunner.ui.uiinterface.OnWindowCloseListener;
package com.james.uicomparerunner.ui;
public class SocketFrame extends JFrame {
private JTextPane devicePane;
| public SocketFrame(JFrame parentFrame, final OnWindowCloseListener onWindowCloseListener) { |
yoichiro/oauth2-server | src/test/java/jp/eisbahn/oauth2/server/models/ClientCredentialTest.java | // Path: src/main/java/jp/eisbahn/oauth2/server/models/ClientCredential.java
// public class ClientCredential {
//
// private String clientId;
// private String clientSecret;
//
// /**
// * Initialize this instance with arguments.
// * @param clientId The client ID.
// * @param clientSecret The client secret string.
// */
// public ClientCredential(String clientId, String clientSecret) {
// super();
// this.clientId = clientId;
// this.clientSecret = clientSecret;
// }
//
// /**
// * Retrieve the client ID.
// * @return The client ID.
// */
// public String getClientId() {
// return clientId;
// }
//
// /**
// * Retrieve the client secret.
// * @return The client secret.
// */
// public String getClientSecret() {
// return clientSecret;
// }
//
// }
| import static org.junit.Assert.*;
import jp.eisbahn.oauth2.server.models.ClientCredential;
import org.junit.Test; | /*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations under the License.
*/
package jp.eisbahn.oauth2.server.models;
public class ClientCredentialTest {
@Test
public void testSimple() {
String clientId = "clientId1";
String clientSecret = "clientSecret1"; | // Path: src/main/java/jp/eisbahn/oauth2/server/models/ClientCredential.java
// public class ClientCredential {
//
// private String clientId;
// private String clientSecret;
//
// /**
// * Initialize this instance with arguments.
// * @param clientId The client ID.
// * @param clientSecret The client secret string.
// */
// public ClientCredential(String clientId, String clientSecret) {
// super();
// this.clientId = clientId;
// this.clientSecret = clientSecret;
// }
//
// /**
// * Retrieve the client ID.
// * @return The client ID.
// */
// public String getClientId() {
// return clientId;
// }
//
// /**
// * Retrieve the client secret.
// * @return The client secret.
// */
// public String getClientSecret() {
// return clientSecret;
// }
//
// }
// Path: src/test/java/jp/eisbahn/oauth2/server/models/ClientCredentialTest.java
import static org.junit.Assert.*;
import jp.eisbahn.oauth2.server.models.ClientCredential;
import org.junit.Test;
/*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations under the License.
*/
package jp.eisbahn.oauth2.server.models;
public class ClientCredentialTest {
@Test
public void testSimple() {
String clientId = "clientId1";
String clientSecret = "clientSecret1"; | ClientCredential target = new ClientCredential(clientId, clientSecret); |
yoichiro/oauth2-server | src/main/java/jp/eisbahn/oauth2/server/fetcher/accesstoken/AccessTokenFetcherProvider.java | // Path: src/main/java/jp/eisbahn/oauth2/server/models/Request.java
// public interface Request {
//
// /**
// * Retrieve the parameter value specified by the parameter name
// * from the request.
// * @param name The parameter name.
// * @return The value against the name.
// */
// public String getParameter(String name);
//
// /**
// * Retrieve all parameter names and values from the request as a Map instance.
// * @return The map instance which has all parameter names and values.
// */
// public Map<String, String> getParameterMap();
//
// /**
// * Retrieve the request header value from the request.
// * @param name The header's name.
// * @return The value against the name.
// */
// public String getHeader(String name);
//
// }
| import jp.eisbahn.oauth2.server.models.Request; | /*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations under the License.
*/
package jp.eisbahn.oauth2.server.fetcher.accesstoken;
/**
* This class provides AccessTokenFetcher implementation classes supported.
* For instance, the request is passed, then this class checks whether
* a fetcher class which can fetch an access token from the request exists or
* not with a match() method of each implementation class.
*
* @author Yoichiro Tanaka
*
*/
public class AccessTokenFetcherProvider {
private AccessTokenFetcher[] fetchers;
/**
* Find a fetcher instance which can fetch an access token from the request
* passed as an argument value and return it. The match() method of each
* implementation class is used to confirm whether the access token can be
* fetched or not.
*
* @param request The request object.
* @return The fetcher instance which can fetch an access token from
* the request. If not found, return null.
*/ | // Path: src/main/java/jp/eisbahn/oauth2/server/models/Request.java
// public interface Request {
//
// /**
// * Retrieve the parameter value specified by the parameter name
// * from the request.
// * @param name The parameter name.
// * @return The value against the name.
// */
// public String getParameter(String name);
//
// /**
// * Retrieve all parameter names and values from the request as a Map instance.
// * @return The map instance which has all parameter names and values.
// */
// public Map<String, String> getParameterMap();
//
// /**
// * Retrieve the request header value from the request.
// * @param name The header's name.
// * @return The value against the name.
// */
// public String getHeader(String name);
//
// }
// Path: src/main/java/jp/eisbahn/oauth2/server/fetcher/accesstoken/AccessTokenFetcherProvider.java
import jp.eisbahn.oauth2.server.models.Request;
/*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations under the License.
*/
package jp.eisbahn.oauth2.server.fetcher.accesstoken;
/**
* This class provides AccessTokenFetcher implementation classes supported.
* For instance, the request is passed, then this class checks whether
* a fetcher class which can fetch an access token from the request exists or
* not with a match() method of each implementation class.
*
* @author Yoichiro Tanaka
*
*/
public class AccessTokenFetcherProvider {
private AccessTokenFetcher[] fetchers;
/**
* Find a fetcher instance which can fetch an access token from the request
* passed as an argument value and return it. The match() method of each
* implementation class is used to confirm whether the access token can be
* fetched or not.
*
* @param request The request object.
* @return The fetcher instance which can fetch an access token from
* the request. If not found, return null.
*/ | public AccessTokenFetcher getFetcher(Request request) { |
yoichiro/oauth2-server | src/test/java/jp/eisbahn/oauth2/server/fetcher/accesstoken/impl/RequestParameterTest.java | // Path: src/main/java/jp/eisbahn/oauth2/server/fetcher/accesstoken/AccessTokenFetcher.java
// public static class FetchResult {
//
// private String token;
// private Map<String, String> params;
//
// /**
// * This constructor initializes like both parameters become a null value.
// */
// public FetchResult() {
// this(null, null);
// }
//
// /**
// * This constructor initializes with the specified argument values.
// * @param token The access token string.
// * @param params Other parameters.
// */
// public FetchResult(String token, Map<String, String> params) {
// super();
// this.token = token;
// this.params = params;
// }
//
// /**
// * Set the access token.
// * @param token The token string.
// */
// public void setToken(String token) {
// this.token = token;
// }
//
// /**
// * Retrieve the access token.
// * @return The token string.
// */
// public String getToken() {
// return token;
// }
//
// /**
// * Set other parameters.
// * @param params The other parameter map object.
// */
// public void setParams(Map<String, String> params) {
// this.params = params;
// }
//
// /**
// * Retrieve the other parameters.
// * @return The other parameter map object.
// */
// public Map<String, String> getParams() {
// return params;
// }
//
// }
//
// Path: src/main/java/jp/eisbahn/oauth2/server/fetcher/accesstoken/impl/RequestParameter.java
// public class RequestParameter implements AccessTokenFetcher {
//
// /**
// * Return whether an access token is included in the request parameter's
// * values. Actually, this method confirms whether the "oauth_token" or
// * "access_token" request parameter exists or not.
// *
// * @param request The request object.
// * @return If either parameter exists, this result is true.
// */
// @Override
// public boolean match(Request request) {
// String oauthToken = request.getParameter("oauth_token");
// String accessToken = request.getParameter("access_token");
// return StringUtils.isNotEmpty(accessToken)
// || StringUtils.isNotEmpty(oauthToken);
// }
//
// /**
// * Fetch an access token from a request parameter and return it.
// * This method must be called when a result of the match() method is true
// * only.
// *
// * @param request The request object.
// * @return the fetched access token.
// */
// @Override
// public FetchResult fetch(Request request) {
// Map<String, String> params = new HashMap<String, String>();
// Map<String, String> parameterMap = request.getParameterMap();
// params.putAll(parameterMap);
// String token = params.get("access_token");
// params.remove("access_token");
// if (StringUtils.isNotEmpty(params.get("oauth_token"))) {
// token = params.get("oauth_token");
// params.remove("oauth_token");
// }
// return new FetchResult(token, params);
// }
//
// }
//
// Path: src/main/java/jp/eisbahn/oauth2/server/models/Request.java
// public interface Request {
//
// /**
// * Retrieve the parameter value specified by the parameter name
// * from the request.
// * @param name The parameter name.
// * @return The value against the name.
// */
// public String getParameter(String name);
//
// /**
// * Retrieve all parameter names and values from the request as a Map instance.
// * @return The map instance which has all parameter names and values.
// */
// public Map<String, String> getParameterMap();
//
// /**
// * Retrieve the request header value from the request.
// * @param name The header's name.
// * @return The value against the name.
// */
// public String getHeader(String name);
//
// }
| import org.junit.After;
import org.junit.Before;
import org.junit.Test;
import jp.eisbahn.oauth2.server.fetcher.accesstoken.AccessTokenFetcher.FetchResult;
import jp.eisbahn.oauth2.server.fetcher.accesstoken.impl.RequestParameter;
import jp.eisbahn.oauth2.server.models.Request;
import static org.easymock.EasyMock.createMock;
import static org.easymock.EasyMock.expect;
import static org.easymock.EasyMock.replay;
import static org.easymock.EasyMock.verify;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertTrue;
import java.util.HashMap;
import java.util.Map;
import org.apache.commons.collections.MapUtils; | /*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations under the License.
*/
package jp.eisbahn.oauth2.server.fetcher.accesstoken.impl;
public class RequestParameterTest {
private RequestParameter target;
@Before
public void setUp() throws Exception {
target = new RequestParameter();
}
@After
public void tearDown() throws Exception {
target = null;
}
@Test
public void testMatch() throws Exception { | // Path: src/main/java/jp/eisbahn/oauth2/server/fetcher/accesstoken/AccessTokenFetcher.java
// public static class FetchResult {
//
// private String token;
// private Map<String, String> params;
//
// /**
// * This constructor initializes like both parameters become a null value.
// */
// public FetchResult() {
// this(null, null);
// }
//
// /**
// * This constructor initializes with the specified argument values.
// * @param token The access token string.
// * @param params Other parameters.
// */
// public FetchResult(String token, Map<String, String> params) {
// super();
// this.token = token;
// this.params = params;
// }
//
// /**
// * Set the access token.
// * @param token The token string.
// */
// public void setToken(String token) {
// this.token = token;
// }
//
// /**
// * Retrieve the access token.
// * @return The token string.
// */
// public String getToken() {
// return token;
// }
//
// /**
// * Set other parameters.
// * @param params The other parameter map object.
// */
// public void setParams(Map<String, String> params) {
// this.params = params;
// }
//
// /**
// * Retrieve the other parameters.
// * @return The other parameter map object.
// */
// public Map<String, String> getParams() {
// return params;
// }
//
// }
//
// Path: src/main/java/jp/eisbahn/oauth2/server/fetcher/accesstoken/impl/RequestParameter.java
// public class RequestParameter implements AccessTokenFetcher {
//
// /**
// * Return whether an access token is included in the request parameter's
// * values. Actually, this method confirms whether the "oauth_token" or
// * "access_token" request parameter exists or not.
// *
// * @param request The request object.
// * @return If either parameter exists, this result is true.
// */
// @Override
// public boolean match(Request request) {
// String oauthToken = request.getParameter("oauth_token");
// String accessToken = request.getParameter("access_token");
// return StringUtils.isNotEmpty(accessToken)
// || StringUtils.isNotEmpty(oauthToken);
// }
//
// /**
// * Fetch an access token from a request parameter and return it.
// * This method must be called when a result of the match() method is true
// * only.
// *
// * @param request The request object.
// * @return the fetched access token.
// */
// @Override
// public FetchResult fetch(Request request) {
// Map<String, String> params = new HashMap<String, String>();
// Map<String, String> parameterMap = request.getParameterMap();
// params.putAll(parameterMap);
// String token = params.get("access_token");
// params.remove("access_token");
// if (StringUtils.isNotEmpty(params.get("oauth_token"))) {
// token = params.get("oauth_token");
// params.remove("oauth_token");
// }
// return new FetchResult(token, params);
// }
//
// }
//
// Path: src/main/java/jp/eisbahn/oauth2/server/models/Request.java
// public interface Request {
//
// /**
// * Retrieve the parameter value specified by the parameter name
// * from the request.
// * @param name The parameter name.
// * @return The value against the name.
// */
// public String getParameter(String name);
//
// /**
// * Retrieve all parameter names and values from the request as a Map instance.
// * @return The map instance which has all parameter names and values.
// */
// public Map<String, String> getParameterMap();
//
// /**
// * Retrieve the request header value from the request.
// * @param name The header's name.
// * @return The value against the name.
// */
// public String getHeader(String name);
//
// }
// Path: src/test/java/jp/eisbahn/oauth2/server/fetcher/accesstoken/impl/RequestParameterTest.java
import org.junit.After;
import org.junit.Before;
import org.junit.Test;
import jp.eisbahn.oauth2.server.fetcher.accesstoken.AccessTokenFetcher.FetchResult;
import jp.eisbahn.oauth2.server.fetcher.accesstoken.impl.RequestParameter;
import jp.eisbahn.oauth2.server.models.Request;
import static org.easymock.EasyMock.createMock;
import static org.easymock.EasyMock.expect;
import static org.easymock.EasyMock.replay;
import static org.easymock.EasyMock.verify;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertTrue;
import java.util.HashMap;
import java.util.Map;
import org.apache.commons.collections.MapUtils;
/*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations under the License.
*/
package jp.eisbahn.oauth2.server.fetcher.accesstoken.impl;
public class RequestParameterTest {
private RequestParameter target;
@Before
public void setUp() throws Exception {
target = new RequestParameter();
}
@After
public void tearDown() throws Exception {
target = null;
}
@Test
public void testMatch() throws Exception { | Request req; |
yoichiro/oauth2-server | src/test/java/jp/eisbahn/oauth2/server/endpoint/ProtectedResourceResponseTest.java | // Path: src/main/java/jp/eisbahn/oauth2/server/endpoint/ProtectedResource.java
// public static class Response {
//
// private String remoteUser;
// private String clientId;
// private String scope;
//
// /**
// * This constructor initializes this instance.
// * @param remoteUser The remote user's ID.
// * @param clientId The client ID.
// * @param scope The scope string authorized by the remote user.
// */
// public Response(String remoteUser, String clientId, String scope) {
// this.remoteUser = remoteUser;
// this.clientId = clientId;
// this.scope = scope;
// }
//
// /**
// * Retrieve the remote user's ID.
// * @return The user ID.
// */
// public String getRemoteUser() {
// return remoteUser;
// }
//
// /**
// * Retrieve the client ID.
// * @return The client ID.
// */
// public String getClientId() {
// return clientId;
// }
//
// /**
// * Retrieve the scope string.
// * @return The scope string authorized by the remote user.
// */
// public String getScope() {
// return scope;
// }
//
// }
| import jp.eisbahn.oauth2.server.endpoint.ProtectedResource.Response;
import static org.junit.Assert.assertEquals;
import org.junit.Test; | /*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations under the License.
*/
package jp.eisbahn.oauth2.server.endpoint;
public class ProtectedResourceResponseTest {
@Test
public void testSimple() { | // Path: src/main/java/jp/eisbahn/oauth2/server/endpoint/ProtectedResource.java
// public static class Response {
//
// private String remoteUser;
// private String clientId;
// private String scope;
//
// /**
// * This constructor initializes this instance.
// * @param remoteUser The remote user's ID.
// * @param clientId The client ID.
// * @param scope The scope string authorized by the remote user.
// */
// public Response(String remoteUser, String clientId, String scope) {
// this.remoteUser = remoteUser;
// this.clientId = clientId;
// this.scope = scope;
// }
//
// /**
// * Retrieve the remote user's ID.
// * @return The user ID.
// */
// public String getRemoteUser() {
// return remoteUser;
// }
//
// /**
// * Retrieve the client ID.
// * @return The client ID.
// */
// public String getClientId() {
// return clientId;
// }
//
// /**
// * Retrieve the scope string.
// * @return The scope string authorized by the remote user.
// */
// public String getScope() {
// return scope;
// }
//
// }
// Path: src/test/java/jp/eisbahn/oauth2/server/endpoint/ProtectedResourceResponseTest.java
import jp.eisbahn.oauth2.server.endpoint.ProtectedResource.Response;
import static org.junit.Assert.assertEquals;
import org.junit.Test;
/*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations under the License.
*/
package jp.eisbahn.oauth2.server.endpoint;
public class ProtectedResourceResponseTest {
@Test
public void testSimple() { | Response target = new Response("remoteUser1", "clientId1", "scope1"); |
yoichiro/oauth2-server | src/test/java/jp/eisbahn/oauth2/server/granttype/GrantHandlerResultTest.java | // Path: src/main/java/jp/eisbahn/oauth2/server/granttype/GrantHandler.java
// @JsonSerialize(include = Inclusion.NON_NULL)
// @JsonPropertyOrder({"token_type",
// "access_token",
// "refresh_token",
// "expires_in",
// "scope"})
// public static class GrantHandlerResult {
//
// @JsonProperty("token_type")
// private String tokenType;
// @JsonProperty("access_token")
// private String accessToken;
// @JsonProperty("expires_in")
// private Long expiresIn;
// @JsonProperty("refresh_token")
// private String refreshToken;
// private String scope;
//
// /**
// * Initialize this instance with these arguments.
// * These parameters is required.
// *
// * @param tokenType The token type string.
// * @param accessToken The access token string.
// */
// public GrantHandlerResult(String tokenType, String accessToken) {
// super();
// this.tokenType = tokenType;
// this.accessToken = accessToken;
// }
//
// /**
// * Retrieve the token type.
// * @return The issued token's type.
// */
// public String getTokenType() {
// return tokenType;
// }
//
// /**
// * Retrieve the access token.
// * @return The issued access token string.
// */
// public String getAccessToken() {
// return accessToken;
// }
//
// /**
// * Set the expires_in parameter's value.
// * An unit of this value is second.
// * @param expiresIn The expires_in value.
// */
// public void setExpiresIn(Long expiresIn) {
// this.expiresIn = expiresIn;
// }
//
// /**
// * Retrieve the expires_in value.
// * @return The expires_in value (this unit is second).
// */
// public Long getExpiresIn() {
// return expiresIn;
// }
//
// /**
// * Set the refresh token.
// * If a grant type which issues the refresh token is specified,
// * the issued refresh token is passed to the client via this method.
// * @param refreshToken The refresh token string.
// */
// public void setRefreshToken(String refreshToken) {
// this.refreshToken = refreshToken;
// }
//
// /**
// * Retrieve the refresh token.
// * @return The issued refresh token string.
// */
// public String getRefreshToken() {
// return refreshToken;
// }
//
// /**
// * Set the scope string.
// * This scope string specified by the client is passed to
// * this method untouched.
// * @param scope The scope string.
// */
// public void setScope(String scope) {
// this.scope = scope;
// }
//
// /**
// * Retrieve the scope string.
// * @return The scope string.
// */
// public String getScope() {
// return scope;
// }
//
// }
| import jp.eisbahn.oauth2.server.granttype.GrantHandler.GrantHandlerResult;
import static org.junit.Assert.*;
import org.junit.Test; | /*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations under the License.
*/
package jp.eisbahn.oauth2.server.granttype;
public class GrantHandlerResultTest {
@Test
public void testSimple() { | // Path: src/main/java/jp/eisbahn/oauth2/server/granttype/GrantHandler.java
// @JsonSerialize(include = Inclusion.NON_NULL)
// @JsonPropertyOrder({"token_type",
// "access_token",
// "refresh_token",
// "expires_in",
// "scope"})
// public static class GrantHandlerResult {
//
// @JsonProperty("token_type")
// private String tokenType;
// @JsonProperty("access_token")
// private String accessToken;
// @JsonProperty("expires_in")
// private Long expiresIn;
// @JsonProperty("refresh_token")
// private String refreshToken;
// private String scope;
//
// /**
// * Initialize this instance with these arguments.
// * These parameters is required.
// *
// * @param tokenType The token type string.
// * @param accessToken The access token string.
// */
// public GrantHandlerResult(String tokenType, String accessToken) {
// super();
// this.tokenType = tokenType;
// this.accessToken = accessToken;
// }
//
// /**
// * Retrieve the token type.
// * @return The issued token's type.
// */
// public String getTokenType() {
// return tokenType;
// }
//
// /**
// * Retrieve the access token.
// * @return The issued access token string.
// */
// public String getAccessToken() {
// return accessToken;
// }
//
// /**
// * Set the expires_in parameter's value.
// * An unit of this value is second.
// * @param expiresIn The expires_in value.
// */
// public void setExpiresIn(Long expiresIn) {
// this.expiresIn = expiresIn;
// }
//
// /**
// * Retrieve the expires_in value.
// * @return The expires_in value (this unit is second).
// */
// public Long getExpiresIn() {
// return expiresIn;
// }
//
// /**
// * Set the refresh token.
// * If a grant type which issues the refresh token is specified,
// * the issued refresh token is passed to the client via this method.
// * @param refreshToken The refresh token string.
// */
// public void setRefreshToken(String refreshToken) {
// this.refreshToken = refreshToken;
// }
//
// /**
// * Retrieve the refresh token.
// * @return The issued refresh token string.
// */
// public String getRefreshToken() {
// return refreshToken;
// }
//
// /**
// * Set the scope string.
// * This scope string specified by the client is passed to
// * this method untouched.
// * @param scope The scope string.
// */
// public void setScope(String scope) {
// this.scope = scope;
// }
//
// /**
// * Retrieve the scope string.
// * @return The scope string.
// */
// public String getScope() {
// return scope;
// }
//
// }
// Path: src/test/java/jp/eisbahn/oauth2/server/granttype/GrantHandlerResultTest.java
import jp.eisbahn.oauth2.server.granttype.GrantHandler.GrantHandlerResult;
import static org.junit.Assert.*;
import org.junit.Test;
/*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations under the License.
*/
package jp.eisbahn.oauth2.server.granttype;
public class GrantHandlerResultTest {
@Test
public void testSimple() { | GrantHandlerResult target = new GrantHandlerResult( |
yoichiro/oauth2-server | src/test/java/jp/eisbahn/oauth2/server/endpoint/TokenResponseTest.java | // Path: src/main/java/jp/eisbahn/oauth2/server/endpoint/Token.java
// public static class Response {
//
// private int code;
// private String body;
//
// /**
// * Initialize this instance with arguments passed.
// * @param code The status code as the result of issuing a token.
// * @param body The JSON string which has a token information.
// */
// public Response(int code, String body) {
// super();
// this.code = code;
// this.body = body;
// }
//
// /**
// * Retrieve the status code value.
// * This status code will be 200 when the issuing token is succeeded.
// * If an error occurs, the code will be the 300 series value.
// * @return The HTTP status code value.
// */
// public int getCode() {
// return code;
// }
//
// /**
// * Retrieve the JSON string which has a token information.
// * The JSON string has the access token, refresh token, expires_in
// * value and the scope string. If the issuing a token failed,
// * this json string has the error type and description.
// * @return The JSON string value.
// */
// public String getBody() {
// return body;
// }
//
// }
| import jp.eisbahn.oauth2.server.endpoint.Token.Response;
import static org.junit.Assert.*;
import org.junit.Test; | /*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations under the License.
*/
package jp.eisbahn.oauth2.server.endpoint;
public class TokenResponseTest {
@Test
public void testSimple() { | // Path: src/main/java/jp/eisbahn/oauth2/server/endpoint/Token.java
// public static class Response {
//
// private int code;
// private String body;
//
// /**
// * Initialize this instance with arguments passed.
// * @param code The status code as the result of issuing a token.
// * @param body The JSON string which has a token information.
// */
// public Response(int code, String body) {
// super();
// this.code = code;
// this.body = body;
// }
//
// /**
// * Retrieve the status code value.
// * This status code will be 200 when the issuing token is succeeded.
// * If an error occurs, the code will be the 300 series value.
// * @return The HTTP status code value.
// */
// public int getCode() {
// return code;
// }
//
// /**
// * Retrieve the JSON string which has a token information.
// * The JSON string has the access token, refresh token, expires_in
// * value and the scope string. If the issuing a token failed,
// * this json string has the error type and description.
// * @return The JSON string value.
// */
// public String getBody() {
// return body;
// }
//
// }
// Path: src/test/java/jp/eisbahn/oauth2/server/endpoint/TokenResponseTest.java
import jp.eisbahn.oauth2.server.endpoint.Token.Response;
import static org.junit.Assert.*;
import org.junit.Test;
/*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations under the License.
*/
package jp.eisbahn.oauth2.server.endpoint;
public class TokenResponseTest {
@Test
public void testSimple() { | Response target = new Response(200, "body1"); |
yoichiro/oauth2-server | src/main/java/jp/eisbahn/oauth2/server/fetcher/clientcredential/ClientCredentialFetcherImpl.java | // Path: src/main/java/jp/eisbahn/oauth2/server/models/ClientCredential.java
// public class ClientCredential {
//
// private String clientId;
// private String clientSecret;
//
// /**
// * Initialize this instance with arguments.
// * @param clientId The client ID.
// * @param clientSecret The client secret string.
// */
// public ClientCredential(String clientId, String clientSecret) {
// super();
// this.clientId = clientId;
// this.clientSecret = clientSecret;
// }
//
// /**
// * Retrieve the client ID.
// * @return The client ID.
// */
// public String getClientId() {
// return clientId;
// }
//
// /**
// * Retrieve the client secret.
// * @return The client secret.
// */
// public String getClientSecret() {
// return clientSecret;
// }
//
// }
//
// Path: src/main/java/jp/eisbahn/oauth2/server/models/Request.java
// public interface Request {
//
// /**
// * Retrieve the parameter value specified by the parameter name
// * from the request.
// * @param name The parameter name.
// * @return The value against the name.
// */
// public String getParameter(String name);
//
// /**
// * Retrieve all parameter names and values from the request as a Map instance.
// * @return The map instance which has all parameter names and values.
// */
// public Map<String, String> getParameterMap();
//
// /**
// * Retrieve the request header value from the request.
// * @param name The header's name.
// * @return The value against the name.
// */
// public String getHeader(String name);
//
// }
//
// Path: src/main/java/jp/eisbahn/oauth2/server/utils/Util.java
// public class Util {
//
// /**
// * Decode the URL encoded string.
// * @param source The URL encoded string.
// * @return The decoded original string.
// */
// public static String decodeParam(String source) {
// try {
// return URLDecoder.decode(source, "UTF-8");
// } catch (UnsupportedEncodingException e) {
// throw new IllegalStateException(e);
// }
// }
//
// /**
// * Decode the BASE64 encoded string.
// * @param source The BASE64 string.
// * @return The decoded original string.
// */
// public static String decodeBase64(String source) {
// try {
// return new String(Base64.decodeBase64(source), "UTF-8");
// } catch (UnsupportedEncodingException e) {
// throw new IllegalStateException(e);
// }
// }
//
// /**
// * Encode the object to JSON format string.
// * @param source The object that you want to change to JSON string.
// * @return The JSON encoded string.
// * @throws IllegalStateException If the translation failed.
// */
// public static String toJson(Object source) {
// try {
// ObjectMapper mapper = new ObjectMapper();
// return mapper.writeValueAsString(source);
// } catch (JsonGenerationException e) {
// throw new IllegalStateException(e);
// } catch (JsonMappingException e) {
// throw new IllegalStateException(e);
// } catch (IOException e) {
// throw new IllegalStateException(e);
// }
// }
//
// }
| import java.util.regex.Matcher;
import java.util.regex.Pattern;
import jp.eisbahn.oauth2.server.models.ClientCredential;
import jp.eisbahn.oauth2.server.models.Request;
import jp.eisbahn.oauth2.server.utils.Util; | /*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations under the License.
*/
package jp.eisbahn.oauth2.server.fetcher.clientcredential;
/**
* This implementation provides a client credential information
* from a request header or request parameters
*
* @author Yoichiro Tanaka
*
*/
public class ClientCredentialFetcherImpl implements ClientCredentialFetcher {
private static final Pattern REGEXP_BASIC =
Pattern.compile("^\\s*(Basic)\\s+(.*)$");
/**
* Fetch a client credential sent from the client as a request header
* or request parameters. First, this method attempts to fetch it from
* the Authorization request header. For instance, it is expected as the
* format "Basic [Base64 encoded]". The encoded value actually has two
* parameter "Client ID" and "Client secret" delimited by ":" character.
* If it does not exist, this method attempt to fetch it from request
* parameter named "client_id" and "client_secret".
*
* @param request The request object.
* @return The client credential information.
*/
@Override | // Path: src/main/java/jp/eisbahn/oauth2/server/models/ClientCredential.java
// public class ClientCredential {
//
// private String clientId;
// private String clientSecret;
//
// /**
// * Initialize this instance with arguments.
// * @param clientId The client ID.
// * @param clientSecret The client secret string.
// */
// public ClientCredential(String clientId, String clientSecret) {
// super();
// this.clientId = clientId;
// this.clientSecret = clientSecret;
// }
//
// /**
// * Retrieve the client ID.
// * @return The client ID.
// */
// public String getClientId() {
// return clientId;
// }
//
// /**
// * Retrieve the client secret.
// * @return The client secret.
// */
// public String getClientSecret() {
// return clientSecret;
// }
//
// }
//
// Path: src/main/java/jp/eisbahn/oauth2/server/models/Request.java
// public interface Request {
//
// /**
// * Retrieve the parameter value specified by the parameter name
// * from the request.
// * @param name The parameter name.
// * @return The value against the name.
// */
// public String getParameter(String name);
//
// /**
// * Retrieve all parameter names and values from the request as a Map instance.
// * @return The map instance which has all parameter names and values.
// */
// public Map<String, String> getParameterMap();
//
// /**
// * Retrieve the request header value from the request.
// * @param name The header's name.
// * @return The value against the name.
// */
// public String getHeader(String name);
//
// }
//
// Path: src/main/java/jp/eisbahn/oauth2/server/utils/Util.java
// public class Util {
//
// /**
// * Decode the URL encoded string.
// * @param source The URL encoded string.
// * @return The decoded original string.
// */
// public static String decodeParam(String source) {
// try {
// return URLDecoder.decode(source, "UTF-8");
// } catch (UnsupportedEncodingException e) {
// throw new IllegalStateException(e);
// }
// }
//
// /**
// * Decode the BASE64 encoded string.
// * @param source The BASE64 string.
// * @return The decoded original string.
// */
// public static String decodeBase64(String source) {
// try {
// return new String(Base64.decodeBase64(source), "UTF-8");
// } catch (UnsupportedEncodingException e) {
// throw new IllegalStateException(e);
// }
// }
//
// /**
// * Encode the object to JSON format string.
// * @param source The object that you want to change to JSON string.
// * @return The JSON encoded string.
// * @throws IllegalStateException If the translation failed.
// */
// public static String toJson(Object source) {
// try {
// ObjectMapper mapper = new ObjectMapper();
// return mapper.writeValueAsString(source);
// } catch (JsonGenerationException e) {
// throw new IllegalStateException(e);
// } catch (JsonMappingException e) {
// throw new IllegalStateException(e);
// } catch (IOException e) {
// throw new IllegalStateException(e);
// }
// }
//
// }
// Path: src/main/java/jp/eisbahn/oauth2/server/fetcher/clientcredential/ClientCredentialFetcherImpl.java
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import jp.eisbahn.oauth2.server.models.ClientCredential;
import jp.eisbahn.oauth2.server.models.Request;
import jp.eisbahn.oauth2.server.utils.Util;
/*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations under the License.
*/
package jp.eisbahn.oauth2.server.fetcher.clientcredential;
/**
* This implementation provides a client credential information
* from a request header or request parameters
*
* @author Yoichiro Tanaka
*
*/
public class ClientCredentialFetcherImpl implements ClientCredentialFetcher {
private static final Pattern REGEXP_BASIC =
Pattern.compile("^\\s*(Basic)\\s+(.*)$");
/**
* Fetch a client credential sent from the client as a request header
* or request parameters. First, this method attempts to fetch it from
* the Authorization request header. For instance, it is expected as the
* format "Basic [Base64 encoded]". The encoded value actually has two
* parameter "Client ID" and "Client secret" delimited by ":" character.
* If it does not exist, this method attempt to fetch it from request
* parameter named "client_id" and "client_secret".
*
* @param request The request object.
* @return The client credential information.
*/
@Override | public ClientCredential fetch(Request request) { |
yoichiro/oauth2-server | src/main/java/jp/eisbahn/oauth2/server/fetcher/clientcredential/ClientCredentialFetcherImpl.java | // Path: src/main/java/jp/eisbahn/oauth2/server/models/ClientCredential.java
// public class ClientCredential {
//
// private String clientId;
// private String clientSecret;
//
// /**
// * Initialize this instance with arguments.
// * @param clientId The client ID.
// * @param clientSecret The client secret string.
// */
// public ClientCredential(String clientId, String clientSecret) {
// super();
// this.clientId = clientId;
// this.clientSecret = clientSecret;
// }
//
// /**
// * Retrieve the client ID.
// * @return The client ID.
// */
// public String getClientId() {
// return clientId;
// }
//
// /**
// * Retrieve the client secret.
// * @return The client secret.
// */
// public String getClientSecret() {
// return clientSecret;
// }
//
// }
//
// Path: src/main/java/jp/eisbahn/oauth2/server/models/Request.java
// public interface Request {
//
// /**
// * Retrieve the parameter value specified by the parameter name
// * from the request.
// * @param name The parameter name.
// * @return The value against the name.
// */
// public String getParameter(String name);
//
// /**
// * Retrieve all parameter names and values from the request as a Map instance.
// * @return The map instance which has all parameter names and values.
// */
// public Map<String, String> getParameterMap();
//
// /**
// * Retrieve the request header value from the request.
// * @param name The header's name.
// * @return The value against the name.
// */
// public String getHeader(String name);
//
// }
//
// Path: src/main/java/jp/eisbahn/oauth2/server/utils/Util.java
// public class Util {
//
// /**
// * Decode the URL encoded string.
// * @param source The URL encoded string.
// * @return The decoded original string.
// */
// public static String decodeParam(String source) {
// try {
// return URLDecoder.decode(source, "UTF-8");
// } catch (UnsupportedEncodingException e) {
// throw new IllegalStateException(e);
// }
// }
//
// /**
// * Decode the BASE64 encoded string.
// * @param source The BASE64 string.
// * @return The decoded original string.
// */
// public static String decodeBase64(String source) {
// try {
// return new String(Base64.decodeBase64(source), "UTF-8");
// } catch (UnsupportedEncodingException e) {
// throw new IllegalStateException(e);
// }
// }
//
// /**
// * Encode the object to JSON format string.
// * @param source The object that you want to change to JSON string.
// * @return The JSON encoded string.
// * @throws IllegalStateException If the translation failed.
// */
// public static String toJson(Object source) {
// try {
// ObjectMapper mapper = new ObjectMapper();
// return mapper.writeValueAsString(source);
// } catch (JsonGenerationException e) {
// throw new IllegalStateException(e);
// } catch (JsonMappingException e) {
// throw new IllegalStateException(e);
// } catch (IOException e) {
// throw new IllegalStateException(e);
// }
// }
//
// }
| import java.util.regex.Matcher;
import java.util.regex.Pattern;
import jp.eisbahn.oauth2.server.models.ClientCredential;
import jp.eisbahn.oauth2.server.models.Request;
import jp.eisbahn.oauth2.server.utils.Util; | /*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations under the License.
*/
package jp.eisbahn.oauth2.server.fetcher.clientcredential;
/**
* This implementation provides a client credential information
* from a request header or request parameters
*
* @author Yoichiro Tanaka
*
*/
public class ClientCredentialFetcherImpl implements ClientCredentialFetcher {
private static final Pattern REGEXP_BASIC =
Pattern.compile("^\\s*(Basic)\\s+(.*)$");
/**
* Fetch a client credential sent from the client as a request header
* or request parameters. First, this method attempts to fetch it from
* the Authorization request header. For instance, it is expected as the
* format "Basic [Base64 encoded]". The encoded value actually has two
* parameter "Client ID" and "Client secret" delimited by ":" character.
* If it does not exist, this method attempt to fetch it from request
* parameter named "client_id" and "client_secret".
*
* @param request The request object.
* @return The client credential information.
*/
@Override | // Path: src/main/java/jp/eisbahn/oauth2/server/models/ClientCredential.java
// public class ClientCredential {
//
// private String clientId;
// private String clientSecret;
//
// /**
// * Initialize this instance with arguments.
// * @param clientId The client ID.
// * @param clientSecret The client secret string.
// */
// public ClientCredential(String clientId, String clientSecret) {
// super();
// this.clientId = clientId;
// this.clientSecret = clientSecret;
// }
//
// /**
// * Retrieve the client ID.
// * @return The client ID.
// */
// public String getClientId() {
// return clientId;
// }
//
// /**
// * Retrieve the client secret.
// * @return The client secret.
// */
// public String getClientSecret() {
// return clientSecret;
// }
//
// }
//
// Path: src/main/java/jp/eisbahn/oauth2/server/models/Request.java
// public interface Request {
//
// /**
// * Retrieve the parameter value specified by the parameter name
// * from the request.
// * @param name The parameter name.
// * @return The value against the name.
// */
// public String getParameter(String name);
//
// /**
// * Retrieve all parameter names and values from the request as a Map instance.
// * @return The map instance which has all parameter names and values.
// */
// public Map<String, String> getParameterMap();
//
// /**
// * Retrieve the request header value from the request.
// * @param name The header's name.
// * @return The value against the name.
// */
// public String getHeader(String name);
//
// }
//
// Path: src/main/java/jp/eisbahn/oauth2/server/utils/Util.java
// public class Util {
//
// /**
// * Decode the URL encoded string.
// * @param source The URL encoded string.
// * @return The decoded original string.
// */
// public static String decodeParam(String source) {
// try {
// return URLDecoder.decode(source, "UTF-8");
// } catch (UnsupportedEncodingException e) {
// throw new IllegalStateException(e);
// }
// }
//
// /**
// * Decode the BASE64 encoded string.
// * @param source The BASE64 string.
// * @return The decoded original string.
// */
// public static String decodeBase64(String source) {
// try {
// return new String(Base64.decodeBase64(source), "UTF-8");
// } catch (UnsupportedEncodingException e) {
// throw new IllegalStateException(e);
// }
// }
//
// /**
// * Encode the object to JSON format string.
// * @param source The object that you want to change to JSON string.
// * @return The JSON encoded string.
// * @throws IllegalStateException If the translation failed.
// */
// public static String toJson(Object source) {
// try {
// ObjectMapper mapper = new ObjectMapper();
// return mapper.writeValueAsString(source);
// } catch (JsonGenerationException e) {
// throw new IllegalStateException(e);
// } catch (JsonMappingException e) {
// throw new IllegalStateException(e);
// } catch (IOException e) {
// throw new IllegalStateException(e);
// }
// }
//
// }
// Path: src/main/java/jp/eisbahn/oauth2/server/fetcher/clientcredential/ClientCredentialFetcherImpl.java
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import jp.eisbahn.oauth2.server.models.ClientCredential;
import jp.eisbahn.oauth2.server.models.Request;
import jp.eisbahn.oauth2.server.utils.Util;
/*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations under the License.
*/
package jp.eisbahn.oauth2.server.fetcher.clientcredential;
/**
* This implementation provides a client credential information
* from a request header or request parameters
*
* @author Yoichiro Tanaka
*
*/
public class ClientCredentialFetcherImpl implements ClientCredentialFetcher {
private static final Pattern REGEXP_BASIC =
Pattern.compile("^\\s*(Basic)\\s+(.*)$");
/**
* Fetch a client credential sent from the client as a request header
* or request parameters. First, this method attempts to fetch it from
* the Authorization request header. For instance, it is expected as the
* format "Basic [Base64 encoded]". The encoded value actually has two
* parameter "Client ID" and "Client secret" delimited by ":" character.
* If it does not exist, this method attempt to fetch it from request
* parameter named "client_id" and "client_secret".
*
* @param request The request object.
* @return The client credential information.
*/
@Override | public ClientCredential fetch(Request request) { |
yoichiro/oauth2-server | src/main/java/jp/eisbahn/oauth2/server/fetcher/clientcredential/ClientCredentialFetcherImpl.java | // Path: src/main/java/jp/eisbahn/oauth2/server/models/ClientCredential.java
// public class ClientCredential {
//
// private String clientId;
// private String clientSecret;
//
// /**
// * Initialize this instance with arguments.
// * @param clientId The client ID.
// * @param clientSecret The client secret string.
// */
// public ClientCredential(String clientId, String clientSecret) {
// super();
// this.clientId = clientId;
// this.clientSecret = clientSecret;
// }
//
// /**
// * Retrieve the client ID.
// * @return The client ID.
// */
// public String getClientId() {
// return clientId;
// }
//
// /**
// * Retrieve the client secret.
// * @return The client secret.
// */
// public String getClientSecret() {
// return clientSecret;
// }
//
// }
//
// Path: src/main/java/jp/eisbahn/oauth2/server/models/Request.java
// public interface Request {
//
// /**
// * Retrieve the parameter value specified by the parameter name
// * from the request.
// * @param name The parameter name.
// * @return The value against the name.
// */
// public String getParameter(String name);
//
// /**
// * Retrieve all parameter names and values from the request as a Map instance.
// * @return The map instance which has all parameter names and values.
// */
// public Map<String, String> getParameterMap();
//
// /**
// * Retrieve the request header value from the request.
// * @param name The header's name.
// * @return The value against the name.
// */
// public String getHeader(String name);
//
// }
//
// Path: src/main/java/jp/eisbahn/oauth2/server/utils/Util.java
// public class Util {
//
// /**
// * Decode the URL encoded string.
// * @param source The URL encoded string.
// * @return The decoded original string.
// */
// public static String decodeParam(String source) {
// try {
// return URLDecoder.decode(source, "UTF-8");
// } catch (UnsupportedEncodingException e) {
// throw new IllegalStateException(e);
// }
// }
//
// /**
// * Decode the BASE64 encoded string.
// * @param source The BASE64 string.
// * @return The decoded original string.
// */
// public static String decodeBase64(String source) {
// try {
// return new String(Base64.decodeBase64(source), "UTF-8");
// } catch (UnsupportedEncodingException e) {
// throw new IllegalStateException(e);
// }
// }
//
// /**
// * Encode the object to JSON format string.
// * @param source The object that you want to change to JSON string.
// * @return The JSON encoded string.
// * @throws IllegalStateException If the translation failed.
// */
// public static String toJson(Object source) {
// try {
// ObjectMapper mapper = new ObjectMapper();
// return mapper.writeValueAsString(source);
// } catch (JsonGenerationException e) {
// throw new IllegalStateException(e);
// } catch (JsonMappingException e) {
// throw new IllegalStateException(e);
// } catch (IOException e) {
// throw new IllegalStateException(e);
// }
// }
//
// }
| import java.util.regex.Matcher;
import java.util.regex.Pattern;
import jp.eisbahn.oauth2.server.models.ClientCredential;
import jp.eisbahn.oauth2.server.models.Request;
import jp.eisbahn.oauth2.server.utils.Util; | /*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations under the License.
*/
package jp.eisbahn.oauth2.server.fetcher.clientcredential;
/**
* This implementation provides a client credential information
* from a request header or request parameters
*
* @author Yoichiro Tanaka
*
*/
public class ClientCredentialFetcherImpl implements ClientCredentialFetcher {
private static final Pattern REGEXP_BASIC =
Pattern.compile("^\\s*(Basic)\\s+(.*)$");
/**
* Fetch a client credential sent from the client as a request header
* or request parameters. First, this method attempts to fetch it from
* the Authorization request header. For instance, it is expected as the
* format "Basic [Base64 encoded]". The encoded value actually has two
* parameter "Client ID" and "Client secret" delimited by ":" character.
* If it does not exist, this method attempt to fetch it from request
* parameter named "client_id" and "client_secret".
*
* @param request The request object.
* @return The client credential information.
*/
@Override
public ClientCredential fetch(Request request) {
String header = request.getHeader("Authorization");
if (header != null) {
Matcher matcher = REGEXP_BASIC.matcher(header);
if (matcher.find()) { | // Path: src/main/java/jp/eisbahn/oauth2/server/models/ClientCredential.java
// public class ClientCredential {
//
// private String clientId;
// private String clientSecret;
//
// /**
// * Initialize this instance with arguments.
// * @param clientId The client ID.
// * @param clientSecret The client secret string.
// */
// public ClientCredential(String clientId, String clientSecret) {
// super();
// this.clientId = clientId;
// this.clientSecret = clientSecret;
// }
//
// /**
// * Retrieve the client ID.
// * @return The client ID.
// */
// public String getClientId() {
// return clientId;
// }
//
// /**
// * Retrieve the client secret.
// * @return The client secret.
// */
// public String getClientSecret() {
// return clientSecret;
// }
//
// }
//
// Path: src/main/java/jp/eisbahn/oauth2/server/models/Request.java
// public interface Request {
//
// /**
// * Retrieve the parameter value specified by the parameter name
// * from the request.
// * @param name The parameter name.
// * @return The value against the name.
// */
// public String getParameter(String name);
//
// /**
// * Retrieve all parameter names and values from the request as a Map instance.
// * @return The map instance which has all parameter names and values.
// */
// public Map<String, String> getParameterMap();
//
// /**
// * Retrieve the request header value from the request.
// * @param name The header's name.
// * @return The value against the name.
// */
// public String getHeader(String name);
//
// }
//
// Path: src/main/java/jp/eisbahn/oauth2/server/utils/Util.java
// public class Util {
//
// /**
// * Decode the URL encoded string.
// * @param source The URL encoded string.
// * @return The decoded original string.
// */
// public static String decodeParam(String source) {
// try {
// return URLDecoder.decode(source, "UTF-8");
// } catch (UnsupportedEncodingException e) {
// throw new IllegalStateException(e);
// }
// }
//
// /**
// * Decode the BASE64 encoded string.
// * @param source The BASE64 string.
// * @return The decoded original string.
// */
// public static String decodeBase64(String source) {
// try {
// return new String(Base64.decodeBase64(source), "UTF-8");
// } catch (UnsupportedEncodingException e) {
// throw new IllegalStateException(e);
// }
// }
//
// /**
// * Encode the object to JSON format string.
// * @param source The object that you want to change to JSON string.
// * @return The JSON encoded string.
// * @throws IllegalStateException If the translation failed.
// */
// public static String toJson(Object source) {
// try {
// ObjectMapper mapper = new ObjectMapper();
// return mapper.writeValueAsString(source);
// } catch (JsonGenerationException e) {
// throw new IllegalStateException(e);
// } catch (JsonMappingException e) {
// throw new IllegalStateException(e);
// } catch (IOException e) {
// throw new IllegalStateException(e);
// }
// }
//
// }
// Path: src/main/java/jp/eisbahn/oauth2/server/fetcher/clientcredential/ClientCredentialFetcherImpl.java
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import jp.eisbahn.oauth2.server.models.ClientCredential;
import jp.eisbahn.oauth2.server.models.Request;
import jp.eisbahn.oauth2.server.utils.Util;
/*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations under the License.
*/
package jp.eisbahn.oauth2.server.fetcher.clientcredential;
/**
* This implementation provides a client credential information
* from a request header or request parameters
*
* @author Yoichiro Tanaka
*
*/
public class ClientCredentialFetcherImpl implements ClientCredentialFetcher {
private static final Pattern REGEXP_BASIC =
Pattern.compile("^\\s*(Basic)\\s+(.*)$");
/**
* Fetch a client credential sent from the client as a request header
* or request parameters. First, this method attempts to fetch it from
* the Authorization request header. For instance, it is expected as the
* format "Basic [Base64 encoded]". The encoded value actually has two
* parameter "Client ID" and "Client secret" delimited by ":" character.
* If it does not exist, this method attempt to fetch it from request
* parameter named "client_id" and "client_secret".
*
* @param request The request object.
* @return The client credential information.
*/
@Override
public ClientCredential fetch(Request request) {
String header = request.getHeader("Authorization");
if (header != null) {
Matcher matcher = REGEXP_BASIC.matcher(header);
if (matcher.find()) { | String decoded = Util.decodeBase64(matcher.group(2)); |
yoichiro/oauth2-server | src/test/java/jp/eisbahn/oauth2/server/fetcher/accesstoken/impl/AuthHeaderTest.java | // Path: src/main/java/jp/eisbahn/oauth2/server/fetcher/accesstoken/AccessTokenFetcher.java
// public static class FetchResult {
//
// private String token;
// private Map<String, String> params;
//
// /**
// * This constructor initializes like both parameters become a null value.
// */
// public FetchResult() {
// this(null, null);
// }
//
// /**
// * This constructor initializes with the specified argument values.
// * @param token The access token string.
// * @param params Other parameters.
// */
// public FetchResult(String token, Map<String, String> params) {
// super();
// this.token = token;
// this.params = params;
// }
//
// /**
// * Set the access token.
// * @param token The token string.
// */
// public void setToken(String token) {
// this.token = token;
// }
//
// /**
// * Retrieve the access token.
// * @return The token string.
// */
// public String getToken() {
// return token;
// }
//
// /**
// * Set other parameters.
// * @param params The other parameter map object.
// */
// public void setParams(Map<String, String> params) {
// this.params = params;
// }
//
// /**
// * Retrieve the other parameters.
// * @return The other parameter map object.
// */
// public Map<String, String> getParams() {
// return params;
// }
//
// }
//
// Path: src/main/java/jp/eisbahn/oauth2/server/fetcher/accesstoken/impl/AuthHeader.java
// public class AuthHeader implements AccessTokenFetcher {
//
// private static final String HEADER_AUTHORIZATION = "Authorization";
// private static final Pattern REGEXP_AUTHORIZATION =
// Pattern.compile("^\\s*(OAuth|Bearer)\\s+([^\\s\\,]*)");
// private static final Pattern REGEXP_TRIM = Pattern.compile("^\\s*,\\s*");
// private static final Pattern REGEXP_DIV_COMMA = Pattern.compile(",\\s*");
//
// /**
// * Return whether an access token is included in the Authorization
// * request header.
// *
// * @param request The request object.
// * @return If the header value has an access token, this result is true.
// */
// @Override
// public boolean match(Request request) {
// String header = request.getHeader(HEADER_AUTHORIZATION);
// return (header != null)
// && (Pattern.matches("^\\s*(OAuth|Bearer)(.*)$", header));
// }
//
// /**
// * Fetch an access token from an Authorization request header and return it.
// * This method must be called when a result of the match() method is true
// * only.
// *
// * @param request The request object.
// * @return the fetched access token.
// */
// @Override
// public FetchResult fetch(Request request) {
// String header = request.getHeader(HEADER_AUTHORIZATION);
// Matcher matcher = REGEXP_AUTHORIZATION.matcher(header);
// if (!matcher.find()) {
// throw new IllegalStateException(
// "parse() method was called when match() result was false.");
// }
// String token = matcher.group(2);
// Map<String, String> params = new HashMap<String, String>();
// int end = matcher.end();
// if (header.length() != end) {
// header = header.substring(end);
// header = REGEXP_TRIM.matcher(header).replaceFirst("");
// String[] expList = REGEXP_DIV_COMMA.split(header);
// for (String exp : expList) {
// String[] keyValue = exp.split("=", 2);
// String value = keyValue[1].replaceFirst("^\"", "");
// value = value.replaceFirst("\"$", "");
// params.put(keyValue[0], Util.decodeParam(value));
// }
// }
// return new FetchResult(token, params);
// }
//
// }
//
// Path: src/main/java/jp/eisbahn/oauth2/server/models/Request.java
// public interface Request {
//
// /**
// * Retrieve the parameter value specified by the parameter name
// * from the request.
// * @param name The parameter name.
// * @return The value against the name.
// */
// public String getParameter(String name);
//
// /**
// * Retrieve all parameter names and values from the request as a Map instance.
// * @return The map instance which has all parameter names and values.
// */
// public Map<String, String> getParameterMap();
//
// /**
// * Retrieve the request header value from the request.
// * @param name The header's name.
// * @return The value against the name.
// */
// public String getHeader(String name);
//
// }
| import static org.junit.Assert.*;
import static org.easymock.EasyMock.*;
import java.util.Map;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;
import jp.eisbahn.oauth2.server.fetcher.accesstoken.AccessTokenFetcher.FetchResult;
import jp.eisbahn.oauth2.server.fetcher.accesstoken.impl.AuthHeader;
import jp.eisbahn.oauth2.server.models.Request; | verify(req);
req = createRequestMock("oauth token1");
assertFalse(target.match(req));
verify(req);
req = createRequestMock("Bearer token1");
assertTrue(target.match(req));
verify(req);
req = createRequestMock("Bearer");
assertTrue(target.match(req));
verify(req);
req = createRequestMock(" Bearer token1");
assertTrue(target.match(req));
verify(req);
req = createRequestMock("Beare token1");
assertFalse(target.match(req));
verify(req);
req = createRequestMock("bearer token1");
assertFalse(target.match(req));
verify(req);
}
@Test
public void testParse() throws Exception {
Request req; | // Path: src/main/java/jp/eisbahn/oauth2/server/fetcher/accesstoken/AccessTokenFetcher.java
// public static class FetchResult {
//
// private String token;
// private Map<String, String> params;
//
// /**
// * This constructor initializes like both parameters become a null value.
// */
// public FetchResult() {
// this(null, null);
// }
//
// /**
// * This constructor initializes with the specified argument values.
// * @param token The access token string.
// * @param params Other parameters.
// */
// public FetchResult(String token, Map<String, String> params) {
// super();
// this.token = token;
// this.params = params;
// }
//
// /**
// * Set the access token.
// * @param token The token string.
// */
// public void setToken(String token) {
// this.token = token;
// }
//
// /**
// * Retrieve the access token.
// * @return The token string.
// */
// public String getToken() {
// return token;
// }
//
// /**
// * Set other parameters.
// * @param params The other parameter map object.
// */
// public void setParams(Map<String, String> params) {
// this.params = params;
// }
//
// /**
// * Retrieve the other parameters.
// * @return The other parameter map object.
// */
// public Map<String, String> getParams() {
// return params;
// }
//
// }
//
// Path: src/main/java/jp/eisbahn/oauth2/server/fetcher/accesstoken/impl/AuthHeader.java
// public class AuthHeader implements AccessTokenFetcher {
//
// private static final String HEADER_AUTHORIZATION = "Authorization";
// private static final Pattern REGEXP_AUTHORIZATION =
// Pattern.compile("^\\s*(OAuth|Bearer)\\s+([^\\s\\,]*)");
// private static final Pattern REGEXP_TRIM = Pattern.compile("^\\s*,\\s*");
// private static final Pattern REGEXP_DIV_COMMA = Pattern.compile(",\\s*");
//
// /**
// * Return whether an access token is included in the Authorization
// * request header.
// *
// * @param request The request object.
// * @return If the header value has an access token, this result is true.
// */
// @Override
// public boolean match(Request request) {
// String header = request.getHeader(HEADER_AUTHORIZATION);
// return (header != null)
// && (Pattern.matches("^\\s*(OAuth|Bearer)(.*)$", header));
// }
//
// /**
// * Fetch an access token from an Authorization request header and return it.
// * This method must be called when a result of the match() method is true
// * only.
// *
// * @param request The request object.
// * @return the fetched access token.
// */
// @Override
// public FetchResult fetch(Request request) {
// String header = request.getHeader(HEADER_AUTHORIZATION);
// Matcher matcher = REGEXP_AUTHORIZATION.matcher(header);
// if (!matcher.find()) {
// throw new IllegalStateException(
// "parse() method was called when match() result was false.");
// }
// String token = matcher.group(2);
// Map<String, String> params = new HashMap<String, String>();
// int end = matcher.end();
// if (header.length() != end) {
// header = header.substring(end);
// header = REGEXP_TRIM.matcher(header).replaceFirst("");
// String[] expList = REGEXP_DIV_COMMA.split(header);
// for (String exp : expList) {
// String[] keyValue = exp.split("=", 2);
// String value = keyValue[1].replaceFirst("^\"", "");
// value = value.replaceFirst("\"$", "");
// params.put(keyValue[0], Util.decodeParam(value));
// }
// }
// return new FetchResult(token, params);
// }
//
// }
//
// Path: src/main/java/jp/eisbahn/oauth2/server/models/Request.java
// public interface Request {
//
// /**
// * Retrieve the parameter value specified by the parameter name
// * from the request.
// * @param name The parameter name.
// * @return The value against the name.
// */
// public String getParameter(String name);
//
// /**
// * Retrieve all parameter names and values from the request as a Map instance.
// * @return The map instance which has all parameter names and values.
// */
// public Map<String, String> getParameterMap();
//
// /**
// * Retrieve the request header value from the request.
// * @param name The header's name.
// * @return The value against the name.
// */
// public String getHeader(String name);
//
// }
// Path: src/test/java/jp/eisbahn/oauth2/server/fetcher/accesstoken/impl/AuthHeaderTest.java
import static org.junit.Assert.*;
import static org.easymock.EasyMock.*;
import java.util.Map;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;
import jp.eisbahn.oauth2.server.fetcher.accesstoken.AccessTokenFetcher.FetchResult;
import jp.eisbahn.oauth2.server.fetcher.accesstoken.impl.AuthHeader;
import jp.eisbahn.oauth2.server.models.Request;
verify(req);
req = createRequestMock("oauth token1");
assertFalse(target.match(req));
verify(req);
req = createRequestMock("Bearer token1");
assertTrue(target.match(req));
verify(req);
req = createRequestMock("Bearer");
assertTrue(target.match(req));
verify(req);
req = createRequestMock(" Bearer token1");
assertTrue(target.match(req));
verify(req);
req = createRequestMock("Beare token1");
assertFalse(target.match(req));
verify(req);
req = createRequestMock("bearer token1");
assertFalse(target.match(req));
verify(req);
}
@Test
public void testParse() throws Exception {
Request req; | FetchResult parseResult; |
yoichiro/oauth2-server | src/test/java/jp/eisbahn/oauth2/server/fetcher/clientcredential/ClientCredentialFetcherImplTest.java | // Path: src/main/java/jp/eisbahn/oauth2/server/fetcher/clientcredential/ClientCredentialFetcherImpl.java
// public class ClientCredentialFetcherImpl implements ClientCredentialFetcher {
//
// private static final Pattern REGEXP_BASIC =
// Pattern.compile("^\\s*(Basic)\\s+(.*)$");
//
// /**
// * Fetch a client credential sent from the client as a request header
// * or request parameters. First, this method attempts to fetch it from
// * the Authorization request header. For instance, it is expected as the
// * format "Basic [Base64 encoded]". The encoded value actually has two
// * parameter "Client ID" and "Client secret" delimited by ":" character.
// * If it does not exist, this method attempt to fetch it from request
// * parameter named "client_id" and "client_secret".
// *
// * @param request The request object.
// * @return The client credential information.
// */
// @Override
// public ClientCredential fetch(Request request) {
// String header = request.getHeader("Authorization");
// if (header != null) {
// Matcher matcher = REGEXP_BASIC.matcher(header);
// if (matcher.find()) {
// String decoded = Util.decodeBase64(matcher.group(2));
// if (decoded.indexOf(':') > 0) {
// String[] credential = decoded.split(":", 2);
// return new ClientCredential(credential[0], credential[1]);
// }
// }
// }
// return new ClientCredential(
// request.getParameter("client_id"),
// request.getParameter("client_secret"));
// }
//
// }
//
// Path: src/main/java/jp/eisbahn/oauth2/server/models/ClientCredential.java
// public class ClientCredential {
//
// private String clientId;
// private String clientSecret;
//
// /**
// * Initialize this instance with arguments.
// * @param clientId The client ID.
// * @param clientSecret The client secret string.
// */
// public ClientCredential(String clientId, String clientSecret) {
// super();
// this.clientId = clientId;
// this.clientSecret = clientSecret;
// }
//
// /**
// * Retrieve the client ID.
// * @return The client ID.
// */
// public String getClientId() {
// return clientId;
// }
//
// /**
// * Retrieve the client secret.
// * @return The client secret.
// */
// public String getClientSecret() {
// return clientSecret;
// }
//
// }
//
// Path: src/main/java/jp/eisbahn/oauth2/server/models/Request.java
// public interface Request {
//
// /**
// * Retrieve the parameter value specified by the parameter name
// * from the request.
// * @param name The parameter name.
// * @return The value against the name.
// */
// public String getParameter(String name);
//
// /**
// * Retrieve all parameter names and values from the request as a Map instance.
// * @return The map instance which has all parameter names and values.
// */
// public Map<String, String> getParameterMap();
//
// /**
// * Retrieve the request header value from the request.
// * @param name The header's name.
// * @return The value against the name.
// */
// public String getHeader(String name);
//
// }
| import static org.easymock.EasyMock.createMock;
import static org.easymock.EasyMock.expect;
import static org.easymock.EasyMock.replay;
import static org.junit.Assert.assertEquals;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;
import jp.eisbahn.oauth2.server.fetcher.clientcredential.ClientCredentialFetcherImpl;
import jp.eisbahn.oauth2.server.models.ClientCredential;
import jp.eisbahn.oauth2.server.models.Request; | /*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations under the License.
*/
package jp.eisbahn.oauth2.server.fetcher.clientcredential;
public class ClientCredentialFetcherImplTest {
private ClientCredentialFetcherImpl target;
@Before
public void setUp() {
target = new ClientCredentialFetcherImpl();
}
@After
public void tearDown() {
target = null;
}
@Test
public void testFetchBasic() throws Exception { | // Path: src/main/java/jp/eisbahn/oauth2/server/fetcher/clientcredential/ClientCredentialFetcherImpl.java
// public class ClientCredentialFetcherImpl implements ClientCredentialFetcher {
//
// private static final Pattern REGEXP_BASIC =
// Pattern.compile("^\\s*(Basic)\\s+(.*)$");
//
// /**
// * Fetch a client credential sent from the client as a request header
// * or request parameters. First, this method attempts to fetch it from
// * the Authorization request header. For instance, it is expected as the
// * format "Basic [Base64 encoded]". The encoded value actually has two
// * parameter "Client ID" and "Client secret" delimited by ":" character.
// * If it does not exist, this method attempt to fetch it from request
// * parameter named "client_id" and "client_secret".
// *
// * @param request The request object.
// * @return The client credential information.
// */
// @Override
// public ClientCredential fetch(Request request) {
// String header = request.getHeader("Authorization");
// if (header != null) {
// Matcher matcher = REGEXP_BASIC.matcher(header);
// if (matcher.find()) {
// String decoded = Util.decodeBase64(matcher.group(2));
// if (decoded.indexOf(':') > 0) {
// String[] credential = decoded.split(":", 2);
// return new ClientCredential(credential[0], credential[1]);
// }
// }
// }
// return new ClientCredential(
// request.getParameter("client_id"),
// request.getParameter("client_secret"));
// }
//
// }
//
// Path: src/main/java/jp/eisbahn/oauth2/server/models/ClientCredential.java
// public class ClientCredential {
//
// private String clientId;
// private String clientSecret;
//
// /**
// * Initialize this instance with arguments.
// * @param clientId The client ID.
// * @param clientSecret The client secret string.
// */
// public ClientCredential(String clientId, String clientSecret) {
// super();
// this.clientId = clientId;
// this.clientSecret = clientSecret;
// }
//
// /**
// * Retrieve the client ID.
// * @return The client ID.
// */
// public String getClientId() {
// return clientId;
// }
//
// /**
// * Retrieve the client secret.
// * @return The client secret.
// */
// public String getClientSecret() {
// return clientSecret;
// }
//
// }
//
// Path: src/main/java/jp/eisbahn/oauth2/server/models/Request.java
// public interface Request {
//
// /**
// * Retrieve the parameter value specified by the parameter name
// * from the request.
// * @param name The parameter name.
// * @return The value against the name.
// */
// public String getParameter(String name);
//
// /**
// * Retrieve all parameter names and values from the request as a Map instance.
// * @return The map instance which has all parameter names and values.
// */
// public Map<String, String> getParameterMap();
//
// /**
// * Retrieve the request header value from the request.
// * @param name The header's name.
// * @return The value against the name.
// */
// public String getHeader(String name);
//
// }
// Path: src/test/java/jp/eisbahn/oauth2/server/fetcher/clientcredential/ClientCredentialFetcherImplTest.java
import static org.easymock.EasyMock.createMock;
import static org.easymock.EasyMock.expect;
import static org.easymock.EasyMock.replay;
import static org.junit.Assert.assertEquals;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;
import jp.eisbahn.oauth2.server.fetcher.clientcredential.ClientCredentialFetcherImpl;
import jp.eisbahn.oauth2.server.models.ClientCredential;
import jp.eisbahn.oauth2.server.models.Request;
/*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations under the License.
*/
package jp.eisbahn.oauth2.server.fetcher.clientcredential;
public class ClientCredentialFetcherImplTest {
private ClientCredentialFetcherImpl target;
@Before
public void setUp() {
target = new ClientCredentialFetcherImpl();
}
@After
public void tearDown() {
target = null;
}
@Test
public void testFetchBasic() throws Exception { | Request request = createMock(Request.class); |
yoichiro/oauth2-server | src/test/java/jp/eisbahn/oauth2/server/fetcher/clientcredential/ClientCredentialFetcherImplTest.java | // Path: src/main/java/jp/eisbahn/oauth2/server/fetcher/clientcredential/ClientCredentialFetcherImpl.java
// public class ClientCredentialFetcherImpl implements ClientCredentialFetcher {
//
// private static final Pattern REGEXP_BASIC =
// Pattern.compile("^\\s*(Basic)\\s+(.*)$");
//
// /**
// * Fetch a client credential sent from the client as a request header
// * or request parameters. First, this method attempts to fetch it from
// * the Authorization request header. For instance, it is expected as the
// * format "Basic [Base64 encoded]". The encoded value actually has two
// * parameter "Client ID" and "Client secret" delimited by ":" character.
// * If it does not exist, this method attempt to fetch it from request
// * parameter named "client_id" and "client_secret".
// *
// * @param request The request object.
// * @return The client credential information.
// */
// @Override
// public ClientCredential fetch(Request request) {
// String header = request.getHeader("Authorization");
// if (header != null) {
// Matcher matcher = REGEXP_BASIC.matcher(header);
// if (matcher.find()) {
// String decoded = Util.decodeBase64(matcher.group(2));
// if (decoded.indexOf(':') > 0) {
// String[] credential = decoded.split(":", 2);
// return new ClientCredential(credential[0], credential[1]);
// }
// }
// }
// return new ClientCredential(
// request.getParameter("client_id"),
// request.getParameter("client_secret"));
// }
//
// }
//
// Path: src/main/java/jp/eisbahn/oauth2/server/models/ClientCredential.java
// public class ClientCredential {
//
// private String clientId;
// private String clientSecret;
//
// /**
// * Initialize this instance with arguments.
// * @param clientId The client ID.
// * @param clientSecret The client secret string.
// */
// public ClientCredential(String clientId, String clientSecret) {
// super();
// this.clientId = clientId;
// this.clientSecret = clientSecret;
// }
//
// /**
// * Retrieve the client ID.
// * @return The client ID.
// */
// public String getClientId() {
// return clientId;
// }
//
// /**
// * Retrieve the client secret.
// * @return The client secret.
// */
// public String getClientSecret() {
// return clientSecret;
// }
//
// }
//
// Path: src/main/java/jp/eisbahn/oauth2/server/models/Request.java
// public interface Request {
//
// /**
// * Retrieve the parameter value specified by the parameter name
// * from the request.
// * @param name The parameter name.
// * @return The value against the name.
// */
// public String getParameter(String name);
//
// /**
// * Retrieve all parameter names and values from the request as a Map instance.
// * @return The map instance which has all parameter names and values.
// */
// public Map<String, String> getParameterMap();
//
// /**
// * Retrieve the request header value from the request.
// * @param name The header's name.
// * @return The value against the name.
// */
// public String getHeader(String name);
//
// }
| import static org.easymock.EasyMock.createMock;
import static org.easymock.EasyMock.expect;
import static org.easymock.EasyMock.replay;
import static org.junit.Assert.assertEquals;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;
import jp.eisbahn.oauth2.server.fetcher.clientcredential.ClientCredentialFetcherImpl;
import jp.eisbahn.oauth2.server.models.ClientCredential;
import jp.eisbahn.oauth2.server.models.Request; | /*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations under the License.
*/
package jp.eisbahn.oauth2.server.fetcher.clientcredential;
public class ClientCredentialFetcherImplTest {
private ClientCredentialFetcherImpl target;
@Before
public void setUp() {
target = new ClientCredentialFetcherImpl();
}
@After
public void tearDown() {
target = null;
}
@Test
public void testFetchBasic() throws Exception {
Request request = createMock(Request.class);
String encoded = "Y2xpZW50X2lkX3ZhbHVlOmNsaWVudF9zZWNyZXRfdmFsdWU=";
expect(request.getHeader("Authorization")).andReturn("Basic " + encoded);
replay(request); | // Path: src/main/java/jp/eisbahn/oauth2/server/fetcher/clientcredential/ClientCredentialFetcherImpl.java
// public class ClientCredentialFetcherImpl implements ClientCredentialFetcher {
//
// private static final Pattern REGEXP_BASIC =
// Pattern.compile("^\\s*(Basic)\\s+(.*)$");
//
// /**
// * Fetch a client credential sent from the client as a request header
// * or request parameters. First, this method attempts to fetch it from
// * the Authorization request header. For instance, it is expected as the
// * format "Basic [Base64 encoded]". The encoded value actually has two
// * parameter "Client ID" and "Client secret" delimited by ":" character.
// * If it does not exist, this method attempt to fetch it from request
// * parameter named "client_id" and "client_secret".
// *
// * @param request The request object.
// * @return The client credential information.
// */
// @Override
// public ClientCredential fetch(Request request) {
// String header = request.getHeader("Authorization");
// if (header != null) {
// Matcher matcher = REGEXP_BASIC.matcher(header);
// if (matcher.find()) {
// String decoded = Util.decodeBase64(matcher.group(2));
// if (decoded.indexOf(':') > 0) {
// String[] credential = decoded.split(":", 2);
// return new ClientCredential(credential[0], credential[1]);
// }
// }
// }
// return new ClientCredential(
// request.getParameter("client_id"),
// request.getParameter("client_secret"));
// }
//
// }
//
// Path: src/main/java/jp/eisbahn/oauth2/server/models/ClientCredential.java
// public class ClientCredential {
//
// private String clientId;
// private String clientSecret;
//
// /**
// * Initialize this instance with arguments.
// * @param clientId The client ID.
// * @param clientSecret The client secret string.
// */
// public ClientCredential(String clientId, String clientSecret) {
// super();
// this.clientId = clientId;
// this.clientSecret = clientSecret;
// }
//
// /**
// * Retrieve the client ID.
// * @return The client ID.
// */
// public String getClientId() {
// return clientId;
// }
//
// /**
// * Retrieve the client secret.
// * @return The client secret.
// */
// public String getClientSecret() {
// return clientSecret;
// }
//
// }
//
// Path: src/main/java/jp/eisbahn/oauth2/server/models/Request.java
// public interface Request {
//
// /**
// * Retrieve the parameter value specified by the parameter name
// * from the request.
// * @param name The parameter name.
// * @return The value against the name.
// */
// public String getParameter(String name);
//
// /**
// * Retrieve all parameter names and values from the request as a Map instance.
// * @return The map instance which has all parameter names and values.
// */
// public Map<String, String> getParameterMap();
//
// /**
// * Retrieve the request header value from the request.
// * @param name The header's name.
// * @return The value against the name.
// */
// public String getHeader(String name);
//
// }
// Path: src/test/java/jp/eisbahn/oauth2/server/fetcher/clientcredential/ClientCredentialFetcherImplTest.java
import static org.easymock.EasyMock.createMock;
import static org.easymock.EasyMock.expect;
import static org.easymock.EasyMock.replay;
import static org.junit.Assert.assertEquals;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;
import jp.eisbahn.oauth2.server.fetcher.clientcredential.ClientCredentialFetcherImpl;
import jp.eisbahn.oauth2.server.models.ClientCredential;
import jp.eisbahn.oauth2.server.models.Request;
/*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations under the License.
*/
package jp.eisbahn.oauth2.server.fetcher.clientcredential;
public class ClientCredentialFetcherImplTest {
private ClientCredentialFetcherImpl target;
@Before
public void setUp() {
target = new ClientCredentialFetcherImpl();
}
@After
public void tearDown() {
target = null;
}
@Test
public void testFetchBasic() throws Exception {
Request request = createMock(Request.class);
String encoded = "Y2xpZW50X2lkX3ZhbHVlOmNsaWVudF9zZWNyZXRfdmFsdWU=";
expect(request.getHeader("Authorization")).andReturn("Basic " + encoded);
replay(request); | ClientCredential clientCredential = target.fetch(request); |
yoichiro/oauth2-server | src/main/java/jp/eisbahn/oauth2/server/fetcher/accesstoken/impl/RequestParameter.java | // Path: src/main/java/jp/eisbahn/oauth2/server/fetcher/accesstoken/AccessTokenFetcher.java
// public interface AccessTokenFetcher {
//
// /**
// * Judge whether a request has an access token or not.
// * @param request The request object.
// * @return If the request has an access token, return true.
// */
// public boolean match(Request request);
//
// /**
// * Retrieve an access token from a request object.
// * This method must be called when a result of the match() method
// * is true only.
// * @param request The request object.
// * @return The fetched access token.
// */
// public FetchResult fetch(Request request);
//
// /**
// * This is a holder class to has an access token with the AccessTokenFetcher
// * instance.
// *
// * @author Yoichiro Tanaka
// *
// */
// public static class FetchResult {
//
// private String token;
// private Map<String, String> params;
//
// /**
// * This constructor initializes like both parameters become a null value.
// */
// public FetchResult() {
// this(null, null);
// }
//
// /**
// * This constructor initializes with the specified argument values.
// * @param token The access token string.
// * @param params Other parameters.
// */
// public FetchResult(String token, Map<String, String> params) {
// super();
// this.token = token;
// this.params = params;
// }
//
// /**
// * Set the access token.
// * @param token The token string.
// */
// public void setToken(String token) {
// this.token = token;
// }
//
// /**
// * Retrieve the access token.
// * @return The token string.
// */
// public String getToken() {
// return token;
// }
//
// /**
// * Set other parameters.
// * @param params The other parameter map object.
// */
// public void setParams(Map<String, String> params) {
// this.params = params;
// }
//
// /**
// * Retrieve the other parameters.
// * @return The other parameter map object.
// */
// public Map<String, String> getParams() {
// return params;
// }
//
// }
//
// }
//
// Path: src/main/java/jp/eisbahn/oauth2/server/models/Request.java
// public interface Request {
//
// /**
// * Retrieve the parameter value specified by the parameter name
// * from the request.
// * @param name The parameter name.
// * @return The value against the name.
// */
// public String getParameter(String name);
//
// /**
// * Retrieve all parameter names and values from the request as a Map instance.
// * @return The map instance which has all parameter names and values.
// */
// public Map<String, String> getParameterMap();
//
// /**
// * Retrieve the request header value from the request.
// * @param name The header's name.
// * @return The value against the name.
// */
// public String getHeader(String name);
//
// }
| import java.util.HashMap;
import java.util.Map;
import org.apache.commons.lang3.StringUtils;
import jp.eisbahn.oauth2.server.fetcher.accesstoken.AccessTokenFetcher;
import jp.eisbahn.oauth2.server.models.Request; | /*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations under the License.
*/
package jp.eisbahn.oauth2.server.fetcher.accesstoken.impl;
/**
* This class fetches an access token from request parameters.
* Actually, the access token is picked up from an "oauth_token" or "access_token"
* parameter's value.
*
* @author Yoichiro Tanaka
*
*/
public class RequestParameter implements AccessTokenFetcher {
/**
* Return whether an access token is included in the request parameter's
* values. Actually, this method confirms whether the "oauth_token" or
* "access_token" request parameter exists or not.
*
* @param request The request object.
* @return If either parameter exists, this result is true.
*/
@Override | // Path: src/main/java/jp/eisbahn/oauth2/server/fetcher/accesstoken/AccessTokenFetcher.java
// public interface AccessTokenFetcher {
//
// /**
// * Judge whether a request has an access token or not.
// * @param request The request object.
// * @return If the request has an access token, return true.
// */
// public boolean match(Request request);
//
// /**
// * Retrieve an access token from a request object.
// * This method must be called when a result of the match() method
// * is true only.
// * @param request The request object.
// * @return The fetched access token.
// */
// public FetchResult fetch(Request request);
//
// /**
// * This is a holder class to has an access token with the AccessTokenFetcher
// * instance.
// *
// * @author Yoichiro Tanaka
// *
// */
// public static class FetchResult {
//
// private String token;
// private Map<String, String> params;
//
// /**
// * This constructor initializes like both parameters become a null value.
// */
// public FetchResult() {
// this(null, null);
// }
//
// /**
// * This constructor initializes with the specified argument values.
// * @param token The access token string.
// * @param params Other parameters.
// */
// public FetchResult(String token, Map<String, String> params) {
// super();
// this.token = token;
// this.params = params;
// }
//
// /**
// * Set the access token.
// * @param token The token string.
// */
// public void setToken(String token) {
// this.token = token;
// }
//
// /**
// * Retrieve the access token.
// * @return The token string.
// */
// public String getToken() {
// return token;
// }
//
// /**
// * Set other parameters.
// * @param params The other parameter map object.
// */
// public void setParams(Map<String, String> params) {
// this.params = params;
// }
//
// /**
// * Retrieve the other parameters.
// * @return The other parameter map object.
// */
// public Map<String, String> getParams() {
// return params;
// }
//
// }
//
// }
//
// Path: src/main/java/jp/eisbahn/oauth2/server/models/Request.java
// public interface Request {
//
// /**
// * Retrieve the parameter value specified by the parameter name
// * from the request.
// * @param name The parameter name.
// * @return The value against the name.
// */
// public String getParameter(String name);
//
// /**
// * Retrieve all parameter names and values from the request as a Map instance.
// * @return The map instance which has all parameter names and values.
// */
// public Map<String, String> getParameterMap();
//
// /**
// * Retrieve the request header value from the request.
// * @param name The header's name.
// * @return The value against the name.
// */
// public String getHeader(String name);
//
// }
// Path: src/main/java/jp/eisbahn/oauth2/server/fetcher/accesstoken/impl/RequestParameter.java
import java.util.HashMap;
import java.util.Map;
import org.apache.commons.lang3.StringUtils;
import jp.eisbahn.oauth2.server.fetcher.accesstoken.AccessTokenFetcher;
import jp.eisbahn.oauth2.server.models.Request;
/*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations under the License.
*/
package jp.eisbahn.oauth2.server.fetcher.accesstoken.impl;
/**
* This class fetches an access token from request parameters.
* Actually, the access token is picked up from an "oauth_token" or "access_token"
* parameter's value.
*
* @author Yoichiro Tanaka
*
*/
public class RequestParameter implements AccessTokenFetcher {
/**
* Return whether an access token is included in the request parameter's
* values. Actually, this method confirms whether the "oauth_token" or
* "access_token" request parameter exists or not.
*
* @param request The request object.
* @return If either parameter exists, this result is true.
*/
@Override | public boolean match(Request request) { |
yoichiro/oauth2-server | src/test/java/jp/eisbahn/oauth2/server/utils/UtilTest.java | // Path: src/main/java/jp/eisbahn/oauth2/server/utils/Util.java
// public class Util {
//
// /**
// * Decode the URL encoded string.
// * @param source The URL encoded string.
// * @return The decoded original string.
// */
// public static String decodeParam(String source) {
// try {
// return URLDecoder.decode(source, "UTF-8");
// } catch (UnsupportedEncodingException e) {
// throw new IllegalStateException(e);
// }
// }
//
// /**
// * Decode the BASE64 encoded string.
// * @param source The BASE64 string.
// * @return The decoded original string.
// */
// public static String decodeBase64(String source) {
// try {
// return new String(Base64.decodeBase64(source), "UTF-8");
// } catch (UnsupportedEncodingException e) {
// throw new IllegalStateException(e);
// }
// }
//
// /**
// * Encode the object to JSON format string.
// * @param source The object that you want to change to JSON string.
// * @return The JSON encoded string.
// * @throws IllegalStateException If the translation failed.
// */
// public static String toJson(Object source) {
// try {
// ObjectMapper mapper = new ObjectMapper();
// return mapper.writeValueAsString(source);
// } catch (JsonGenerationException e) {
// throw new IllegalStateException(e);
// } catch (JsonMappingException e) {
// throw new IllegalStateException(e);
// } catch (IOException e) {
// throw new IllegalStateException(e);
// }
// }
//
// }
| import org.junit.Test;
import static org.junit.Assert.assertEquals;
import jp.eisbahn.oauth2.server.utils.Util;
import org.codehaus.jackson.annotate.JsonPropertyOrder; | /*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations under the License.
*/
package jp.eisbahn.oauth2.server.utils;
public class UtilTest {
@Test
public void testDecodeParam() throws Exception {
String source = "wOJIO9A2W5mFwDgiDvZbTSMK%2FPY%3D"; | // Path: src/main/java/jp/eisbahn/oauth2/server/utils/Util.java
// public class Util {
//
// /**
// * Decode the URL encoded string.
// * @param source The URL encoded string.
// * @return The decoded original string.
// */
// public static String decodeParam(String source) {
// try {
// return URLDecoder.decode(source, "UTF-8");
// } catch (UnsupportedEncodingException e) {
// throw new IllegalStateException(e);
// }
// }
//
// /**
// * Decode the BASE64 encoded string.
// * @param source The BASE64 string.
// * @return The decoded original string.
// */
// public static String decodeBase64(String source) {
// try {
// return new String(Base64.decodeBase64(source), "UTF-8");
// } catch (UnsupportedEncodingException e) {
// throw new IllegalStateException(e);
// }
// }
//
// /**
// * Encode the object to JSON format string.
// * @param source The object that you want to change to JSON string.
// * @return The JSON encoded string.
// * @throws IllegalStateException If the translation failed.
// */
// public static String toJson(Object source) {
// try {
// ObjectMapper mapper = new ObjectMapper();
// return mapper.writeValueAsString(source);
// } catch (JsonGenerationException e) {
// throw new IllegalStateException(e);
// } catch (JsonMappingException e) {
// throw new IllegalStateException(e);
// } catch (IOException e) {
// throw new IllegalStateException(e);
// }
// }
//
// }
// Path: src/test/java/jp/eisbahn/oauth2/server/utils/UtilTest.java
import org.junit.Test;
import static org.junit.Assert.assertEquals;
import jp.eisbahn.oauth2.server.utils.Util;
import org.codehaus.jackson.annotate.JsonPropertyOrder;
/*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations under the License.
*/
package jp.eisbahn.oauth2.server.utils;
public class UtilTest {
@Test
public void testDecodeParam() throws Exception {
String source = "wOJIO9A2W5mFwDgiDvZbTSMK%2FPY%3D"; | String result = Util.decodeParam(source); |
yoichiro/oauth2-server | src/main/java/jp/eisbahn/oauth2/server/fetcher/accesstoken/impl/DefaultAccessTokenFetcherProvider.java | // Path: src/main/java/jp/eisbahn/oauth2/server/fetcher/accesstoken/AccessTokenFetcher.java
// public interface AccessTokenFetcher {
//
// /**
// * Judge whether a request has an access token or not.
// * @param request The request object.
// * @return If the request has an access token, return true.
// */
// public boolean match(Request request);
//
// /**
// * Retrieve an access token from a request object.
// * This method must be called when a result of the match() method
// * is true only.
// * @param request The request object.
// * @return The fetched access token.
// */
// public FetchResult fetch(Request request);
//
// /**
// * This is a holder class to has an access token with the AccessTokenFetcher
// * instance.
// *
// * @author Yoichiro Tanaka
// *
// */
// public static class FetchResult {
//
// private String token;
// private Map<String, String> params;
//
// /**
// * This constructor initializes like both parameters become a null value.
// */
// public FetchResult() {
// this(null, null);
// }
//
// /**
// * This constructor initializes with the specified argument values.
// * @param token The access token string.
// * @param params Other parameters.
// */
// public FetchResult(String token, Map<String, String> params) {
// super();
// this.token = token;
// this.params = params;
// }
//
// /**
// * Set the access token.
// * @param token The token string.
// */
// public void setToken(String token) {
// this.token = token;
// }
//
// /**
// * Retrieve the access token.
// * @return The token string.
// */
// public String getToken() {
// return token;
// }
//
// /**
// * Set other parameters.
// * @param params The other parameter map object.
// */
// public void setParams(Map<String, String> params) {
// this.params = params;
// }
//
// /**
// * Retrieve the other parameters.
// * @return The other parameter map object.
// */
// public Map<String, String> getParams() {
// return params;
// }
//
// }
//
// }
//
// Path: src/main/java/jp/eisbahn/oauth2/server/fetcher/accesstoken/AccessTokenFetcherProvider.java
// public class AccessTokenFetcherProvider {
//
// private AccessTokenFetcher[] fetchers;
//
// /**
// * Find a fetcher instance which can fetch an access token from the request
// * passed as an argument value and return it. The match() method of each
// * implementation class is used to confirm whether the access token can be
// * fetched or not.
// *
// * @param request The request object.
// * @return The fetcher instance which can fetch an access token from
// * the request. If not found, return null.
// */
// public AccessTokenFetcher getFetcher(Request request) {
// for (AccessTokenFetcher fetcher : fetchers) {
// if (fetcher.match(request)) {
// return fetcher;
// }
// }
// return null;
// }
//
// /**
// * Set AccessTokenFetcher implementation instances you support.
// * @param fetchers The implementation instance of the AccessTokenFetcher
// * class.
// */
// public void setAccessTokenFetchers(AccessTokenFetcher[] fetchers) {
// this.fetchers = fetchers;
// }
//
// /**
// * Retrieve the supported AccessTokenFetcher instances.
// * @return The fetcher instances.
// */
// public AccessTokenFetcher[] getAccessTokenFetchers() {
// return fetchers;
// }
//
// }
| import jp.eisbahn.oauth2.server.fetcher.accesstoken.AccessTokenFetcher;
import jp.eisbahn.oauth2.server.fetcher.accesstoken.AccessTokenFetcherProvider; | /*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations under the License.
*/
package jp.eisbahn.oauth2.server.fetcher.accesstoken.impl;
/**
* This class is the implementation class of the AccessTokenFetcherProvider.
* This implementation provides two instances to fetch an access token
* "AuthHeader" and "RequestParameter".
*
* @author Yoichiro Tanaka
*
*/
public class DefaultAccessTokenFetcherProvider extends AccessTokenFetcherProvider {
/**
* This constructor creates instances of AuthHeader and RequestParameter
* implementation classes.
*/
public DefaultAccessTokenFetcherProvider() {
super(); | // Path: src/main/java/jp/eisbahn/oauth2/server/fetcher/accesstoken/AccessTokenFetcher.java
// public interface AccessTokenFetcher {
//
// /**
// * Judge whether a request has an access token or not.
// * @param request The request object.
// * @return If the request has an access token, return true.
// */
// public boolean match(Request request);
//
// /**
// * Retrieve an access token from a request object.
// * This method must be called when a result of the match() method
// * is true only.
// * @param request The request object.
// * @return The fetched access token.
// */
// public FetchResult fetch(Request request);
//
// /**
// * This is a holder class to has an access token with the AccessTokenFetcher
// * instance.
// *
// * @author Yoichiro Tanaka
// *
// */
// public static class FetchResult {
//
// private String token;
// private Map<String, String> params;
//
// /**
// * This constructor initializes like both parameters become a null value.
// */
// public FetchResult() {
// this(null, null);
// }
//
// /**
// * This constructor initializes with the specified argument values.
// * @param token The access token string.
// * @param params Other parameters.
// */
// public FetchResult(String token, Map<String, String> params) {
// super();
// this.token = token;
// this.params = params;
// }
//
// /**
// * Set the access token.
// * @param token The token string.
// */
// public void setToken(String token) {
// this.token = token;
// }
//
// /**
// * Retrieve the access token.
// * @return The token string.
// */
// public String getToken() {
// return token;
// }
//
// /**
// * Set other parameters.
// * @param params The other parameter map object.
// */
// public void setParams(Map<String, String> params) {
// this.params = params;
// }
//
// /**
// * Retrieve the other parameters.
// * @return The other parameter map object.
// */
// public Map<String, String> getParams() {
// return params;
// }
//
// }
//
// }
//
// Path: src/main/java/jp/eisbahn/oauth2/server/fetcher/accesstoken/AccessTokenFetcherProvider.java
// public class AccessTokenFetcherProvider {
//
// private AccessTokenFetcher[] fetchers;
//
// /**
// * Find a fetcher instance which can fetch an access token from the request
// * passed as an argument value and return it. The match() method of each
// * implementation class is used to confirm whether the access token can be
// * fetched or not.
// *
// * @param request The request object.
// * @return The fetcher instance which can fetch an access token from
// * the request. If not found, return null.
// */
// public AccessTokenFetcher getFetcher(Request request) {
// for (AccessTokenFetcher fetcher : fetchers) {
// if (fetcher.match(request)) {
// return fetcher;
// }
// }
// return null;
// }
//
// /**
// * Set AccessTokenFetcher implementation instances you support.
// * @param fetchers The implementation instance of the AccessTokenFetcher
// * class.
// */
// public void setAccessTokenFetchers(AccessTokenFetcher[] fetchers) {
// this.fetchers = fetchers;
// }
//
// /**
// * Retrieve the supported AccessTokenFetcher instances.
// * @return The fetcher instances.
// */
// public AccessTokenFetcher[] getAccessTokenFetchers() {
// return fetchers;
// }
//
// }
// Path: src/main/java/jp/eisbahn/oauth2/server/fetcher/accesstoken/impl/DefaultAccessTokenFetcherProvider.java
import jp.eisbahn.oauth2.server.fetcher.accesstoken.AccessTokenFetcher;
import jp.eisbahn.oauth2.server.fetcher.accesstoken.AccessTokenFetcherProvider;
/*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations under the License.
*/
package jp.eisbahn.oauth2.server.fetcher.accesstoken.impl;
/**
* This class is the implementation class of the AccessTokenFetcherProvider.
* This implementation provides two instances to fetch an access token
* "AuthHeader" and "RequestParameter".
*
* @author Yoichiro Tanaka
*
*/
public class DefaultAccessTokenFetcherProvider extends AccessTokenFetcherProvider {
/**
* This constructor creates instances of AuthHeader and RequestParameter
* implementation classes.
*/
public DefaultAccessTokenFetcherProvider() {
super(); | setAccessTokenFetchers(new AccessTokenFetcher[] { |
yoichiro/oauth2-server | src/test/java/jp/eisbahn/oauth2/server/models/AccessTokenTest.java | // Path: src/main/java/jp/eisbahn/oauth2/server/models/AccessToken.java
// public class AccessToken {
//
// private String authId;
// private String token;
// private long expiresIn;
// private Date createdOn;
//
// /**
// * Set the ID of the authorization information to relate between the
// * information and this access token.
// * @param authId The ID of the authorization information.
// */
// public void setAuthId(String authId) {
// this.authId = authId;
// }
//
// /**
// * Retrieve the ID of the authorization information.
// * @return The ID string.
// */
// public String getAuthId() {
// return authId;
// }
//
// /**
// * Set the issued access token.
// * @param token The access token string.
// */
// public void setToken(String token) {
// this.token = token;
// }
//
// /**
// * Retrieve the access token.
// * @return The access token string.
// */
// public String getToken() {
// return token;
// }
//
// /**
// * Set the expiration time of this access token.
// * If this access token has a time limitation, this value must be positive.
// * @param expiresIn The expiration time value. The unit is second.
// */
// public void setExpiresIn(long expiresIn) {
// this.expiresIn = expiresIn;
// }
//
// /**
// * Retrieve the expiration time of this access token.
// * @return The expiration time value. This unit is second.
// */
// public long getExpiresIn() {
// return expiresIn;
// }
//
// /**
// * Set the time when this access token is created.
// * @param createdOn The date and time value.
// */
// public void setCreatedOn(Date createdOn) {
// this.createdOn = createdOn;
// }
//
// /**
// * Retrieve the time when this access token is created.
// * @return The date and time value when this is created.
// */
// public Date getCreatedOn() {
// return createdOn;
// }
//
// }
| import jp.eisbahn.oauth2.server.models.AccessToken;
import org.junit.Test;
import static org.junit.Assert.assertEquals;
import java.util.Date; | /*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations under the License.
*/
package jp.eisbahn.oauth2.server.models;
public class AccessTokenTest {
@Test
public void testAuthIdProperty() throws Exception { | // Path: src/main/java/jp/eisbahn/oauth2/server/models/AccessToken.java
// public class AccessToken {
//
// private String authId;
// private String token;
// private long expiresIn;
// private Date createdOn;
//
// /**
// * Set the ID of the authorization information to relate between the
// * information and this access token.
// * @param authId The ID of the authorization information.
// */
// public void setAuthId(String authId) {
// this.authId = authId;
// }
//
// /**
// * Retrieve the ID of the authorization information.
// * @return The ID string.
// */
// public String getAuthId() {
// return authId;
// }
//
// /**
// * Set the issued access token.
// * @param token The access token string.
// */
// public void setToken(String token) {
// this.token = token;
// }
//
// /**
// * Retrieve the access token.
// * @return The access token string.
// */
// public String getToken() {
// return token;
// }
//
// /**
// * Set the expiration time of this access token.
// * If this access token has a time limitation, this value must be positive.
// * @param expiresIn The expiration time value. The unit is second.
// */
// public void setExpiresIn(long expiresIn) {
// this.expiresIn = expiresIn;
// }
//
// /**
// * Retrieve the expiration time of this access token.
// * @return The expiration time value. This unit is second.
// */
// public long getExpiresIn() {
// return expiresIn;
// }
//
// /**
// * Set the time when this access token is created.
// * @param createdOn The date and time value.
// */
// public void setCreatedOn(Date createdOn) {
// this.createdOn = createdOn;
// }
//
// /**
// * Retrieve the time when this access token is created.
// * @return The date and time value when this is created.
// */
// public Date getCreatedOn() {
// return createdOn;
// }
//
// }
// Path: src/test/java/jp/eisbahn/oauth2/server/models/AccessTokenTest.java
import jp.eisbahn.oauth2.server.models.AccessToken;
import org.junit.Test;
import static org.junit.Assert.assertEquals;
import java.util.Date;
/*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations under the License.
*/
package jp.eisbahn.oauth2.server.models;
public class AccessTokenTest {
@Test
public void testAuthIdProperty() throws Exception { | AccessToken target = new AccessToken(); |
free-iot/freeiot-android | app/src/main/java/com/pandocloud/freeiot/ui/db/DBManager.java | // Path: app/src/main/java/com/pandocloud/freeiot/ui/bean/Device.java
// public class Device implements Serializable {
//
// public String identifier;
//
// public String name;
//
// /**
// * online/offline/unknown
// */
// public String status;
//
// public boolean is_owner = true;
//
// public String icon;
//
// public String app;
//
// public boolean isOnline() {
// return "online".equals(status);
// }
//
// public boolean isOffline() {
// return "offline".equals(status);
// }
//
// public boolean isUnknown() {
// return "unknown".equals(status);
// }
//
// public boolean isOwner() {
// return is_owner;
// }
//
// @Override
// public String toString() {
// return "Device [identifier=" + identifier + ", name=" + name
// + ", status=" + status + "]";
// }
//
// }
| import java.util.HashMap;
import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import com.pandocloud.freeiot.ui.bean.Device; | package com.pandocloud.freeiot.ui.db;
public class DBManager {
private static DBManager dbManager;
private DBHelper dbHelper;
private SQLiteDatabase readDB;
private SQLiteDatabase writeDB;
private DBManager(Context context) {
dbHelper = new DBHelper(context);
readDB = dbHelper.getReadableDatabase();
writeDB = dbHelper.getWritableDatabase();
}
public static DBManager getInstances(Context context) {
if (dbManager == null) {
dbManager = new DBManager(context.getApplicationContext());
}
return dbManager;
}
| // Path: app/src/main/java/com/pandocloud/freeiot/ui/bean/Device.java
// public class Device implements Serializable {
//
// public String identifier;
//
// public String name;
//
// /**
// * online/offline/unknown
// */
// public String status;
//
// public boolean is_owner = true;
//
// public String icon;
//
// public String app;
//
// public boolean isOnline() {
// return "online".equals(status);
// }
//
// public boolean isOffline() {
// return "offline".equals(status);
// }
//
// public boolean isUnknown() {
// return "unknown".equals(status);
// }
//
// public boolean isOwner() {
// return is_owner;
// }
//
// @Override
// public String toString() {
// return "Device [identifier=" + identifier + ", name=" + name
// + ", status=" + status + "]";
// }
//
// }
// Path: app/src/main/java/com/pandocloud/freeiot/ui/db/DBManager.java
import java.util.HashMap;
import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import com.pandocloud.freeiot.ui.bean.Device;
package com.pandocloud.freeiot.ui.db;
public class DBManager {
private static DBManager dbManager;
private DBHelper dbHelper;
private SQLiteDatabase readDB;
private SQLiteDatabase writeDB;
private DBManager(Context context) {
dbHelper = new DBHelper(context);
readDB = dbHelper.getReadableDatabase();
writeDB = dbHelper.getWritableDatabase();
}
public static DBManager getInstances(Context context) {
if (dbManager == null) {
dbManager = new DBManager(context.getApplicationContext());
}
return dbManager;
}
| public synchronized HashMap<String, Device> queryDeviceInfo() { |
free-iot/freeiot-android | app/src/main/java/com/pandocloud/freeiot/ui/helper/DeviceRegisterHelper.java | // Path: app/src/main/java/com/pandocloud/freeiot/ui/app/AppConstants.java
// public class AppConstants {
//
// public static final String VENDOR_KEY = "570f93557db3532727b54336e47f1a3500b3c0e564";
//
// //FreeIOT
// public static final String PRODUCT_KEY = "f07fd3f2782ff4964b74d51e89ad0aabf0192ec066";
// }
| import android.content.Context;
import com.pandocloud.android.api.DeviceLoginManager;
import com.pandocloud.android.api.DeviceState;
import com.pandocloud.android.api.interfaces.SimpleRequestListener;
import com.pandocloud.freeiot.ui.app.AppConstants;
| package com.pandocloud.freeiot.ui.helper;
public class DeviceRegisterHelper {
private static DeviceRegisterHelper sInstances;
private int tryCount = 0;
private static final int MAX_TRY_COUNT = 3;
private DeviceRegisterHelper(){
}
public static DeviceRegisterHelper getInstances() {
if (sInstances == null) {
synchronized (DeviceRegisterHelper.class) {
if (sInstances == null) {
sInstances = new DeviceRegisterHelper();
}
}
}
return sInstances;
}
public void checkDeviceRegister(Context context) {
if (!DeviceState.getInstances(context).hasAccessToken()) {
registerDevice(context);
}
}
private void registerDevice(final Context context) {
tryCount ++;
if (tryCount > MAX_TRY_COUNT) {
tryCount = 0;
return;
}
DeviceLoginManager.getInstances().registerDevice(context,
| // Path: app/src/main/java/com/pandocloud/freeiot/ui/app/AppConstants.java
// public class AppConstants {
//
// public static final String VENDOR_KEY = "570f93557db3532727b54336e47f1a3500b3c0e564";
//
// //FreeIOT
// public static final String PRODUCT_KEY = "f07fd3f2782ff4964b74d51e89ad0aabf0192ec066";
// }
// Path: app/src/main/java/com/pandocloud/freeiot/ui/helper/DeviceRegisterHelper.java
import android.content.Context;
import com.pandocloud.android.api.DeviceLoginManager;
import com.pandocloud.android.api.DeviceState;
import com.pandocloud.android.api.interfaces.SimpleRequestListener;
import com.pandocloud.freeiot.ui.app.AppConstants;
package com.pandocloud.freeiot.ui.helper;
public class DeviceRegisterHelper {
private static DeviceRegisterHelper sInstances;
private int tryCount = 0;
private static final int MAX_TRY_COUNT = 3;
private DeviceRegisterHelper(){
}
public static DeviceRegisterHelper getInstances() {
if (sInstances == null) {
synchronized (DeviceRegisterHelper.class) {
if (sInstances == null) {
sInstances = new DeviceRegisterHelper();
}
}
}
return sInstances;
}
public void checkDeviceRegister(Context context) {
if (!DeviceState.getInstances(context).hasAccessToken()) {
registerDevice(context);
}
}
private void registerDevice(final Context context) {
tryCount ++;
if (tryCount > MAX_TRY_COUNT) {
tryCount = 0;
return;
}
DeviceLoginManager.getInstances().registerDevice(context,
| AppConstants.VENDOR_KEY,
|
free-iot/freeiot-android | app/src/main/java/com/pandocloud/freeiot/jsbridge/DefaultHandler.java | // Path: app/src/main/java/com/pandocloud/freeiot/utils/LogUtils.java
// public class LogUtils {
// public static final int VERBOSE = 0x0001;
// public static final int DEBUG = 0x0002;
// public static final int INFO = 0x0004;
// public static final int WARN = 0x0008;
// public static final int ERROR = 0x0010;
//
// public static final int LEVEL_RELEASE = 0x0000;
//
// public static final int LEVEL_TEST = VERBOSE | DEBUG | INFO | WARN | ERROR;
//
// private static int LEVEL = LEVEL_TEST;//上线时改成LEVEL_RELEASE
//
// private static final String TAG = "PANDO_LOG";
//
// public static final void setLevel(int level) {
// LEVEL = level;
// }
//
// private static boolean check(int level) {
// if ((LEVEL & level) > 0) {
// return true;
// }
// return false;
// }
//
// public static void v(String text) {
// if (check(VERBOSE)) android.util.Log.v(TAG, text);
// }
//
// public static void v(String tag, String text) {
// if (check(VERBOSE)) android.util.Log.v(tag, text);
// }
//
// public static void d(String text) {
// if (check(DEBUG)) android.util.Log.d(TAG, text);
// }
//
// public static void d(String text, Throwable tr) {
// if (check(DEBUG)) android.util.Log.d(TAG, text, tr);
// }
//
// public static void d(String tag, String text) {
// if (check(DEBUG)) android.util.Log.d(tag, text);
// }
//
// public static void d(String tag, String text, Throwable tr) {
// if (check(DEBUG)) android.util.Log.d(tag, text, tr);
// }
//
// public static void i(String text) {
// if (check(INFO)) android.util.Log.i(TAG, text);
// }
//
// public static void i(String text, Throwable tr) {
// if (check(INFO)) android.util.Log.i(TAG, text, tr);
// }
//
// public static void i(String tag, String text) {
// if (check(INFO)) android.util.Log.i(tag, text);
// }
//
// public static void i(String tag, String text, Throwable tr) {
// if (check(INFO)) android.util.Log.i(tag, text, tr);
// }
//
// public static void w(String text) {
// if (check(WARN)) android.util.Log.w(TAG, text);
// }
//
// public static void w(String text, Throwable tr) {
// if (check(WARN)) android.util.Log.w(TAG, text, tr);
// }
//
// public static void w(String tag, String text) {
// if (check(WARN)) android.util.Log.w(tag, text);
// }
//
// public static void w(String tag, String text, Throwable tr) {
// if (check(WARN)) android.util.Log.w(tag, text, tr);
// }
//
// public static void e(String text) {
// if (check(ERROR)) android.util.Log.e(TAG, text);
// }
//
// public static void e(Throwable e) {
// e(getStringFromThrowable(e));
// }
//
// public static void e(Throwable e, String message) {
// e(message +"\n" + getStringFromThrowable(e));
// }
//
// public static void e(String text, Throwable tr) {
// if (check(ERROR)) android.util.Log.e(TAG, text, tr);
// }
//
// public static void e(String tag, String text) {
// if (check(ERROR)) android.util.Log.e(tag, text);
// }
//
// public static void e(String tag, String text, Throwable tr) {
// if (check(ERROR)) android.util.Log.e(tag, text, tr);
// }
//
// public static String getStackTraceString(Throwable tr) {
// return android.util.Log.getStackTraceString(tr);
// }
//
// public static int println(int priority, String tag, String msg) {
// return android.util.Log.println(priority, tag, msg);
// }
//
// public static String getStringFromThrowable(Throwable e) {
// StringWriter sw = new StringWriter();
// PrintWriter pw = new PrintWriter(sw);
// e.printStackTrace(pw);
// return sw.toString();
// }
//
// public static void e(String tag, byte[] data) {
// if (data == null) {
// return;
// }
// StringBuffer sBuffer = new StringBuffer();
// for (int i = 0; i< data.length; i++) {
// sBuffer.append(Integer.toHexString(data[i])).append(" ");
// }
// LogUtils.e("body length: " + sBuffer.toString());
// }
// }
| import com.pandocloud.freeiot.utils.LogUtils;
import org.json.JSONException;
import org.json.JSONObject; | package com.pandocloud.freeiot.jsbridge;
public class DefaultHandler implements BridgeHandler{
String TAG = "DefaultHandler";
@Override
public void handler(String data, CallBackFunction function) { | // Path: app/src/main/java/com/pandocloud/freeiot/utils/LogUtils.java
// public class LogUtils {
// public static final int VERBOSE = 0x0001;
// public static final int DEBUG = 0x0002;
// public static final int INFO = 0x0004;
// public static final int WARN = 0x0008;
// public static final int ERROR = 0x0010;
//
// public static final int LEVEL_RELEASE = 0x0000;
//
// public static final int LEVEL_TEST = VERBOSE | DEBUG | INFO | WARN | ERROR;
//
// private static int LEVEL = LEVEL_TEST;//上线时改成LEVEL_RELEASE
//
// private static final String TAG = "PANDO_LOG";
//
// public static final void setLevel(int level) {
// LEVEL = level;
// }
//
// private static boolean check(int level) {
// if ((LEVEL & level) > 0) {
// return true;
// }
// return false;
// }
//
// public static void v(String text) {
// if (check(VERBOSE)) android.util.Log.v(TAG, text);
// }
//
// public static void v(String tag, String text) {
// if (check(VERBOSE)) android.util.Log.v(tag, text);
// }
//
// public static void d(String text) {
// if (check(DEBUG)) android.util.Log.d(TAG, text);
// }
//
// public static void d(String text, Throwable tr) {
// if (check(DEBUG)) android.util.Log.d(TAG, text, tr);
// }
//
// public static void d(String tag, String text) {
// if (check(DEBUG)) android.util.Log.d(tag, text);
// }
//
// public static void d(String tag, String text, Throwable tr) {
// if (check(DEBUG)) android.util.Log.d(tag, text, tr);
// }
//
// public static void i(String text) {
// if (check(INFO)) android.util.Log.i(TAG, text);
// }
//
// public static void i(String text, Throwable tr) {
// if (check(INFO)) android.util.Log.i(TAG, text, tr);
// }
//
// public static void i(String tag, String text) {
// if (check(INFO)) android.util.Log.i(tag, text);
// }
//
// public static void i(String tag, String text, Throwable tr) {
// if (check(INFO)) android.util.Log.i(tag, text, tr);
// }
//
// public static void w(String text) {
// if (check(WARN)) android.util.Log.w(TAG, text);
// }
//
// public static void w(String text, Throwable tr) {
// if (check(WARN)) android.util.Log.w(TAG, text, tr);
// }
//
// public static void w(String tag, String text) {
// if (check(WARN)) android.util.Log.w(tag, text);
// }
//
// public static void w(String tag, String text, Throwable tr) {
// if (check(WARN)) android.util.Log.w(tag, text, tr);
// }
//
// public static void e(String text) {
// if (check(ERROR)) android.util.Log.e(TAG, text);
// }
//
// public static void e(Throwable e) {
// e(getStringFromThrowable(e));
// }
//
// public static void e(Throwable e, String message) {
// e(message +"\n" + getStringFromThrowable(e));
// }
//
// public static void e(String text, Throwable tr) {
// if (check(ERROR)) android.util.Log.e(TAG, text, tr);
// }
//
// public static void e(String tag, String text) {
// if (check(ERROR)) android.util.Log.e(tag, text);
// }
//
// public static void e(String tag, String text, Throwable tr) {
// if (check(ERROR)) android.util.Log.e(tag, text, tr);
// }
//
// public static String getStackTraceString(Throwable tr) {
// return android.util.Log.getStackTraceString(tr);
// }
//
// public static int println(int priority, String tag, String msg) {
// return android.util.Log.println(priority, tag, msg);
// }
//
// public static String getStringFromThrowable(Throwable e) {
// StringWriter sw = new StringWriter();
// PrintWriter pw = new PrintWriter(sw);
// e.printStackTrace(pw);
// return sw.toString();
// }
//
// public static void e(String tag, byte[] data) {
// if (data == null) {
// return;
// }
// StringBuffer sBuffer = new StringBuffer();
// for (int i = 0; i< data.length; i++) {
// sBuffer.append(Integer.toHexString(data[i])).append(" ");
// }
// LogUtils.e("body length: " + sBuffer.toString());
// }
// }
// Path: app/src/main/java/com/pandocloud/freeiot/jsbridge/DefaultHandler.java
import com.pandocloud.freeiot.utils.LogUtils;
import org.json.JSONException;
import org.json.JSONObject;
package com.pandocloud.freeiot.jsbridge;
public class DefaultHandler implements BridgeHandler{
String TAG = "DefaultHandler";
@Override
public void handler(String data, CallBackFunction function) { | LogUtils.i(TAG, "receive data" + data); |
free-iot/freeiot-android | app/src/main/java/com/pandocloud/freeiot/ui/base/BaseActivity.java | // Path: app/src/main/java/com/pandocloud/freeiot/utils/ActivityUtils.java
// public class ActivityUtils {
//
// public static final int REQUEST_CODE_INVALID = -1;
//
// public static void start(Fragment fragment, Class<?> cls) {
// start(null, fragment, cls, null, REQUEST_CODE_INVALID, 0, 0);
// }
//
// public static void start(Fragment fragment, Class<?> cls, Bundle extras) {
// start(null, fragment, cls, extras, REQUEST_CODE_INVALID, 0, 0);
// }
//
// public static void start(Fragment fragment, Class<?> cls, int req_code) {
// start(null, fragment, cls, null, req_code, 0, 0);
// }
//
// public static void start(Fragment fragment, Class<?> cls, Bundle extras, int req_code) {
// start(null, fragment, cls, extras, req_code, 0, 0);
// }
//
// public static void start(Activity activity, Class<?> cls) {
// start(activity, null, cls, null, REQUEST_CODE_INVALID, 0, 0);
// }
//
// public static void start(Activity activity, Class<?> cls, Bundle extras) {
// start(activity, null, cls, extras, REQUEST_CODE_INVALID, 0, 0);
// }
//
// public static void start(Activity activity, Class<?> cls, int req_code) {
// start(activity, null, cls, null, req_code, 0, 0);
// }
//
// public static void start(Activity activity, Class<?> cls, Bundle extras, int req_code) {
// start(activity, null, cls, extras, req_code, 0, 0);
// }
//
// public static void start(Activity activity, Class<?> cls, int enterAnim, int exitAnim) {
// start(activity, null, cls, null, REQUEST_CODE_INVALID, enterAnim, exitAnim);
// }
//
// public static void start(Activity activity, Class<?> cls, Bundle extras, int enterAnim, int exitAnim) {
// start(activity, null, cls, extras, REQUEST_CODE_INVALID, enterAnim, exitAnim);
// }
//
// public static void start(Activity activity, Class<?> cls, int req_code, int enterAnim, int exitAnim) {
// start(activity, null, cls, null, req_code, enterAnim, exitAnim);
// }
//
// public static void start(Activity activity, Class<?> cls, Bundle extras, int req_code, int enterAnim, int exitAnim) {
// start(activity, null, cls, extras, req_code, enterAnim, exitAnim);
// }
//
// public static void start(Activity activity, Fragment fragment, Class<?> cls, Bundle extras, int req_code,
// int enterAnim, int exitAnim) {
// if (null != activity) {
// Intent intent = new Intent(activity, cls);
// if (null != extras) {
// intent.putExtras(extras);
// }
//
// if (REQUEST_CODE_INVALID == req_code) {
// activity.startActivity(intent);
// } else {
// activity.startActivityForResult(intent, req_code);
// }
//
// if (0 != enterAnim || 0 != exitAnim) {
// activity.overridePendingTransition(enterAnim, exitAnim);
// }
// } else if (null != fragment) {
// activity = fragment.getActivity();
//
// if (null != activity) {
// Intent intent = new Intent(activity, cls);
// if (null != extras) {
// intent.putExtras(extras);
// }
// if (REQUEST_CODE_INVALID == req_code) {
// fragment.startActivity(intent);
// } else {
// fragment.startActivityForResult(intent, req_code);
// }
//
// if (0 != enterAnim || 0 != exitAnim) {
// activity.overridePendingTransition(enterAnim, exitAnim);
// }
// }
// }
// }
//
// public static void animFinish(Activity activity, int enterAnim, int exitAnim) {
// if (activity == null) {
// return;
// }
// activity.finish();
// activity.overridePendingTransition(enterAnim, exitAnim);
// }
// }
| import android.support.v4.app.FragmentActivity;
import com.pandocloud.freeiot.R;
import com.pandocloud.freeiot.utils.ActivityUtils;
| package com.pandocloud.freeiot.ui.base;
public class BaseActivity extends FragmentActivity {
@Override
public void onBackPressed() {
super.onBackPressed();
| // Path: app/src/main/java/com/pandocloud/freeiot/utils/ActivityUtils.java
// public class ActivityUtils {
//
// public static final int REQUEST_CODE_INVALID = -1;
//
// public static void start(Fragment fragment, Class<?> cls) {
// start(null, fragment, cls, null, REQUEST_CODE_INVALID, 0, 0);
// }
//
// public static void start(Fragment fragment, Class<?> cls, Bundle extras) {
// start(null, fragment, cls, extras, REQUEST_CODE_INVALID, 0, 0);
// }
//
// public static void start(Fragment fragment, Class<?> cls, int req_code) {
// start(null, fragment, cls, null, req_code, 0, 0);
// }
//
// public static void start(Fragment fragment, Class<?> cls, Bundle extras, int req_code) {
// start(null, fragment, cls, extras, req_code, 0, 0);
// }
//
// public static void start(Activity activity, Class<?> cls) {
// start(activity, null, cls, null, REQUEST_CODE_INVALID, 0, 0);
// }
//
// public static void start(Activity activity, Class<?> cls, Bundle extras) {
// start(activity, null, cls, extras, REQUEST_CODE_INVALID, 0, 0);
// }
//
// public static void start(Activity activity, Class<?> cls, int req_code) {
// start(activity, null, cls, null, req_code, 0, 0);
// }
//
// public static void start(Activity activity, Class<?> cls, Bundle extras, int req_code) {
// start(activity, null, cls, extras, req_code, 0, 0);
// }
//
// public static void start(Activity activity, Class<?> cls, int enterAnim, int exitAnim) {
// start(activity, null, cls, null, REQUEST_CODE_INVALID, enterAnim, exitAnim);
// }
//
// public static void start(Activity activity, Class<?> cls, Bundle extras, int enterAnim, int exitAnim) {
// start(activity, null, cls, extras, REQUEST_CODE_INVALID, enterAnim, exitAnim);
// }
//
// public static void start(Activity activity, Class<?> cls, int req_code, int enterAnim, int exitAnim) {
// start(activity, null, cls, null, req_code, enterAnim, exitAnim);
// }
//
// public static void start(Activity activity, Class<?> cls, Bundle extras, int req_code, int enterAnim, int exitAnim) {
// start(activity, null, cls, extras, req_code, enterAnim, exitAnim);
// }
//
// public static void start(Activity activity, Fragment fragment, Class<?> cls, Bundle extras, int req_code,
// int enterAnim, int exitAnim) {
// if (null != activity) {
// Intent intent = new Intent(activity, cls);
// if (null != extras) {
// intent.putExtras(extras);
// }
//
// if (REQUEST_CODE_INVALID == req_code) {
// activity.startActivity(intent);
// } else {
// activity.startActivityForResult(intent, req_code);
// }
//
// if (0 != enterAnim || 0 != exitAnim) {
// activity.overridePendingTransition(enterAnim, exitAnim);
// }
// } else if (null != fragment) {
// activity = fragment.getActivity();
//
// if (null != activity) {
// Intent intent = new Intent(activity, cls);
// if (null != extras) {
// intent.putExtras(extras);
// }
// if (REQUEST_CODE_INVALID == req_code) {
// fragment.startActivity(intent);
// } else {
// fragment.startActivityForResult(intent, req_code);
// }
//
// if (0 != enterAnim || 0 != exitAnim) {
// activity.overridePendingTransition(enterAnim, exitAnim);
// }
// }
// }
// }
//
// public static void animFinish(Activity activity, int enterAnim, int exitAnim) {
// if (activity == null) {
// return;
// }
// activity.finish();
// activity.overridePendingTransition(enterAnim, exitAnim);
// }
// }
// Path: app/src/main/java/com/pandocloud/freeiot/ui/base/BaseActivity.java
import android.support.v4.app.FragmentActivity;
import com.pandocloud.freeiot.R;
import com.pandocloud.freeiot.utils.ActivityUtils;
package com.pandocloud.freeiot.ui.base;
public class BaseActivity extends FragmentActivity {
@Override
public void onBackPressed() {
super.onBackPressed();
| ActivityUtils.animFinish(this, R.anim.slide_in_from_left, R.anim.slide_out_to_right);
|
lastfm/musicbrainz-data | src/main/java/fm/last/musicbrainz/data/dao/impl/ArtistDaoImpl.java | // Path: src/main/java/fm/last/musicbrainz/data/dao/ArtistDao.java
// public interface ArtistDao extends MusicBrainzDao<Artist> {
//
// /**
// * Ignores the casing of {@code name}.
// *
// * @return Empty list when no {@link Artist}s are found
// */
// public List<Artist> getByName(String name);
//
// }
//
// Path: src/main/java/fm/last/musicbrainz/data/model/Artist.java
// @Access(AccessType.FIELD)
// @Entity
// @Table(name = "artist", schema = "musicbrainz")
// @Cache(usage = CacheConcurrencyStrategy.READ_WRITE)
// public class Artist extends AbstractCoreEntity {
//
// @ElementCollection(fetch = FetchType.LAZY)
// @CollectionTable(name = "artist_gid_redirect", schema = "musicbrainz", joinColumns = @JoinColumn(name = "new_id"))
// @Column(name = "gid")
// @Type(type = "pg-uuid")
// private final Set<UUID> redirectedGids = Sets.newHashSet();
//
// @Column(name = "name")
// private String name;
//
// @Column(name = "type")
// @Type(type = "fm.last.musicbrainz.data.hibernate.ArtistTypeUserType")
// private ArtistType type;
//
// @ManyToOne(optional = true, fetch = FetchType.LAZY)
// @JoinColumn(name = "area", nullable = false)
// private Area area;
//
// @Column(name = "gender")
// @Type(type = "fm.last.musicbrainz.data.hibernate.GenderUserType")
// private Gender gender;
//
// @Embedded
// @AttributeOverrides({ @AttributeOverride(name = "year", column = @Column(name = "begin_date_year")),
// @AttributeOverride(name = "month", column = @Column(name = "begin_date_month")),
// @AttributeOverride(name = "day", column = @Column(name = "begin_date_day")) })
// private PartialDate beginDate;
//
// @Embedded
// @AttributeOverrides({ @AttributeOverride(name = "year", column = @Column(name = "end_date_year")),
// @AttributeOverride(name = "month", column = @Column(name = "end_date_month")),
// @AttributeOverride(name = "day", column = @Column(name = "end_date_day")) })
// private PartialDate endDate;
//
// @Column(name = "ended")
// private boolean ended;
//
// @ManyToOne(optional = true, fetch = FetchType.LAZY)
// @JoinColumn(name = "begin_area", nullable = false)
// private Area beginArea;
//
// @ManyToOne(optional = true, fetch = FetchType.LAZY)
// @JoinColumn(name = "end_area", nullable = false)
// private Area endArea;
//
// public ArtistType getType() {
// return type;
// }
//
// public Area getArea() {
// return area;
// }
//
// public Area getBeginArea() {
// return beginArea;
// }
//
// public Area getEndArea() {
// return endArea;
// }
//
// public Gender getGender() {
// return gender;
// }
//
// public boolean hasEnded() {
// return ended;
// }
//
// public String getName() {
// return name;
// }
//
// /**
// * Returns an immutable set of all associated GIDs (canonical and redirected).
// */
// public Set<UUID> getGids() {
// return new ImmutableSet.Builder<UUID>().addAll(redirectedGids).add(gid).build();
// }
//
// public PartialDate getBeginDate() {
// return beginDate;
// }
//
// public PartialDate getEndDate() {
// return endDate;
// }
//
// }
| import java.util.List;
import java.util.UUID;
import org.hibernate.type.PostgresUUIDType;
import org.springframework.stereotype.Repository;
import org.springframework.transaction.annotation.Transactional;
import fm.last.musicbrainz.data.dao.ArtistDao;
import fm.last.musicbrainz.data.model.Artist; | /*
* Copyright 2013 The musicbrainz-data Authors
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package fm.last.musicbrainz.data.dao.impl;
@Repository("musicBrainzArtistDaoImpl")
@Transactional("musicBrainzTransactionManager") | // Path: src/main/java/fm/last/musicbrainz/data/dao/ArtistDao.java
// public interface ArtistDao extends MusicBrainzDao<Artist> {
//
// /**
// * Ignores the casing of {@code name}.
// *
// * @return Empty list when no {@link Artist}s are found
// */
// public List<Artist> getByName(String name);
//
// }
//
// Path: src/main/java/fm/last/musicbrainz/data/model/Artist.java
// @Access(AccessType.FIELD)
// @Entity
// @Table(name = "artist", schema = "musicbrainz")
// @Cache(usage = CacheConcurrencyStrategy.READ_WRITE)
// public class Artist extends AbstractCoreEntity {
//
// @ElementCollection(fetch = FetchType.LAZY)
// @CollectionTable(name = "artist_gid_redirect", schema = "musicbrainz", joinColumns = @JoinColumn(name = "new_id"))
// @Column(name = "gid")
// @Type(type = "pg-uuid")
// private final Set<UUID> redirectedGids = Sets.newHashSet();
//
// @Column(name = "name")
// private String name;
//
// @Column(name = "type")
// @Type(type = "fm.last.musicbrainz.data.hibernate.ArtistTypeUserType")
// private ArtistType type;
//
// @ManyToOne(optional = true, fetch = FetchType.LAZY)
// @JoinColumn(name = "area", nullable = false)
// private Area area;
//
// @Column(name = "gender")
// @Type(type = "fm.last.musicbrainz.data.hibernate.GenderUserType")
// private Gender gender;
//
// @Embedded
// @AttributeOverrides({ @AttributeOverride(name = "year", column = @Column(name = "begin_date_year")),
// @AttributeOverride(name = "month", column = @Column(name = "begin_date_month")),
// @AttributeOverride(name = "day", column = @Column(name = "begin_date_day")) })
// private PartialDate beginDate;
//
// @Embedded
// @AttributeOverrides({ @AttributeOverride(name = "year", column = @Column(name = "end_date_year")),
// @AttributeOverride(name = "month", column = @Column(name = "end_date_month")),
// @AttributeOverride(name = "day", column = @Column(name = "end_date_day")) })
// private PartialDate endDate;
//
// @Column(name = "ended")
// private boolean ended;
//
// @ManyToOne(optional = true, fetch = FetchType.LAZY)
// @JoinColumn(name = "begin_area", nullable = false)
// private Area beginArea;
//
// @ManyToOne(optional = true, fetch = FetchType.LAZY)
// @JoinColumn(name = "end_area", nullable = false)
// private Area endArea;
//
// public ArtistType getType() {
// return type;
// }
//
// public Area getArea() {
// return area;
// }
//
// public Area getBeginArea() {
// return beginArea;
// }
//
// public Area getEndArea() {
// return endArea;
// }
//
// public Gender getGender() {
// return gender;
// }
//
// public boolean hasEnded() {
// return ended;
// }
//
// public String getName() {
// return name;
// }
//
// /**
// * Returns an immutable set of all associated GIDs (canonical and redirected).
// */
// public Set<UUID> getGids() {
// return new ImmutableSet.Builder<UUID>().addAll(redirectedGids).add(gid).build();
// }
//
// public PartialDate getBeginDate() {
// return beginDate;
// }
//
// public PartialDate getEndDate() {
// return endDate;
// }
//
// }
// Path: src/main/java/fm/last/musicbrainz/data/dao/impl/ArtistDaoImpl.java
import java.util.List;
import java.util.UUID;
import org.hibernate.type.PostgresUUIDType;
import org.springframework.stereotype.Repository;
import org.springframework.transaction.annotation.Transactional;
import fm.last.musicbrainz.data.dao.ArtistDao;
import fm.last.musicbrainz.data.model.Artist;
/*
* Copyright 2013 The musicbrainz-data Authors
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package fm.last.musicbrainz.data.dao.impl;
@Repository("musicBrainzArtistDaoImpl")
@Transactional("musicBrainzTransactionManager") | public class ArtistDaoImpl extends AbstractMusicBrainzHibernateDao<Artist> implements ArtistDao { |
lastfm/musicbrainz-data | src/main/java/fm/last/musicbrainz/data/dao/impl/ArtistDaoImpl.java | // Path: src/main/java/fm/last/musicbrainz/data/dao/ArtistDao.java
// public interface ArtistDao extends MusicBrainzDao<Artist> {
//
// /**
// * Ignores the casing of {@code name}.
// *
// * @return Empty list when no {@link Artist}s are found
// */
// public List<Artist> getByName(String name);
//
// }
//
// Path: src/main/java/fm/last/musicbrainz/data/model/Artist.java
// @Access(AccessType.FIELD)
// @Entity
// @Table(name = "artist", schema = "musicbrainz")
// @Cache(usage = CacheConcurrencyStrategy.READ_WRITE)
// public class Artist extends AbstractCoreEntity {
//
// @ElementCollection(fetch = FetchType.LAZY)
// @CollectionTable(name = "artist_gid_redirect", schema = "musicbrainz", joinColumns = @JoinColumn(name = "new_id"))
// @Column(name = "gid")
// @Type(type = "pg-uuid")
// private final Set<UUID> redirectedGids = Sets.newHashSet();
//
// @Column(name = "name")
// private String name;
//
// @Column(name = "type")
// @Type(type = "fm.last.musicbrainz.data.hibernate.ArtistTypeUserType")
// private ArtistType type;
//
// @ManyToOne(optional = true, fetch = FetchType.LAZY)
// @JoinColumn(name = "area", nullable = false)
// private Area area;
//
// @Column(name = "gender")
// @Type(type = "fm.last.musicbrainz.data.hibernate.GenderUserType")
// private Gender gender;
//
// @Embedded
// @AttributeOverrides({ @AttributeOverride(name = "year", column = @Column(name = "begin_date_year")),
// @AttributeOverride(name = "month", column = @Column(name = "begin_date_month")),
// @AttributeOverride(name = "day", column = @Column(name = "begin_date_day")) })
// private PartialDate beginDate;
//
// @Embedded
// @AttributeOverrides({ @AttributeOverride(name = "year", column = @Column(name = "end_date_year")),
// @AttributeOverride(name = "month", column = @Column(name = "end_date_month")),
// @AttributeOverride(name = "day", column = @Column(name = "end_date_day")) })
// private PartialDate endDate;
//
// @Column(name = "ended")
// private boolean ended;
//
// @ManyToOne(optional = true, fetch = FetchType.LAZY)
// @JoinColumn(name = "begin_area", nullable = false)
// private Area beginArea;
//
// @ManyToOne(optional = true, fetch = FetchType.LAZY)
// @JoinColumn(name = "end_area", nullable = false)
// private Area endArea;
//
// public ArtistType getType() {
// return type;
// }
//
// public Area getArea() {
// return area;
// }
//
// public Area getBeginArea() {
// return beginArea;
// }
//
// public Area getEndArea() {
// return endArea;
// }
//
// public Gender getGender() {
// return gender;
// }
//
// public boolean hasEnded() {
// return ended;
// }
//
// public String getName() {
// return name;
// }
//
// /**
// * Returns an immutable set of all associated GIDs (canonical and redirected).
// */
// public Set<UUID> getGids() {
// return new ImmutableSet.Builder<UUID>().addAll(redirectedGids).add(gid).build();
// }
//
// public PartialDate getBeginDate() {
// return beginDate;
// }
//
// public PartialDate getEndDate() {
// return endDate;
// }
//
// }
| import java.util.List;
import java.util.UUID;
import org.hibernate.type.PostgresUUIDType;
import org.springframework.stereotype.Repository;
import org.springframework.transaction.annotation.Transactional;
import fm.last.musicbrainz.data.dao.ArtistDao;
import fm.last.musicbrainz.data.model.Artist; | /*
* Copyright 2013 The musicbrainz-data Authors
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package fm.last.musicbrainz.data.dao.impl;
@Repository("musicBrainzArtistDaoImpl")
@Transactional("musicBrainzTransactionManager") | // Path: src/main/java/fm/last/musicbrainz/data/dao/ArtistDao.java
// public interface ArtistDao extends MusicBrainzDao<Artist> {
//
// /**
// * Ignores the casing of {@code name}.
// *
// * @return Empty list when no {@link Artist}s are found
// */
// public List<Artist> getByName(String name);
//
// }
//
// Path: src/main/java/fm/last/musicbrainz/data/model/Artist.java
// @Access(AccessType.FIELD)
// @Entity
// @Table(name = "artist", schema = "musicbrainz")
// @Cache(usage = CacheConcurrencyStrategy.READ_WRITE)
// public class Artist extends AbstractCoreEntity {
//
// @ElementCollection(fetch = FetchType.LAZY)
// @CollectionTable(name = "artist_gid_redirect", schema = "musicbrainz", joinColumns = @JoinColumn(name = "new_id"))
// @Column(name = "gid")
// @Type(type = "pg-uuid")
// private final Set<UUID> redirectedGids = Sets.newHashSet();
//
// @Column(name = "name")
// private String name;
//
// @Column(name = "type")
// @Type(type = "fm.last.musicbrainz.data.hibernate.ArtistTypeUserType")
// private ArtistType type;
//
// @ManyToOne(optional = true, fetch = FetchType.LAZY)
// @JoinColumn(name = "area", nullable = false)
// private Area area;
//
// @Column(name = "gender")
// @Type(type = "fm.last.musicbrainz.data.hibernate.GenderUserType")
// private Gender gender;
//
// @Embedded
// @AttributeOverrides({ @AttributeOverride(name = "year", column = @Column(name = "begin_date_year")),
// @AttributeOverride(name = "month", column = @Column(name = "begin_date_month")),
// @AttributeOverride(name = "day", column = @Column(name = "begin_date_day")) })
// private PartialDate beginDate;
//
// @Embedded
// @AttributeOverrides({ @AttributeOverride(name = "year", column = @Column(name = "end_date_year")),
// @AttributeOverride(name = "month", column = @Column(name = "end_date_month")),
// @AttributeOverride(name = "day", column = @Column(name = "end_date_day")) })
// private PartialDate endDate;
//
// @Column(name = "ended")
// private boolean ended;
//
// @ManyToOne(optional = true, fetch = FetchType.LAZY)
// @JoinColumn(name = "begin_area", nullable = false)
// private Area beginArea;
//
// @ManyToOne(optional = true, fetch = FetchType.LAZY)
// @JoinColumn(name = "end_area", nullable = false)
// private Area endArea;
//
// public ArtistType getType() {
// return type;
// }
//
// public Area getArea() {
// return area;
// }
//
// public Area getBeginArea() {
// return beginArea;
// }
//
// public Area getEndArea() {
// return endArea;
// }
//
// public Gender getGender() {
// return gender;
// }
//
// public boolean hasEnded() {
// return ended;
// }
//
// public String getName() {
// return name;
// }
//
// /**
// * Returns an immutable set of all associated GIDs (canonical and redirected).
// */
// public Set<UUID> getGids() {
// return new ImmutableSet.Builder<UUID>().addAll(redirectedGids).add(gid).build();
// }
//
// public PartialDate getBeginDate() {
// return beginDate;
// }
//
// public PartialDate getEndDate() {
// return endDate;
// }
//
// }
// Path: src/main/java/fm/last/musicbrainz/data/dao/impl/ArtistDaoImpl.java
import java.util.List;
import java.util.UUID;
import org.hibernate.type.PostgresUUIDType;
import org.springframework.stereotype.Repository;
import org.springframework.transaction.annotation.Transactional;
import fm.last.musicbrainz.data.dao.ArtistDao;
import fm.last.musicbrainz.data.model.Artist;
/*
* Copyright 2013 The musicbrainz-data Authors
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package fm.last.musicbrainz.data.dao.impl;
@Repository("musicBrainzArtistDaoImpl")
@Transactional("musicBrainzTransactionManager") | public class ArtistDaoImpl extends AbstractMusicBrainzHibernateDao<Artist> implements ArtistDao { |
hcqt/dazzle | src/org/dazzle/utils/DateUtils.java | // Path: src/org/dazzle/common/exception/BaseException.java
// public class BaseException extends RuntimeException {
//
// private static final long serialVersionUID = 7369919371075409501L;
//
// private String code = null;
//
// /** 获取异常编码
// * @author hcqt@qq.com*/
// public String getCode() {
// if(null != code) {
// return code;
// }
// return code;
// }
//
// /** @author hcqt@qq.com */
// public BaseException() {
// super();
// }
//
// /** @author hcqt@qq.com */
// public BaseException(
// final String code,
// final String message,
// final Object... msgArg) {
// super(MsgI18n.getMsg(code, message, msgArg));
// this.code = code;
// }
//
// /** @author hcqt@qq.com */
// public BaseException(
// final String code,
// final String message,
// final Throwable cause,
// final Object... msgArg) {
// super(MsgI18n.getMsg(code, message, msgArg), cause);
// this.code = code;
// }
//
// }
| import java.text.DateFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import org.dazzle.common.exception.BaseException; | package org.dazzle.utils;
/** @author hcqt@qq.com */
public class DateUtils {
public static final String DEF_FMT = "yyyy-MM-dd HH:mm:ss";
private static final DateFormat DATE_FORMAT = new SimpleDateFormat(DEF_FMT);
/** 得到几天前的时间
* @author hcqt@qq.com */
public static Date getBeforeDay(Date date, Integer day) {
if(null == date) {
return null;
}
if(null == day){
return date;
} else {
Calendar now = Calendar.getInstance();
now.setTime(date);
now.set(Calendar.DATE, now.get(Calendar.DATE) - day);
return now.getTime();
}
}
/** 得到几天后的时间
* @author hcqt@qq.com */
public static Date getAfterDay(Date date, Integer day) {
if(null == date) {
return null;
}
if(null == day){
return date;
} else {
Calendar now = Calendar.getInstance();
now.setTime(date);
now.set(Calendar.DATE, now.get(Calendar.DATE) + day);
return now.getTime();
}
}
/** @author hcqt@qq.com */
public static final Date parse(String date, String format) {
if(date == null || date.trim().isEmpty()) {
return null;
}
DateFormat df = null;
if(format == null || format.trim().isEmpty()) {
df = DATE_FORMAT;
} else {
df = new SimpleDateFormat(format);
}
if(df == null) {
df = DATE_FORMAT;
}
try {
return df.parse(date);
} catch (ParseException e) { | // Path: src/org/dazzle/common/exception/BaseException.java
// public class BaseException extends RuntimeException {
//
// private static final long serialVersionUID = 7369919371075409501L;
//
// private String code = null;
//
// /** 获取异常编码
// * @author hcqt@qq.com*/
// public String getCode() {
// if(null != code) {
// return code;
// }
// return code;
// }
//
// /** @author hcqt@qq.com */
// public BaseException() {
// super();
// }
//
// /** @author hcqt@qq.com */
// public BaseException(
// final String code,
// final String message,
// final Object... msgArg) {
// super(MsgI18n.getMsg(code, message, msgArg));
// this.code = code;
// }
//
// /** @author hcqt@qq.com */
// public BaseException(
// final String code,
// final String message,
// final Throwable cause,
// final Object... msgArg) {
// super(MsgI18n.getMsg(code, message, msgArg), cause);
// this.code = code;
// }
//
// }
// Path: src/org/dazzle/utils/DateUtils.java
import java.text.DateFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import org.dazzle.common.exception.BaseException;
package org.dazzle.utils;
/** @author hcqt@qq.com */
public class DateUtils {
public static final String DEF_FMT = "yyyy-MM-dd HH:mm:ss";
private static final DateFormat DATE_FORMAT = new SimpleDateFormat(DEF_FMT);
/** 得到几天前的时间
* @author hcqt@qq.com */
public static Date getBeforeDay(Date date, Integer day) {
if(null == date) {
return null;
}
if(null == day){
return date;
} else {
Calendar now = Calendar.getInstance();
now.setTime(date);
now.set(Calendar.DATE, now.get(Calendar.DATE) - day);
return now.getTime();
}
}
/** 得到几天后的时间
* @author hcqt@qq.com */
public static Date getAfterDay(Date date, Integer day) {
if(null == date) {
return null;
}
if(null == day){
return date;
} else {
Calendar now = Calendar.getInstance();
now.setTime(date);
now.set(Calendar.DATE, now.get(Calendar.DATE) + day);
return now.getTime();
}
}
/** @author hcqt@qq.com */
public static final Date parse(String date, String format) {
if(date == null || date.trim().isEmpty()) {
return null;
}
DateFormat df = null;
if(format == null || format.trim().isEmpty()) {
df = DATE_FORMAT;
} else {
df = new SimpleDateFormat(format);
}
if(df == null) {
df = DATE_FORMAT;
}
try {
return df.parse(date);
} catch (ParseException e) { | throw new BaseException("ser_date_39H8n", "传入的字符串\"{0}\"无法转换为时间格式\"{1}\"", e, date, ((format == null || format.trim().isEmpty() ? DEF_FMT : format))); |
hcqt/dazzle | src/org/dazzle/utils/EncryptUtils.java | // Path: src/org/dazzle/common/exception/BaseException.java
// public class BaseException extends RuntimeException {
//
// private static final long serialVersionUID = 7369919371075409501L;
//
// private String code = null;
//
// /** 获取异常编码
// * @author hcqt@qq.com*/
// public String getCode() {
// if(null != code) {
// return code;
// }
// return code;
// }
//
// /** @author hcqt@qq.com */
// public BaseException() {
// super();
// }
//
// /** @author hcqt@qq.com */
// public BaseException(
// final String code,
// final String message,
// final Object... msgArg) {
// super(MsgI18n.getMsg(code, message, msgArg));
// this.code = code;
// }
//
// /** @author hcqt@qq.com */
// public BaseException(
// final String code,
// final String message,
// final Throwable cause,
// final Object... msgArg) {
// super(MsgI18n.getMsg(code, message, msgArg), cause);
// this.code = code;
// }
//
// }
| import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import org.dazzle.common.exception.BaseException; | *
* @param bytes 待转换Byte数组
* @return 转换结果
* @since 0.2
* @author hcqt@qq.com
*/
public static final String bytesToHex(byte[] bytes) {
int length = bytes.length;
StringBuilder sb = new StringBuilder(2 * length);
for (int i = 0; i < length; i++) {
sb.append(HEX_DIGITS[(bytes[i] & 0xf0) >> 4]);
sb.append(HEX_DIGITS[bytes[i] & 0xf]);
}
return sb.toString();
}
/**
* 获得指定的算法加密器
*
* @param algorithm 算法
* @throws CatGroupException 如果没有参数algorithm指定的加密算法则抛出此异常
* @return 加密器
* @since 0.2
* @author hcqt@qq.com
*/
private static final MessageDigest getEncrypt(String algorithm) {
try {
return MessageDigest.getInstance(algorithm);
}
catch (NoSuchAlgorithmException ex) { | // Path: src/org/dazzle/common/exception/BaseException.java
// public class BaseException extends RuntimeException {
//
// private static final long serialVersionUID = 7369919371075409501L;
//
// private String code = null;
//
// /** 获取异常编码
// * @author hcqt@qq.com*/
// public String getCode() {
// if(null != code) {
// return code;
// }
// return code;
// }
//
// /** @author hcqt@qq.com */
// public BaseException() {
// super();
// }
//
// /** @author hcqt@qq.com */
// public BaseException(
// final String code,
// final String message,
// final Object... msgArg) {
// super(MsgI18n.getMsg(code, message, msgArg));
// this.code = code;
// }
//
// /** @author hcqt@qq.com */
// public BaseException(
// final String code,
// final String message,
// final Throwable cause,
// final Object... msgArg) {
// super(MsgI18n.getMsg(code, message, msgArg), cause);
// this.code = code;
// }
//
// }
// Path: src/org/dazzle/utils/EncryptUtils.java
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import org.dazzle.common.exception.BaseException;
*
* @param bytes 待转换Byte数组
* @return 转换结果
* @since 0.2
* @author hcqt@qq.com
*/
public static final String bytesToHex(byte[] bytes) {
int length = bytes.length;
StringBuilder sb = new StringBuilder(2 * length);
for (int i = 0; i < length; i++) {
sb.append(HEX_DIGITS[(bytes[i] & 0xf0) >> 4]);
sb.append(HEX_DIGITS[bytes[i] & 0xf]);
}
return sb.toString();
}
/**
* 获得指定的算法加密器
*
* @param algorithm 算法
* @throws CatGroupException 如果没有参数algorithm指定的加密算法则抛出此异常
* @return 加密器
* @since 0.2
* @author hcqt@qq.com
*/
private static final MessageDigest getEncrypt(String algorithm) {
try {
return MessageDigest.getInstance(algorithm);
}
catch (NoSuchAlgorithmException ex) { | throw new BaseException("encrypt_file_j3fvU", "创建{0}算法加密器失败,详情——{1}", ex, algorithm, EU.out(ex)); |
hcqt/dazzle | src/org/dazzle/common/exception/MsgI18n.java | // Path: src/org/dazzle/utils/RMU.java
// public final class RMU extends ResMsgUtils {
//
// }
| import java.util.Locale;
import java.util.MissingResourceException;
import java.util.ResourceBundle;
import org.dazzle.utils.RMU; | package org.dazzle.common.exception;
/** @author hcqt@qq.com */
public class MsgI18n {
private static ThreadLocal<Locale> currentLocale = new ThreadLocal<Locale>() {
@Override protected Locale initialValue() {
return Locale.getDefault();// 初始化采用虚拟机的默认地区
}
};
/** @author hcqt@qq.com */
public static void setLocale(Locale locale) {
currentLocale.set(locale);
}
/** @author hcqt@qq.com */
public static Locale getLocale() {
return currentLocale.get();
}
/** @author hcqt@qq.com */
public static void clearLocale() {
currentLocale.remove();
}
/**
* 到国际化资源文件当中找到code键相应的值作为msg,如果找不到,那么使用传入的defaultMsg<br />
* msg中的占位符会以msgArg逐个按顺序替换<br />
* 占位符例子:<br />
* 你好{0}先生;你好{1}女士,好久不见;<br />
* @author hcqt@qq.com
*/
public static String getMsg(String code, String defaultMsg, Object... msgArg) {
String ret = null;
try {
ResourceBundle rb = ResourceBundle.getBundle("message", MsgI18n.getLocale());
if(null != rb) {
String cfgMsg = rb.getString(code);
if(null != cfgMsg) { | // Path: src/org/dazzle/utils/RMU.java
// public final class RMU extends ResMsgUtils {
//
// }
// Path: src/org/dazzle/common/exception/MsgI18n.java
import java.util.Locale;
import java.util.MissingResourceException;
import java.util.ResourceBundle;
import org.dazzle.utils.RMU;
package org.dazzle.common.exception;
/** @author hcqt@qq.com */
public class MsgI18n {
private static ThreadLocal<Locale> currentLocale = new ThreadLocal<Locale>() {
@Override protected Locale initialValue() {
return Locale.getDefault();// 初始化采用虚拟机的默认地区
}
};
/** @author hcqt@qq.com */
public static void setLocale(Locale locale) {
currentLocale.set(locale);
}
/** @author hcqt@qq.com */
public static Locale getLocale() {
return currentLocale.get();
}
/** @author hcqt@qq.com */
public static void clearLocale() {
currentLocale.remove();
}
/**
* 到国际化资源文件当中找到code键相应的值作为msg,如果找不到,那么使用传入的defaultMsg<br />
* msg中的占位符会以msgArg逐个按顺序替换<br />
* 占位符例子:<br />
* 你好{0}先生;你好{1}女士,好久不见;<br />
* @author hcqt@qq.com
*/
public static String getMsg(String code, String defaultMsg, Object... msgArg) {
String ret = null;
try {
ResourceBundle rb = ResourceBundle.getBundle("message", MsgI18n.getLocale());
if(null != rb) {
String cfgMsg = rb.getString(code);
if(null != cfgMsg) { | ret = RMU.resolve(cfgMsg, msgArg); |
hcqt/dazzle | src/org/dazzle/utils/JsonUtils.java | // Path: src/org/dazzle/common/exception/BaseException.java
// public class BaseException extends RuntimeException {
//
// private static final long serialVersionUID = 7369919371075409501L;
//
// private String code = null;
//
// /** 获取异常编码
// * @author hcqt@qq.com*/
// public String getCode() {
// if(null != code) {
// return code;
// }
// return code;
// }
//
// /** @author hcqt@qq.com */
// public BaseException() {
// super();
// }
//
// /** @author hcqt@qq.com */
// public BaseException(
// final String code,
// final String message,
// final Object... msgArg) {
// super(MsgI18n.getMsg(code, message, msgArg));
// this.code = code;
// }
//
// /** @author hcqt@qq.com */
// public BaseException(
// final String code,
// final String message,
// final Throwable cause,
// final Object... msgArg) {
// super(MsgI18n.getMsg(code, message, msgArg), cause);
// this.code = code;
// }
//
// }
| import java.util.ArrayList;
import java.util.Iterator;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
import org.dazzle.common.exception.BaseException;
import com.google.gson.GsonBuilder;
import com.google.gson.JsonArray;
import com.google.gson.JsonElement;
import com.google.gson.JsonObject;
import com.google.gson.JsonParser;
import com.google.gson.JsonPrimitive; | package org.dazzle.utils;
/**本软件为开源项目,最新项目发布于github,可提交您的代码到本开源软件,项目网址:<a href="https://github.com/hcqt/dazzle">https://github.com/hcqt/dazzle</a><br />
* 本软件内的大多数方法禁止Override,原因是作者提倡组合,而非继承,如果您确实需要用到继承,而又希望用本软件提供的方法名称与参数列表,建议您自行采用适配器设计模式,逐个用同名方法包裹本软件所提供的方法,这样您依然可以使用继承
* @see #toObj(String)
* @author hcqt@qq.com*/
public class JsonUtils {
/**把json字符串转换成集合类<br />
* array将转换为List<Object>对象<br />
* key-value将转换为Map<String, Object>对象<br />
* 普通类型将转换为String<br />
* 若json为数组与键值对嵌套,将会转换为list与map嵌套,嵌套不限层级
* @author hcqt@qq.com */
public static Object toObj(final String jsonString) {
if(jsonString != null) {
return toObj0(new JsonParser().parse(jsonString), null, null);
} else {
return null;
}
}
/** hcqt@qq.com */
public static Object toObj(String jsonString, @SuppressWarnings("rawtypes") Class listClazz, @SuppressWarnings("rawtypes") Class mapClazz) {
return toObj0(new JsonParser().parse(jsonString), listClazz, mapClazz);
}
/**一些dom4j、response等流对象无法转换
* @author hcqt@qq.com */
public static String toJson(Object obj) {
if(obj == null) { | // Path: src/org/dazzle/common/exception/BaseException.java
// public class BaseException extends RuntimeException {
//
// private static final long serialVersionUID = 7369919371075409501L;
//
// private String code = null;
//
// /** 获取异常编码
// * @author hcqt@qq.com*/
// public String getCode() {
// if(null != code) {
// return code;
// }
// return code;
// }
//
// /** @author hcqt@qq.com */
// public BaseException() {
// super();
// }
//
// /** @author hcqt@qq.com */
// public BaseException(
// final String code,
// final String message,
// final Object... msgArg) {
// super(MsgI18n.getMsg(code, message, msgArg));
// this.code = code;
// }
//
// /** @author hcqt@qq.com */
// public BaseException(
// final String code,
// final String message,
// final Throwable cause,
// final Object... msgArg) {
// super(MsgI18n.getMsg(code, message, msgArg), cause);
// this.code = code;
// }
//
// }
// Path: src/org/dazzle/utils/JsonUtils.java
import java.util.ArrayList;
import java.util.Iterator;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
import org.dazzle.common.exception.BaseException;
import com.google.gson.GsonBuilder;
import com.google.gson.JsonArray;
import com.google.gson.JsonElement;
import com.google.gson.JsonObject;
import com.google.gson.JsonParser;
import com.google.gson.JsonPrimitive;
package org.dazzle.utils;
/**本软件为开源项目,最新项目发布于github,可提交您的代码到本开源软件,项目网址:<a href="https://github.com/hcqt/dazzle">https://github.com/hcqt/dazzle</a><br />
* 本软件内的大多数方法禁止Override,原因是作者提倡组合,而非继承,如果您确实需要用到继承,而又希望用本软件提供的方法名称与参数列表,建议您自行采用适配器设计模式,逐个用同名方法包裹本软件所提供的方法,这样您依然可以使用继承
* @see #toObj(String)
* @author hcqt@qq.com*/
public class JsonUtils {
/**把json字符串转换成集合类<br />
* array将转换为List<Object>对象<br />
* key-value将转换为Map<String, Object>对象<br />
* 普通类型将转换为String<br />
* 若json为数组与键值对嵌套,将会转换为list与map嵌套,嵌套不限层级
* @author hcqt@qq.com */
public static Object toObj(final String jsonString) {
if(jsonString != null) {
return toObj0(new JsonParser().parse(jsonString), null, null);
} else {
return null;
}
}
/** hcqt@qq.com */
public static Object toObj(String jsonString, @SuppressWarnings("rawtypes") Class listClazz, @SuppressWarnings("rawtypes") Class mapClazz) {
return toObj0(new JsonParser().parse(jsonString), listClazz, mapClazz);
}
/**一些dom4j、response等流对象无法转换
* @author hcqt@qq.com */
public static String toJson(Object obj) {
if(obj == null) { | throw new BaseException("json_convert_3ghc", "obj参数不能为空"); |
hcqt/dazzle | src/org/dazzle/utils/URLUtils.java | // Path: src/org/dazzle/common/exception/BaseException.java
// public class BaseException extends RuntimeException {
//
// private static final long serialVersionUID = 7369919371075409501L;
//
// private String code = null;
//
// /** 获取异常编码
// * @author hcqt@qq.com*/
// public String getCode() {
// if(null != code) {
// return code;
// }
// return code;
// }
//
// /** @author hcqt@qq.com */
// public BaseException() {
// super();
// }
//
// /** @author hcqt@qq.com */
// public BaseException(
// final String code,
// final String message,
// final Object... msgArg) {
// super(MsgI18n.getMsg(code, message, msgArg));
// this.code = code;
// }
//
// /** @author hcqt@qq.com */
// public BaseException(
// final String code,
// final String message,
// final Throwable cause,
// final Object... msgArg) {
// super(MsgI18n.getMsg(code, message, msgArg), cause);
// this.code = code;
// }
//
// }
| import java.net.MalformedURLException;
import java.net.URI;
import java.net.URISyntaxException;
import java.net.URL;
import java.util.Map;
import org.dazzle.common.exception.BaseException; | package org.dazzle.utils;
/**本软件为开源项目,最新项目发布于github,可提交您的代码到本开源软件,项目网址:<a href="https://github.com/hcqt/dazzle">https://github.com/hcqt/dazzle</a><br />
* 本软件内的大多数方法禁止Override,原因是作者提倡组合,而非继承,如果您确实需要用到继承,而又希望用本软件提供的方法名称与参数列表,建议您自行采用适配器设计模式,逐个用同名方法包裹本软件所提供的方法,这样您依然可以使用继承
* @see #get(Class, Map, String)
* @author hcqt@qq.com*/
public final class URLUtils {
private static final String msg1Code = "SER_COMMON_CLASSPATH_km3Ns";
private static final String msg1 = "无法获取程序的classpath路径";
private static final String msg2Code = "SER_COMMON_IO_UTIL_WRITE_i92nU";
private static final String msg2 = "把输入流写入指定URI:{0}的时候,发现未捕获异常,详情——{1}";
public static final String SCHEME_CLASSPATH = "classpath";
/**@see #resolve(URI)
* @author hcqt@qq.com */
public static final URL resolve(final URL url) {
try {
return resolve(url.toURI()).toURL();
} catch (MalformedURLException | URISyntaxException e) { | // Path: src/org/dazzle/common/exception/BaseException.java
// public class BaseException extends RuntimeException {
//
// private static final long serialVersionUID = 7369919371075409501L;
//
// private String code = null;
//
// /** 获取异常编码
// * @author hcqt@qq.com*/
// public String getCode() {
// if(null != code) {
// return code;
// }
// return code;
// }
//
// /** @author hcqt@qq.com */
// public BaseException() {
// super();
// }
//
// /** @author hcqt@qq.com */
// public BaseException(
// final String code,
// final String message,
// final Object... msgArg) {
// super(MsgI18n.getMsg(code, message, msgArg));
// this.code = code;
// }
//
// /** @author hcqt@qq.com */
// public BaseException(
// final String code,
// final String message,
// final Throwable cause,
// final Object... msgArg) {
// super(MsgI18n.getMsg(code, message, msgArg), cause);
// this.code = code;
// }
//
// }
// Path: src/org/dazzle/utils/URLUtils.java
import java.net.MalformedURLException;
import java.net.URI;
import java.net.URISyntaxException;
import java.net.URL;
import java.util.Map;
import org.dazzle.common.exception.BaseException;
package org.dazzle.utils;
/**本软件为开源项目,最新项目发布于github,可提交您的代码到本开源软件,项目网址:<a href="https://github.com/hcqt/dazzle">https://github.com/hcqt/dazzle</a><br />
* 本软件内的大多数方法禁止Override,原因是作者提倡组合,而非继承,如果您确实需要用到继承,而又希望用本软件提供的方法名称与参数列表,建议您自行采用适配器设计模式,逐个用同名方法包裹本软件所提供的方法,这样您依然可以使用继承
* @see #get(Class, Map, String)
* @author hcqt@qq.com*/
public final class URLUtils {
private static final String msg1Code = "SER_COMMON_CLASSPATH_km3Ns";
private static final String msg1 = "无法获取程序的classpath路径";
private static final String msg2Code = "SER_COMMON_IO_UTIL_WRITE_i92nU";
private static final String msg2 = "把输入流写入指定URI:{0}的时候,发现未捕获异常,详情——{1}";
public static final String SCHEME_CLASSPATH = "classpath";
/**@see #resolve(URI)
* @author hcqt@qq.com */
public static final URL resolve(final URL url) {
try {
return resolve(url.toURI()).toURL();
} catch (MalformedURLException | URISyntaxException e) { | throw new BaseException("SYS_COMMON_RESOLVE_REAL_PATH_9nm3g", "URL[{0}]语法错误,详情——{1}", e, url, EU.out(e)); |
hcqt/dazzle | src/org/dazzle/utils/DataTypeUtils.java | // Path: src/org/dazzle/common/exception/BaseException.java
// public class BaseException extends RuntimeException {
//
// private static final long serialVersionUID = 7369919371075409501L;
//
// private String code = null;
//
// /** 获取异常编码
// * @author hcqt@qq.com*/
// public String getCode() {
// if(null != code) {
// return code;
// }
// return code;
// }
//
// /** @author hcqt@qq.com */
// public BaseException() {
// super();
// }
//
// /** @author hcqt@qq.com */
// public BaseException(
// final String code,
// final String message,
// final Object... msgArg) {
// super(MsgI18n.getMsg(code, message, msgArg));
// this.code = code;
// }
//
// /** @author hcqt@qq.com */
// public BaseException(
// final String code,
// final String message,
// final Throwable cause,
// final Object... msgArg) {
// super(MsgI18n.getMsg(code, message, msgArg), cause);
// this.code = code;
// }
//
// }
| import java.lang.reflect.Array;
import java.lang.reflect.Method;
import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collection;
import java.util.Date;
import java.util.HashSet;
import java.util.LinkedList;
import java.util.List;
import java.util.Queue;
import java.util.Set;
import org.dazzle.common.exception.BaseException; | }
else if(BigDecimal.class.isAssignableFrom(destClazz)) {
ret = (T) Object2BigDecimal.convert(srcObj);
}
else if(Double.class.isAssignableFrom(destClazz)) {
ret = (T) Object2Double.convert(srcObj);
}
else if(Float.class.isAssignableFrom(destClazz)) {
ret = (T) Object2Float.convert(srcObj);
}
else if(Short.class.isAssignableFrom(destClazz)) {
ret = (T) Object2Short.convert(srcObj);
}
else if(Byte.class.isAssignableFrom(destClazz)) {
ret = (T) Object2Byte.convert(srcObj);
}
}
else if(Date.class.isAssignableFrom(destClazz)) {
ret = (T) Object2Date.convert(srcObj);
}
else if(Boolean.class.isAssignableFrom(destClazz)) {
ret = (T) Object2Boolean.convert(srcObj);
}
else if(Character.class.isAssignableFrom(destClazz)) {
ret = (T) Object2Character.convert(srcObj);
}
else if(Collection.class.isAssignableFrom(destClazz)) {
return (T) toCollection(destClazz, srcObj);
}
else { | // Path: src/org/dazzle/common/exception/BaseException.java
// public class BaseException extends RuntimeException {
//
// private static final long serialVersionUID = 7369919371075409501L;
//
// private String code = null;
//
// /** 获取异常编码
// * @author hcqt@qq.com*/
// public String getCode() {
// if(null != code) {
// return code;
// }
// return code;
// }
//
// /** @author hcqt@qq.com */
// public BaseException() {
// super();
// }
//
// /** @author hcqt@qq.com */
// public BaseException(
// final String code,
// final String message,
// final Object... msgArg) {
// super(MsgI18n.getMsg(code, message, msgArg));
// this.code = code;
// }
//
// /** @author hcqt@qq.com */
// public BaseException(
// final String code,
// final String message,
// final Throwable cause,
// final Object... msgArg) {
// super(MsgI18n.getMsg(code, message, msgArg), cause);
// this.code = code;
// }
//
// }
// Path: src/org/dazzle/utils/DataTypeUtils.java
import java.lang.reflect.Array;
import java.lang.reflect.Method;
import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collection;
import java.util.Date;
import java.util.HashSet;
import java.util.LinkedList;
import java.util.List;
import java.util.Queue;
import java.util.Set;
import org.dazzle.common.exception.BaseException;
}
else if(BigDecimal.class.isAssignableFrom(destClazz)) {
ret = (T) Object2BigDecimal.convert(srcObj);
}
else if(Double.class.isAssignableFrom(destClazz)) {
ret = (T) Object2Double.convert(srcObj);
}
else if(Float.class.isAssignableFrom(destClazz)) {
ret = (T) Object2Float.convert(srcObj);
}
else if(Short.class.isAssignableFrom(destClazz)) {
ret = (T) Object2Short.convert(srcObj);
}
else if(Byte.class.isAssignableFrom(destClazz)) {
ret = (T) Object2Byte.convert(srcObj);
}
}
else if(Date.class.isAssignableFrom(destClazz)) {
ret = (T) Object2Date.convert(srcObj);
}
else if(Boolean.class.isAssignableFrom(destClazz)) {
ret = (T) Object2Boolean.convert(srcObj);
}
else if(Character.class.isAssignableFrom(destClazz)) {
ret = (T) Object2Character.convert(srcObj);
}
else if(Collection.class.isAssignableFrom(destClazz)) {
return (T) toCollection(destClazz, srcObj);
}
else { | throw new BaseException(msg2Code, msg2, destClazz.getName()); |
hcqt/dazzle | src/org/dazzle/utils/MapUtils.java | // Path: src/org/dazzle/common/exception/BaseException.java
// public class BaseException extends RuntimeException {
//
// private static final long serialVersionUID = 7369919371075409501L;
//
// private String code = null;
//
// /** 获取异常编码
// * @author hcqt@qq.com*/
// public String getCode() {
// if(null != code) {
// return code;
// }
// return code;
// }
//
// /** @author hcqt@qq.com */
// public BaseException() {
// super();
// }
//
// /** @author hcqt@qq.com */
// public BaseException(
// final String code,
// final String message,
// final Object... msgArg) {
// super(MsgI18n.getMsg(code, message, msgArg));
// this.code = code;
// }
//
// /** @author hcqt@qq.com */
// public BaseException(
// final String code,
// final String message,
// final Throwable cause,
// final Object... msgArg) {
// super(MsgI18n.getMsg(code, message, msgArg), cause);
// this.code = code;
// }
//
// }
| import java.util.Arrays;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Map;
import java.util.Map.Entry;
import java.util.Set;
import org.dazzle.common.exception.BaseException; | }
/**从map当中获取指定key相应的value,解决多层嵌套map取值的需求,避免了书写重复代码,且健壮性差的问题<br />
* 注意,如果你的map嵌套只有3层,但是你书写的表达式有10层,那么是取不到值的,将返回null
* @param clazz 取值以何种数据类型返回
* @param express 格式:“keyx.keyxx.keyxxx”每一层key之间以“.”分隔
* @author hcqt@qq.com */
@SuppressWarnings("unchecked")
public static final <T> T get(Class<T> clazz, Map<String, ?> map, String express) {
if(map == null || map.isEmpty()) {
return null;
}
if(clazz == null) {
return null;
}
String[] keys = null;
if(express == null) {
return null;
} else {
keys = express.split("\\.");
}
if(keys == null || keys.length <= 0) {
return null;
}
for (int i = 0; i < keys.length; i++) {
if(i == keys.length - 1) {
return DTU.convert(clazz, map.get(keys[i]));
} else {
try {
map = DTU.convert(Map.class, map.get(keys[i])); | // Path: src/org/dazzle/common/exception/BaseException.java
// public class BaseException extends RuntimeException {
//
// private static final long serialVersionUID = 7369919371075409501L;
//
// private String code = null;
//
// /** 获取异常编码
// * @author hcqt@qq.com*/
// public String getCode() {
// if(null != code) {
// return code;
// }
// return code;
// }
//
// /** @author hcqt@qq.com */
// public BaseException() {
// super();
// }
//
// /** @author hcqt@qq.com */
// public BaseException(
// final String code,
// final String message,
// final Object... msgArg) {
// super(MsgI18n.getMsg(code, message, msgArg));
// this.code = code;
// }
//
// /** @author hcqt@qq.com */
// public BaseException(
// final String code,
// final String message,
// final Throwable cause,
// final Object... msgArg) {
// super(MsgI18n.getMsg(code, message, msgArg), cause);
// this.code = code;
// }
//
// }
// Path: src/org/dazzle/utils/MapUtils.java
import java.util.Arrays;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Map;
import java.util.Map.Entry;
import java.util.Set;
import org.dazzle.common.exception.BaseException;
}
/**从map当中获取指定key相应的value,解决多层嵌套map取值的需求,避免了书写重复代码,且健壮性差的问题<br />
* 注意,如果你的map嵌套只有3层,但是你书写的表达式有10层,那么是取不到值的,将返回null
* @param clazz 取值以何种数据类型返回
* @param express 格式:“keyx.keyxx.keyxxx”每一层key之间以“.”分隔
* @author hcqt@qq.com */
@SuppressWarnings("unchecked")
public static final <T> T get(Class<T> clazz, Map<String, ?> map, String express) {
if(map == null || map.isEmpty()) {
return null;
}
if(clazz == null) {
return null;
}
String[] keys = null;
if(express == null) {
return null;
} else {
keys = express.split("\\.");
}
if(keys == null || keys.length <= 0) {
return null;
}
for (int i = 0; i < keys.length; i++) {
if(i == keys.length - 1) {
return DTU.convert(clazz, map.get(keys[i]));
} else {
try {
map = DTU.convert(Map.class, map.get(keys[i])); | } catch(BaseException e) { |
daneren2005/Subsonic | app/src/main/java/github/daneren2005/dsub/view/UpdateView.java | // Path: app/src/main/java/github/daneren2005/dsub/util/DrawableTint.java
// public class DrawableTint {
// private static final Map<Integer, Integer> attrMap = new HashMap<>();
// private static final WeakHashMap<Integer, Drawable> tintedDrawables = new WeakHashMap<>();
//
// public static Drawable getTintedDrawable(Context context, @DrawableRes int drawableRes) {
// return getTintedDrawable(context, drawableRes, R.attr.colorAccent);
// }
// public static Drawable getTintedDrawable(Context context, @DrawableRes int drawableRes, @AttrRes int colorAttr) {
// if(tintedDrawables.containsKey(drawableRes)) {
// return tintedDrawables.get(drawableRes);
// }
//
// int color = getColorRes(context, colorAttr);
// Drawable background = context.getResources().getDrawable(drawableRes);
// background.setColorFilter(color, PorterDuff.Mode.SRC_IN);
// tintedDrawables.put(drawableRes, background);
// return background;
// }
// public static Drawable getTintedDrawableFromColor(Context context, @DrawableRes int drawableRes, @ColorRes int colorRes) {
// if(tintedDrawables.containsKey(drawableRes)) {
// return tintedDrawables.get(drawableRes);
// }
//
// int color = context.getResources().getColor(colorRes);
// Drawable background = context.getResources().getDrawable(drawableRes);
// background.setColorFilter(color, PorterDuff.Mode.SRC_IN);
// tintedDrawables.put(drawableRes, background);
// return background;
// }
// public static int getColorRes(Context context, @AttrRes int colorAttr) {
// int color;
// if(attrMap.containsKey(colorAttr)) {
// color = attrMap.get(colorAttr);
// } else {
// TypedValue typedValue = new TypedValue();
// Resources.Theme theme = context.getTheme();
// theme.resolveAttribute(colorAttr, typedValue, true);
// color = typedValue.data;
// attrMap.put(colorAttr, color);
// }
//
// return color;
// }
// public static int getDrawableRes(Context context, @AttrRes int drawableAttr) {
// if(attrMap.containsKey(drawableAttr)) {
// return attrMap.get(drawableAttr);
// } else {
// int[] attrs = new int[]{drawableAttr};
// TypedArray typedArray = context.obtainStyledAttributes(attrs);
// @DrawableRes int drawableRes = typedArray.getResourceId(0, 0);
// typedArray.recycle();
// attrMap.put(drawableAttr, drawableRes);
// return drawableRes;
// }
// }
// public static Drawable getTintedAttrDrawable(Context context, @AttrRes int drawableAttr, @AttrRes int colorAttr) {
// if(tintedDrawables.containsKey(drawableAttr)) {
// return getTintedDrawable(context, attrMap.get(drawableAttr), colorAttr);
// }
//
// @DrawableRes int drawableRes = getDrawableRes(context, drawableAttr);
// return getTintedDrawable(context, drawableRes, colorAttr);
// }
//
// public static void clearCache() {
// attrMap.clear();
// tintedDrawables.clear();
// }
// }
//
// Path: app/src/main/java/github/daneren2005/dsub/util/SilentBackgroundTask.java
// public abstract class SilentBackgroundTask<T> extends BackgroundTask<T> {
// public SilentBackgroundTask(Context context) {
// super(context);
// }
//
// @Override
// public void execute() {
// queue.offer(task = new Task());
// }
//
// @Override
// protected void done(T result) {
// // Don't do anything unless overriden
// }
//
// @Override
// public void updateProgress(int messageId) {
// }
//
// @Override
// public void updateProgress(String message) {
// }
// }
| import android.content.Context;
import android.graphics.drawable.Drawable;
import android.os.Handler;
import android.os.Looper;
import android.support.v7.widget.RecyclerView;
import android.util.Log;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AbsListView;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RatingBar;
import java.util.ArrayList;
import java.util.List;
import java.util.WeakHashMap;
import github.daneren2005.dsub.domain.MusicDirectory;
import github.daneren2005.dsub.R;
import github.daneren2005.dsub.util.DrawableTint;
import github.daneren2005.dsub.util.SilentBackgroundTask; | /*
This file is part of Subsonic.
Subsonic is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
Subsonic is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with Subsonic. If not, see <http://www.gnu.org/licenses/>.
Copyright 2009 (C) Sindre Mehus
*/
package github.daneren2005.dsub.view;
public abstract class UpdateView<T> extends LinearLayout {
private static final String TAG = UpdateView.class.getSimpleName();
private static final WeakHashMap<UpdateView, ?> INSTANCES = new WeakHashMap<UpdateView, Object>();
protected static Handler backgroundHandler;
protected static Handler uiHandler;
private static Runnable updateRunnable;
private static int activeActivities = 0;
protected Context context;
protected T item;
protected RatingBar ratingBar;
protected ImageButton starButton;
protected ImageView moreButton;
protected View coverArtView;
protected boolean exists = false;
protected boolean pinned = false;
protected boolean shaded = false;
protected boolean starred = false;
protected boolean isStarred = false;
protected int isRated = 0;
protected int rating = 0; | // Path: app/src/main/java/github/daneren2005/dsub/util/DrawableTint.java
// public class DrawableTint {
// private static final Map<Integer, Integer> attrMap = new HashMap<>();
// private static final WeakHashMap<Integer, Drawable> tintedDrawables = new WeakHashMap<>();
//
// public static Drawable getTintedDrawable(Context context, @DrawableRes int drawableRes) {
// return getTintedDrawable(context, drawableRes, R.attr.colorAccent);
// }
// public static Drawable getTintedDrawable(Context context, @DrawableRes int drawableRes, @AttrRes int colorAttr) {
// if(tintedDrawables.containsKey(drawableRes)) {
// return tintedDrawables.get(drawableRes);
// }
//
// int color = getColorRes(context, colorAttr);
// Drawable background = context.getResources().getDrawable(drawableRes);
// background.setColorFilter(color, PorterDuff.Mode.SRC_IN);
// tintedDrawables.put(drawableRes, background);
// return background;
// }
// public static Drawable getTintedDrawableFromColor(Context context, @DrawableRes int drawableRes, @ColorRes int colorRes) {
// if(tintedDrawables.containsKey(drawableRes)) {
// return tintedDrawables.get(drawableRes);
// }
//
// int color = context.getResources().getColor(colorRes);
// Drawable background = context.getResources().getDrawable(drawableRes);
// background.setColorFilter(color, PorterDuff.Mode.SRC_IN);
// tintedDrawables.put(drawableRes, background);
// return background;
// }
// public static int getColorRes(Context context, @AttrRes int colorAttr) {
// int color;
// if(attrMap.containsKey(colorAttr)) {
// color = attrMap.get(colorAttr);
// } else {
// TypedValue typedValue = new TypedValue();
// Resources.Theme theme = context.getTheme();
// theme.resolveAttribute(colorAttr, typedValue, true);
// color = typedValue.data;
// attrMap.put(colorAttr, color);
// }
//
// return color;
// }
// public static int getDrawableRes(Context context, @AttrRes int drawableAttr) {
// if(attrMap.containsKey(drawableAttr)) {
// return attrMap.get(drawableAttr);
// } else {
// int[] attrs = new int[]{drawableAttr};
// TypedArray typedArray = context.obtainStyledAttributes(attrs);
// @DrawableRes int drawableRes = typedArray.getResourceId(0, 0);
// typedArray.recycle();
// attrMap.put(drawableAttr, drawableRes);
// return drawableRes;
// }
// }
// public static Drawable getTintedAttrDrawable(Context context, @AttrRes int drawableAttr, @AttrRes int colorAttr) {
// if(tintedDrawables.containsKey(drawableAttr)) {
// return getTintedDrawable(context, attrMap.get(drawableAttr), colorAttr);
// }
//
// @DrawableRes int drawableRes = getDrawableRes(context, drawableAttr);
// return getTintedDrawable(context, drawableRes, colorAttr);
// }
//
// public static void clearCache() {
// attrMap.clear();
// tintedDrawables.clear();
// }
// }
//
// Path: app/src/main/java/github/daneren2005/dsub/util/SilentBackgroundTask.java
// public abstract class SilentBackgroundTask<T> extends BackgroundTask<T> {
// public SilentBackgroundTask(Context context) {
// super(context);
// }
//
// @Override
// public void execute() {
// queue.offer(task = new Task());
// }
//
// @Override
// protected void done(T result) {
// // Don't do anything unless overriden
// }
//
// @Override
// public void updateProgress(int messageId) {
// }
//
// @Override
// public void updateProgress(String message) {
// }
// }
// Path: app/src/main/java/github/daneren2005/dsub/view/UpdateView.java
import android.content.Context;
import android.graphics.drawable.Drawable;
import android.os.Handler;
import android.os.Looper;
import android.support.v7.widget.RecyclerView;
import android.util.Log;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AbsListView;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RatingBar;
import java.util.ArrayList;
import java.util.List;
import java.util.WeakHashMap;
import github.daneren2005.dsub.domain.MusicDirectory;
import github.daneren2005.dsub.R;
import github.daneren2005.dsub.util.DrawableTint;
import github.daneren2005.dsub.util.SilentBackgroundTask;
/*
This file is part of Subsonic.
Subsonic is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
Subsonic is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with Subsonic. If not, see <http://www.gnu.org/licenses/>.
Copyright 2009 (C) Sindre Mehus
*/
package github.daneren2005.dsub.view;
public abstract class UpdateView<T> extends LinearLayout {
private static final String TAG = UpdateView.class.getSimpleName();
private static final WeakHashMap<UpdateView, ?> INSTANCES = new WeakHashMap<UpdateView, Object>();
protected static Handler backgroundHandler;
protected static Handler uiHandler;
private static Runnable updateRunnable;
private static int activeActivities = 0;
protected Context context;
protected T item;
protected RatingBar ratingBar;
protected ImageButton starButton;
protected ImageView moreButton;
protected View coverArtView;
protected boolean exists = false;
protected boolean pinned = false;
protected boolean shaded = false;
protected boolean starred = false;
protected boolean isStarred = false;
protected int isRated = 0;
protected int rating = 0; | protected SilentBackgroundTask<Void> imageTask = null; |
daneren2005/Subsonic | app/src/main/java/github/daneren2005/dsub/view/UpdateView.java | // Path: app/src/main/java/github/daneren2005/dsub/util/DrawableTint.java
// public class DrawableTint {
// private static final Map<Integer, Integer> attrMap = new HashMap<>();
// private static final WeakHashMap<Integer, Drawable> tintedDrawables = new WeakHashMap<>();
//
// public static Drawable getTintedDrawable(Context context, @DrawableRes int drawableRes) {
// return getTintedDrawable(context, drawableRes, R.attr.colorAccent);
// }
// public static Drawable getTintedDrawable(Context context, @DrawableRes int drawableRes, @AttrRes int colorAttr) {
// if(tintedDrawables.containsKey(drawableRes)) {
// return tintedDrawables.get(drawableRes);
// }
//
// int color = getColorRes(context, colorAttr);
// Drawable background = context.getResources().getDrawable(drawableRes);
// background.setColorFilter(color, PorterDuff.Mode.SRC_IN);
// tintedDrawables.put(drawableRes, background);
// return background;
// }
// public static Drawable getTintedDrawableFromColor(Context context, @DrawableRes int drawableRes, @ColorRes int colorRes) {
// if(tintedDrawables.containsKey(drawableRes)) {
// return tintedDrawables.get(drawableRes);
// }
//
// int color = context.getResources().getColor(colorRes);
// Drawable background = context.getResources().getDrawable(drawableRes);
// background.setColorFilter(color, PorterDuff.Mode.SRC_IN);
// tintedDrawables.put(drawableRes, background);
// return background;
// }
// public static int getColorRes(Context context, @AttrRes int colorAttr) {
// int color;
// if(attrMap.containsKey(colorAttr)) {
// color = attrMap.get(colorAttr);
// } else {
// TypedValue typedValue = new TypedValue();
// Resources.Theme theme = context.getTheme();
// theme.resolveAttribute(colorAttr, typedValue, true);
// color = typedValue.data;
// attrMap.put(colorAttr, color);
// }
//
// return color;
// }
// public static int getDrawableRes(Context context, @AttrRes int drawableAttr) {
// if(attrMap.containsKey(drawableAttr)) {
// return attrMap.get(drawableAttr);
// } else {
// int[] attrs = new int[]{drawableAttr};
// TypedArray typedArray = context.obtainStyledAttributes(attrs);
// @DrawableRes int drawableRes = typedArray.getResourceId(0, 0);
// typedArray.recycle();
// attrMap.put(drawableAttr, drawableRes);
// return drawableRes;
// }
// }
// public static Drawable getTintedAttrDrawable(Context context, @AttrRes int drawableAttr, @AttrRes int colorAttr) {
// if(tintedDrawables.containsKey(drawableAttr)) {
// return getTintedDrawable(context, attrMap.get(drawableAttr), colorAttr);
// }
//
// @DrawableRes int drawableRes = getDrawableRes(context, drawableAttr);
// return getTintedDrawable(context, drawableRes, colorAttr);
// }
//
// public static void clearCache() {
// attrMap.clear();
// tintedDrawables.clear();
// }
// }
//
// Path: app/src/main/java/github/daneren2005/dsub/util/SilentBackgroundTask.java
// public abstract class SilentBackgroundTask<T> extends BackgroundTask<T> {
// public SilentBackgroundTask(Context context) {
// super(context);
// }
//
// @Override
// public void execute() {
// queue.offer(task = new Task());
// }
//
// @Override
// protected void done(T result) {
// // Don't do anything unless overriden
// }
//
// @Override
// public void updateProgress(int messageId) {
// }
//
// @Override
// public void updateProgress(String message) {
// }
// }
| import android.content.Context;
import android.graphics.drawable.Drawable;
import android.os.Handler;
import android.os.Looper;
import android.support.v7.widget.RecyclerView;
import android.util.Log;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AbsListView;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RatingBar;
import java.util.ArrayList;
import java.util.List;
import java.util.WeakHashMap;
import github.daneren2005.dsub.domain.MusicDirectory;
import github.daneren2005.dsub.R;
import github.daneren2005.dsub.util.DrawableTint;
import github.daneren2005.dsub.util.SilentBackgroundTask; |
public static MusicDirectory.Entry findEntry(MusicDirectory.Entry entry) {
for(UpdateView view: INSTANCES.keySet()) {
MusicDirectory.Entry check = null;
if(view instanceof SongView) {
check = ((SongView) view).getEntry();
} else if(view instanceof AlbumView) {
check = ((AlbumView) view).getEntry();
}
if(check != null && entry != check && check.getId().equals(entry.getId())) {
return check;
}
}
return null;
}
protected void updateBackground() {
}
protected void update() {
if(moreButton != null) {
if(exists || pinned) {
if(!shaded) {
moreButton.setImageResource(exists ? R.drawable.download_cached : R.drawable.download_pinned);
shaded = true;
}
} else {
if(shaded) { | // Path: app/src/main/java/github/daneren2005/dsub/util/DrawableTint.java
// public class DrawableTint {
// private static final Map<Integer, Integer> attrMap = new HashMap<>();
// private static final WeakHashMap<Integer, Drawable> tintedDrawables = new WeakHashMap<>();
//
// public static Drawable getTintedDrawable(Context context, @DrawableRes int drawableRes) {
// return getTintedDrawable(context, drawableRes, R.attr.colorAccent);
// }
// public static Drawable getTintedDrawable(Context context, @DrawableRes int drawableRes, @AttrRes int colorAttr) {
// if(tintedDrawables.containsKey(drawableRes)) {
// return tintedDrawables.get(drawableRes);
// }
//
// int color = getColorRes(context, colorAttr);
// Drawable background = context.getResources().getDrawable(drawableRes);
// background.setColorFilter(color, PorterDuff.Mode.SRC_IN);
// tintedDrawables.put(drawableRes, background);
// return background;
// }
// public static Drawable getTintedDrawableFromColor(Context context, @DrawableRes int drawableRes, @ColorRes int colorRes) {
// if(tintedDrawables.containsKey(drawableRes)) {
// return tintedDrawables.get(drawableRes);
// }
//
// int color = context.getResources().getColor(colorRes);
// Drawable background = context.getResources().getDrawable(drawableRes);
// background.setColorFilter(color, PorterDuff.Mode.SRC_IN);
// tintedDrawables.put(drawableRes, background);
// return background;
// }
// public static int getColorRes(Context context, @AttrRes int colorAttr) {
// int color;
// if(attrMap.containsKey(colorAttr)) {
// color = attrMap.get(colorAttr);
// } else {
// TypedValue typedValue = new TypedValue();
// Resources.Theme theme = context.getTheme();
// theme.resolveAttribute(colorAttr, typedValue, true);
// color = typedValue.data;
// attrMap.put(colorAttr, color);
// }
//
// return color;
// }
// public static int getDrawableRes(Context context, @AttrRes int drawableAttr) {
// if(attrMap.containsKey(drawableAttr)) {
// return attrMap.get(drawableAttr);
// } else {
// int[] attrs = new int[]{drawableAttr};
// TypedArray typedArray = context.obtainStyledAttributes(attrs);
// @DrawableRes int drawableRes = typedArray.getResourceId(0, 0);
// typedArray.recycle();
// attrMap.put(drawableAttr, drawableRes);
// return drawableRes;
// }
// }
// public static Drawable getTintedAttrDrawable(Context context, @AttrRes int drawableAttr, @AttrRes int colorAttr) {
// if(tintedDrawables.containsKey(drawableAttr)) {
// return getTintedDrawable(context, attrMap.get(drawableAttr), colorAttr);
// }
//
// @DrawableRes int drawableRes = getDrawableRes(context, drawableAttr);
// return getTintedDrawable(context, drawableRes, colorAttr);
// }
//
// public static void clearCache() {
// attrMap.clear();
// tintedDrawables.clear();
// }
// }
//
// Path: app/src/main/java/github/daneren2005/dsub/util/SilentBackgroundTask.java
// public abstract class SilentBackgroundTask<T> extends BackgroundTask<T> {
// public SilentBackgroundTask(Context context) {
// super(context);
// }
//
// @Override
// public void execute() {
// queue.offer(task = new Task());
// }
//
// @Override
// protected void done(T result) {
// // Don't do anything unless overriden
// }
//
// @Override
// public void updateProgress(int messageId) {
// }
//
// @Override
// public void updateProgress(String message) {
// }
// }
// Path: app/src/main/java/github/daneren2005/dsub/view/UpdateView.java
import android.content.Context;
import android.graphics.drawable.Drawable;
import android.os.Handler;
import android.os.Looper;
import android.support.v7.widget.RecyclerView;
import android.util.Log;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AbsListView;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RatingBar;
import java.util.ArrayList;
import java.util.List;
import java.util.WeakHashMap;
import github.daneren2005.dsub.domain.MusicDirectory;
import github.daneren2005.dsub.R;
import github.daneren2005.dsub.util.DrawableTint;
import github.daneren2005.dsub.util.SilentBackgroundTask;
public static MusicDirectory.Entry findEntry(MusicDirectory.Entry entry) {
for(UpdateView view: INSTANCES.keySet()) {
MusicDirectory.Entry check = null;
if(view instanceof SongView) {
check = ((SongView) view).getEntry();
} else if(view instanceof AlbumView) {
check = ((AlbumView) view).getEntry();
}
if(check != null && entry != check && check.getId().equals(entry.getId())) {
return check;
}
}
return null;
}
protected void updateBackground() {
}
protected void update() {
if(moreButton != null) {
if(exists || pinned) {
if(!shaded) {
moreButton.setImageResource(exists ? R.drawable.download_cached : R.drawable.download_pinned);
shaded = true;
}
} else {
if(shaded) { | moreButton.setImageResource(DrawableTint.getDrawableRes(context, R.attr.download_none)); |
daneren2005/Subsonic | app/src/main/java/github/daneren2005/dsub/service/parser/GenreParser.java | // Path: app/src/main/java/github/daneren2005/dsub/domain/Genre.java
// public class Genre implements Serializable {
// private String name;
// private String index;
// private Integer albumCount;
// private Integer songCount;
//
// public String getName() {
// return name;
// }
//
// public void setName(String name) {
// this.name = name;
// }
//
// public String getIndex() {
// return index;
// }
//
// public void setIndex(String index) {
// this.index = index;
// }
//
// @Override
// public String toString() {
// return name;
// }
//
// public Integer getAlbumCount() {
// return albumCount;
// }
//
// public void setAlbumCount(Integer albumCount) {
// this.albumCount = albumCount;
// }
//
// public Integer getSongCount() {
// return songCount;
// }
//
// public void setSongCount(Integer songCount) {
// this.songCount = songCount;
// }
//
// public static class GenreComparator implements Comparator<Genre> {
// @Override
// public int compare(Genre genre1, Genre genre2) {
// String genre1Name = genre1.getName() != null ? genre1.getName() : "";
// String genre2Name = genre2.getName() != null ? genre2.getName() : "";
//
// return genre1Name.compareToIgnoreCase(genre2Name);
// }
//
// public static List<Genre> sort(List<Genre> genres) {
// Collections.sort(genres, new GenreComparator());
// return genres;
// }
//
// }
// }
| import java.io.StringReader;
import java.util.ArrayList;
import java.util.List;
import android.content.Context;
import android.text.Html;
import android.util.Log;
import github.daneren2005.dsub.R;
import github.daneren2005.dsub.domain.Genre;
import github.daneren2005.dsub.util.ProgressListener;
import org.xmlpull.v1.XmlPullParser;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.Reader; | /*
This file is part of Subsonic.
Subsonic is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
Subsonic is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with Subsonic. If not, see <http://www.gnu.org/licenses/>.
Copyright 2010 (C) Sindre Mehus
*/
package github.daneren2005.dsub.service.parser;
/**
* @author Joshua Bahnsen
*/
public class GenreParser extends AbstractParser {
private static final String TAG = GenreParser.class.getSimpleName();
public GenreParser(Context context, int instance) {
super(context, instance);
}
| // Path: app/src/main/java/github/daneren2005/dsub/domain/Genre.java
// public class Genre implements Serializable {
// private String name;
// private String index;
// private Integer albumCount;
// private Integer songCount;
//
// public String getName() {
// return name;
// }
//
// public void setName(String name) {
// this.name = name;
// }
//
// public String getIndex() {
// return index;
// }
//
// public void setIndex(String index) {
// this.index = index;
// }
//
// @Override
// public String toString() {
// return name;
// }
//
// public Integer getAlbumCount() {
// return albumCount;
// }
//
// public void setAlbumCount(Integer albumCount) {
// this.albumCount = albumCount;
// }
//
// public Integer getSongCount() {
// return songCount;
// }
//
// public void setSongCount(Integer songCount) {
// this.songCount = songCount;
// }
//
// public static class GenreComparator implements Comparator<Genre> {
// @Override
// public int compare(Genre genre1, Genre genre2) {
// String genre1Name = genre1.getName() != null ? genre1.getName() : "";
// String genre2Name = genre2.getName() != null ? genre2.getName() : "";
//
// return genre1Name.compareToIgnoreCase(genre2Name);
// }
//
// public static List<Genre> sort(List<Genre> genres) {
// Collections.sort(genres, new GenreComparator());
// return genres;
// }
//
// }
// }
// Path: app/src/main/java/github/daneren2005/dsub/service/parser/GenreParser.java
import java.io.StringReader;
import java.util.ArrayList;
import java.util.List;
import android.content.Context;
import android.text.Html;
import android.util.Log;
import github.daneren2005.dsub.R;
import github.daneren2005.dsub.domain.Genre;
import github.daneren2005.dsub.util.ProgressListener;
import org.xmlpull.v1.XmlPullParser;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.Reader;
/*
This file is part of Subsonic.
Subsonic is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
Subsonic is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with Subsonic. If not, see <http://www.gnu.org/licenses/>.
Copyright 2010 (C) Sindre Mehus
*/
package github.daneren2005.dsub.service.parser;
/**
* @author Joshua Bahnsen
*/
public class GenreParser extends AbstractParser {
private static final String TAG = GenreParser.class.getSimpleName();
public GenreParser(Context context, int instance) {
super(context, instance);
}
| public List<Genre> parse(Reader reader, ProgressListener progressListener) throws Exception { |
erdemolkun/instant-rates | app/src/main/java/dynoapps/exchange_rates/network/YahooService.java | // Path: app/src/main/java/dynoapps/exchange_rates/model/rates/YahooRate.java
// public class YahooRate extends AvgRate {
// @Override
// public void toRateType() {
// if (TextUtils.isEmpty(type)) rateType = UNKNOWN;
// int rateType = UNKNOWN;
// if (type.contains("USDTRY")) {
// rateType = USD;
// } else if (type.contains("EURTRY")) {
// rateType = EUR;
// } else if (type.contains("EURUSD")) {
// rateType = EUR_USD;
// } else if (type.contains("GC")) {
// rateType = ONS;
// }
// this.rateType = rateType;
// }
//
// @Override
// public void setRealValues() {
// if (rateType == UNKNOWN) return;
// val_real_avg = Float.parseFloat(avg_val);
// }
// }
| import java.util.List;
import dynoapps.exchange_rates.model.rates.YahooRate;
import io.reactivex.Observable;
import retrofit2.http.GET; | package dynoapps.exchange_rates.network;
/**
* Created by @Erdem OLKUN on 10/12/2016.
*/
public interface YahooService {
@GET("d/quotes.csv?e=.csv&f=sl1d1t1&s=USDTRY=X,EURTRY=X,EURUSD=X,GC=F") | // Path: app/src/main/java/dynoapps/exchange_rates/model/rates/YahooRate.java
// public class YahooRate extends AvgRate {
// @Override
// public void toRateType() {
// if (TextUtils.isEmpty(type)) rateType = UNKNOWN;
// int rateType = UNKNOWN;
// if (type.contains("USDTRY")) {
// rateType = USD;
// } else if (type.contains("EURTRY")) {
// rateType = EUR;
// } else if (type.contains("EURUSD")) {
// rateType = EUR_USD;
// } else if (type.contains("GC")) {
// rateType = ONS;
// }
// this.rateType = rateType;
// }
//
// @Override
// public void setRealValues() {
// if (rateType == UNKNOWN) return;
// val_real_avg = Float.parseFloat(avg_val);
// }
// }
// Path: app/src/main/java/dynoapps/exchange_rates/network/YahooService.java
import java.util.List;
import dynoapps.exchange_rates.model.rates.YahooRate;
import io.reactivex.Observable;
import retrofit2.http.GET;
package dynoapps.exchange_rates.network;
/**
* Created by @Erdem OLKUN on 10/12/2016.
*/
public interface YahooService {
@GET("d/quotes.csv?e=.csv&f=sl1d1t1&s=USDTRY=X,EURTRY=X,EURUSD=X,GC=F") | Observable<List<YahooRate>> rates(); |
erdemolkun/instant-rates | app/src/main/java/dynoapps/exchange_rates/network/ParaGarantiService.java | // Path: app/src/main/java/dynoapps/exchange_rates/model/rates/ParaGarantiRate.java
// public class ParaGarantiRate extends AvgRate {
//
// public String symbol;
// public String last;
//
// @Override
// public void toRateType() {
// if (TextUtils.isEmpty(symbol)) rateType = UNKNOWN;
// int rateType = UNKNOWN;
// switch (symbol) {
// case "KUSD":
// rateType = USD;
// break;
// case "KEUR":
// rateType = EUR;
// break;
// case "EUR":
// rateType = EUR_USD;
// break;
// }
// this.rateType = rateType;
// }
//
// @Override
// public void setRealValues() {
// if (rateType == UNKNOWN) return;
// last = last.replace(',', '.');
// String val = last.replace("'", "").replace("$", "").trim();
// Float real_val = RateUtils.toFloat(val);
// val_real_avg = real_val != null ? real_val : 0.0f;
// }
//
// @Override
// @NonNull
// public String toString() {
// return "SYMBOL : " + symbol + " Value : " + last;
// }
//
// }
| import java.util.List;
import dynoapps.exchange_rates.model.rates.ParaGarantiRate;
import io.reactivex.Observable;
import retrofit2.http.GET;
import retrofit2.http.Headers; | package dynoapps.exchange_rates.network;
/**
* Created by erdemmac on 24/10/2016.
*/
public interface ParaGarantiService {
@Headers({
"Content-Type:text/html;charset=UTF-8"
})
@GET("asp/xml/icpiyasaX.xml") | // Path: app/src/main/java/dynoapps/exchange_rates/model/rates/ParaGarantiRate.java
// public class ParaGarantiRate extends AvgRate {
//
// public String symbol;
// public String last;
//
// @Override
// public void toRateType() {
// if (TextUtils.isEmpty(symbol)) rateType = UNKNOWN;
// int rateType = UNKNOWN;
// switch (symbol) {
// case "KUSD":
// rateType = USD;
// break;
// case "KEUR":
// rateType = EUR;
// break;
// case "EUR":
// rateType = EUR_USD;
// break;
// }
// this.rateType = rateType;
// }
//
// @Override
// public void setRealValues() {
// if (rateType == UNKNOWN) return;
// last = last.replace(',', '.');
// String val = last.replace("'", "").replace("$", "").trim();
// Float real_val = RateUtils.toFloat(val);
// val_real_avg = real_val != null ? real_val : 0.0f;
// }
//
// @Override
// @NonNull
// public String toString() {
// return "SYMBOL : " + symbol + " Value : " + last;
// }
//
// }
// Path: app/src/main/java/dynoapps/exchange_rates/network/ParaGarantiService.java
import java.util.List;
import dynoapps.exchange_rates.model.rates.ParaGarantiRate;
import io.reactivex.Observable;
import retrofit2.http.GET;
import retrofit2.http.Headers;
package dynoapps.exchange_rates.network;
/**
* Created by erdemmac on 24/10/2016.
*/
public interface ParaGarantiService {
@Headers({
"Content-Type:text/html;charset=UTF-8"
})
@GET("asp/xml/icpiyasaX.xml") | Observable<List<ParaGarantiRate>> rates(); |
erdemolkun/instant-rates | app/src/main/java/dynoapps/exchange_rates/BaseActivity.java | // Path: app/src/main/java/dynoapps/exchange_rates/util/L.java
// public class L {
//
// private static final String TAG = "ExchangeRates";
//
// private static final String LOG_PREFIX = "";
// private static final int LOG_PREFIX_LENGTH = LOG_PREFIX.length();
// private static final int MAX_LOG_TAG_LENGTH = 23;
// private static final int MAX_CHAR_LENGTH = 320;
//
// public static String makeLogTag(String str) {
// if (str.length() > MAX_LOG_TAG_LENGTH - LOG_PREFIX_LENGTH) {
// return LOG_PREFIX + str.substring(0, MAX_LOG_TAG_LENGTH - LOG_PREFIX_LENGTH - 1);
// }
//
// return LOG_PREFIX + str;
// }
//
// public static void e(String tag, String msg) {
// Log.e(makeLogTag(tag), msg);
// }
//
// public static void e(String tag, Throwable th) {
// Log.e(tag, "", th);
// }
//
// public static void i(String tag, String msg) {
// Log.i(makeLogTag(tag), msg);
// }
//
// public static void ex(Exception ex) {
// Log.e(TAG, "", ex);
// }
//
// public static void ex(Exception ex, String message) {
// Log.e(TAG, message, ex);
// }
// }
| import android.content.res.TypedArray;
import android.graphics.Color;
import android.graphics.PorterDuff;
import android.graphics.PorterDuffColorFilter;
import android.graphics.drawable.Drawable;
import android.os.Bundle;
import androidx.annotation.DrawableRes;
import androidx.annotation.LayoutRes;
import androidx.annotation.Nullable;
import androidx.appcompat.app.AppCompatActivity;
import androidx.appcompat.widget.Toolbar;
import androidx.core.content.ContextCompat;
import butterknife.ButterKnife;
import dynoapps.exchange_rates.util.L; | super.onCreate(savedInstanceState);
setContentView(getLayoutId());
ButterKnife.bind(this);
}
protected Toolbar getActionBarToolbar() {
if (mActionBarToolbar == null) {
mActionBarToolbar = findViewById(R.id.toolbar_actionbar);
if (mActionBarToolbar != null) {
setSupportActionBar(mActionBarToolbar);
}
}
return mActionBarToolbar;
}
@LayoutRes
public abstract int getLayoutId();
protected void setNavigationIcon(@DrawableRes Integer resId) {
Drawable drawable = ContextCompat.getDrawable(this, resId);
setNavigationIcon(drawable);
}
protected void setNavigationIcon(Drawable drawable) {
Integer color = null;
try {
TypedArray a = getTheme().obtainStyledAttributes(new int[]{R.attr.actionBarIconColor});
color = a.getColor(0, Color.WHITE);
} catch (Exception e) { | // Path: app/src/main/java/dynoapps/exchange_rates/util/L.java
// public class L {
//
// private static final String TAG = "ExchangeRates";
//
// private static final String LOG_PREFIX = "";
// private static final int LOG_PREFIX_LENGTH = LOG_PREFIX.length();
// private static final int MAX_LOG_TAG_LENGTH = 23;
// private static final int MAX_CHAR_LENGTH = 320;
//
// public static String makeLogTag(String str) {
// if (str.length() > MAX_LOG_TAG_LENGTH - LOG_PREFIX_LENGTH) {
// return LOG_PREFIX + str.substring(0, MAX_LOG_TAG_LENGTH - LOG_PREFIX_LENGTH - 1);
// }
//
// return LOG_PREFIX + str;
// }
//
// public static void e(String tag, String msg) {
// Log.e(makeLogTag(tag), msg);
// }
//
// public static void e(String tag, Throwable th) {
// Log.e(tag, "", th);
// }
//
// public static void i(String tag, String msg) {
// Log.i(makeLogTag(tag), msg);
// }
//
// public static void ex(Exception ex) {
// Log.e(TAG, "", ex);
// }
//
// public static void ex(Exception ex, String message) {
// Log.e(TAG, message, ex);
// }
// }
// Path: app/src/main/java/dynoapps/exchange_rates/BaseActivity.java
import android.content.res.TypedArray;
import android.graphics.Color;
import android.graphics.PorterDuff;
import android.graphics.PorterDuffColorFilter;
import android.graphics.drawable.Drawable;
import android.os.Bundle;
import androidx.annotation.DrawableRes;
import androidx.annotation.LayoutRes;
import androidx.annotation.Nullable;
import androidx.appcompat.app.AppCompatActivity;
import androidx.appcompat.widget.Toolbar;
import androidx.core.content.ContextCompat;
import butterknife.ButterKnife;
import dynoapps.exchange_rates.util.L;
super.onCreate(savedInstanceState);
setContentView(getLayoutId());
ButterKnife.bind(this);
}
protected Toolbar getActionBarToolbar() {
if (mActionBarToolbar == null) {
mActionBarToolbar = findViewById(R.id.toolbar_actionbar);
if (mActionBarToolbar != null) {
setSupportActionBar(mActionBarToolbar);
}
}
return mActionBarToolbar;
}
@LayoutRes
public abstract int getLayoutId();
protected void setNavigationIcon(@DrawableRes Integer resId) {
Drawable drawable = ContextCompat.getDrawable(this, resId);
setNavigationIcon(drawable);
}
protected void setNavigationIcon(Drawable drawable) {
Integer color = null;
try {
TypedArray a = getTheme().obtainStyledAttributes(new int[]{R.attr.actionBarIconColor});
color = a.getColor(0, Color.WHITE);
} catch (Exception e) { | L.ex(e); |
erdemolkun/instant-rates | app/src/main/java/dynoapps/exchange_rates/network/YorumlarService.java | // Path: app/src/main/java/dynoapps/exchange_rates/model/rates/YorumlarRate.java
// public class YorumlarRate extends AvgRate {
//
// public String time;
//
// @Override
// public void toRateType() {
// if (TextUtils.isEmpty(type)) rateType = UNKNOWN;
// int rateType = UNKNOWN;
// switch (type) {
// case "dolar_guncelle":
// rateType = USD;
// break;
// case "euro_guncelle":
// rateType = EUR;
// break;
// case "parite_guncelle":
// rateType = EUR_USD;
// break;
// case "ons_guncelle":
// rateType = ONS;
// break;
// }
// this.rateType = rateType;
// }
//
// @Override
// public void setRealValues() {
// if (rateType == UNKNOWN) return;
// String val = avg_val.replace("'", "").replace("$", "").trim();
// val_real_avg = Float.parseFloat(val);
// }
//
// @Override
// @NonNull
// public String toString() {
// return type.split("_")[0] + " -> : " + val_real_avg + " : Time -> " + time.replace("'", "");
// }
//
// }
| import java.util.List;
import dynoapps.exchange_rates.model.rates.YorumlarRate;
import io.reactivex.Observable;
import retrofit2.http.GET;
import retrofit2.http.Headers;
import retrofit2.http.Query; | package dynoapps.exchange_rates.network;
/**
* Created by erdemmac on 24/10/2016.
*/
public interface YorumlarService {
@Headers({
"Content-Type:text/html; Charset=iso-8859-9"
})
@GET("guncel.asp") | // Path: app/src/main/java/dynoapps/exchange_rates/model/rates/YorumlarRate.java
// public class YorumlarRate extends AvgRate {
//
// public String time;
//
// @Override
// public void toRateType() {
// if (TextUtils.isEmpty(type)) rateType = UNKNOWN;
// int rateType = UNKNOWN;
// switch (type) {
// case "dolar_guncelle":
// rateType = USD;
// break;
// case "euro_guncelle":
// rateType = EUR;
// break;
// case "parite_guncelle":
// rateType = EUR_USD;
// break;
// case "ons_guncelle":
// rateType = ONS;
// break;
// }
// this.rateType = rateType;
// }
//
// @Override
// public void setRealValues() {
// if (rateType == UNKNOWN) return;
// String val = avg_val.replace("'", "").replace("$", "").trim();
// val_real_avg = Float.parseFloat(val);
// }
//
// @Override
// @NonNull
// public String toString() {
// return type.split("_")[0] + " -> : " + val_real_avg + " : Time -> " + time.replace("'", "");
// }
//
// }
// Path: app/src/main/java/dynoapps/exchange_rates/network/YorumlarService.java
import java.util.List;
import dynoapps.exchange_rates.model.rates.YorumlarRate;
import io.reactivex.Observable;
import retrofit2.http.GET;
import retrofit2.http.Headers;
import retrofit2.http.Query;
package dynoapps.exchange_rates.network;
/**
* Created by erdemmac on 24/10/2016.
*/
public interface YorumlarService {
@Headers({
"Content-Type:text/html; Charset=iso-8859-9"
})
@GET("guncel.asp") | Observable<List<YorumlarRate>> rates(@Query("ajax") String type); |
erdemolkun/instant-rates | app/src/main/java/dynoapps/exchange_rates/App.java | // Path: app/src/main/java/dynoapps/exchange_rates/alarm/AlarmsRepository.java
// public class AlarmsRepository implements AlarmsDataSource {
//
// private static AlarmsRepository INSTANCE = null;
// /**
// * Marks the cache as invalid, to force an update the next time data is requested. This variable
// * has package local visibility so it can be accessed from tests.
// */
// boolean mCacheIsDirty = false;
// /**
// * This variable has package local visibility so it can be accessed from tests.
// */
// Map<Long, Alarm> cachedAlarms;
// private final AlarmsDataSource localAlarmsDataSource;
// private Boolean alarmEnabled = null;
//
//
// private AlarmsRepository(AlarmsDataSource localAlarmsDataSource) {
// this.localAlarmsDataSource = localAlarmsDataSource;
// }
//
// public static AlarmsRepository getInstance(@NonNull Context context) {
// if (INSTANCE == null) {
// synchronized (AlarmsRepository.class) {
// if (INSTANCE == null) {
// INSTANCE = new AlarmsRepository(new LocalAlarmsDataSource(context));
// }
// }
// }
// return INSTANCE;
// }
//
// @Override
// public void getAlarms(final AlarmsLoadCallback callback) {
// // Respond immediately with cache if available and not dirty
// if (cachedAlarms != null && !mCacheIsDirty) {
// callback.onAlarmsLoaded(new ArrayList<>(cachedAlarms.values()));
// return;
// }
// localAlarmsDataSource.getAlarms(alarms -> {
// refreshCache(alarms);
// callback.onAlarmsLoaded(new ArrayList<>(cachedAlarms.values()));
// });
// }
//
// @Override
// public void saveAlarm(@NonNull Alarm alarm, final AlarmUpdateInsertCallback alarmUpdateInsertCallback) {
// localAlarmsDataSource.saveAlarm(alarm, alarm1 -> {
// // Do in memory cache update to keep the app UI up to date
// if (cachedAlarms == null) {
// cachedAlarms = new LinkedHashMap<>();
// }
// cachedAlarms.put(alarm1.id, alarm1);
// if (alarmUpdateInsertCallback != null) {
// alarmUpdateInsertCallback.onAlarmUpdate(alarm1);
// }
// });
// }
//
// @Override
// public Single<Alarm> deleteAlarm(@NonNull Alarm alarm) {
// return localAlarmsDataSource.deleteAlarm(alarm).doAfterSuccess(alarm1 -> {
// cachedAlarms.remove(alarm1.id);
// });
// }
//
// @Override
// public Single<Alarm> updateAlarm(@NonNull Alarm alarm) {
//
// return localAlarmsDataSource.updateAlarm(alarm).doAfterSuccess(updatedAlarm -> {
// // Do in memory cache update to keep the app UI up to date
// if (cachedAlarms == null) {
// cachedAlarms = new LinkedHashMap<>();
// }
// cachedAlarms.put(updatedAlarm.id, updatedAlarm);
// });
// }
//
// @Override
// public void refreshAlarms() {
// mCacheIsDirty = true;
// }
//
// private void refreshCache(List<Alarm> alarms) {
// if (cachedAlarms == null) {
// cachedAlarms = new LinkedHashMap<>();
// }
// cachedAlarms.clear();
// for (Alarm alarm : alarms) {
// cachedAlarms.put(alarm.id, alarm);
// }
// mCacheIsDirty = false;
// }
//
// public boolean isEnabled() {
// if (alarmEnabled == null) alarmEnabled = Prefs.isAlarmEnabled();
// return alarmEnabled;
// }
//
// public void updateEnabled(boolean alarmEnabled) {
// this.alarmEnabled = alarmEnabled;
// Prefs.saveAlarmEnabled(alarmEnabled);
// }
//
// public boolean hasAnyActive() {
//
// if (!isEnabled()) return false;
// if (cachedAlarms == null || cachedAlarms.size() < 1) return false;
// for (Alarm alarm : cachedAlarms.values()) {
// if (alarm.isEnabled) {
// for (CurrencySource source : SourcesManager.getCurrencySources()) {
// if (source.isEnabled() && source.getType() == alarm.sourceType) {
// return true;
// }
// }
// }
// }
// return false;
// }
// }
//
// Path: app/src/main/java/dynoapps/exchange_rates/util/L.java
// public class L {
//
// private static final String TAG = "ExchangeRates";
//
// private static final String LOG_PREFIX = "";
// private static final int LOG_PREFIX_LENGTH = LOG_PREFIX.length();
// private static final int MAX_LOG_TAG_LENGTH = 23;
// private static final int MAX_CHAR_LENGTH = 320;
//
// public static String makeLogTag(String str) {
// if (str.length() > MAX_LOG_TAG_LENGTH - LOG_PREFIX_LENGTH) {
// return LOG_PREFIX + str.substring(0, MAX_LOG_TAG_LENGTH - LOG_PREFIX_LENGTH - 1);
// }
//
// return LOG_PREFIX + str;
// }
//
// public static void e(String tag, String msg) {
// Log.e(makeLogTag(tag), msg);
// }
//
// public static void e(String tag, Throwable th) {
// Log.e(tag, "", th);
// }
//
// public static void i(String tag, String msg) {
// Log.i(makeLogTag(tag), msg);
// }
//
// public static void ex(Exception ex) {
// Log.e(TAG, "", ex);
// }
//
// public static void ex(Exception ex, String message) {
// Log.e(TAG, message, ex);
// }
// }
| import android.annotation.SuppressLint;
import android.app.Application;
import android.content.Context;
import androidx.annotation.NonNull;
import dynoapps.exchange_rates.alarm.AlarmsRepository;
import dynoapps.exchange_rates.util.L;
import io.reactivex.plugins.RxJavaPlugins; | package dynoapps.exchange_rates;
/**
* Created by erdemmac on 21/10/2016.
*/
public class App extends Application {
private static App appInstance;
public static App getInstance() {
return appInstance;
}
@NonNull
public static Context context() {
return appInstance.getApplicationContext();
}
| // Path: app/src/main/java/dynoapps/exchange_rates/alarm/AlarmsRepository.java
// public class AlarmsRepository implements AlarmsDataSource {
//
// private static AlarmsRepository INSTANCE = null;
// /**
// * Marks the cache as invalid, to force an update the next time data is requested. This variable
// * has package local visibility so it can be accessed from tests.
// */
// boolean mCacheIsDirty = false;
// /**
// * This variable has package local visibility so it can be accessed from tests.
// */
// Map<Long, Alarm> cachedAlarms;
// private final AlarmsDataSource localAlarmsDataSource;
// private Boolean alarmEnabled = null;
//
//
// private AlarmsRepository(AlarmsDataSource localAlarmsDataSource) {
// this.localAlarmsDataSource = localAlarmsDataSource;
// }
//
// public static AlarmsRepository getInstance(@NonNull Context context) {
// if (INSTANCE == null) {
// synchronized (AlarmsRepository.class) {
// if (INSTANCE == null) {
// INSTANCE = new AlarmsRepository(new LocalAlarmsDataSource(context));
// }
// }
// }
// return INSTANCE;
// }
//
// @Override
// public void getAlarms(final AlarmsLoadCallback callback) {
// // Respond immediately with cache if available and not dirty
// if (cachedAlarms != null && !mCacheIsDirty) {
// callback.onAlarmsLoaded(new ArrayList<>(cachedAlarms.values()));
// return;
// }
// localAlarmsDataSource.getAlarms(alarms -> {
// refreshCache(alarms);
// callback.onAlarmsLoaded(new ArrayList<>(cachedAlarms.values()));
// });
// }
//
// @Override
// public void saveAlarm(@NonNull Alarm alarm, final AlarmUpdateInsertCallback alarmUpdateInsertCallback) {
// localAlarmsDataSource.saveAlarm(alarm, alarm1 -> {
// // Do in memory cache update to keep the app UI up to date
// if (cachedAlarms == null) {
// cachedAlarms = new LinkedHashMap<>();
// }
// cachedAlarms.put(alarm1.id, alarm1);
// if (alarmUpdateInsertCallback != null) {
// alarmUpdateInsertCallback.onAlarmUpdate(alarm1);
// }
// });
// }
//
// @Override
// public Single<Alarm> deleteAlarm(@NonNull Alarm alarm) {
// return localAlarmsDataSource.deleteAlarm(alarm).doAfterSuccess(alarm1 -> {
// cachedAlarms.remove(alarm1.id);
// });
// }
//
// @Override
// public Single<Alarm> updateAlarm(@NonNull Alarm alarm) {
//
// return localAlarmsDataSource.updateAlarm(alarm).doAfterSuccess(updatedAlarm -> {
// // Do in memory cache update to keep the app UI up to date
// if (cachedAlarms == null) {
// cachedAlarms = new LinkedHashMap<>();
// }
// cachedAlarms.put(updatedAlarm.id, updatedAlarm);
// });
// }
//
// @Override
// public void refreshAlarms() {
// mCacheIsDirty = true;
// }
//
// private void refreshCache(List<Alarm> alarms) {
// if (cachedAlarms == null) {
// cachedAlarms = new LinkedHashMap<>();
// }
// cachedAlarms.clear();
// for (Alarm alarm : alarms) {
// cachedAlarms.put(alarm.id, alarm);
// }
// mCacheIsDirty = false;
// }
//
// public boolean isEnabled() {
// if (alarmEnabled == null) alarmEnabled = Prefs.isAlarmEnabled();
// return alarmEnabled;
// }
//
// public void updateEnabled(boolean alarmEnabled) {
// this.alarmEnabled = alarmEnabled;
// Prefs.saveAlarmEnabled(alarmEnabled);
// }
//
// public boolean hasAnyActive() {
//
// if (!isEnabled()) return false;
// if (cachedAlarms == null || cachedAlarms.size() < 1) return false;
// for (Alarm alarm : cachedAlarms.values()) {
// if (alarm.isEnabled) {
// for (CurrencySource source : SourcesManager.getCurrencySources()) {
// if (source.isEnabled() && source.getType() == alarm.sourceType) {
// return true;
// }
// }
// }
// }
// return false;
// }
// }
//
// Path: app/src/main/java/dynoapps/exchange_rates/util/L.java
// public class L {
//
// private static final String TAG = "ExchangeRates";
//
// private static final String LOG_PREFIX = "";
// private static final int LOG_PREFIX_LENGTH = LOG_PREFIX.length();
// private static final int MAX_LOG_TAG_LENGTH = 23;
// private static final int MAX_CHAR_LENGTH = 320;
//
// public static String makeLogTag(String str) {
// if (str.length() > MAX_LOG_TAG_LENGTH - LOG_PREFIX_LENGTH) {
// return LOG_PREFIX + str.substring(0, MAX_LOG_TAG_LENGTH - LOG_PREFIX_LENGTH - 1);
// }
//
// return LOG_PREFIX + str;
// }
//
// public static void e(String tag, String msg) {
// Log.e(makeLogTag(tag), msg);
// }
//
// public static void e(String tag, Throwable th) {
// Log.e(tag, "", th);
// }
//
// public static void i(String tag, String msg) {
// Log.i(makeLogTag(tag), msg);
// }
//
// public static void ex(Exception ex) {
// Log.e(TAG, "", ex);
// }
//
// public static void ex(Exception ex, String message) {
// Log.e(TAG, message, ex);
// }
// }
// Path: app/src/main/java/dynoapps/exchange_rates/App.java
import android.annotation.SuppressLint;
import android.app.Application;
import android.content.Context;
import androidx.annotation.NonNull;
import dynoapps.exchange_rates.alarm.AlarmsRepository;
import dynoapps.exchange_rates.util.L;
import io.reactivex.plugins.RxJavaPlugins;
package dynoapps.exchange_rates;
/**
* Created by erdemmac on 21/10/2016.
*/
public class App extends Application {
private static App appInstance;
public static App getInstance() {
return appInstance;
}
@NonNull
public static Context context() {
return appInstance.getApplicationContext();
}
| public AlarmsRepository provideAlarmsRepository() { |
erdemolkun/instant-rates | app/src/main/java/dynoapps/exchange_rates/BaseServiceActivity.java | // Path: app/src/main/java/dynoapps/exchange_rates/time/TimeIntervalManager.java
// public final class TimeIntervalManager {
//
// private static final int DEFAULT_INTERVAL_INDEX = 2;
// private static final int INTERVAL_SERVICE_INDEX = 4;
// private static final long PREF_INTERVAL_MILLIS = Prefs.getInterval(App.context());
// private static ArrayList<TimeInterval> intervals;
// private static Integer selectedIntervalIndexUser = getSelectedIndexViaPrefs();
// private static boolean isAlarmMode = false;
// private static int userSelectedItemIndex = -1;
//
// private static final PublishSubject<Boolean> intervalUpdates = PublishSubject.create();
//
// private static boolean isAlarmMode() {
// return isAlarmMode;
// }
//
// public static void setAlarmMode(boolean enabled) {
// TimeIntervalManager.isAlarmMode = enabled;
// TimeIntervalManager.updateIntervalsToUIMode();// Intervals should be updated on ui mode.
// }
//
// public static void updateIntervalsToUIMode() {
// intervalUpdates.onNext(true);
// }
//
// private static ArrayList<TimeInterval> getDefaultIntervals() {
// if (CollectionUtils.isNullOrEmpty(intervals)) {
// intervals = new ArrayList<>();
// intervals.add(new TimeInterval(3, TimeUnit.SECONDS));
// intervals.add(new TimeInterval(5, TimeUnit.SECONDS));
// intervals.add(new TimeInterval(10, TimeUnit.SECONDS));
// intervals.add(new TimeInterval(15, TimeUnit.SECONDS));
// intervals.add(new TimeInterval(20, TimeUnit.SECONDS));
// intervals.add(new TimeInterval(30, TimeUnit.SECONDS));
// intervals.add(new TimeInterval(1, TimeUnit.MINUTES));
// }
// return intervals;
// }
//
// public static PublishSubject<Boolean> getIntervalUpdates() {
// return intervalUpdates;
// }
//
// public static String getSelectionStr() {
// return getDefaultIntervals().get(getSelectedIndex()).toString();
// }
//
// public static void selectInterval(final Activity activity) {
//
// final ArrayList<TimeInterval> timeIntervals = TimeIntervalManager.getDefaultIntervals();
// userSelectedItemIndex = TimeIntervalManager.getSelectedIndex();
// String[] time_values = new String[CollectionUtils.size(timeIntervals)];
// for (int i = 0; i < time_values.length; i++) {
// time_values[i] = timeIntervals.get(i).toString();
// }
// AlertDialog.Builder builder = new AlertDialog.Builder(activity, R.style.AppTheme_Alert);
//
// builder.setSingleChoiceItems(time_values, userSelectedItemIndex, (dialogInterface, i) -> userSelectedItemIndex = i);
//
// builder.setCancelable(true);
// builder.setTitle(R.string.select_time_interval);
// builder.setPositiveButton(R.string.apply, (dialog, which) -> {
// if (userSelectedItemIndex != TimeIntervalManager.getSelectedIndex()) {
// TimeIntervalManager.updateUserInvertalSelection(userSelectedItemIndex);
// intervalUpdates.onNext(false);
// }
// });
//
// builder.setNegativeButton(R.string.dismiss, null);
//
// AlertDialog dialog = builder.create();
// if (dialog.getWindow() != null) {
// dialog.getWindow().setWindowAnimations(R.style.DialogAnimationFade);
// }
// dialog.show();
// }
//
// private static int getSelectedIndexViaPrefs() {
// long saved = Prefs.getInterval(App.context());
// if (saved < 0)
// return -1;
// int index = 0;
// for (TimeInterval timeInterval : getDefaultIntervals()) {
// if (timeInterval.to(TimeUnit.MILLISECONDS) == saved) {
// return index;
// }
// index++;
// }
// return -1;
// }
//
// private static int getSelectedIndex() {
// if (!isAlarmMode()) {
// if (selectedIntervalIndexUser < 0) {
// return DEFAULT_INTERVAL_INDEX;
// }
// return selectedIntervalIndexUser;
// } else {
// return selectedIntervalIndexUser > INTERVAL_SERVICE_INDEX ? selectedIntervalIndexUser : INTERVAL_SERVICE_INDEX;
// }
// }
//
//
// public static void updateUserInvertalSelection(int index) {
// selectedIntervalIndexUser = Math.min(CollectionUtils.size(getDefaultIntervals()), index);
// Prefs.saveInterval(App.context(), getDefaultIntervals().get(selectedIntervalIndexUser).to(TimeUnit.MILLISECONDS));
// }
//
// /**
// * Returns time interval for polling in {@link TimeUnit#MILLISECONDS} milliseconds
// */
// public static long getPollingInterval() {
// if (!isAlarmMode() && selectedIntervalIndexUser < 0) {
// if (PREF_INTERVAL_MILLIS < 0) {
// return getDefaultIntervals().get(DEFAULT_INTERVAL_INDEX).to(TimeUnit.MILLISECONDS);
// } else {
// return PREF_INTERVAL_MILLIS;
// }
// } else {
// return getDefaultIntervals().get(getSelectedIndex()).to(TimeUnit.MILLISECONDS);
// }
// }
// }
| import android.os.Bundle;
import androidx.annotation.Nullable;
import dynoapps.exchange_rates.time.TimeIntervalManager;
import io.reactivex.disposables.CompositeDisposable; | package dynoapps.exchange_rates;
public abstract class BaseServiceActivity extends BaseActivity {
protected CompositeDisposable compositeDisposable = new CompositeDisposable();
@Override
protected void onCreate(@Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
}
@Override
protected void onResume() {
super.onResume(); | // Path: app/src/main/java/dynoapps/exchange_rates/time/TimeIntervalManager.java
// public final class TimeIntervalManager {
//
// private static final int DEFAULT_INTERVAL_INDEX = 2;
// private static final int INTERVAL_SERVICE_INDEX = 4;
// private static final long PREF_INTERVAL_MILLIS = Prefs.getInterval(App.context());
// private static ArrayList<TimeInterval> intervals;
// private static Integer selectedIntervalIndexUser = getSelectedIndexViaPrefs();
// private static boolean isAlarmMode = false;
// private static int userSelectedItemIndex = -1;
//
// private static final PublishSubject<Boolean> intervalUpdates = PublishSubject.create();
//
// private static boolean isAlarmMode() {
// return isAlarmMode;
// }
//
// public static void setAlarmMode(boolean enabled) {
// TimeIntervalManager.isAlarmMode = enabled;
// TimeIntervalManager.updateIntervalsToUIMode();// Intervals should be updated on ui mode.
// }
//
// public static void updateIntervalsToUIMode() {
// intervalUpdates.onNext(true);
// }
//
// private static ArrayList<TimeInterval> getDefaultIntervals() {
// if (CollectionUtils.isNullOrEmpty(intervals)) {
// intervals = new ArrayList<>();
// intervals.add(new TimeInterval(3, TimeUnit.SECONDS));
// intervals.add(new TimeInterval(5, TimeUnit.SECONDS));
// intervals.add(new TimeInterval(10, TimeUnit.SECONDS));
// intervals.add(new TimeInterval(15, TimeUnit.SECONDS));
// intervals.add(new TimeInterval(20, TimeUnit.SECONDS));
// intervals.add(new TimeInterval(30, TimeUnit.SECONDS));
// intervals.add(new TimeInterval(1, TimeUnit.MINUTES));
// }
// return intervals;
// }
//
// public static PublishSubject<Boolean> getIntervalUpdates() {
// return intervalUpdates;
// }
//
// public static String getSelectionStr() {
// return getDefaultIntervals().get(getSelectedIndex()).toString();
// }
//
// public static void selectInterval(final Activity activity) {
//
// final ArrayList<TimeInterval> timeIntervals = TimeIntervalManager.getDefaultIntervals();
// userSelectedItemIndex = TimeIntervalManager.getSelectedIndex();
// String[] time_values = new String[CollectionUtils.size(timeIntervals)];
// for (int i = 0; i < time_values.length; i++) {
// time_values[i] = timeIntervals.get(i).toString();
// }
// AlertDialog.Builder builder = new AlertDialog.Builder(activity, R.style.AppTheme_Alert);
//
// builder.setSingleChoiceItems(time_values, userSelectedItemIndex, (dialogInterface, i) -> userSelectedItemIndex = i);
//
// builder.setCancelable(true);
// builder.setTitle(R.string.select_time_interval);
// builder.setPositiveButton(R.string.apply, (dialog, which) -> {
// if (userSelectedItemIndex != TimeIntervalManager.getSelectedIndex()) {
// TimeIntervalManager.updateUserInvertalSelection(userSelectedItemIndex);
// intervalUpdates.onNext(false);
// }
// });
//
// builder.setNegativeButton(R.string.dismiss, null);
//
// AlertDialog dialog = builder.create();
// if (dialog.getWindow() != null) {
// dialog.getWindow().setWindowAnimations(R.style.DialogAnimationFade);
// }
// dialog.show();
// }
//
// private static int getSelectedIndexViaPrefs() {
// long saved = Prefs.getInterval(App.context());
// if (saved < 0)
// return -1;
// int index = 0;
// for (TimeInterval timeInterval : getDefaultIntervals()) {
// if (timeInterval.to(TimeUnit.MILLISECONDS) == saved) {
// return index;
// }
// index++;
// }
// return -1;
// }
//
// private static int getSelectedIndex() {
// if (!isAlarmMode()) {
// if (selectedIntervalIndexUser < 0) {
// return DEFAULT_INTERVAL_INDEX;
// }
// return selectedIntervalIndexUser;
// } else {
// return selectedIntervalIndexUser > INTERVAL_SERVICE_INDEX ? selectedIntervalIndexUser : INTERVAL_SERVICE_INDEX;
// }
// }
//
//
// public static void updateUserInvertalSelection(int index) {
// selectedIntervalIndexUser = Math.min(CollectionUtils.size(getDefaultIntervals()), index);
// Prefs.saveInterval(App.context(), getDefaultIntervals().get(selectedIntervalIndexUser).to(TimeUnit.MILLISECONDS));
// }
//
// /**
// * Returns time interval for polling in {@link TimeUnit#MILLISECONDS} milliseconds
// */
// public static long getPollingInterval() {
// if (!isAlarmMode() && selectedIntervalIndexUser < 0) {
// if (PREF_INTERVAL_MILLIS < 0) {
// return getDefaultIntervals().get(DEFAULT_INTERVAL_INDEX).to(TimeUnit.MILLISECONDS);
// } else {
// return PREF_INTERVAL_MILLIS;
// }
// } else {
// return getDefaultIntervals().get(getSelectedIndex()).to(TimeUnit.MILLISECONDS);
// }
// }
// }
// Path: app/src/main/java/dynoapps/exchange_rates/BaseServiceActivity.java
import android.os.Bundle;
import androidx.annotation.Nullable;
import dynoapps.exchange_rates.time.TimeIntervalManager;
import io.reactivex.disposables.CompositeDisposable;
package dynoapps.exchange_rates;
public abstract class BaseServiceActivity extends BaseActivity {
protected CompositeDisposable compositeDisposable = new CompositeDisposable();
@Override
protected void onCreate(@Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
}
@Override
protected void onResume() {
super.onResume(); | TimeIntervalManager.setAlarmMode(false); |
erdemolkun/instant-rates | app/src/main/java/dynoapps/exchange_rates/converters/BigparaConverter.java | // Path: app/src/main/java/dynoapps/exchange_rates/model/rates/BaseRate.java
// public abstract class BaseRate implements IConvertable, IRate {
//
// public String type;
//
// @RateDef
// protected int rateType;
//
// BaseRate() {
// }
//
// @Override
// public int getRateType() {
// return rateType;
// }
//
// public String getFormatted(float val) {
// return RateUtils.valueToUI(val, rateType);
// }
// }
//
// Path: app/src/main/java/dynoapps/exchange_rates/model/rates/BigparaRate.java
// public class BigparaRate extends BuySellRate {
//
// @Override
// public void toRateType() {
// int rateType = UNKNOWN;
// String plain_type = type;
// plain_type = plain_type.toLowerCase();
// if (plain_type.contains("dolar")) {
// rateType = USD;
// } else if (plain_type.contains("euro")) {
// rateType = EUR;
// } else if (plain_type.contains("altın")) {
// rateType = ONS_TRY;
// } else if (plain_type.contains("parite")) {
// rateType = EUR_USD;
// }
// this.rateType = rateType;
// }
// }
//
// Path: app/src/main/java/dynoapps/exchange_rates/model/rates/BuySellRate.java
// public abstract class BuySellRate extends BaseRate {
// public Float valueSellReal, valueBuyReal;
// public String valueSell, valueBuy;
//
//
// @Override
// public void toRateType() {
// int rateType = UNKNOWN;
// String plain_type = type.replace("\n", "");
// if (plain_type.equals("USD")) {
// rateType = USD;
// } else if (plain_type.equals("EUR")) {
// rateType = EUR;
// } else if (plain_type.contains("altın")) {
// rateType = ONS_TRY;
// } else if (plain_type.contains("parite")) {
// rateType = EUR_USD;
// }
// this.rateType = rateType;
// }
//
// @Override
// public void setRealValues() {
// String val = valueSell.replace(" TL", "").replace(",", ".").trim();
// valueSellReal = Float.valueOf(val);
//
// val = valueBuy.replace(" TL", "").replace(",", ".").trim();
// valueBuyReal = Float.valueOf(val);
// }
//
//
// @Override
// public float getValue(int valueType) {
// if (valueType == ValueType.BUY) {
// return valueBuyReal;
// } else if (valueType == ValueType.SELL) {
// return valueSellReal;
// }
// return 0.0f;
// }
//
// @Override
// @NonNull
// public String toString() {
// return type.split("_")[0] + " -> " + valueSellReal + " : " + valueBuyReal;
// }
// }
| import org.jsoup.Jsoup;
import org.jsoup.nodes.Element;
import java.io.IOException;
import java.lang.annotation.Annotation;
import java.lang.reflect.Type;
import java.util.ArrayList;
import java.util.List;
import androidx.annotation.NonNull;
import dynoapps.exchange_rates.model.rates.BaseRate;
import dynoapps.exchange_rates.model.rates.BigparaRate;
import dynoapps.exchange_rates.model.rates.BuySellRate;
import okhttp3.ResponseBody;
import retrofit2.Converter;
import retrofit2.Retrofit; | package dynoapps.exchange_rates.converters;
/**
* Created by erdemmac on 24/11/2016.
*/
public class BigparaConverter implements Converter<ResponseBody, List<BaseRate>> {
private static final BigparaConverter INSTANCE = new BigparaConverter();
private static final String HOST = "http://www.bigpara.com";
private BigparaConverter() {
}
@Override
public List<BaseRate> convert(@NonNull ResponseBody value) throws IOException {
ArrayList<BaseRate> rates = new ArrayList<>();
String responseBody = value.string();
ArrayList<Element> elements = Jsoup.parse(responseBody, HOST).select("#content").select(".kurdetail").select(".kurbox");
String val_buy = elements.get(1).select(".value").text();
String val_sell = elements.get(2).select(".value").text();
| // Path: app/src/main/java/dynoapps/exchange_rates/model/rates/BaseRate.java
// public abstract class BaseRate implements IConvertable, IRate {
//
// public String type;
//
// @RateDef
// protected int rateType;
//
// BaseRate() {
// }
//
// @Override
// public int getRateType() {
// return rateType;
// }
//
// public String getFormatted(float val) {
// return RateUtils.valueToUI(val, rateType);
// }
// }
//
// Path: app/src/main/java/dynoapps/exchange_rates/model/rates/BigparaRate.java
// public class BigparaRate extends BuySellRate {
//
// @Override
// public void toRateType() {
// int rateType = UNKNOWN;
// String plain_type = type;
// plain_type = plain_type.toLowerCase();
// if (plain_type.contains("dolar")) {
// rateType = USD;
// } else if (plain_type.contains("euro")) {
// rateType = EUR;
// } else if (plain_type.contains("altın")) {
// rateType = ONS_TRY;
// } else if (plain_type.contains("parite")) {
// rateType = EUR_USD;
// }
// this.rateType = rateType;
// }
// }
//
// Path: app/src/main/java/dynoapps/exchange_rates/model/rates/BuySellRate.java
// public abstract class BuySellRate extends BaseRate {
// public Float valueSellReal, valueBuyReal;
// public String valueSell, valueBuy;
//
//
// @Override
// public void toRateType() {
// int rateType = UNKNOWN;
// String plain_type = type.replace("\n", "");
// if (plain_type.equals("USD")) {
// rateType = USD;
// } else if (plain_type.equals("EUR")) {
// rateType = EUR;
// } else if (plain_type.contains("altın")) {
// rateType = ONS_TRY;
// } else if (plain_type.contains("parite")) {
// rateType = EUR_USD;
// }
// this.rateType = rateType;
// }
//
// @Override
// public void setRealValues() {
// String val = valueSell.replace(" TL", "").replace(",", ".").trim();
// valueSellReal = Float.valueOf(val);
//
// val = valueBuy.replace(" TL", "").replace(",", ".").trim();
// valueBuyReal = Float.valueOf(val);
// }
//
//
// @Override
// public float getValue(int valueType) {
// if (valueType == ValueType.BUY) {
// return valueBuyReal;
// } else if (valueType == ValueType.SELL) {
// return valueSellReal;
// }
// return 0.0f;
// }
//
// @Override
// @NonNull
// public String toString() {
// return type.split("_")[0] + " -> " + valueSellReal + " : " + valueBuyReal;
// }
// }
// Path: app/src/main/java/dynoapps/exchange_rates/converters/BigparaConverter.java
import org.jsoup.Jsoup;
import org.jsoup.nodes.Element;
import java.io.IOException;
import java.lang.annotation.Annotation;
import java.lang.reflect.Type;
import java.util.ArrayList;
import java.util.List;
import androidx.annotation.NonNull;
import dynoapps.exchange_rates.model.rates.BaseRate;
import dynoapps.exchange_rates.model.rates.BigparaRate;
import dynoapps.exchange_rates.model.rates.BuySellRate;
import okhttp3.ResponseBody;
import retrofit2.Converter;
import retrofit2.Retrofit;
package dynoapps.exchange_rates.converters;
/**
* Created by erdemmac on 24/11/2016.
*/
public class BigparaConverter implements Converter<ResponseBody, List<BaseRate>> {
private static final BigparaConverter INSTANCE = new BigparaConverter();
private static final String HOST = "http://www.bigpara.com";
private BigparaConverter() {
}
@Override
public List<BaseRate> convert(@NonNull ResponseBody value) throws IOException {
ArrayList<BaseRate> rates = new ArrayList<>();
String responseBody = value.string();
ArrayList<Element> elements = Jsoup.parse(responseBody, HOST).select("#content").select(".kurdetail").select(".kurbox");
String val_buy = elements.get(1).select(".value").text();
String val_sell = elements.get(2).select(".value").text();
| BuySellRate buySellRate = new BigparaRate(); |
erdemolkun/instant-rates | app/src/main/java/dynoapps/exchange_rates/converters/BigparaConverter.java | // Path: app/src/main/java/dynoapps/exchange_rates/model/rates/BaseRate.java
// public abstract class BaseRate implements IConvertable, IRate {
//
// public String type;
//
// @RateDef
// protected int rateType;
//
// BaseRate() {
// }
//
// @Override
// public int getRateType() {
// return rateType;
// }
//
// public String getFormatted(float val) {
// return RateUtils.valueToUI(val, rateType);
// }
// }
//
// Path: app/src/main/java/dynoapps/exchange_rates/model/rates/BigparaRate.java
// public class BigparaRate extends BuySellRate {
//
// @Override
// public void toRateType() {
// int rateType = UNKNOWN;
// String plain_type = type;
// plain_type = plain_type.toLowerCase();
// if (plain_type.contains("dolar")) {
// rateType = USD;
// } else if (plain_type.contains("euro")) {
// rateType = EUR;
// } else if (plain_type.contains("altın")) {
// rateType = ONS_TRY;
// } else if (plain_type.contains("parite")) {
// rateType = EUR_USD;
// }
// this.rateType = rateType;
// }
// }
//
// Path: app/src/main/java/dynoapps/exchange_rates/model/rates/BuySellRate.java
// public abstract class BuySellRate extends BaseRate {
// public Float valueSellReal, valueBuyReal;
// public String valueSell, valueBuy;
//
//
// @Override
// public void toRateType() {
// int rateType = UNKNOWN;
// String plain_type = type.replace("\n", "");
// if (plain_type.equals("USD")) {
// rateType = USD;
// } else if (plain_type.equals("EUR")) {
// rateType = EUR;
// } else if (plain_type.contains("altın")) {
// rateType = ONS_TRY;
// } else if (plain_type.contains("parite")) {
// rateType = EUR_USD;
// }
// this.rateType = rateType;
// }
//
// @Override
// public void setRealValues() {
// String val = valueSell.replace(" TL", "").replace(",", ".").trim();
// valueSellReal = Float.valueOf(val);
//
// val = valueBuy.replace(" TL", "").replace(",", ".").trim();
// valueBuyReal = Float.valueOf(val);
// }
//
//
// @Override
// public float getValue(int valueType) {
// if (valueType == ValueType.BUY) {
// return valueBuyReal;
// } else if (valueType == ValueType.SELL) {
// return valueSellReal;
// }
// return 0.0f;
// }
//
// @Override
// @NonNull
// public String toString() {
// return type.split("_")[0] + " -> " + valueSellReal + " : " + valueBuyReal;
// }
// }
| import org.jsoup.Jsoup;
import org.jsoup.nodes.Element;
import java.io.IOException;
import java.lang.annotation.Annotation;
import java.lang.reflect.Type;
import java.util.ArrayList;
import java.util.List;
import androidx.annotation.NonNull;
import dynoapps.exchange_rates.model.rates.BaseRate;
import dynoapps.exchange_rates.model.rates.BigparaRate;
import dynoapps.exchange_rates.model.rates.BuySellRate;
import okhttp3.ResponseBody;
import retrofit2.Converter;
import retrofit2.Retrofit; | package dynoapps.exchange_rates.converters;
/**
* Created by erdemmac on 24/11/2016.
*/
public class BigparaConverter implements Converter<ResponseBody, List<BaseRate>> {
private static final BigparaConverter INSTANCE = new BigparaConverter();
private static final String HOST = "http://www.bigpara.com";
private BigparaConverter() {
}
@Override
public List<BaseRate> convert(@NonNull ResponseBody value) throws IOException {
ArrayList<BaseRate> rates = new ArrayList<>();
String responseBody = value.string();
ArrayList<Element> elements = Jsoup.parse(responseBody, HOST).select("#content").select(".kurdetail").select(".kurbox");
String val_buy = elements.get(1).select(".value").text();
String val_sell = elements.get(2).select(".value").text();
| // Path: app/src/main/java/dynoapps/exchange_rates/model/rates/BaseRate.java
// public abstract class BaseRate implements IConvertable, IRate {
//
// public String type;
//
// @RateDef
// protected int rateType;
//
// BaseRate() {
// }
//
// @Override
// public int getRateType() {
// return rateType;
// }
//
// public String getFormatted(float val) {
// return RateUtils.valueToUI(val, rateType);
// }
// }
//
// Path: app/src/main/java/dynoapps/exchange_rates/model/rates/BigparaRate.java
// public class BigparaRate extends BuySellRate {
//
// @Override
// public void toRateType() {
// int rateType = UNKNOWN;
// String plain_type = type;
// plain_type = plain_type.toLowerCase();
// if (plain_type.contains("dolar")) {
// rateType = USD;
// } else if (plain_type.contains("euro")) {
// rateType = EUR;
// } else if (plain_type.contains("altın")) {
// rateType = ONS_TRY;
// } else if (plain_type.contains("parite")) {
// rateType = EUR_USD;
// }
// this.rateType = rateType;
// }
// }
//
// Path: app/src/main/java/dynoapps/exchange_rates/model/rates/BuySellRate.java
// public abstract class BuySellRate extends BaseRate {
// public Float valueSellReal, valueBuyReal;
// public String valueSell, valueBuy;
//
//
// @Override
// public void toRateType() {
// int rateType = UNKNOWN;
// String plain_type = type.replace("\n", "");
// if (plain_type.equals("USD")) {
// rateType = USD;
// } else if (plain_type.equals("EUR")) {
// rateType = EUR;
// } else if (plain_type.contains("altın")) {
// rateType = ONS_TRY;
// } else if (plain_type.contains("parite")) {
// rateType = EUR_USD;
// }
// this.rateType = rateType;
// }
//
// @Override
// public void setRealValues() {
// String val = valueSell.replace(" TL", "").replace(",", ".").trim();
// valueSellReal = Float.valueOf(val);
//
// val = valueBuy.replace(" TL", "").replace(",", ".").trim();
// valueBuyReal = Float.valueOf(val);
// }
//
//
// @Override
// public float getValue(int valueType) {
// if (valueType == ValueType.BUY) {
// return valueBuyReal;
// } else if (valueType == ValueType.SELL) {
// return valueSellReal;
// }
// return 0.0f;
// }
//
// @Override
// @NonNull
// public String toString() {
// return type.split("_")[0] + " -> " + valueSellReal + " : " + valueBuyReal;
// }
// }
// Path: app/src/main/java/dynoapps/exchange_rates/converters/BigparaConverter.java
import org.jsoup.Jsoup;
import org.jsoup.nodes.Element;
import java.io.IOException;
import java.lang.annotation.Annotation;
import java.lang.reflect.Type;
import java.util.ArrayList;
import java.util.List;
import androidx.annotation.NonNull;
import dynoapps.exchange_rates.model.rates.BaseRate;
import dynoapps.exchange_rates.model.rates.BigparaRate;
import dynoapps.exchange_rates.model.rates.BuySellRate;
import okhttp3.ResponseBody;
import retrofit2.Converter;
import retrofit2.Retrofit;
package dynoapps.exchange_rates.converters;
/**
* Created by erdemmac on 24/11/2016.
*/
public class BigparaConverter implements Converter<ResponseBody, List<BaseRate>> {
private static final BigparaConverter INSTANCE = new BigparaConverter();
private static final String HOST = "http://www.bigpara.com";
private BigparaConverter() {
}
@Override
public List<BaseRate> convert(@NonNull ResponseBody value) throws IOException {
ArrayList<BaseRate> rates = new ArrayList<>();
String responseBody = value.string();
ArrayList<Element> elements = Jsoup.parse(responseBody, HOST).select("#content").select(".kurdetail").select(".kurbox");
String val_buy = elements.get(1).select(".value").text();
String val_sell = elements.get(2).select(".value").text();
| BuySellRate buySellRate = new BigparaRate(); |
erdemolkun/instant-rates | app/src/main/java/dynoapps/exchange_rates/model/rates/BaseRate.java | // Path: app/src/main/java/dynoapps/exchange_rates/util/RateUtils.java
// public class RateUtils {
// private static final Formatter formatter2 = new Formatter(2, 0);
// private static final Formatter formatter5 = new Formatter(5, 2);
//
// public static <T extends BaseRate> T getRate(List<T> rates, @IRate.RateDef int rateType) {
// if (rates == null) return null;
// for (T rate : rates) {
// if (rate.getRateType() == rateType) {
// return rate;
// }
// }
// return null;
// }
//
// public static String valueToUI(Float val, @IRate.RateDef int rateType) {
// if (val == null) return "";
// String formatted = formatValue(val, rateType);
// if (rateType == IRate.EUR_USD) {
// return formatted;
// } else if (rateType == IRate.ONS) {
// return App.context().getString(R.string.placeholder_dollar, formatted);
// } else {
// return App.context().getString(R.string.placeholder_tl, formatted);
// }
// }
//
// public static String formatValue(float val, int rateType) {
// if (rateType == IRate.ONS || rateType == IRate.ONS_TRY) {
// return formatter2.format(val);
// } else {
// return formatter5.format(val);
// }
// }
//
// public static String rateName(int rate_type) {
// if (rate_type == IRate.EUR) {
// return "EUR"; // todo refactor with side menu names.
// } else if (rate_type == IRate.USD) {
// return "USD";
// } else if (rate_type == IRate.EUR_USD) {
// return "EUR_USD";
// } else if (rate_type == IRate.ONS) {
// return "ONS";
// }
// return "";
// }
//
// public static
// @DrawableRes
// int getRateIcon(int rateType) {
// if (rateType == IRate.EUR) {
// return R.drawable.ic_euro;
// } else if (rateType == IRate.ONS) {
// return R.drawable.ic_gold;
// } else if (rateType == IRate.USD) {
// return R.drawable.ic_dollar;
// } else if (rateType == IRate.EUR_USD) {
// return R.drawable.ic_exchange_eur_usd;
// }
// return -1;
// }
//
// @Nullable
// public static Float toFloat(String str) {
// if (TextUtils.isEmpty(str)) return null;
// str = str.trim();
//
// try {
// return Float.parseFloat(str);
// } catch (Exception e) {
// try {
// DecimalFormatSymbols symbols = new DecimalFormatSymbols();
// symbols.setDecimalSeparator(DecimalFormatSymbols.getInstance().getDecimalSeparator());
// symbols.setGroupingSeparator(DecimalFormatSymbols.getInstance().getGroupingSeparator());
// DecimalFormat format = new DecimalFormat("###,###,###,##0.#####");
// format.setDecimalFormatSymbols(symbols);
// return format.parse(str).floatValue();
// } catch (Exception ignored) {
//
// }
// }
// return null;
// }
// }
| import dynoapps.exchange_rates.util.RateUtils; | package dynoapps.exchange_rates.model.rates;
/**
* Created by erdemmac on 24/11/2016.
*/
public abstract class BaseRate implements IConvertable, IRate {
public String type;
@RateDef
protected int rateType;
BaseRate() {
}
@Override
public int getRateType() {
return rateType;
}
public String getFormatted(float val) { | // Path: app/src/main/java/dynoapps/exchange_rates/util/RateUtils.java
// public class RateUtils {
// private static final Formatter formatter2 = new Formatter(2, 0);
// private static final Formatter formatter5 = new Formatter(5, 2);
//
// public static <T extends BaseRate> T getRate(List<T> rates, @IRate.RateDef int rateType) {
// if (rates == null) return null;
// for (T rate : rates) {
// if (rate.getRateType() == rateType) {
// return rate;
// }
// }
// return null;
// }
//
// public static String valueToUI(Float val, @IRate.RateDef int rateType) {
// if (val == null) return "";
// String formatted = formatValue(val, rateType);
// if (rateType == IRate.EUR_USD) {
// return formatted;
// } else if (rateType == IRate.ONS) {
// return App.context().getString(R.string.placeholder_dollar, formatted);
// } else {
// return App.context().getString(R.string.placeholder_tl, formatted);
// }
// }
//
// public static String formatValue(float val, int rateType) {
// if (rateType == IRate.ONS || rateType == IRate.ONS_TRY) {
// return formatter2.format(val);
// } else {
// return formatter5.format(val);
// }
// }
//
// public static String rateName(int rate_type) {
// if (rate_type == IRate.EUR) {
// return "EUR"; // todo refactor with side menu names.
// } else if (rate_type == IRate.USD) {
// return "USD";
// } else if (rate_type == IRate.EUR_USD) {
// return "EUR_USD";
// } else if (rate_type == IRate.ONS) {
// return "ONS";
// }
// return "";
// }
//
// public static
// @DrawableRes
// int getRateIcon(int rateType) {
// if (rateType == IRate.EUR) {
// return R.drawable.ic_euro;
// } else if (rateType == IRate.ONS) {
// return R.drawable.ic_gold;
// } else if (rateType == IRate.USD) {
// return R.drawable.ic_dollar;
// } else if (rateType == IRate.EUR_USD) {
// return R.drawable.ic_exchange_eur_usd;
// }
// return -1;
// }
//
// @Nullable
// public static Float toFloat(String str) {
// if (TextUtils.isEmpty(str)) return null;
// str = str.trim();
//
// try {
// return Float.parseFloat(str);
// } catch (Exception e) {
// try {
// DecimalFormatSymbols symbols = new DecimalFormatSymbols();
// symbols.setDecimalSeparator(DecimalFormatSymbols.getInstance().getDecimalSeparator());
// symbols.setGroupingSeparator(DecimalFormatSymbols.getInstance().getGroupingSeparator());
// DecimalFormat format = new DecimalFormat("###,###,###,##0.#####");
// format.setDecimalFormatSymbols(symbols);
// return format.parse(str).floatValue();
// } catch (Exception ignored) {
//
// }
// }
// return null;
// }
// }
// Path: app/src/main/java/dynoapps/exchange_rates/model/rates/BaseRate.java
import dynoapps.exchange_rates.util.RateUtils;
package dynoapps.exchange_rates.model.rates;
/**
* Created by erdemmac on 24/11/2016.
*/
public abstract class BaseRate implements IConvertable, IRate {
public String type;
@RateDef
protected int rateType;
BaseRate() {
}
@Override
public int getRateType() {
return rateType;
}
public String getFormatted(float val) { | return RateUtils.valueToUI(val, rateType); |
erdemolkun/instant-rates | app/src/main/java/dynoapps/exchange_rates/provider/YapıKrediRateProvider.java | // Path: app/src/main/java/dynoapps/exchange_rates/data/CurrencyType.java
// public interface CurrencyType {
// int NOT_SET = 0;
// int ALTININ = 1;
// int ENPARA = 2;
// int BIGPARA = 3;
// int TLKUR = 4;
// int YAPIKREDI = 5;
// int YAHOO = 6;
// int PARAGARANTI = 7;
// int BLOOMBERGHT = 8;
//
// }
//
// Path: app/src/main/java/dynoapps/exchange_rates/model/rates/YapıKrediRate.java
// public class YapıKrediRate extends BuySellRate {
// @Override
// public void toRateType() {
// int rateType = UNKNOWN;
// String plain_type = type.replace("\n", "");
// plain_type = plain_type.toLowerCase();
// if (plain_type.equals("usd")) {
// rateType = USD;
// } else if (plain_type.equals("eur")) {
// rateType = EUR;
// } else if (plain_type.contains("altın")) {
// rateType = ONS_TRY;
// } else if (plain_type.contains("parite")) {
// rateType = EUR_USD;
// }
// this.rateType = rateType;
// }
//
// @Override
// public void setRealValues() {
// String val = valueSell.replace(" TL", "").replace(",", ".").trim();
// valueSellReal = Float.valueOf(val);
//
// val = valueBuy.replace(" TL", "").replace(",", ".").trim();
// valueBuyReal = Float.valueOf(val);
// }
//
//
// }
| import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
import org.jsoup.select.Elements;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.Callable;
import dynoapps.exchange_rates.data.CurrencyType;
import dynoapps.exchange_rates.model.rates.YapıKrediRate;
import io.reactivex.Observable; | .timeout(6000)
.userAgent("Mozilla/5.0 (Macintosh; Intel Mac OS X 10_12_1) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/54.0.2840.98 Safari/537.36")
.get();
Elements elements = doc.select("#currencyResultContent").select("tr");
ArrayList<YapıKrediRate> rates = new ArrayList<>();
if (elements != null) {
try {
for (Element element : elements) {
Elements innerElements = element.select("td");
YapıKrediRate rate = new YapıKrediRate();
if (innerElements.size() > 3) {
rate.valueSell = innerElements.get(2).text();
rate.valueBuy = innerElements.get(3).text();
rate.type = innerElements.get(0).text();
rate.toRateType();
rate.setRealValues();
rates.add(rate);
}
}
} catch (Exception ignored) {
}
}
return rates;
}
});
}
@Override
public int getSourceType() { | // Path: app/src/main/java/dynoapps/exchange_rates/data/CurrencyType.java
// public interface CurrencyType {
// int NOT_SET = 0;
// int ALTININ = 1;
// int ENPARA = 2;
// int BIGPARA = 3;
// int TLKUR = 4;
// int YAPIKREDI = 5;
// int YAHOO = 6;
// int PARAGARANTI = 7;
// int BLOOMBERGHT = 8;
//
// }
//
// Path: app/src/main/java/dynoapps/exchange_rates/model/rates/YapıKrediRate.java
// public class YapıKrediRate extends BuySellRate {
// @Override
// public void toRateType() {
// int rateType = UNKNOWN;
// String plain_type = type.replace("\n", "");
// plain_type = plain_type.toLowerCase();
// if (plain_type.equals("usd")) {
// rateType = USD;
// } else if (plain_type.equals("eur")) {
// rateType = EUR;
// } else if (plain_type.contains("altın")) {
// rateType = ONS_TRY;
// } else if (plain_type.contains("parite")) {
// rateType = EUR_USD;
// }
// this.rateType = rateType;
// }
//
// @Override
// public void setRealValues() {
// String val = valueSell.replace(" TL", "").replace(",", ".").trim();
// valueSellReal = Float.valueOf(val);
//
// val = valueBuy.replace(" TL", "").replace(",", ".").trim();
// valueBuyReal = Float.valueOf(val);
// }
//
//
// }
// Path: app/src/main/java/dynoapps/exchange_rates/provider/YapıKrediRateProvider.java
import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
import org.jsoup.select.Elements;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.Callable;
import dynoapps.exchange_rates.data.CurrencyType;
import dynoapps.exchange_rates.model.rates.YapıKrediRate;
import io.reactivex.Observable;
.timeout(6000)
.userAgent("Mozilla/5.0 (Macintosh; Intel Mac OS X 10_12_1) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/54.0.2840.98 Safari/537.36")
.get();
Elements elements = doc.select("#currencyResultContent").select("tr");
ArrayList<YapıKrediRate> rates = new ArrayList<>();
if (elements != null) {
try {
for (Element element : elements) {
Elements innerElements = element.select("td");
YapıKrediRate rate = new YapıKrediRate();
if (innerElements.size() > 3) {
rate.valueSell = innerElements.get(2).text();
rate.valueBuy = innerElements.get(3).text();
rate.type = innerElements.get(0).text();
rate.toRateType();
rate.setRealValues();
rates.add(rate);
}
}
} catch (Exception ignored) {
}
}
return rates;
}
});
}
@Override
public int getSourceType() { | return CurrencyType.YAPIKREDI; |
erdemolkun/instant-rates | app/src/main/java/dynoapps/exchange_rates/time/TimeIntervalManager.java | // Path: app/src/main/java/dynoapps/exchange_rates/App.java
// public class App extends Application {
// private static App appInstance;
//
// public static App getInstance() {
// return appInstance;
// }
//
// @NonNull
// public static Context context() {
// return appInstance.getApplicationContext();
// }
//
// public AlarmsRepository provideAlarmsRepository() {
// return AlarmsRepository.getInstance(getApplicationContext());
// }
//
// @SuppressLint("CheckResult")
// @Override
// public void onCreate() {
// super.onCreate();
// appInstance = this;
//
// RxJavaPlugins.setErrorHandler(throwable -> L.e("App", throwable.getLocalizedMessage()));
// }
//
// /**
// * Enum used to identify the tracker that needs to be used for tracking.
// * <p/>
// * A single tracker is usually enough for most purposes. In case you do need multiple trackers,
// * storing them all in Application object helps ensure that they are created only once per
// * application instance.
// */
// public enum TrackerName {
// APP_TRACKER, // Tracker used only in this app.
// GLOBAL_TRACKER, // Tracker used by all the apps from a company. eg: roll-up tracking.
// }
//
//
// }
//
// Path: app/src/main/java/dynoapps/exchange_rates/Prefs.java
// public class Prefs {
// private static final String SOURCES = "SOURCES";
// private static final String INTERVAL = "INTERVAL";
// private static final String ALARMS = "ALARMS";
// private static final String ALARM_ENABLED = "ALARM_ENABLED";
//
// private static SharedPreferences getPrefs(Context context) {
// return PreferenceManager.getDefaultSharedPreferences(context);
// }
//
// public static boolean isAlarmEnabled() {
// return getPrefs(App.context()).getBoolean(ALARM_ENABLED, true);
// }
//
// public static void saveAlarmEnabled(boolean enabled) {
// saveBoolean(ALARM_ENABLED, enabled);
// }
//
//
// public static void saveSources(String sources) {
// saveString(SOURCES, sources);
// }
//
// public static String getSources() {
// return getPrefs(App.context()).getString(SOURCES, null);
// }
//
//
// public static void saveAlarms(String alarms_json) {
// saveString(ALARMS, alarms_json);
// }
//
// public static String getAlarms() {
// return getPrefs(App.context()).getString(ALARMS, null);
// }
//
// public static void saveInterval(Context context, long interval) {
// SharedPreferences preferences = getPrefs(context);
// SharedPreferences.Editor editor = preferences.edit();
// editor.putLong(INTERVAL, interval);
// editor.apply();
// }
//
// public static long getInterval(Context context) {
// return getPrefs(context).getLong(INTERVAL, -1);
// }
//
// private static void saveString(String key, String value) {
// SharedPreferences preferences = getPrefs(App.context());
// SharedPreferences.Editor editor = preferences.edit();
// editor.putString(key, value);
// editor.apply();
// }
//
// private static void saveBoolean(String key, boolean value) {
// SharedPreferences preferences = getPrefs(App.context());
// SharedPreferences.Editor editor = preferences.edit();
// editor.putBoolean(key, value);
// editor.apply();
// }
//
// }
//
// Path: app/src/main/java/dynoapps/exchange_rates/util/CollectionUtils.java
// public class CollectionUtils {
// public static <E> E getInstance(List<E> list, Class<?> clazz) {
// for (E e : list) {
// if (clazz.isInstance(e)) {
// return e;
// }
// }
// return null;
// }
//
// public static <E> int size(List<E> list) {
// return list == null ? 0 : list.size();
// }
//
// public static <E> int size(E[] array) {
// return array == null ? 0 : array.length;
// }
//
// public static <E> boolean isNullOrEmpty(List<E> list) {
// return list == null || list.size() < 1;
// }
//
// public static <E> boolean isNullOrEmpty(E[] array) {
// return array == null || array.length < 1;
// }
//
// }
| import android.app.Activity;
import java.util.ArrayList;
import java.util.concurrent.TimeUnit;
import androidx.appcompat.app.AlertDialog;
import dynoapps.exchange_rates.App;
import dynoapps.exchange_rates.Prefs;
import dynoapps.exchange_rates.R;
import dynoapps.exchange_rates.util.CollectionUtils;
import io.reactivex.subjects.PublishSubject; | package dynoapps.exchange_rates.time;
/**
* Created by erdemmac on 03/12/2016.
*/
public final class TimeIntervalManager {
private static final int DEFAULT_INTERVAL_INDEX = 2;
private static final int INTERVAL_SERVICE_INDEX = 4; | // Path: app/src/main/java/dynoapps/exchange_rates/App.java
// public class App extends Application {
// private static App appInstance;
//
// public static App getInstance() {
// return appInstance;
// }
//
// @NonNull
// public static Context context() {
// return appInstance.getApplicationContext();
// }
//
// public AlarmsRepository provideAlarmsRepository() {
// return AlarmsRepository.getInstance(getApplicationContext());
// }
//
// @SuppressLint("CheckResult")
// @Override
// public void onCreate() {
// super.onCreate();
// appInstance = this;
//
// RxJavaPlugins.setErrorHandler(throwable -> L.e("App", throwable.getLocalizedMessage()));
// }
//
// /**
// * Enum used to identify the tracker that needs to be used for tracking.
// * <p/>
// * A single tracker is usually enough for most purposes. In case you do need multiple trackers,
// * storing them all in Application object helps ensure that they are created only once per
// * application instance.
// */
// public enum TrackerName {
// APP_TRACKER, // Tracker used only in this app.
// GLOBAL_TRACKER, // Tracker used by all the apps from a company. eg: roll-up tracking.
// }
//
//
// }
//
// Path: app/src/main/java/dynoapps/exchange_rates/Prefs.java
// public class Prefs {
// private static final String SOURCES = "SOURCES";
// private static final String INTERVAL = "INTERVAL";
// private static final String ALARMS = "ALARMS";
// private static final String ALARM_ENABLED = "ALARM_ENABLED";
//
// private static SharedPreferences getPrefs(Context context) {
// return PreferenceManager.getDefaultSharedPreferences(context);
// }
//
// public static boolean isAlarmEnabled() {
// return getPrefs(App.context()).getBoolean(ALARM_ENABLED, true);
// }
//
// public static void saveAlarmEnabled(boolean enabled) {
// saveBoolean(ALARM_ENABLED, enabled);
// }
//
//
// public static void saveSources(String sources) {
// saveString(SOURCES, sources);
// }
//
// public static String getSources() {
// return getPrefs(App.context()).getString(SOURCES, null);
// }
//
//
// public static void saveAlarms(String alarms_json) {
// saveString(ALARMS, alarms_json);
// }
//
// public static String getAlarms() {
// return getPrefs(App.context()).getString(ALARMS, null);
// }
//
// public static void saveInterval(Context context, long interval) {
// SharedPreferences preferences = getPrefs(context);
// SharedPreferences.Editor editor = preferences.edit();
// editor.putLong(INTERVAL, interval);
// editor.apply();
// }
//
// public static long getInterval(Context context) {
// return getPrefs(context).getLong(INTERVAL, -1);
// }
//
// private static void saveString(String key, String value) {
// SharedPreferences preferences = getPrefs(App.context());
// SharedPreferences.Editor editor = preferences.edit();
// editor.putString(key, value);
// editor.apply();
// }
//
// private static void saveBoolean(String key, boolean value) {
// SharedPreferences preferences = getPrefs(App.context());
// SharedPreferences.Editor editor = preferences.edit();
// editor.putBoolean(key, value);
// editor.apply();
// }
//
// }
//
// Path: app/src/main/java/dynoapps/exchange_rates/util/CollectionUtils.java
// public class CollectionUtils {
// public static <E> E getInstance(List<E> list, Class<?> clazz) {
// for (E e : list) {
// if (clazz.isInstance(e)) {
// return e;
// }
// }
// return null;
// }
//
// public static <E> int size(List<E> list) {
// return list == null ? 0 : list.size();
// }
//
// public static <E> int size(E[] array) {
// return array == null ? 0 : array.length;
// }
//
// public static <E> boolean isNullOrEmpty(List<E> list) {
// return list == null || list.size() < 1;
// }
//
// public static <E> boolean isNullOrEmpty(E[] array) {
// return array == null || array.length < 1;
// }
//
// }
// Path: app/src/main/java/dynoapps/exchange_rates/time/TimeIntervalManager.java
import android.app.Activity;
import java.util.ArrayList;
import java.util.concurrent.TimeUnit;
import androidx.appcompat.app.AlertDialog;
import dynoapps.exchange_rates.App;
import dynoapps.exchange_rates.Prefs;
import dynoapps.exchange_rates.R;
import dynoapps.exchange_rates.util.CollectionUtils;
import io.reactivex.subjects.PublishSubject;
package dynoapps.exchange_rates.time;
/**
* Created by erdemmac on 03/12/2016.
*/
public final class TimeIntervalManager {
private static final int DEFAULT_INTERVAL_INDEX = 2;
private static final int INTERVAL_SERVICE_INDEX = 4; | private static final long PREF_INTERVAL_MILLIS = Prefs.getInterval(App.context()); |
erdemolkun/instant-rates | app/src/main/java/dynoapps/exchange_rates/time/TimeIntervalManager.java | // Path: app/src/main/java/dynoapps/exchange_rates/App.java
// public class App extends Application {
// private static App appInstance;
//
// public static App getInstance() {
// return appInstance;
// }
//
// @NonNull
// public static Context context() {
// return appInstance.getApplicationContext();
// }
//
// public AlarmsRepository provideAlarmsRepository() {
// return AlarmsRepository.getInstance(getApplicationContext());
// }
//
// @SuppressLint("CheckResult")
// @Override
// public void onCreate() {
// super.onCreate();
// appInstance = this;
//
// RxJavaPlugins.setErrorHandler(throwable -> L.e("App", throwable.getLocalizedMessage()));
// }
//
// /**
// * Enum used to identify the tracker that needs to be used for tracking.
// * <p/>
// * A single tracker is usually enough for most purposes. In case you do need multiple trackers,
// * storing them all in Application object helps ensure that they are created only once per
// * application instance.
// */
// public enum TrackerName {
// APP_TRACKER, // Tracker used only in this app.
// GLOBAL_TRACKER, // Tracker used by all the apps from a company. eg: roll-up tracking.
// }
//
//
// }
//
// Path: app/src/main/java/dynoapps/exchange_rates/Prefs.java
// public class Prefs {
// private static final String SOURCES = "SOURCES";
// private static final String INTERVAL = "INTERVAL";
// private static final String ALARMS = "ALARMS";
// private static final String ALARM_ENABLED = "ALARM_ENABLED";
//
// private static SharedPreferences getPrefs(Context context) {
// return PreferenceManager.getDefaultSharedPreferences(context);
// }
//
// public static boolean isAlarmEnabled() {
// return getPrefs(App.context()).getBoolean(ALARM_ENABLED, true);
// }
//
// public static void saveAlarmEnabled(boolean enabled) {
// saveBoolean(ALARM_ENABLED, enabled);
// }
//
//
// public static void saveSources(String sources) {
// saveString(SOURCES, sources);
// }
//
// public static String getSources() {
// return getPrefs(App.context()).getString(SOURCES, null);
// }
//
//
// public static void saveAlarms(String alarms_json) {
// saveString(ALARMS, alarms_json);
// }
//
// public static String getAlarms() {
// return getPrefs(App.context()).getString(ALARMS, null);
// }
//
// public static void saveInterval(Context context, long interval) {
// SharedPreferences preferences = getPrefs(context);
// SharedPreferences.Editor editor = preferences.edit();
// editor.putLong(INTERVAL, interval);
// editor.apply();
// }
//
// public static long getInterval(Context context) {
// return getPrefs(context).getLong(INTERVAL, -1);
// }
//
// private static void saveString(String key, String value) {
// SharedPreferences preferences = getPrefs(App.context());
// SharedPreferences.Editor editor = preferences.edit();
// editor.putString(key, value);
// editor.apply();
// }
//
// private static void saveBoolean(String key, boolean value) {
// SharedPreferences preferences = getPrefs(App.context());
// SharedPreferences.Editor editor = preferences.edit();
// editor.putBoolean(key, value);
// editor.apply();
// }
//
// }
//
// Path: app/src/main/java/dynoapps/exchange_rates/util/CollectionUtils.java
// public class CollectionUtils {
// public static <E> E getInstance(List<E> list, Class<?> clazz) {
// for (E e : list) {
// if (clazz.isInstance(e)) {
// return e;
// }
// }
// return null;
// }
//
// public static <E> int size(List<E> list) {
// return list == null ? 0 : list.size();
// }
//
// public static <E> int size(E[] array) {
// return array == null ? 0 : array.length;
// }
//
// public static <E> boolean isNullOrEmpty(List<E> list) {
// return list == null || list.size() < 1;
// }
//
// public static <E> boolean isNullOrEmpty(E[] array) {
// return array == null || array.length < 1;
// }
//
// }
| import android.app.Activity;
import java.util.ArrayList;
import java.util.concurrent.TimeUnit;
import androidx.appcompat.app.AlertDialog;
import dynoapps.exchange_rates.App;
import dynoapps.exchange_rates.Prefs;
import dynoapps.exchange_rates.R;
import dynoapps.exchange_rates.util.CollectionUtils;
import io.reactivex.subjects.PublishSubject; | package dynoapps.exchange_rates.time;
/**
* Created by erdemmac on 03/12/2016.
*/
public final class TimeIntervalManager {
private static final int DEFAULT_INTERVAL_INDEX = 2;
private static final int INTERVAL_SERVICE_INDEX = 4; | // Path: app/src/main/java/dynoapps/exchange_rates/App.java
// public class App extends Application {
// private static App appInstance;
//
// public static App getInstance() {
// return appInstance;
// }
//
// @NonNull
// public static Context context() {
// return appInstance.getApplicationContext();
// }
//
// public AlarmsRepository provideAlarmsRepository() {
// return AlarmsRepository.getInstance(getApplicationContext());
// }
//
// @SuppressLint("CheckResult")
// @Override
// public void onCreate() {
// super.onCreate();
// appInstance = this;
//
// RxJavaPlugins.setErrorHandler(throwable -> L.e("App", throwable.getLocalizedMessage()));
// }
//
// /**
// * Enum used to identify the tracker that needs to be used for tracking.
// * <p/>
// * A single tracker is usually enough for most purposes. In case you do need multiple trackers,
// * storing them all in Application object helps ensure that they are created only once per
// * application instance.
// */
// public enum TrackerName {
// APP_TRACKER, // Tracker used only in this app.
// GLOBAL_TRACKER, // Tracker used by all the apps from a company. eg: roll-up tracking.
// }
//
//
// }
//
// Path: app/src/main/java/dynoapps/exchange_rates/Prefs.java
// public class Prefs {
// private static final String SOURCES = "SOURCES";
// private static final String INTERVAL = "INTERVAL";
// private static final String ALARMS = "ALARMS";
// private static final String ALARM_ENABLED = "ALARM_ENABLED";
//
// private static SharedPreferences getPrefs(Context context) {
// return PreferenceManager.getDefaultSharedPreferences(context);
// }
//
// public static boolean isAlarmEnabled() {
// return getPrefs(App.context()).getBoolean(ALARM_ENABLED, true);
// }
//
// public static void saveAlarmEnabled(boolean enabled) {
// saveBoolean(ALARM_ENABLED, enabled);
// }
//
//
// public static void saveSources(String sources) {
// saveString(SOURCES, sources);
// }
//
// public static String getSources() {
// return getPrefs(App.context()).getString(SOURCES, null);
// }
//
//
// public static void saveAlarms(String alarms_json) {
// saveString(ALARMS, alarms_json);
// }
//
// public static String getAlarms() {
// return getPrefs(App.context()).getString(ALARMS, null);
// }
//
// public static void saveInterval(Context context, long interval) {
// SharedPreferences preferences = getPrefs(context);
// SharedPreferences.Editor editor = preferences.edit();
// editor.putLong(INTERVAL, interval);
// editor.apply();
// }
//
// public static long getInterval(Context context) {
// return getPrefs(context).getLong(INTERVAL, -1);
// }
//
// private static void saveString(String key, String value) {
// SharedPreferences preferences = getPrefs(App.context());
// SharedPreferences.Editor editor = preferences.edit();
// editor.putString(key, value);
// editor.apply();
// }
//
// private static void saveBoolean(String key, boolean value) {
// SharedPreferences preferences = getPrefs(App.context());
// SharedPreferences.Editor editor = preferences.edit();
// editor.putBoolean(key, value);
// editor.apply();
// }
//
// }
//
// Path: app/src/main/java/dynoapps/exchange_rates/util/CollectionUtils.java
// public class CollectionUtils {
// public static <E> E getInstance(List<E> list, Class<?> clazz) {
// for (E e : list) {
// if (clazz.isInstance(e)) {
// return e;
// }
// }
// return null;
// }
//
// public static <E> int size(List<E> list) {
// return list == null ? 0 : list.size();
// }
//
// public static <E> int size(E[] array) {
// return array == null ? 0 : array.length;
// }
//
// public static <E> boolean isNullOrEmpty(List<E> list) {
// return list == null || list.size() < 1;
// }
//
// public static <E> boolean isNullOrEmpty(E[] array) {
// return array == null || array.length < 1;
// }
//
// }
// Path: app/src/main/java/dynoapps/exchange_rates/time/TimeIntervalManager.java
import android.app.Activity;
import java.util.ArrayList;
import java.util.concurrent.TimeUnit;
import androidx.appcompat.app.AlertDialog;
import dynoapps.exchange_rates.App;
import dynoapps.exchange_rates.Prefs;
import dynoapps.exchange_rates.R;
import dynoapps.exchange_rates.util.CollectionUtils;
import io.reactivex.subjects.PublishSubject;
package dynoapps.exchange_rates.time;
/**
* Created by erdemmac on 03/12/2016.
*/
public final class TimeIntervalManager {
private static final int DEFAULT_INTERVAL_INDEX = 2;
private static final int INTERVAL_SERVICE_INDEX = 4; | private static final long PREF_INTERVAL_MILLIS = Prefs.getInterval(App.context()); |
erdemolkun/instant-rates | app/src/main/java/dynoapps/exchange_rates/time/TimeIntervalManager.java | // Path: app/src/main/java/dynoapps/exchange_rates/App.java
// public class App extends Application {
// private static App appInstance;
//
// public static App getInstance() {
// return appInstance;
// }
//
// @NonNull
// public static Context context() {
// return appInstance.getApplicationContext();
// }
//
// public AlarmsRepository provideAlarmsRepository() {
// return AlarmsRepository.getInstance(getApplicationContext());
// }
//
// @SuppressLint("CheckResult")
// @Override
// public void onCreate() {
// super.onCreate();
// appInstance = this;
//
// RxJavaPlugins.setErrorHandler(throwable -> L.e("App", throwable.getLocalizedMessage()));
// }
//
// /**
// * Enum used to identify the tracker that needs to be used for tracking.
// * <p/>
// * A single tracker is usually enough for most purposes. In case you do need multiple trackers,
// * storing them all in Application object helps ensure that they are created only once per
// * application instance.
// */
// public enum TrackerName {
// APP_TRACKER, // Tracker used only in this app.
// GLOBAL_TRACKER, // Tracker used by all the apps from a company. eg: roll-up tracking.
// }
//
//
// }
//
// Path: app/src/main/java/dynoapps/exchange_rates/Prefs.java
// public class Prefs {
// private static final String SOURCES = "SOURCES";
// private static final String INTERVAL = "INTERVAL";
// private static final String ALARMS = "ALARMS";
// private static final String ALARM_ENABLED = "ALARM_ENABLED";
//
// private static SharedPreferences getPrefs(Context context) {
// return PreferenceManager.getDefaultSharedPreferences(context);
// }
//
// public static boolean isAlarmEnabled() {
// return getPrefs(App.context()).getBoolean(ALARM_ENABLED, true);
// }
//
// public static void saveAlarmEnabled(boolean enabled) {
// saveBoolean(ALARM_ENABLED, enabled);
// }
//
//
// public static void saveSources(String sources) {
// saveString(SOURCES, sources);
// }
//
// public static String getSources() {
// return getPrefs(App.context()).getString(SOURCES, null);
// }
//
//
// public static void saveAlarms(String alarms_json) {
// saveString(ALARMS, alarms_json);
// }
//
// public static String getAlarms() {
// return getPrefs(App.context()).getString(ALARMS, null);
// }
//
// public static void saveInterval(Context context, long interval) {
// SharedPreferences preferences = getPrefs(context);
// SharedPreferences.Editor editor = preferences.edit();
// editor.putLong(INTERVAL, interval);
// editor.apply();
// }
//
// public static long getInterval(Context context) {
// return getPrefs(context).getLong(INTERVAL, -1);
// }
//
// private static void saveString(String key, String value) {
// SharedPreferences preferences = getPrefs(App.context());
// SharedPreferences.Editor editor = preferences.edit();
// editor.putString(key, value);
// editor.apply();
// }
//
// private static void saveBoolean(String key, boolean value) {
// SharedPreferences preferences = getPrefs(App.context());
// SharedPreferences.Editor editor = preferences.edit();
// editor.putBoolean(key, value);
// editor.apply();
// }
//
// }
//
// Path: app/src/main/java/dynoapps/exchange_rates/util/CollectionUtils.java
// public class CollectionUtils {
// public static <E> E getInstance(List<E> list, Class<?> clazz) {
// for (E e : list) {
// if (clazz.isInstance(e)) {
// return e;
// }
// }
// return null;
// }
//
// public static <E> int size(List<E> list) {
// return list == null ? 0 : list.size();
// }
//
// public static <E> int size(E[] array) {
// return array == null ? 0 : array.length;
// }
//
// public static <E> boolean isNullOrEmpty(List<E> list) {
// return list == null || list.size() < 1;
// }
//
// public static <E> boolean isNullOrEmpty(E[] array) {
// return array == null || array.length < 1;
// }
//
// }
| import android.app.Activity;
import java.util.ArrayList;
import java.util.concurrent.TimeUnit;
import androidx.appcompat.app.AlertDialog;
import dynoapps.exchange_rates.App;
import dynoapps.exchange_rates.Prefs;
import dynoapps.exchange_rates.R;
import dynoapps.exchange_rates.util.CollectionUtils;
import io.reactivex.subjects.PublishSubject; | package dynoapps.exchange_rates.time;
/**
* Created by erdemmac on 03/12/2016.
*/
public final class TimeIntervalManager {
private static final int DEFAULT_INTERVAL_INDEX = 2;
private static final int INTERVAL_SERVICE_INDEX = 4;
private static final long PREF_INTERVAL_MILLIS = Prefs.getInterval(App.context());
private static ArrayList<TimeInterval> intervals;
private static Integer selectedIntervalIndexUser = getSelectedIndexViaPrefs();
private static boolean isAlarmMode = false;
private static int userSelectedItemIndex = -1;
private static final PublishSubject<Boolean> intervalUpdates = PublishSubject.create();
private static boolean isAlarmMode() {
return isAlarmMode;
}
public static void setAlarmMode(boolean enabled) {
TimeIntervalManager.isAlarmMode = enabled;
TimeIntervalManager.updateIntervalsToUIMode();// Intervals should be updated on ui mode.
}
public static void updateIntervalsToUIMode() {
intervalUpdates.onNext(true);
}
private static ArrayList<TimeInterval> getDefaultIntervals() { | // Path: app/src/main/java/dynoapps/exchange_rates/App.java
// public class App extends Application {
// private static App appInstance;
//
// public static App getInstance() {
// return appInstance;
// }
//
// @NonNull
// public static Context context() {
// return appInstance.getApplicationContext();
// }
//
// public AlarmsRepository provideAlarmsRepository() {
// return AlarmsRepository.getInstance(getApplicationContext());
// }
//
// @SuppressLint("CheckResult")
// @Override
// public void onCreate() {
// super.onCreate();
// appInstance = this;
//
// RxJavaPlugins.setErrorHandler(throwable -> L.e("App", throwable.getLocalizedMessage()));
// }
//
// /**
// * Enum used to identify the tracker that needs to be used for tracking.
// * <p/>
// * A single tracker is usually enough for most purposes. In case you do need multiple trackers,
// * storing them all in Application object helps ensure that they are created only once per
// * application instance.
// */
// public enum TrackerName {
// APP_TRACKER, // Tracker used only in this app.
// GLOBAL_TRACKER, // Tracker used by all the apps from a company. eg: roll-up tracking.
// }
//
//
// }
//
// Path: app/src/main/java/dynoapps/exchange_rates/Prefs.java
// public class Prefs {
// private static final String SOURCES = "SOURCES";
// private static final String INTERVAL = "INTERVAL";
// private static final String ALARMS = "ALARMS";
// private static final String ALARM_ENABLED = "ALARM_ENABLED";
//
// private static SharedPreferences getPrefs(Context context) {
// return PreferenceManager.getDefaultSharedPreferences(context);
// }
//
// public static boolean isAlarmEnabled() {
// return getPrefs(App.context()).getBoolean(ALARM_ENABLED, true);
// }
//
// public static void saveAlarmEnabled(boolean enabled) {
// saveBoolean(ALARM_ENABLED, enabled);
// }
//
//
// public static void saveSources(String sources) {
// saveString(SOURCES, sources);
// }
//
// public static String getSources() {
// return getPrefs(App.context()).getString(SOURCES, null);
// }
//
//
// public static void saveAlarms(String alarms_json) {
// saveString(ALARMS, alarms_json);
// }
//
// public static String getAlarms() {
// return getPrefs(App.context()).getString(ALARMS, null);
// }
//
// public static void saveInterval(Context context, long interval) {
// SharedPreferences preferences = getPrefs(context);
// SharedPreferences.Editor editor = preferences.edit();
// editor.putLong(INTERVAL, interval);
// editor.apply();
// }
//
// public static long getInterval(Context context) {
// return getPrefs(context).getLong(INTERVAL, -1);
// }
//
// private static void saveString(String key, String value) {
// SharedPreferences preferences = getPrefs(App.context());
// SharedPreferences.Editor editor = preferences.edit();
// editor.putString(key, value);
// editor.apply();
// }
//
// private static void saveBoolean(String key, boolean value) {
// SharedPreferences preferences = getPrefs(App.context());
// SharedPreferences.Editor editor = preferences.edit();
// editor.putBoolean(key, value);
// editor.apply();
// }
//
// }
//
// Path: app/src/main/java/dynoapps/exchange_rates/util/CollectionUtils.java
// public class CollectionUtils {
// public static <E> E getInstance(List<E> list, Class<?> clazz) {
// for (E e : list) {
// if (clazz.isInstance(e)) {
// return e;
// }
// }
// return null;
// }
//
// public static <E> int size(List<E> list) {
// return list == null ? 0 : list.size();
// }
//
// public static <E> int size(E[] array) {
// return array == null ? 0 : array.length;
// }
//
// public static <E> boolean isNullOrEmpty(List<E> list) {
// return list == null || list.size() < 1;
// }
//
// public static <E> boolean isNullOrEmpty(E[] array) {
// return array == null || array.length < 1;
// }
//
// }
// Path: app/src/main/java/dynoapps/exchange_rates/time/TimeIntervalManager.java
import android.app.Activity;
import java.util.ArrayList;
import java.util.concurrent.TimeUnit;
import androidx.appcompat.app.AlertDialog;
import dynoapps.exchange_rates.App;
import dynoapps.exchange_rates.Prefs;
import dynoapps.exchange_rates.R;
import dynoapps.exchange_rates.util.CollectionUtils;
import io.reactivex.subjects.PublishSubject;
package dynoapps.exchange_rates.time;
/**
* Created by erdemmac on 03/12/2016.
*/
public final class TimeIntervalManager {
private static final int DEFAULT_INTERVAL_INDEX = 2;
private static final int INTERVAL_SERVICE_INDEX = 4;
private static final long PREF_INTERVAL_MILLIS = Prefs.getInterval(App.context());
private static ArrayList<TimeInterval> intervals;
private static Integer selectedIntervalIndexUser = getSelectedIndexViaPrefs();
private static boolean isAlarmMode = false;
private static int userSelectedItemIndex = -1;
private static final PublishSubject<Boolean> intervalUpdates = PublishSubject.create();
private static boolean isAlarmMode() {
return isAlarmMode;
}
public static void setAlarmMode(boolean enabled) {
TimeIntervalManager.isAlarmMode = enabled;
TimeIntervalManager.updateIntervalsToUIMode();// Intervals should be updated on ui mode.
}
public static void updateIntervalsToUIMode() {
intervalUpdates.onNext(true);
}
private static ArrayList<TimeInterval> getDefaultIntervals() { | if (CollectionUtils.isNullOrEmpty(intervals)) { |
erdemolkun/instant-rates | app/src/main/java/dynoapps/exchange_rates/converters/YahooConverter.java | // Path: app/src/main/java/dynoapps/exchange_rates/model/rates/BaseRate.java
// public abstract class BaseRate implements IConvertable, IRate {
//
// public String type;
//
// @RateDef
// protected int rateType;
//
// BaseRate() {
// }
//
// @Override
// public int getRateType() {
// return rateType;
// }
//
// public String getFormatted(float val) {
// return RateUtils.valueToUI(val, rateType);
// }
// }
//
// Path: app/src/main/java/dynoapps/exchange_rates/model/rates/YahooRate.java
// public class YahooRate extends AvgRate {
// @Override
// public void toRateType() {
// if (TextUtils.isEmpty(type)) rateType = UNKNOWN;
// int rateType = UNKNOWN;
// if (type.contains("USDTRY")) {
// rateType = USD;
// } else if (type.contains("EURTRY")) {
// rateType = EUR;
// } else if (type.contains("EURUSD")) {
// rateType = EUR_USD;
// } else if (type.contains("GC")) {
// rateType = ONS;
// }
// this.rateType = rateType;
// }
//
// @Override
// public void setRealValues() {
// if (rateType == UNKNOWN) return;
// val_real_avg = Float.parseFloat(avg_val);
// }
// }
| import android.text.TextUtils;
import java.io.IOException;
import java.lang.annotation.Annotation;
import java.lang.reflect.Type;
import java.util.ArrayList;
import java.util.List;
import androidx.annotation.NonNull;
import dynoapps.exchange_rates.model.rates.BaseRate;
import dynoapps.exchange_rates.model.rates.YahooRate;
import okhttp3.ResponseBody;
import retrofit2.Converter;
import retrofit2.Retrofit; | package dynoapps.exchange_rates.converters;
/**
* Created by erdemmac on 24/11/2016.
*/
public class YahooConverter implements Converter<ResponseBody, List<BaseRate>> {
private static final YahooConverter INSTANCE = new YahooConverter();
private YahooConverter() {
}
/**
* Sample response body <p> <p> "USDTRY=X",3.4837,"12/9/2016","11:45pm"
* "EURTRY=X",3.6767,"12/9/2016","10:30pm" </p>
**/
@Override
public List<BaseRate> convert(@NonNull ResponseBody value) throws IOException {
ArrayList<BaseRate> rates = new ArrayList<>();
String responseBody = value.string();
if (!TextUtils.isEmpty(responseBody)) {
String[] splitsMoney = responseBody.split("\n");
if (splitsMoney.length > 0) {
for (String singleSplit : splitsMoney) {
String[] splits = singleSplit.split(","); // ysi Type not supported
if (splits.length > 2) { | // Path: app/src/main/java/dynoapps/exchange_rates/model/rates/BaseRate.java
// public abstract class BaseRate implements IConvertable, IRate {
//
// public String type;
//
// @RateDef
// protected int rateType;
//
// BaseRate() {
// }
//
// @Override
// public int getRateType() {
// return rateType;
// }
//
// public String getFormatted(float val) {
// return RateUtils.valueToUI(val, rateType);
// }
// }
//
// Path: app/src/main/java/dynoapps/exchange_rates/model/rates/YahooRate.java
// public class YahooRate extends AvgRate {
// @Override
// public void toRateType() {
// if (TextUtils.isEmpty(type)) rateType = UNKNOWN;
// int rateType = UNKNOWN;
// if (type.contains("USDTRY")) {
// rateType = USD;
// } else if (type.contains("EURTRY")) {
// rateType = EUR;
// } else if (type.contains("EURUSD")) {
// rateType = EUR_USD;
// } else if (type.contains("GC")) {
// rateType = ONS;
// }
// this.rateType = rateType;
// }
//
// @Override
// public void setRealValues() {
// if (rateType == UNKNOWN) return;
// val_real_avg = Float.parseFloat(avg_val);
// }
// }
// Path: app/src/main/java/dynoapps/exchange_rates/converters/YahooConverter.java
import android.text.TextUtils;
import java.io.IOException;
import java.lang.annotation.Annotation;
import java.lang.reflect.Type;
import java.util.ArrayList;
import java.util.List;
import androidx.annotation.NonNull;
import dynoapps.exchange_rates.model.rates.BaseRate;
import dynoapps.exchange_rates.model.rates.YahooRate;
import okhttp3.ResponseBody;
import retrofit2.Converter;
import retrofit2.Retrofit;
package dynoapps.exchange_rates.converters;
/**
* Created by erdemmac on 24/11/2016.
*/
public class YahooConverter implements Converter<ResponseBody, List<BaseRate>> {
private static final YahooConverter INSTANCE = new YahooConverter();
private YahooConverter() {
}
/**
* Sample response body <p> <p> "USDTRY=X",3.4837,"12/9/2016","11:45pm"
* "EURTRY=X",3.6767,"12/9/2016","10:30pm" </p>
**/
@Override
public List<BaseRate> convert(@NonNull ResponseBody value) throws IOException {
ArrayList<BaseRate> rates = new ArrayList<>();
String responseBody = value.string();
if (!TextUtils.isEmpty(responseBody)) {
String[] splitsMoney = responseBody.split("\n");
if (splitsMoney.length > 0) {
for (String singleSplit : splitsMoney) {
String[] splits = singleSplit.split(","); // ysi Type not supported
if (splits.length > 2) { | YahooRate rate = new YahooRate(); |
erdemolkun/instant-rates | app/src/main/java/dynoapps/exchange_rates/converters/DolarTlKurAjaxConverter.java | // Path: app/src/main/java/dynoapps/exchange_rates/model/rates/BaseRate.java
// public abstract class BaseRate implements IConvertable, IRate {
//
// public String type;
//
// @RateDef
// protected int rateType;
//
// BaseRate() {
// }
//
// @Override
// public int getRateType() {
// return rateType;
// }
//
// public String getFormatted(float val) {
// return RateUtils.valueToUI(val, rateType);
// }
// }
//
// Path: app/src/main/java/dynoapps/exchange_rates/model/rates/DolarTlKurRate.java
// public class DolarTlKurRate extends AvgRate {
//
// @Override
// public void toRateType() {
// if (TextUtils.isEmpty(type)) rateType = UNKNOWN;
// int rateType = UNKNOWN;
// switch (type) {
// case "USDTRY":
// rateType = USD;
// break;
// case "EURTRY":
// rateType = EUR;
// break;
// case "EURUSD":
// rateType = EUR_USD;
// break;
// case "XAUUSD":
// rateType = ONS;
// break;
// }
// this.rateType = rateType;
// }
//
// @Override
// public void setRealValues() {
// if (rateType == UNKNOWN) return;
// String val = avg_val.replace("'", "").replace("$", "").trim();
// val_real_avg = Float.parseFloat(val);
// }
//
// @Override
// @NonNull
// public String toString() {
// return type.split("_")[0] + " -> : " + val_real_avg;
// }
//
// }
| import android.text.TextUtils;
import java.io.IOException;
import java.lang.annotation.Annotation;
import java.lang.reflect.Type;
import java.util.ArrayList;
import java.util.List;
import androidx.annotation.NonNull;
import dynoapps.exchange_rates.model.rates.BaseRate;
import dynoapps.exchange_rates.model.rates.DolarTlKurRate;
import okhttp3.ResponseBody;
import retrofit2.Converter;
import retrofit2.Retrofit; | package dynoapps.exchange_rates.converters;
/**
* Copyright 2016 Erdem OLKUN
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except
* in compliance with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software distributed under the License
* is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express
* or implied. See the License for the specific language governing permissions and limitations under
* the License.
*/
public class DolarTlKurAjaxConverter implements Converter<ResponseBody, List<BaseRate>> {
private static final DolarTlKurAjaxConverter INSTANCE = new DolarTlKurAjaxConverter();
private DolarTlKurAjaxConverter() {
}
/**
* Sample response body <p> <p> USDTRY:3.4560: EURTRY:3.6623: EURUSD:1.0595: XAUUSD:1187.34:
* GBPTRY:4.2978: CHFTRY:3.4122: SARTRY:0.9216: 16:33:31 </p>
**/
@Override
public List<BaseRate> convert(@NonNull ResponseBody value) throws IOException {
ArrayList<BaseRate> rates = new ArrayList<>();
String responseBody = value.string();
if (!TextUtils.isEmpty(responseBody)) {
String[] splitsMoney = responseBody.split("\n");
if (splitsMoney.length > 0) {
for (String singleSplit : splitsMoney) {
String[] splits = singleSplit.split(":"); // ysi Type not supported
if (splits.length == 2) { | // Path: app/src/main/java/dynoapps/exchange_rates/model/rates/BaseRate.java
// public abstract class BaseRate implements IConvertable, IRate {
//
// public String type;
//
// @RateDef
// protected int rateType;
//
// BaseRate() {
// }
//
// @Override
// public int getRateType() {
// return rateType;
// }
//
// public String getFormatted(float val) {
// return RateUtils.valueToUI(val, rateType);
// }
// }
//
// Path: app/src/main/java/dynoapps/exchange_rates/model/rates/DolarTlKurRate.java
// public class DolarTlKurRate extends AvgRate {
//
// @Override
// public void toRateType() {
// if (TextUtils.isEmpty(type)) rateType = UNKNOWN;
// int rateType = UNKNOWN;
// switch (type) {
// case "USDTRY":
// rateType = USD;
// break;
// case "EURTRY":
// rateType = EUR;
// break;
// case "EURUSD":
// rateType = EUR_USD;
// break;
// case "XAUUSD":
// rateType = ONS;
// break;
// }
// this.rateType = rateType;
// }
//
// @Override
// public void setRealValues() {
// if (rateType == UNKNOWN) return;
// String val = avg_val.replace("'", "").replace("$", "").trim();
// val_real_avg = Float.parseFloat(val);
// }
//
// @Override
// @NonNull
// public String toString() {
// return type.split("_")[0] + " -> : " + val_real_avg;
// }
//
// }
// Path: app/src/main/java/dynoapps/exchange_rates/converters/DolarTlKurAjaxConverter.java
import android.text.TextUtils;
import java.io.IOException;
import java.lang.annotation.Annotation;
import java.lang.reflect.Type;
import java.util.ArrayList;
import java.util.List;
import androidx.annotation.NonNull;
import dynoapps.exchange_rates.model.rates.BaseRate;
import dynoapps.exchange_rates.model.rates.DolarTlKurRate;
import okhttp3.ResponseBody;
import retrofit2.Converter;
import retrofit2.Retrofit;
package dynoapps.exchange_rates.converters;
/**
* Copyright 2016 Erdem OLKUN
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except
* in compliance with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software distributed under the License
* is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express
* or implied. See the License for the specific language governing permissions and limitations under
* the License.
*/
public class DolarTlKurAjaxConverter implements Converter<ResponseBody, List<BaseRate>> {
private static final DolarTlKurAjaxConverter INSTANCE = new DolarTlKurAjaxConverter();
private DolarTlKurAjaxConverter() {
}
/**
* Sample response body <p> <p> USDTRY:3.4560: EURTRY:3.6623: EURUSD:1.0595: XAUUSD:1187.34:
* GBPTRY:4.2978: CHFTRY:3.4122: SARTRY:0.9216: 16:33:31 </p>
**/
@Override
public List<BaseRate> convert(@NonNull ResponseBody value) throws IOException {
ArrayList<BaseRate> rates = new ArrayList<>();
String responseBody = value.string();
if (!TextUtils.isEmpty(responseBody)) {
String[] splitsMoney = responseBody.split("\n");
if (splitsMoney.length > 0) {
for (String singleSplit : splitsMoney) {
String[] splits = singleSplit.split(":"); // ysi Type not supported
if (splits.length == 2) { | DolarTlKurRate rate = new DolarTlKurRate(); |
erdemolkun/instant-rates | app/src/main/java/dynoapps/exchange_rates/network/EnparaService.java | // Path: app/src/main/java/dynoapps/exchange_rates/model/rates/EnparaRate.java
// public class EnparaRate extends BuySellRate {
//
// @Override
// public void toRateType() {
// int rateType = UNKNOWN;
// String plain_type = type.replace("\n", "");
// plain_type = plain_type.toLowerCase();
// if (plain_type.contains("parite")) {
// rateType = EUR_USD;
// } else if (plain_type.contains("usd")) {
// rateType = USD;
// } else if (plain_type.contains("eur")) {
// rateType = EUR;
// } else if (plain_type.contains("altın (gram)")) {
// rateType = ONS_TRY;
// }
// this.rateType = rateType;
// }
//
// @Override
// public void setRealValues() {
// String val = valueSell.replace(" TL", "").replace(",", ".").trim();
// valueSellReal = Float.valueOf(val);
//
// val = valueBuy.replace(" TL", "").replace(",", ".").trim();
// valueBuyReal = Float.valueOf(val);
// }
// }
| import java.util.List;
import dynoapps.exchange_rates.model.rates.EnparaRate;
import io.reactivex.Observable;
import retrofit2.http.GET;
import retrofit2.http.Headers; | package dynoapps.exchange_rates.network;
/**
* Created by erdemmac on 24/10/2016.
*/
public interface EnparaService {
@Headers({
"Content-Type:text/html; charset=utf-8"
})
@GET("doviz-kur-bilgileri/doviz-altin-kurlari.aspx") | // Path: app/src/main/java/dynoapps/exchange_rates/model/rates/EnparaRate.java
// public class EnparaRate extends BuySellRate {
//
// @Override
// public void toRateType() {
// int rateType = UNKNOWN;
// String plain_type = type.replace("\n", "");
// plain_type = plain_type.toLowerCase();
// if (plain_type.contains("parite")) {
// rateType = EUR_USD;
// } else if (plain_type.contains("usd")) {
// rateType = USD;
// } else if (plain_type.contains("eur")) {
// rateType = EUR;
// } else if (plain_type.contains("altın (gram)")) {
// rateType = ONS_TRY;
// }
// this.rateType = rateType;
// }
//
// @Override
// public void setRealValues() {
// String val = valueSell.replace(" TL", "").replace(",", ".").trim();
// valueSellReal = Float.valueOf(val);
//
// val = valueBuy.replace(" TL", "").replace(",", ".").trim();
// valueBuyReal = Float.valueOf(val);
// }
// }
// Path: app/src/main/java/dynoapps/exchange_rates/network/EnparaService.java
import java.util.List;
import dynoapps.exchange_rates.model.rates.EnparaRate;
import io.reactivex.Observable;
import retrofit2.http.GET;
import retrofit2.http.Headers;
package dynoapps.exchange_rates.network;
/**
* Created by erdemmac on 24/10/2016.
*/
public interface EnparaService {
@Headers({
"Content-Type:text/html; charset=utf-8"
})
@GET("doviz-kur-bilgileri/doviz-altin-kurlari.aspx") | Observable<List<EnparaRate>> rates(); |
erdemolkun/instant-rates | app/src/main/java/dynoapps/exchange_rates/model/rates/BuySellRate.java | // Path: app/src/main/java/dynoapps/exchange_rates/interfaces/ValueType.java
// public interface ValueType {
// int NONE = -1;
// int BUY = 1;
// int SELL = 2;
// int AVG = 3;
// }
| import androidx.annotation.NonNull;
import dynoapps.exchange_rates.interfaces.ValueType; | package dynoapps.exchange_rates.model.rates;
/**
* Created by erdemmac on 24/11/2016.
*/
public abstract class BuySellRate extends BaseRate {
public Float valueSellReal, valueBuyReal;
public String valueSell, valueBuy;
@Override
public void toRateType() {
int rateType = UNKNOWN;
String plain_type = type.replace("\n", "");
if (plain_type.equals("USD")) {
rateType = USD;
} else if (plain_type.equals("EUR")) {
rateType = EUR;
} else if (plain_type.contains("altın")) {
rateType = ONS_TRY;
} else if (plain_type.contains("parite")) {
rateType = EUR_USD;
}
this.rateType = rateType;
}
@Override
public void setRealValues() {
String val = valueSell.replace(" TL", "").replace(",", ".").trim();
valueSellReal = Float.valueOf(val);
val = valueBuy.replace(" TL", "").replace(",", ".").trim();
valueBuyReal = Float.valueOf(val);
}
@Override
public float getValue(int valueType) { | // Path: app/src/main/java/dynoapps/exchange_rates/interfaces/ValueType.java
// public interface ValueType {
// int NONE = -1;
// int BUY = 1;
// int SELL = 2;
// int AVG = 3;
// }
// Path: app/src/main/java/dynoapps/exchange_rates/model/rates/BuySellRate.java
import androidx.annotation.NonNull;
import dynoapps.exchange_rates.interfaces.ValueType;
package dynoapps.exchange_rates.model.rates;
/**
* Created by erdemmac on 24/11/2016.
*/
public abstract class BuySellRate extends BaseRate {
public Float valueSellReal, valueBuyReal;
public String valueSell, valueBuy;
@Override
public void toRateType() {
int rateType = UNKNOWN;
String plain_type = type.replace("\n", "");
if (plain_type.equals("USD")) {
rateType = USD;
} else if (plain_type.equals("EUR")) {
rateType = EUR;
} else if (plain_type.contains("altın")) {
rateType = ONS_TRY;
} else if (plain_type.contains("parite")) {
rateType = EUR_USD;
}
this.rateType = rateType;
}
@Override
public void setRealValues() {
String val = valueSell.replace(" TL", "").replace(",", ".").trim();
valueSellReal = Float.valueOf(val);
val = valueBuy.replace(" TL", "").replace(",", ".").trim();
valueBuyReal = Float.valueOf(val);
}
@Override
public float getValue(int valueType) { | if (valueType == ValueType.BUY) { |
erdemolkun/instant-rates | app/src/main/java/dynoapps/exchange_rates/alarm/Alarm.java | // Path: app/src/main/java/dynoapps/exchange_rates/interfaces/ValueType.java
// public interface ValueType {
// int NONE = -1;
// int BUY = 1;
// int SELL = 2;
// int AVG = 3;
// }
| import android.provider.BaseColumns;
import java.io.Serializable;
import java.util.Comparator;
import androidx.room.ColumnInfo;
import androidx.room.Entity;
import androidx.room.PrimaryKey;
import dynoapps.exchange_rates.interfaces.ValueType; | package dynoapps.exchange_rates.alarm;
/**
* Created by erdemmac on 13/12/2016.
*/
@Entity(tableName = Alarm.TABLE_NAME)
public class Alarm implements Serializable {
/**
* The name of the Alarm table.
*/
public static final String TABLE_NAME = "tables";
/**
* The name of the ID column.
*/
public static final String COLUMN_ID = BaseColumns._ID;
public static Comparator<Alarm> COMPARATOR = (first, second) -> {
int i = compare(first.sourceType, second.sourceType);
if (i != 0) return i;
i = compare(first.rateType, second.rateType);
if (i != 0) return i;
i = compare(first.val, second.val);
return i;
};
/**
* The unique ID of the alarm.
*/
@PrimaryKey(autoGenerate = true)
@ColumnInfo(index = true, name = COLUMN_ID)
public long id;
@ColumnInfo(name = "value")
public Float val;
@ColumnInfo(name = "is_above")
public boolean isAbove = false;
@ColumnInfo(name = "is_enabled")
public boolean isEnabled = true;
/**
* {@link dynoapps.exchange_rates.model.rates.IRate}
*/
@ColumnInfo(name = "rate_type")
public int rateType;
/**
* {@link dynoapps.exchange_rates.data.CurrencyType}
*/
@ColumnInfo(name = "source_type")
public int sourceType;
/**
* {@link dynoapps.exchange_rates.interfaces.ValueType}
*/ | // Path: app/src/main/java/dynoapps/exchange_rates/interfaces/ValueType.java
// public interface ValueType {
// int NONE = -1;
// int BUY = 1;
// int SELL = 2;
// int AVG = 3;
// }
// Path: app/src/main/java/dynoapps/exchange_rates/alarm/Alarm.java
import android.provider.BaseColumns;
import java.io.Serializable;
import java.util.Comparator;
import androidx.room.ColumnInfo;
import androidx.room.Entity;
import androidx.room.PrimaryKey;
import dynoapps.exchange_rates.interfaces.ValueType;
package dynoapps.exchange_rates.alarm;
/**
* Created by erdemmac on 13/12/2016.
*/
@Entity(tableName = Alarm.TABLE_NAME)
public class Alarm implements Serializable {
/**
* The name of the Alarm table.
*/
public static final String TABLE_NAME = "tables";
/**
* The name of the ID column.
*/
public static final String COLUMN_ID = BaseColumns._ID;
public static Comparator<Alarm> COMPARATOR = (first, second) -> {
int i = compare(first.sourceType, second.sourceType);
if (i != 0) return i;
i = compare(first.rateType, second.rateType);
if (i != 0) return i;
i = compare(first.val, second.val);
return i;
};
/**
* The unique ID of the alarm.
*/
@PrimaryKey(autoGenerate = true)
@ColumnInfo(index = true, name = COLUMN_ID)
public long id;
@ColumnInfo(name = "value")
public Float val;
@ColumnInfo(name = "is_above")
public boolean isAbove = false;
@ColumnInfo(name = "is_enabled")
public boolean isEnabled = true;
/**
* {@link dynoapps.exchange_rates.model.rates.IRate}
*/
@ColumnInfo(name = "rate_type")
public int rateType;
/**
* {@link dynoapps.exchange_rates.data.CurrencyType}
*/
@ColumnInfo(name = "source_type")
public int sourceType;
/**
* {@link dynoapps.exchange_rates.interfaces.ValueType}
*/ | public int value_type = ValueType.NONE; |
erdemolkun/instant-rates | app/src/main/java/dynoapps/exchange_rates/PublishSettings.java | // Path: app/src/main/java/dynoapps/exchange_rates/util/AppUtils.java
// public class AppUtils {
//
// public static PackageInfo getPackageInfo(Context context) {
// try {
// return context.getPackageManager().getPackageInfo(context.getPackageName(), 0);
// } catch (PackageManager.NameNotFoundException e) {
// // Should not happen.
// throw new RuntimeException("Could not get package name: " + e);
// }
// }
//
// public static String getAppVersion() {
// Context context = App.context();
// PackageInfo pInfo;
// pInfo = getPackageInfo(context);
// return pInfo.versionName;
// }
//
// public static String getPlainVersion() {
// String version = getAppVersion();
// if (TextUtils.isEmpty(version)) return "";
// return version.split(" ")[0];
// }
//
// /**
// * Converts to http://semver.org/ standards.
// */
// public static String getAppVersionForSemver() {
// String appVersion = getAppVersion();
// return versionSemverCompat(appVersion, 3);
// }
//
//
// public static String versionSemverCompat(String version, int max_digit) {
// if (TextUtils.isEmpty(version)) return "";
// else {
// String firstPart = version.split(" ")[0];
// String[] splittedSemVer = firstPart.split("\\.");
// ArrayList<String> parts = new ArrayList<>();
// Collections.addAll(parts, splittedSemVer);
// for (int i = parts.size(); i < max_digit; i++) {
// parts.add("0");
// }
// List<String> limitedParts = parts.subList(0, max_digit);
// return TextUtils.join(".", limitedParts);
// }
// }
// }
| import android.content.Context;
import android.content.pm.PackageInfo;
import dynoapps.exchange_rates.util.AppUtils; | return BuildConfig.DEBUG;
}
public static boolean isNotReleaseType() {
return getReleaseType() == ReleaseTypes.Alpha || getReleaseType() == ReleaseTypes.Beta || getReleaseType() == ReleaseTypes.Debug;
}
public static boolean isProd() {
return getReleaseType() == ReleaseTypes.Prod;
}
public static boolean isAlpha() {
return getReleaseType() == ReleaseTypes.Alpha;
}
public static boolean canUpdate() {
return PublishSettings.getReleaseType() == PublishSettings.ReleaseTypes.Alpha
|| PublishSettings.getReleaseType() == PublishSettings.ReleaseTypes.Beta
|| PublishSettings.getReleaseType() == ReleaseTypes.Uat;
}
/**
* Returns release rate_type by extracting build rate_type from version name. Build Type
* extracted from application versionNameSuffix
*/
private static ReleaseTypes getReleaseTypeByVersionName() {
PackageInfo pInfo;
Context context = App.context();
if (context != null) { | // Path: app/src/main/java/dynoapps/exchange_rates/util/AppUtils.java
// public class AppUtils {
//
// public static PackageInfo getPackageInfo(Context context) {
// try {
// return context.getPackageManager().getPackageInfo(context.getPackageName(), 0);
// } catch (PackageManager.NameNotFoundException e) {
// // Should not happen.
// throw new RuntimeException("Could not get package name: " + e);
// }
// }
//
// public static String getAppVersion() {
// Context context = App.context();
// PackageInfo pInfo;
// pInfo = getPackageInfo(context);
// return pInfo.versionName;
// }
//
// public static String getPlainVersion() {
// String version = getAppVersion();
// if (TextUtils.isEmpty(version)) return "";
// return version.split(" ")[0];
// }
//
// /**
// * Converts to http://semver.org/ standards.
// */
// public static String getAppVersionForSemver() {
// String appVersion = getAppVersion();
// return versionSemverCompat(appVersion, 3);
// }
//
//
// public static String versionSemverCompat(String version, int max_digit) {
// if (TextUtils.isEmpty(version)) return "";
// else {
// String firstPart = version.split(" ")[0];
// String[] splittedSemVer = firstPart.split("\\.");
// ArrayList<String> parts = new ArrayList<>();
// Collections.addAll(parts, splittedSemVer);
// for (int i = parts.size(); i < max_digit; i++) {
// parts.add("0");
// }
// List<String> limitedParts = parts.subList(0, max_digit);
// return TextUtils.join(".", limitedParts);
// }
// }
// }
// Path: app/src/main/java/dynoapps/exchange_rates/PublishSettings.java
import android.content.Context;
import android.content.pm.PackageInfo;
import dynoapps.exchange_rates.util.AppUtils;
return BuildConfig.DEBUG;
}
public static boolean isNotReleaseType() {
return getReleaseType() == ReleaseTypes.Alpha || getReleaseType() == ReleaseTypes.Beta || getReleaseType() == ReleaseTypes.Debug;
}
public static boolean isProd() {
return getReleaseType() == ReleaseTypes.Prod;
}
public static boolean isAlpha() {
return getReleaseType() == ReleaseTypes.Alpha;
}
public static boolean canUpdate() {
return PublishSettings.getReleaseType() == PublishSettings.ReleaseTypes.Alpha
|| PublishSettings.getReleaseType() == PublishSettings.ReleaseTypes.Beta
|| PublishSettings.getReleaseType() == ReleaseTypes.Uat;
}
/**
* Returns release rate_type by extracting build rate_type from version name. Build Type
* extracted from application versionNameSuffix
*/
private static ReleaseTypes getReleaseTypeByVersionName() {
PackageInfo pInfo;
Context context = App.context();
if (context != null) { | pInfo = AppUtils.getPackageInfo(context); |
erdemolkun/instant-rates | app/src/main/java/dynoapps/exchange_rates/converters/YorumlarConverter.java | // Path: app/src/main/java/dynoapps/exchange_rates/model/rates/BaseRate.java
// public abstract class BaseRate implements IConvertable, IRate {
//
// public String type;
//
// @RateDef
// protected int rateType;
//
// BaseRate() {
// }
//
// @Override
// public int getRateType() {
// return rateType;
// }
//
// public String getFormatted(float val) {
// return RateUtils.valueToUI(val, rateType);
// }
// }
//
// Path: app/src/main/java/dynoapps/exchange_rates/model/rates/YorumlarRate.java
// public class YorumlarRate extends AvgRate {
//
// public String time;
//
// @Override
// public void toRateType() {
// if (TextUtils.isEmpty(type)) rateType = UNKNOWN;
// int rateType = UNKNOWN;
// switch (type) {
// case "dolar_guncelle":
// rateType = USD;
// break;
// case "euro_guncelle":
// rateType = EUR;
// break;
// case "parite_guncelle":
// rateType = EUR_USD;
// break;
// case "ons_guncelle":
// rateType = ONS;
// break;
// }
// this.rateType = rateType;
// }
//
// @Override
// public void setRealValues() {
// if (rateType == UNKNOWN) return;
// String val = avg_val.replace("'", "").replace("$", "").trim();
// val_real_avg = Float.parseFloat(val);
// }
//
// @Override
// @NonNull
// public String toString() {
// return type.split("_")[0] + " -> : " + val_real_avg + " : Time -> " + time.replace("'", "");
// }
//
// }
| import android.text.TextUtils;
import java.io.IOException;
import java.lang.annotation.Annotation;
import java.lang.reflect.Type;
import java.util.ArrayList;
import java.util.List;
import androidx.annotation.NonNull;
import dynoapps.exchange_rates.model.rates.BaseRate;
import dynoapps.exchange_rates.model.rates.YorumlarRate;
import okhttp3.ResponseBody;
import retrofit2.Converter;
import retrofit2.Retrofit; | package dynoapps.exchange_rates.converters;
/**
* Created by erdemmac on 24/11/2016.
*/
public class YorumlarConverter implements Converter<ResponseBody, List<BaseRate>> {
private static final YorumlarConverter INSTANCE = new YorumlarConverter();
private YorumlarConverter() {
}
/**
* Sample response body <p> <p> dolar_guncelle('3.4047','13:01:36');euro_guncelle('3.6012','13:01:36');sterlin_guncelle('4.2431','13:01:36');gumus_guncelle('1.7921','1.7941','13:01:36');parite_guncelle('1.0570','13:01:36');ons_guncelle('$1190.0000','13:01:36');ySi('[5164806,5388042,5387395,5387090]');
* </p>
**/
@Override
public List<BaseRate> convert(@NonNull ResponseBody value) throws IOException {
ArrayList<BaseRate> rates = new ArrayList<>();
String responseBody = value.string();
if (!TextUtils.isEmpty(responseBody)) {
String[] splitsMoney = responseBody.split(";");
if (splitsMoney.length > 0) {
for (String singleSplit : splitsMoney) {
String[] splits = singleSplit.split("[(),]"); // ysi Type not supported
if (splits.length > 2) { | // Path: app/src/main/java/dynoapps/exchange_rates/model/rates/BaseRate.java
// public abstract class BaseRate implements IConvertable, IRate {
//
// public String type;
//
// @RateDef
// protected int rateType;
//
// BaseRate() {
// }
//
// @Override
// public int getRateType() {
// return rateType;
// }
//
// public String getFormatted(float val) {
// return RateUtils.valueToUI(val, rateType);
// }
// }
//
// Path: app/src/main/java/dynoapps/exchange_rates/model/rates/YorumlarRate.java
// public class YorumlarRate extends AvgRate {
//
// public String time;
//
// @Override
// public void toRateType() {
// if (TextUtils.isEmpty(type)) rateType = UNKNOWN;
// int rateType = UNKNOWN;
// switch (type) {
// case "dolar_guncelle":
// rateType = USD;
// break;
// case "euro_guncelle":
// rateType = EUR;
// break;
// case "parite_guncelle":
// rateType = EUR_USD;
// break;
// case "ons_guncelle":
// rateType = ONS;
// break;
// }
// this.rateType = rateType;
// }
//
// @Override
// public void setRealValues() {
// if (rateType == UNKNOWN) return;
// String val = avg_val.replace("'", "").replace("$", "").trim();
// val_real_avg = Float.parseFloat(val);
// }
//
// @Override
// @NonNull
// public String toString() {
// return type.split("_")[0] + " -> : " + val_real_avg + " : Time -> " + time.replace("'", "");
// }
//
// }
// Path: app/src/main/java/dynoapps/exchange_rates/converters/YorumlarConverter.java
import android.text.TextUtils;
import java.io.IOException;
import java.lang.annotation.Annotation;
import java.lang.reflect.Type;
import java.util.ArrayList;
import java.util.List;
import androidx.annotation.NonNull;
import dynoapps.exchange_rates.model.rates.BaseRate;
import dynoapps.exchange_rates.model.rates.YorumlarRate;
import okhttp3.ResponseBody;
import retrofit2.Converter;
import retrofit2.Retrofit;
package dynoapps.exchange_rates.converters;
/**
* Created by erdemmac on 24/11/2016.
*/
public class YorumlarConverter implements Converter<ResponseBody, List<BaseRate>> {
private static final YorumlarConverter INSTANCE = new YorumlarConverter();
private YorumlarConverter() {
}
/**
* Sample response body <p> <p> dolar_guncelle('3.4047','13:01:36');euro_guncelle('3.6012','13:01:36');sterlin_guncelle('4.2431','13:01:36');gumus_guncelle('1.7921','1.7941','13:01:36');parite_guncelle('1.0570','13:01:36');ons_guncelle('$1190.0000','13:01:36');ySi('[5164806,5388042,5387395,5387090]');
* </p>
**/
@Override
public List<BaseRate> convert(@NonNull ResponseBody value) throws IOException {
ArrayList<BaseRate> rates = new ArrayList<>();
String responseBody = value.string();
if (!TextUtils.isEmpty(responseBody)) {
String[] splitsMoney = responseBody.split(";");
if (splitsMoney.length > 0) {
for (String singleSplit : splitsMoney) {
String[] splits = singleSplit.split("[(),]"); // ysi Type not supported
if (splits.length > 2) { | YorumlarRate rate = new YorumlarRate(); |
erdemolkun/instant-rates | app/src/main/java/dynoapps/exchange_rates/alarm/LocalAlarmsDataSource.java | // Path: app/src/main/java/dynoapps/exchange_rates/AppDatabase.java
// @Database(entities = {Alarm.class}, version = 1, exportSchema = false)
// public abstract class AppDatabase extends RoomDatabase {
// /**
// * The only instance
// */
// private static AppDatabase sInstance;
//
// /**
// * Gets the singleton instance of SampleDatabase.
// *
// * @param context The context.
// * @return The singleton instance of SampleDatabase.
// */
// public static synchronized AppDatabase getInstance(Context context) {
// if (sInstance == null) {
// sInstance = Room
// .databaseBuilder(context.getApplicationContext(), AppDatabase.class, "alarms")
// .build();
// }
// return sInstance;
// }
//
// /**
// * @return The DAO for the Alarm table.
// */
// public abstract AlarmDao alarm();
// }
| import android.annotation.SuppressLint;
import android.content.Context;
import androidx.annotation.NonNull;
import dynoapps.exchange_rates.AppDatabase;
import io.reactivex.Single;
import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.schedulers.Schedulers; | package dynoapps.exchange_rates.alarm;
/**
* Created by erdemmac on 19/07/2017.
*/
public class LocalAlarmsDataSource implements AlarmsDataSource {
private final AlarmDao alarmDao;
public LocalAlarmsDataSource(@NonNull Context context) { | // Path: app/src/main/java/dynoapps/exchange_rates/AppDatabase.java
// @Database(entities = {Alarm.class}, version = 1, exportSchema = false)
// public abstract class AppDatabase extends RoomDatabase {
// /**
// * The only instance
// */
// private static AppDatabase sInstance;
//
// /**
// * Gets the singleton instance of SampleDatabase.
// *
// * @param context The context.
// * @return The singleton instance of SampleDatabase.
// */
// public static synchronized AppDatabase getInstance(Context context) {
// if (sInstance == null) {
// sInstance = Room
// .databaseBuilder(context.getApplicationContext(), AppDatabase.class, "alarms")
// .build();
// }
// return sInstance;
// }
//
// /**
// * @return The DAO for the Alarm table.
// */
// public abstract AlarmDao alarm();
// }
// Path: app/src/main/java/dynoapps/exchange_rates/alarm/LocalAlarmsDataSource.java
import android.annotation.SuppressLint;
import android.content.Context;
import androidx.annotation.NonNull;
import dynoapps.exchange_rates.AppDatabase;
import io.reactivex.Single;
import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.schedulers.Schedulers;
package dynoapps.exchange_rates.alarm;
/**
* Created by erdemmac on 19/07/2017.
*/
public class LocalAlarmsDataSource implements AlarmsDataSource {
private final AlarmDao alarmDao;
public LocalAlarmsDataSource(@NonNull Context context) { | alarmDao = AppDatabase.getInstance(context.getApplicationContext()).alarm(); |
erdemolkun/instant-rates | app/src/main/java/dynoapps/exchange_rates/util/ViewUtils.java | // Path: app/src/main/java/dynoapps/exchange_rates/App.java
// public class App extends Application {
// private static App appInstance;
//
// public static App getInstance() {
// return appInstance;
// }
//
// @NonNull
// public static Context context() {
// return appInstance.getApplicationContext();
// }
//
// public AlarmsRepository provideAlarmsRepository() {
// return AlarmsRepository.getInstance(getApplicationContext());
// }
//
// @SuppressLint("CheckResult")
// @Override
// public void onCreate() {
// super.onCreate();
// appInstance = this;
//
// RxJavaPlugins.setErrorHandler(throwable -> L.e("App", throwable.getLocalizedMessage()));
// }
//
// /**
// * Enum used to identify the tracker that needs to be used for tracking.
// * <p/>
// * A single tracker is usually enough for most purposes. In case you do need multiple trackers,
// * storing them all in Application object helps ensure that they are created only once per
// * application instance.
// */
// public enum TrackerName {
// APP_TRACKER, // Tracker used only in this app.
// GLOBAL_TRACKER, // Tracker used by all the apps from a company. eg: roll-up tracking.
// }
//
//
// }
| import android.content.Context;
import android.content.res.Resources;
import android.content.res.TypedArray;
import android.util.TypedValue;
import android.view.View;
import dynoapps.exchange_rates.App;
import dynoapps.exchange_rates.R; | package dynoapps.exchange_rates.util;
/**
* Created by eolkun on 6.2.2015.
*/
public class ViewUtils {
private static final int[] RES_IDS_ACTION_BAR_SIZE = {R.attr.actionBarSize};
public static void visibility(View v, boolean isVisible) {
if (v == null) return;
v.setVisibility(isVisible ? View.VISIBLE : View.GONE);
}
private static int dpToPx(float dp, Resources res) {
return (int) TypedValue.applyDimension(
TypedValue.COMPLEX_UNIT_DIP,
dp,
res.getDisplayMetrics());
}
/**
* This method converts dp unit to equivalent pixels, depending on device density.
*
* @param dp A value in dp (density independent pixels) unit. Which we need to convert into
* pixels
* @return A float value to represent px equivalent to dp depending on device density
*/
public static int dpToPx(float dp) { | // Path: app/src/main/java/dynoapps/exchange_rates/App.java
// public class App extends Application {
// private static App appInstance;
//
// public static App getInstance() {
// return appInstance;
// }
//
// @NonNull
// public static Context context() {
// return appInstance.getApplicationContext();
// }
//
// public AlarmsRepository provideAlarmsRepository() {
// return AlarmsRepository.getInstance(getApplicationContext());
// }
//
// @SuppressLint("CheckResult")
// @Override
// public void onCreate() {
// super.onCreate();
// appInstance = this;
//
// RxJavaPlugins.setErrorHandler(throwable -> L.e("App", throwable.getLocalizedMessage()));
// }
//
// /**
// * Enum used to identify the tracker that needs to be used for tracking.
// * <p/>
// * A single tracker is usually enough for most purposes. In case you do need multiple trackers,
// * storing them all in Application object helps ensure that they are created only once per
// * application instance.
// */
// public enum TrackerName {
// APP_TRACKER, // Tracker used only in this app.
// GLOBAL_TRACKER, // Tracker used by all the apps from a company. eg: roll-up tracking.
// }
//
//
// }
// Path: app/src/main/java/dynoapps/exchange_rates/util/ViewUtils.java
import android.content.Context;
import android.content.res.Resources;
import android.content.res.TypedArray;
import android.util.TypedValue;
import android.view.View;
import dynoapps.exchange_rates.App;
import dynoapps.exchange_rates.R;
package dynoapps.exchange_rates.util;
/**
* Created by eolkun on 6.2.2015.
*/
public class ViewUtils {
private static final int[] RES_IDS_ACTION_BAR_SIZE = {R.attr.actionBarSize};
public static void visibility(View v, boolean isVisible) {
if (v == null) return;
v.setVisibility(isVisible ? View.VISIBLE : View.GONE);
}
private static int dpToPx(float dp, Resources res) {
return (int) TypedValue.applyDimension(
TypedValue.COMPLEX_UNIT_DIP,
dp,
res.getDisplayMetrics());
}
/**
* This method converts dp unit to equivalent pixels, depending on device density.
*
* @param dp A value in dp (density independent pixels) unit. Which we need to convert into
* pixels
* @return A float value to represent px equivalent to dp depending on device density
*/
public static int dpToPx(float dp) { | Context context = App.context(); |
erdemolkun/instant-rates | app/src/main/java/dynoapps/exchange_rates/AppDatabase.java | // Path: app/src/main/java/dynoapps/exchange_rates/alarm/Alarm.java
// @Entity(tableName = Alarm.TABLE_NAME)
// public class Alarm implements Serializable {
//
// /**
// * The name of the Alarm table.
// */
// public static final String TABLE_NAME = "tables";
//
// /**
// * The name of the ID column.
// */
// public static final String COLUMN_ID = BaseColumns._ID;
// public static Comparator<Alarm> COMPARATOR = (first, second) -> {
//
// int i = compare(first.sourceType, second.sourceType);
// if (i != 0) return i;
//
// i = compare(first.rateType, second.rateType);
// if (i != 0) return i;
//
// i = compare(first.val, second.val);
// return i;
//
// };
// /**
// * The unique ID of the alarm.
// */
// @PrimaryKey(autoGenerate = true)
// @ColumnInfo(index = true, name = COLUMN_ID)
// public long id;
// @ColumnInfo(name = "value")
// public Float val;
// @ColumnInfo(name = "is_above")
// public boolean isAbove = false;
// @ColumnInfo(name = "is_enabled")
// public boolean isEnabled = true;
// /**
// * {@link dynoapps.exchange_rates.model.rates.IRate}
// */
// @ColumnInfo(name = "rate_type")
// public int rateType;
// /**
// * {@link dynoapps.exchange_rates.data.CurrencyType}
// */
// @ColumnInfo(name = "source_type")
// public int sourceType;
// /**
// * {@link dynoapps.exchange_rates.interfaces.ValueType}
// */
// public int value_type = ValueType.NONE;
//
// public static int getPushId(Alarm alarm) {
// return alarm.rateType * 100 + alarm.sourceType;
// }
//
// private static int compare(int x, int y) {
// return Integer.compare(x, y);
// }
//
// private static int compare(float x, float y) {
// return Float.compare(x, y);
// }
// }
//
// Path: app/src/main/java/dynoapps/exchange_rates/alarm/AlarmDao.java
// @Dao
// public interface AlarmDao {
//
// /**
// * Inserts a alarm into the table.
// *
// * @param alarm A new alarm.
// * @return The row ID of the newly inserted alarm.
// */
// @Insert
// Single<Long> insert(Alarm alarm);
//
// /**
// * Inserts multiple alarms into the database
// *
// * @param alarms An array of new alarms.
// * @return The row IDs of the newly inserted alarms.
// */
// @Insert
// long[] insertAll(Alarm[] alarms);
//
// /**
// * Select all alarms.
// *
// * @return A {@link Cursor} of all the cheeses in the table.
// */
// @Query("SELECT * FROM " + Alarm.TABLE_NAME)
// Flowable<List<Alarm>> selectAll();
//
// /**
// * Select all alarms.
// *
// * @return A {@link Cursor} of all the cheeses in the table.
// */
// @Query("SELECT * FROM " + Alarm.TABLE_NAME)
// Single<List<Alarm>> list();
//
//
// /**
// * Delete a alarm by the ID.
// *
// * @param id The row ID.
// * @return A number of alarms deleted. This should always be {@code 1}.
// */
// @Query("DELETE FROM " + Alarm.TABLE_NAME + " WHERE " + Alarm.COLUMN_ID + " = :id")
// Single<Integer> deleteById(long id);
//
// /**
// * Update the alarm. The alarm is identified by the row ID.
// *
// * @param alarm The alarm to update.
// * @return A number of alarms updated. This should always be {@code 1}.
// */
// @Update
// Single<Integer> update(Alarm alarm);
//
// }
| import android.content.Context;
import androidx.room.Database;
import androidx.room.Room;
import androidx.room.RoomDatabase;
import dynoapps.exchange_rates.alarm.Alarm;
import dynoapps.exchange_rates.alarm.AlarmDao; | package dynoapps.exchange_rates;
/**
* Created by erdemmac on 18/07/2017.
*/
@Database(entities = {Alarm.class}, version = 1, exportSchema = false)
public abstract class AppDatabase extends RoomDatabase {
/**
* The only instance
*/
private static AppDatabase sInstance;
/**
* Gets the singleton instance of SampleDatabase.
*
* @param context The context.
* @return The singleton instance of SampleDatabase.
*/
public static synchronized AppDatabase getInstance(Context context) {
if (sInstance == null) {
sInstance = Room
.databaseBuilder(context.getApplicationContext(), AppDatabase.class, "alarms")
.build();
}
return sInstance;
}
/**
* @return The DAO for the Alarm table.
*/ | // Path: app/src/main/java/dynoapps/exchange_rates/alarm/Alarm.java
// @Entity(tableName = Alarm.TABLE_NAME)
// public class Alarm implements Serializable {
//
// /**
// * The name of the Alarm table.
// */
// public static final String TABLE_NAME = "tables";
//
// /**
// * The name of the ID column.
// */
// public static final String COLUMN_ID = BaseColumns._ID;
// public static Comparator<Alarm> COMPARATOR = (first, second) -> {
//
// int i = compare(first.sourceType, second.sourceType);
// if (i != 0) return i;
//
// i = compare(first.rateType, second.rateType);
// if (i != 0) return i;
//
// i = compare(first.val, second.val);
// return i;
//
// };
// /**
// * The unique ID of the alarm.
// */
// @PrimaryKey(autoGenerate = true)
// @ColumnInfo(index = true, name = COLUMN_ID)
// public long id;
// @ColumnInfo(name = "value")
// public Float val;
// @ColumnInfo(name = "is_above")
// public boolean isAbove = false;
// @ColumnInfo(name = "is_enabled")
// public boolean isEnabled = true;
// /**
// * {@link dynoapps.exchange_rates.model.rates.IRate}
// */
// @ColumnInfo(name = "rate_type")
// public int rateType;
// /**
// * {@link dynoapps.exchange_rates.data.CurrencyType}
// */
// @ColumnInfo(name = "source_type")
// public int sourceType;
// /**
// * {@link dynoapps.exchange_rates.interfaces.ValueType}
// */
// public int value_type = ValueType.NONE;
//
// public static int getPushId(Alarm alarm) {
// return alarm.rateType * 100 + alarm.sourceType;
// }
//
// private static int compare(int x, int y) {
// return Integer.compare(x, y);
// }
//
// private static int compare(float x, float y) {
// return Float.compare(x, y);
// }
// }
//
// Path: app/src/main/java/dynoapps/exchange_rates/alarm/AlarmDao.java
// @Dao
// public interface AlarmDao {
//
// /**
// * Inserts a alarm into the table.
// *
// * @param alarm A new alarm.
// * @return The row ID of the newly inserted alarm.
// */
// @Insert
// Single<Long> insert(Alarm alarm);
//
// /**
// * Inserts multiple alarms into the database
// *
// * @param alarms An array of new alarms.
// * @return The row IDs of the newly inserted alarms.
// */
// @Insert
// long[] insertAll(Alarm[] alarms);
//
// /**
// * Select all alarms.
// *
// * @return A {@link Cursor} of all the cheeses in the table.
// */
// @Query("SELECT * FROM " + Alarm.TABLE_NAME)
// Flowable<List<Alarm>> selectAll();
//
// /**
// * Select all alarms.
// *
// * @return A {@link Cursor} of all the cheeses in the table.
// */
// @Query("SELECT * FROM " + Alarm.TABLE_NAME)
// Single<List<Alarm>> list();
//
//
// /**
// * Delete a alarm by the ID.
// *
// * @param id The row ID.
// * @return A number of alarms deleted. This should always be {@code 1}.
// */
// @Query("DELETE FROM " + Alarm.TABLE_NAME + " WHERE " + Alarm.COLUMN_ID + " = :id")
// Single<Integer> deleteById(long id);
//
// /**
// * Update the alarm. The alarm is identified by the row ID.
// *
// * @param alarm The alarm to update.
// * @return A number of alarms updated. This should always be {@code 1}.
// */
// @Update
// Single<Integer> update(Alarm alarm);
//
// }
// Path: app/src/main/java/dynoapps/exchange_rates/AppDatabase.java
import android.content.Context;
import androidx.room.Database;
import androidx.room.Room;
import androidx.room.RoomDatabase;
import dynoapps.exchange_rates.alarm.Alarm;
import dynoapps.exchange_rates.alarm.AlarmDao;
package dynoapps.exchange_rates;
/**
* Created by erdemmac on 18/07/2017.
*/
@Database(entities = {Alarm.class}, version = 1, exportSchema = false)
public abstract class AppDatabase extends RoomDatabase {
/**
* The only instance
*/
private static AppDatabase sInstance;
/**
* Gets the singleton instance of SampleDatabase.
*
* @param context The context.
* @return The singleton instance of SampleDatabase.
*/
public static synchronized AppDatabase getInstance(Context context) {
if (sInstance == null) {
sInstance = Room
.databaseBuilder(context.getApplicationContext(), AppDatabase.class, "alarms")
.build();
}
return sInstance;
}
/**
* @return The DAO for the Alarm table.
*/ | public abstract AlarmDao alarm(); |
erdemolkun/instant-rates | app/src/main/java/dynoapps/exchange_rates/util/RateUtils.java | // Path: app/src/main/java/dynoapps/exchange_rates/App.java
// public class App extends Application {
// private static App appInstance;
//
// public static App getInstance() {
// return appInstance;
// }
//
// @NonNull
// public static Context context() {
// return appInstance.getApplicationContext();
// }
//
// public AlarmsRepository provideAlarmsRepository() {
// return AlarmsRepository.getInstance(getApplicationContext());
// }
//
// @SuppressLint("CheckResult")
// @Override
// public void onCreate() {
// super.onCreate();
// appInstance = this;
//
// RxJavaPlugins.setErrorHandler(throwable -> L.e("App", throwable.getLocalizedMessage()));
// }
//
// /**
// * Enum used to identify the tracker that needs to be used for tracking.
// * <p/>
// * A single tracker is usually enough for most purposes. In case you do need multiple trackers,
// * storing them all in Application object helps ensure that they are created only once per
// * application instance.
// */
// public enum TrackerName {
// APP_TRACKER, // Tracker used only in this app.
// GLOBAL_TRACKER, // Tracker used by all the apps from a company. eg: roll-up tracking.
// }
//
//
// }
//
// Path: app/src/main/java/dynoapps/exchange_rates/model/rates/BaseRate.java
// public abstract class BaseRate implements IConvertable, IRate {
//
// public String type;
//
// @RateDef
// protected int rateType;
//
// BaseRate() {
// }
//
// @Override
// public int getRateType() {
// return rateType;
// }
//
// public String getFormatted(float val) {
// return RateUtils.valueToUI(val, rateType);
// }
// }
//
// Path: app/src/main/java/dynoapps/exchange_rates/model/rates/IRate.java
// public interface IRate {
// int UNKNOWN = 0;
// int USD = 1;
// int EUR = 2;
// int ONS = 3;
// int ONS_TRY = 4;
// int EUR_USD = 5;
//
// @RateDef
// int getRateType();
//
// float getValue(int valueType);
//
// @Retention(RetentionPolicy.SOURCE)
// @IntDef({
// UNKNOWN,
// USD,
// EUR,
// ONS,
// ONS_TRY,
// EUR_USD
// })
// @interface RateDef {
// }
// }
| import android.text.TextUtils;
import java.text.DecimalFormat;
import java.text.DecimalFormatSymbols;
import java.util.List;
import androidx.annotation.DrawableRes;
import androidx.annotation.Nullable;
import dynoapps.exchange_rates.App;
import dynoapps.exchange_rates.R;
import dynoapps.exchange_rates.model.rates.BaseRate;
import dynoapps.exchange_rates.model.rates.IRate; | package dynoapps.exchange_rates.util;
/**
* Created by erdemmac on 01/12/2016.
*/
public class RateUtils {
private static final Formatter formatter2 = new Formatter(2, 0);
private static final Formatter formatter5 = new Formatter(5, 2);
| // Path: app/src/main/java/dynoapps/exchange_rates/App.java
// public class App extends Application {
// private static App appInstance;
//
// public static App getInstance() {
// return appInstance;
// }
//
// @NonNull
// public static Context context() {
// return appInstance.getApplicationContext();
// }
//
// public AlarmsRepository provideAlarmsRepository() {
// return AlarmsRepository.getInstance(getApplicationContext());
// }
//
// @SuppressLint("CheckResult")
// @Override
// public void onCreate() {
// super.onCreate();
// appInstance = this;
//
// RxJavaPlugins.setErrorHandler(throwable -> L.e("App", throwable.getLocalizedMessage()));
// }
//
// /**
// * Enum used to identify the tracker that needs to be used for tracking.
// * <p/>
// * A single tracker is usually enough for most purposes. In case you do need multiple trackers,
// * storing them all in Application object helps ensure that they are created only once per
// * application instance.
// */
// public enum TrackerName {
// APP_TRACKER, // Tracker used only in this app.
// GLOBAL_TRACKER, // Tracker used by all the apps from a company. eg: roll-up tracking.
// }
//
//
// }
//
// Path: app/src/main/java/dynoapps/exchange_rates/model/rates/BaseRate.java
// public abstract class BaseRate implements IConvertable, IRate {
//
// public String type;
//
// @RateDef
// protected int rateType;
//
// BaseRate() {
// }
//
// @Override
// public int getRateType() {
// return rateType;
// }
//
// public String getFormatted(float val) {
// return RateUtils.valueToUI(val, rateType);
// }
// }
//
// Path: app/src/main/java/dynoapps/exchange_rates/model/rates/IRate.java
// public interface IRate {
// int UNKNOWN = 0;
// int USD = 1;
// int EUR = 2;
// int ONS = 3;
// int ONS_TRY = 4;
// int EUR_USD = 5;
//
// @RateDef
// int getRateType();
//
// float getValue(int valueType);
//
// @Retention(RetentionPolicy.SOURCE)
// @IntDef({
// UNKNOWN,
// USD,
// EUR,
// ONS,
// ONS_TRY,
// EUR_USD
// })
// @interface RateDef {
// }
// }
// Path: app/src/main/java/dynoapps/exchange_rates/util/RateUtils.java
import android.text.TextUtils;
import java.text.DecimalFormat;
import java.text.DecimalFormatSymbols;
import java.util.List;
import androidx.annotation.DrawableRes;
import androidx.annotation.Nullable;
import dynoapps.exchange_rates.App;
import dynoapps.exchange_rates.R;
import dynoapps.exchange_rates.model.rates.BaseRate;
import dynoapps.exchange_rates.model.rates.IRate;
package dynoapps.exchange_rates.util;
/**
* Created by erdemmac on 01/12/2016.
*/
public class RateUtils {
private static final Formatter formatter2 = new Formatter(2, 0);
private static final Formatter formatter5 = new Formatter(5, 2);
| public static <T extends BaseRate> T getRate(List<T> rates, @IRate.RateDef int rateType) { |
erdemolkun/instant-rates | app/src/main/java/dynoapps/exchange_rates/util/RateUtils.java | // Path: app/src/main/java/dynoapps/exchange_rates/App.java
// public class App extends Application {
// private static App appInstance;
//
// public static App getInstance() {
// return appInstance;
// }
//
// @NonNull
// public static Context context() {
// return appInstance.getApplicationContext();
// }
//
// public AlarmsRepository provideAlarmsRepository() {
// return AlarmsRepository.getInstance(getApplicationContext());
// }
//
// @SuppressLint("CheckResult")
// @Override
// public void onCreate() {
// super.onCreate();
// appInstance = this;
//
// RxJavaPlugins.setErrorHandler(throwable -> L.e("App", throwable.getLocalizedMessage()));
// }
//
// /**
// * Enum used to identify the tracker that needs to be used for tracking.
// * <p/>
// * A single tracker is usually enough for most purposes. In case you do need multiple trackers,
// * storing them all in Application object helps ensure that they are created only once per
// * application instance.
// */
// public enum TrackerName {
// APP_TRACKER, // Tracker used only in this app.
// GLOBAL_TRACKER, // Tracker used by all the apps from a company. eg: roll-up tracking.
// }
//
//
// }
//
// Path: app/src/main/java/dynoapps/exchange_rates/model/rates/BaseRate.java
// public abstract class BaseRate implements IConvertable, IRate {
//
// public String type;
//
// @RateDef
// protected int rateType;
//
// BaseRate() {
// }
//
// @Override
// public int getRateType() {
// return rateType;
// }
//
// public String getFormatted(float val) {
// return RateUtils.valueToUI(val, rateType);
// }
// }
//
// Path: app/src/main/java/dynoapps/exchange_rates/model/rates/IRate.java
// public interface IRate {
// int UNKNOWN = 0;
// int USD = 1;
// int EUR = 2;
// int ONS = 3;
// int ONS_TRY = 4;
// int EUR_USD = 5;
//
// @RateDef
// int getRateType();
//
// float getValue(int valueType);
//
// @Retention(RetentionPolicy.SOURCE)
// @IntDef({
// UNKNOWN,
// USD,
// EUR,
// ONS,
// ONS_TRY,
// EUR_USD
// })
// @interface RateDef {
// }
// }
| import android.text.TextUtils;
import java.text.DecimalFormat;
import java.text.DecimalFormatSymbols;
import java.util.List;
import androidx.annotation.DrawableRes;
import androidx.annotation.Nullable;
import dynoapps.exchange_rates.App;
import dynoapps.exchange_rates.R;
import dynoapps.exchange_rates.model.rates.BaseRate;
import dynoapps.exchange_rates.model.rates.IRate; | package dynoapps.exchange_rates.util;
/**
* Created by erdemmac on 01/12/2016.
*/
public class RateUtils {
private static final Formatter formatter2 = new Formatter(2, 0);
private static final Formatter formatter5 = new Formatter(5, 2);
| // Path: app/src/main/java/dynoapps/exchange_rates/App.java
// public class App extends Application {
// private static App appInstance;
//
// public static App getInstance() {
// return appInstance;
// }
//
// @NonNull
// public static Context context() {
// return appInstance.getApplicationContext();
// }
//
// public AlarmsRepository provideAlarmsRepository() {
// return AlarmsRepository.getInstance(getApplicationContext());
// }
//
// @SuppressLint("CheckResult")
// @Override
// public void onCreate() {
// super.onCreate();
// appInstance = this;
//
// RxJavaPlugins.setErrorHandler(throwable -> L.e("App", throwable.getLocalizedMessage()));
// }
//
// /**
// * Enum used to identify the tracker that needs to be used for tracking.
// * <p/>
// * A single tracker is usually enough for most purposes. In case you do need multiple trackers,
// * storing them all in Application object helps ensure that they are created only once per
// * application instance.
// */
// public enum TrackerName {
// APP_TRACKER, // Tracker used only in this app.
// GLOBAL_TRACKER, // Tracker used by all the apps from a company. eg: roll-up tracking.
// }
//
//
// }
//
// Path: app/src/main/java/dynoapps/exchange_rates/model/rates/BaseRate.java
// public abstract class BaseRate implements IConvertable, IRate {
//
// public String type;
//
// @RateDef
// protected int rateType;
//
// BaseRate() {
// }
//
// @Override
// public int getRateType() {
// return rateType;
// }
//
// public String getFormatted(float val) {
// return RateUtils.valueToUI(val, rateType);
// }
// }
//
// Path: app/src/main/java/dynoapps/exchange_rates/model/rates/IRate.java
// public interface IRate {
// int UNKNOWN = 0;
// int USD = 1;
// int EUR = 2;
// int ONS = 3;
// int ONS_TRY = 4;
// int EUR_USD = 5;
//
// @RateDef
// int getRateType();
//
// float getValue(int valueType);
//
// @Retention(RetentionPolicy.SOURCE)
// @IntDef({
// UNKNOWN,
// USD,
// EUR,
// ONS,
// ONS_TRY,
// EUR_USD
// })
// @interface RateDef {
// }
// }
// Path: app/src/main/java/dynoapps/exchange_rates/util/RateUtils.java
import android.text.TextUtils;
import java.text.DecimalFormat;
import java.text.DecimalFormatSymbols;
import java.util.List;
import androidx.annotation.DrawableRes;
import androidx.annotation.Nullable;
import dynoapps.exchange_rates.App;
import dynoapps.exchange_rates.R;
import dynoapps.exchange_rates.model.rates.BaseRate;
import dynoapps.exchange_rates.model.rates.IRate;
package dynoapps.exchange_rates.util;
/**
* Created by erdemmac on 01/12/2016.
*/
public class RateUtils {
private static final Formatter formatter2 = new Formatter(2, 0);
private static final Formatter formatter5 = new Formatter(5, 2);
| public static <T extends BaseRate> T getRate(List<T> rates, @IRate.RateDef int rateType) { |
erdemolkun/instant-rates | app/src/main/java/dynoapps/exchange_rates/util/RateUtils.java | // Path: app/src/main/java/dynoapps/exchange_rates/App.java
// public class App extends Application {
// private static App appInstance;
//
// public static App getInstance() {
// return appInstance;
// }
//
// @NonNull
// public static Context context() {
// return appInstance.getApplicationContext();
// }
//
// public AlarmsRepository provideAlarmsRepository() {
// return AlarmsRepository.getInstance(getApplicationContext());
// }
//
// @SuppressLint("CheckResult")
// @Override
// public void onCreate() {
// super.onCreate();
// appInstance = this;
//
// RxJavaPlugins.setErrorHandler(throwable -> L.e("App", throwable.getLocalizedMessage()));
// }
//
// /**
// * Enum used to identify the tracker that needs to be used for tracking.
// * <p/>
// * A single tracker is usually enough for most purposes. In case you do need multiple trackers,
// * storing them all in Application object helps ensure that they are created only once per
// * application instance.
// */
// public enum TrackerName {
// APP_TRACKER, // Tracker used only in this app.
// GLOBAL_TRACKER, // Tracker used by all the apps from a company. eg: roll-up tracking.
// }
//
//
// }
//
// Path: app/src/main/java/dynoapps/exchange_rates/model/rates/BaseRate.java
// public abstract class BaseRate implements IConvertable, IRate {
//
// public String type;
//
// @RateDef
// protected int rateType;
//
// BaseRate() {
// }
//
// @Override
// public int getRateType() {
// return rateType;
// }
//
// public String getFormatted(float val) {
// return RateUtils.valueToUI(val, rateType);
// }
// }
//
// Path: app/src/main/java/dynoapps/exchange_rates/model/rates/IRate.java
// public interface IRate {
// int UNKNOWN = 0;
// int USD = 1;
// int EUR = 2;
// int ONS = 3;
// int ONS_TRY = 4;
// int EUR_USD = 5;
//
// @RateDef
// int getRateType();
//
// float getValue(int valueType);
//
// @Retention(RetentionPolicy.SOURCE)
// @IntDef({
// UNKNOWN,
// USD,
// EUR,
// ONS,
// ONS_TRY,
// EUR_USD
// })
// @interface RateDef {
// }
// }
| import android.text.TextUtils;
import java.text.DecimalFormat;
import java.text.DecimalFormatSymbols;
import java.util.List;
import androidx.annotation.DrawableRes;
import androidx.annotation.Nullable;
import dynoapps.exchange_rates.App;
import dynoapps.exchange_rates.R;
import dynoapps.exchange_rates.model.rates.BaseRate;
import dynoapps.exchange_rates.model.rates.IRate; | package dynoapps.exchange_rates.util;
/**
* Created by erdemmac on 01/12/2016.
*/
public class RateUtils {
private static final Formatter formatter2 = new Formatter(2, 0);
private static final Formatter formatter5 = new Formatter(5, 2);
public static <T extends BaseRate> T getRate(List<T> rates, @IRate.RateDef int rateType) {
if (rates == null) return null;
for (T rate : rates) {
if (rate.getRateType() == rateType) {
return rate;
}
}
return null;
}
public static String valueToUI(Float val, @IRate.RateDef int rateType) {
if (val == null) return "";
String formatted = formatValue(val, rateType);
if (rateType == IRate.EUR_USD) {
return formatted;
} else if (rateType == IRate.ONS) { | // Path: app/src/main/java/dynoapps/exchange_rates/App.java
// public class App extends Application {
// private static App appInstance;
//
// public static App getInstance() {
// return appInstance;
// }
//
// @NonNull
// public static Context context() {
// return appInstance.getApplicationContext();
// }
//
// public AlarmsRepository provideAlarmsRepository() {
// return AlarmsRepository.getInstance(getApplicationContext());
// }
//
// @SuppressLint("CheckResult")
// @Override
// public void onCreate() {
// super.onCreate();
// appInstance = this;
//
// RxJavaPlugins.setErrorHandler(throwable -> L.e("App", throwable.getLocalizedMessage()));
// }
//
// /**
// * Enum used to identify the tracker that needs to be used for tracking.
// * <p/>
// * A single tracker is usually enough for most purposes. In case you do need multiple trackers,
// * storing them all in Application object helps ensure that they are created only once per
// * application instance.
// */
// public enum TrackerName {
// APP_TRACKER, // Tracker used only in this app.
// GLOBAL_TRACKER, // Tracker used by all the apps from a company. eg: roll-up tracking.
// }
//
//
// }
//
// Path: app/src/main/java/dynoapps/exchange_rates/model/rates/BaseRate.java
// public abstract class BaseRate implements IConvertable, IRate {
//
// public String type;
//
// @RateDef
// protected int rateType;
//
// BaseRate() {
// }
//
// @Override
// public int getRateType() {
// return rateType;
// }
//
// public String getFormatted(float val) {
// return RateUtils.valueToUI(val, rateType);
// }
// }
//
// Path: app/src/main/java/dynoapps/exchange_rates/model/rates/IRate.java
// public interface IRate {
// int UNKNOWN = 0;
// int USD = 1;
// int EUR = 2;
// int ONS = 3;
// int ONS_TRY = 4;
// int EUR_USD = 5;
//
// @RateDef
// int getRateType();
//
// float getValue(int valueType);
//
// @Retention(RetentionPolicy.SOURCE)
// @IntDef({
// UNKNOWN,
// USD,
// EUR,
// ONS,
// ONS_TRY,
// EUR_USD
// })
// @interface RateDef {
// }
// }
// Path: app/src/main/java/dynoapps/exchange_rates/util/RateUtils.java
import android.text.TextUtils;
import java.text.DecimalFormat;
import java.text.DecimalFormatSymbols;
import java.util.List;
import androidx.annotation.DrawableRes;
import androidx.annotation.Nullable;
import dynoapps.exchange_rates.App;
import dynoapps.exchange_rates.R;
import dynoapps.exchange_rates.model.rates.BaseRate;
import dynoapps.exchange_rates.model.rates.IRate;
package dynoapps.exchange_rates.util;
/**
* Created by erdemmac on 01/12/2016.
*/
public class RateUtils {
private static final Formatter formatter2 = new Formatter(2, 0);
private static final Formatter formatter5 = new Formatter(5, 2);
public static <T extends BaseRate> T getRate(List<T> rates, @IRate.RateDef int rateType) {
if (rates == null) return null;
for (T rate : rates) {
if (rate.getRateType() == rateType) {
return rate;
}
}
return null;
}
public static String valueToUI(Float val, @IRate.RateDef int rateType) {
if (val == null) return "";
String formatted = formatValue(val, rateType);
if (rateType == IRate.EUR_USD) {
return formatted;
} else if (rateType == IRate.ONS) { | return App.context().getString(R.string.placeholder_dollar, formatted); |
erdemolkun/instant-rates | app/src/main/java/dynoapps/exchange_rates/converters/BloombergConverter.java | // Path: app/src/main/java/dynoapps/exchange_rates/data/RatesHolder.java
// public class RatesHolder {
//
// private static final int MAX_RATES_COUNT = 10;
//
// private static RatesHolder instance;
// private SparseArray<List<RatesEvent>> rateEventsSparse;
//
// public static RatesHolder getInstance() {
// if (instance == null)
// instance = new RatesHolder();
// return instance;
// }
//
// public RatesEvent getLatestEvent(int source_type) {
// if (rateEventsSparse != null && rateEventsSparse.get(source_type, null) != null) {
// List<RatesEvent> events = rateEventsSparse.get(source_type);
// return events.get(events.size() - 1);
// }
// return null;
// }
//
// public <T extends BaseRate> void addRate(List<T> rates, long fetchTime, int type) {
// if (rateEventsSparse == null) {
// rateEventsSparse = new SparseArray<>();
// }
// RatesEvent ratesEvent = new RatesEvent<>(rates, type, fetchTime);
// List<RatesEvent> ratesEvents = rateEventsSparse.get(type);
// if (ratesEvents == null) ratesEvents = new ArrayList<>();
// ratesEvents.add(ratesEvent);
// if (ratesEvents.size() > MAX_RATES_COUNT) {
// ratesEvents.remove(0);
// }
// rateEventsSparse.put(type, ratesEvents);
// }
//
// public <T extends BaseRate> void addRate(List<T> rates, int type) {
// if (rateEventsSparse == null) {
// rateEventsSparse = new SparseArray<>();
// }
// RatesEvent ratesEvent = new RatesEvent<>(rates, type, System.currentTimeMillis());
// List<RatesEvent> ratesEvents = rateEventsSparse.get(type);
// if (ratesEvents == null) ratesEvents = new ArrayList<>();
// ratesEvents.add(ratesEvent);
// rateEventsSparse.put(type, ratesEvents);
// }
// }
//
// Path: app/src/main/java/dynoapps/exchange_rates/model/rates/BaseRate.java
// public abstract class BaseRate implements IConvertable, IRate {
//
// public String type;
//
// @RateDef
// protected int rateType;
//
// BaseRate() {
// }
//
// @Override
// public int getRateType() {
// return rateType;
// }
//
// public String getFormatted(float val) {
// return RateUtils.valueToUI(val, rateType);
// }
// }
//
// Path: app/src/main/java/dynoapps/exchange_rates/model/rates/BloombergRate.java
// public class BloombergRate extends AvgRate {
//
// @Override
// public void toRateType() {
// if (TextUtils.isEmpty(type)) rateType = UNKNOWN;
// int rateType = UNKNOWN;
// switch (type) {
// case "USDTRY Curncy":
// rateType = USD;
// break;
// case "EURTRY Curncy":
// rateType = EUR;
// break;
// case "EURUSD Curncy":
// rateType = EUR_USD;
// break;
// case "XAU Curncy":
// rateType = ONS;
// break;
// }
// this.rateType = rateType;
// }
//
// @Override
// public void setRealValues() {
// if (rateType == UNKNOWN) return;
// avg_val = avg_val.replace(".", "").replace(',', '.');
// val_real_avg = Float.parseFloat(avg_val);
// }
// }
//
// Path: app/src/main/java/dynoapps/exchange_rates/model/rates/EnparaRate.java
// public class EnparaRate extends BuySellRate {
//
// @Override
// public void toRateType() {
// int rateType = UNKNOWN;
// String plain_type = type.replace("\n", "");
// plain_type = plain_type.toLowerCase();
// if (plain_type.contains("parite")) {
// rateType = EUR_USD;
// } else if (plain_type.contains("usd")) {
// rateType = USD;
// } else if (plain_type.contains("eur")) {
// rateType = EUR;
// } else if (plain_type.contains("altın (gram)")) {
// rateType = ONS_TRY;
// }
// this.rateType = rateType;
// }
//
// @Override
// public void setRealValues() {
// String val = valueSell.replace(" TL", "").replace(",", ".").trim();
// valueSellReal = Float.valueOf(val);
//
// val = valueBuy.replace(" TL", "").replace(",", ".").trim();
// valueBuyReal = Float.valueOf(val);
// }
// }
| import android.provider.Telephony;
import org.jsoup.Jsoup;
import org.jsoup.nodes.Element;
import org.jsoup.nodes.TextNode;
import org.jsoup.select.Elements;
import java.io.IOException;
import java.lang.annotation.Annotation;
import java.lang.reflect.Type;
import java.util.ArrayList;
import java.util.List;
import androidx.annotation.NonNull;
import dynoapps.exchange_rates.data.RatesHolder;
import dynoapps.exchange_rates.model.rates.BaseRate;
import dynoapps.exchange_rates.model.rates.BloombergRate;
import dynoapps.exchange_rates.model.rates.EnparaRate;
import okhttp3.ResponseBody;
import retrofit2.Converter;
import retrofit2.Retrofit; | package dynoapps.exchange_rates.converters;
public class BloombergConverter implements Converter<ResponseBody, List<BaseRate>> {
private static final BloombergConverter INSTANCE = new BloombergConverter();
private static final String HOST = "https://www.bloomberght.com";
private BloombergConverter() {
}
@Override
public List<BaseRate> convert(@NonNull ResponseBody value) throws IOException {
ArrayList<BaseRate> rates = new ArrayList<>();
String responseBody = value.string();
final Elements shotElements = Jsoup.parse(responseBody, HOST).getElementsByClass("data-info");
for (Element element : shotElements) {
BaseRate rate = parseRate(element);
rates.add(rate);
}
return rates;
}
| // Path: app/src/main/java/dynoapps/exchange_rates/data/RatesHolder.java
// public class RatesHolder {
//
// private static final int MAX_RATES_COUNT = 10;
//
// private static RatesHolder instance;
// private SparseArray<List<RatesEvent>> rateEventsSparse;
//
// public static RatesHolder getInstance() {
// if (instance == null)
// instance = new RatesHolder();
// return instance;
// }
//
// public RatesEvent getLatestEvent(int source_type) {
// if (rateEventsSparse != null && rateEventsSparse.get(source_type, null) != null) {
// List<RatesEvent> events = rateEventsSparse.get(source_type);
// return events.get(events.size() - 1);
// }
// return null;
// }
//
// public <T extends BaseRate> void addRate(List<T> rates, long fetchTime, int type) {
// if (rateEventsSparse == null) {
// rateEventsSparse = new SparseArray<>();
// }
// RatesEvent ratesEvent = new RatesEvent<>(rates, type, fetchTime);
// List<RatesEvent> ratesEvents = rateEventsSparse.get(type);
// if (ratesEvents == null) ratesEvents = new ArrayList<>();
// ratesEvents.add(ratesEvent);
// if (ratesEvents.size() > MAX_RATES_COUNT) {
// ratesEvents.remove(0);
// }
// rateEventsSparse.put(type, ratesEvents);
// }
//
// public <T extends BaseRate> void addRate(List<T> rates, int type) {
// if (rateEventsSparse == null) {
// rateEventsSparse = new SparseArray<>();
// }
// RatesEvent ratesEvent = new RatesEvent<>(rates, type, System.currentTimeMillis());
// List<RatesEvent> ratesEvents = rateEventsSparse.get(type);
// if (ratesEvents == null) ratesEvents = new ArrayList<>();
// ratesEvents.add(ratesEvent);
// rateEventsSparse.put(type, ratesEvents);
// }
// }
//
// Path: app/src/main/java/dynoapps/exchange_rates/model/rates/BaseRate.java
// public abstract class BaseRate implements IConvertable, IRate {
//
// public String type;
//
// @RateDef
// protected int rateType;
//
// BaseRate() {
// }
//
// @Override
// public int getRateType() {
// return rateType;
// }
//
// public String getFormatted(float val) {
// return RateUtils.valueToUI(val, rateType);
// }
// }
//
// Path: app/src/main/java/dynoapps/exchange_rates/model/rates/BloombergRate.java
// public class BloombergRate extends AvgRate {
//
// @Override
// public void toRateType() {
// if (TextUtils.isEmpty(type)) rateType = UNKNOWN;
// int rateType = UNKNOWN;
// switch (type) {
// case "USDTRY Curncy":
// rateType = USD;
// break;
// case "EURTRY Curncy":
// rateType = EUR;
// break;
// case "EURUSD Curncy":
// rateType = EUR_USD;
// break;
// case "XAU Curncy":
// rateType = ONS;
// break;
// }
// this.rateType = rateType;
// }
//
// @Override
// public void setRealValues() {
// if (rateType == UNKNOWN) return;
// avg_val = avg_val.replace(".", "").replace(',', '.');
// val_real_avg = Float.parseFloat(avg_val);
// }
// }
//
// Path: app/src/main/java/dynoapps/exchange_rates/model/rates/EnparaRate.java
// public class EnparaRate extends BuySellRate {
//
// @Override
// public void toRateType() {
// int rateType = UNKNOWN;
// String plain_type = type.replace("\n", "");
// plain_type = plain_type.toLowerCase();
// if (plain_type.contains("parite")) {
// rateType = EUR_USD;
// } else if (plain_type.contains("usd")) {
// rateType = USD;
// } else if (plain_type.contains("eur")) {
// rateType = EUR;
// } else if (plain_type.contains("altın (gram)")) {
// rateType = ONS_TRY;
// }
// this.rateType = rateType;
// }
//
// @Override
// public void setRealValues() {
// String val = valueSell.replace(" TL", "").replace(",", ".").trim();
// valueSellReal = Float.valueOf(val);
//
// val = valueBuy.replace(" TL", "").replace(",", ".").trim();
// valueBuyReal = Float.valueOf(val);
// }
// }
// Path: app/src/main/java/dynoapps/exchange_rates/converters/BloombergConverter.java
import android.provider.Telephony;
import org.jsoup.Jsoup;
import org.jsoup.nodes.Element;
import org.jsoup.nodes.TextNode;
import org.jsoup.select.Elements;
import java.io.IOException;
import java.lang.annotation.Annotation;
import java.lang.reflect.Type;
import java.util.ArrayList;
import java.util.List;
import androidx.annotation.NonNull;
import dynoapps.exchange_rates.data.RatesHolder;
import dynoapps.exchange_rates.model.rates.BaseRate;
import dynoapps.exchange_rates.model.rates.BloombergRate;
import dynoapps.exchange_rates.model.rates.EnparaRate;
import okhttp3.ResponseBody;
import retrofit2.Converter;
import retrofit2.Retrofit;
package dynoapps.exchange_rates.converters;
public class BloombergConverter implements Converter<ResponseBody, List<BaseRate>> {
private static final BloombergConverter INSTANCE = new BloombergConverter();
private static final String HOST = "https://www.bloomberght.com";
private BloombergConverter() {
}
@Override
public List<BaseRate> convert(@NonNull ResponseBody value) throws IOException {
ArrayList<BaseRate> rates = new ArrayList<>();
String responseBody = value.string();
final Elements shotElements = Jsoup.parse(responseBody, HOST).getElementsByClass("data-info");
for (Element element : shotElements) {
BaseRate rate = parseRate(element);
rates.add(rate);
}
return rates;
}
| private BloombergRate parseRate(Element element) { |
erdemolkun/instant-rates | app/src/main/java/dynoapps/exchange_rates/time/TimeInterval.java | // Path: app/src/main/java/dynoapps/exchange_rates/App.java
// public class App extends Application {
// private static App appInstance;
//
// public static App getInstance() {
// return appInstance;
// }
//
// @NonNull
// public static Context context() {
// return appInstance.getApplicationContext();
// }
//
// public AlarmsRepository provideAlarmsRepository() {
// return AlarmsRepository.getInstance(getApplicationContext());
// }
//
// @SuppressLint("CheckResult")
// @Override
// public void onCreate() {
// super.onCreate();
// appInstance = this;
//
// RxJavaPlugins.setErrorHandler(throwable -> L.e("App", throwable.getLocalizedMessage()));
// }
//
// /**
// * Enum used to identify the tracker that needs to be used for tracking.
// * <p/>
// * A single tracker is usually enough for most purposes. In case you do need multiple trackers,
// * storing them all in Application object helps ensure that they are created only once per
// * application instance.
// */
// public enum TrackerName {
// APP_TRACKER, // Tracker used only in this app.
// GLOBAL_TRACKER, // Tracker used by all the apps from a company. eg: roll-up tracking.
// }
//
//
// }
| import java.util.concurrent.TimeUnit;
import androidx.annotation.NonNull;
import dynoapps.exchange_rates.App;
import dynoapps.exchange_rates.R; | package dynoapps.exchange_rates.time;
/**
* Created by erdemmac on 14/12/2016.
*/
public class TimeInterval {
private TimeUnit timeUnit;
private int value;
TimeInterval(int value, TimeUnit timeUnit) {
this.value = value;
this.timeUnit = timeUnit;
}
public long to(TimeUnit unit) {
return unit.convert(value, timeUnit);
}
@Override
@NonNull
public String toString() {
if (timeUnit == TimeUnit.SECONDS) { | // Path: app/src/main/java/dynoapps/exchange_rates/App.java
// public class App extends Application {
// private static App appInstance;
//
// public static App getInstance() {
// return appInstance;
// }
//
// @NonNull
// public static Context context() {
// return appInstance.getApplicationContext();
// }
//
// public AlarmsRepository provideAlarmsRepository() {
// return AlarmsRepository.getInstance(getApplicationContext());
// }
//
// @SuppressLint("CheckResult")
// @Override
// public void onCreate() {
// super.onCreate();
// appInstance = this;
//
// RxJavaPlugins.setErrorHandler(throwable -> L.e("App", throwable.getLocalizedMessage()));
// }
//
// /**
// * Enum used to identify the tracker that needs to be used for tracking.
// * <p/>
// * A single tracker is usually enough for most purposes. In case you do need multiple trackers,
// * storing them all in Application object helps ensure that they are created only once per
// * application instance.
// */
// public enum TrackerName {
// APP_TRACKER, // Tracker used only in this app.
// GLOBAL_TRACKER, // Tracker used by all the apps from a company. eg: roll-up tracking.
// }
//
//
// }
// Path: app/src/main/java/dynoapps/exchange_rates/time/TimeInterval.java
import java.util.concurrent.TimeUnit;
import androidx.annotation.NonNull;
import dynoapps.exchange_rates.App;
import dynoapps.exchange_rates.R;
package dynoapps.exchange_rates.time;
/**
* Created by erdemmac on 14/12/2016.
*/
public class TimeInterval {
private TimeUnit timeUnit;
private int value;
TimeInterval(int value, TimeUnit timeUnit) {
this.value = value;
this.timeUnit = timeUnit;
}
public long to(TimeUnit unit) {
return unit.convert(value, timeUnit);
}
@Override
@NonNull
public String toString() {
if (timeUnit == TimeUnit.SECONDS) { | return App.context().getResources().getQuantityString(R.plurals.sec_short, value, value); |
erdemolkun/instant-rates | app/src/main/java/dynoapps/exchange_rates/data/RatesHolder.java | // Path: app/src/main/java/dynoapps/exchange_rates/event/RatesEvent.java
// public class RatesEvent<T extends BaseRate> {
//
// public int sourceType;
// public long fetchTime;
// public List<T> rates;
//
// public RatesEvent(List<T> rates, int sourceType, long fetchTime) {
// this.rates = rates;
// this.sourceType = sourceType;
// this.fetchTime = fetchTime;
// }
// }
//
// Path: app/src/main/java/dynoapps/exchange_rates/model/rates/BaseRate.java
// public abstract class BaseRate implements IConvertable, IRate {
//
// public String type;
//
// @RateDef
// protected int rateType;
//
// BaseRate() {
// }
//
// @Override
// public int getRateType() {
// return rateType;
// }
//
// public String getFormatted(float val) {
// return RateUtils.valueToUI(val, rateType);
// }
// }
| import android.util.SparseArray;
import java.util.ArrayList;
import java.util.List;
import dynoapps.exchange_rates.event.RatesEvent;
import dynoapps.exchange_rates.model.rates.BaseRate; | package dynoapps.exchange_rates.data;
/**
* Copyright 2016 Erdem OLKUN
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except
* in compliance with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software distributed under the License
* is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express
* or implied. See the License for the specific language governing permissions and limitations under
* the License.
*/
public class RatesHolder {
private static final int MAX_RATES_COUNT = 10;
private static RatesHolder instance; | // Path: app/src/main/java/dynoapps/exchange_rates/event/RatesEvent.java
// public class RatesEvent<T extends BaseRate> {
//
// public int sourceType;
// public long fetchTime;
// public List<T> rates;
//
// public RatesEvent(List<T> rates, int sourceType, long fetchTime) {
// this.rates = rates;
// this.sourceType = sourceType;
// this.fetchTime = fetchTime;
// }
// }
//
// Path: app/src/main/java/dynoapps/exchange_rates/model/rates/BaseRate.java
// public abstract class BaseRate implements IConvertable, IRate {
//
// public String type;
//
// @RateDef
// protected int rateType;
//
// BaseRate() {
// }
//
// @Override
// public int getRateType() {
// return rateType;
// }
//
// public String getFormatted(float val) {
// return RateUtils.valueToUI(val, rateType);
// }
// }
// Path: app/src/main/java/dynoapps/exchange_rates/data/RatesHolder.java
import android.util.SparseArray;
import java.util.ArrayList;
import java.util.List;
import dynoapps.exchange_rates.event.RatesEvent;
import dynoapps.exchange_rates.model.rates.BaseRate;
package dynoapps.exchange_rates.data;
/**
* Copyright 2016 Erdem OLKUN
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except
* in compliance with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software distributed under the License
* is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express
* or implied. See the License for the specific language governing permissions and limitations under
* the License.
*/
public class RatesHolder {
private static final int MAX_RATES_COUNT = 10;
private static RatesHolder instance; | private SparseArray<List<RatesEvent>> rateEventsSparse; |
erdemolkun/instant-rates | app/src/main/java/dynoapps/exchange_rates/data/RatesHolder.java | // Path: app/src/main/java/dynoapps/exchange_rates/event/RatesEvent.java
// public class RatesEvent<T extends BaseRate> {
//
// public int sourceType;
// public long fetchTime;
// public List<T> rates;
//
// public RatesEvent(List<T> rates, int sourceType, long fetchTime) {
// this.rates = rates;
// this.sourceType = sourceType;
// this.fetchTime = fetchTime;
// }
// }
//
// Path: app/src/main/java/dynoapps/exchange_rates/model/rates/BaseRate.java
// public abstract class BaseRate implements IConvertable, IRate {
//
// public String type;
//
// @RateDef
// protected int rateType;
//
// BaseRate() {
// }
//
// @Override
// public int getRateType() {
// return rateType;
// }
//
// public String getFormatted(float val) {
// return RateUtils.valueToUI(val, rateType);
// }
// }
| import android.util.SparseArray;
import java.util.ArrayList;
import java.util.List;
import dynoapps.exchange_rates.event.RatesEvent;
import dynoapps.exchange_rates.model.rates.BaseRate; | package dynoapps.exchange_rates.data;
/**
* Copyright 2016 Erdem OLKUN
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except
* in compliance with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software distributed under the License
* is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express
* or implied. See the License for the specific language governing permissions and limitations under
* the License.
*/
public class RatesHolder {
private static final int MAX_RATES_COUNT = 10;
private static RatesHolder instance;
private SparseArray<List<RatesEvent>> rateEventsSparse;
public static RatesHolder getInstance() {
if (instance == null)
instance = new RatesHolder();
return instance;
}
public RatesEvent getLatestEvent(int source_type) {
if (rateEventsSparse != null && rateEventsSparse.get(source_type, null) != null) {
List<RatesEvent> events = rateEventsSparse.get(source_type);
return events.get(events.size() - 1);
}
return null;
}
| // Path: app/src/main/java/dynoapps/exchange_rates/event/RatesEvent.java
// public class RatesEvent<T extends BaseRate> {
//
// public int sourceType;
// public long fetchTime;
// public List<T> rates;
//
// public RatesEvent(List<T> rates, int sourceType, long fetchTime) {
// this.rates = rates;
// this.sourceType = sourceType;
// this.fetchTime = fetchTime;
// }
// }
//
// Path: app/src/main/java/dynoapps/exchange_rates/model/rates/BaseRate.java
// public abstract class BaseRate implements IConvertable, IRate {
//
// public String type;
//
// @RateDef
// protected int rateType;
//
// BaseRate() {
// }
//
// @Override
// public int getRateType() {
// return rateType;
// }
//
// public String getFormatted(float val) {
// return RateUtils.valueToUI(val, rateType);
// }
// }
// Path: app/src/main/java/dynoapps/exchange_rates/data/RatesHolder.java
import android.util.SparseArray;
import java.util.ArrayList;
import java.util.List;
import dynoapps.exchange_rates.event.RatesEvent;
import dynoapps.exchange_rates.model.rates.BaseRate;
package dynoapps.exchange_rates.data;
/**
* Copyright 2016 Erdem OLKUN
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except
* in compliance with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software distributed under the License
* is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express
* or implied. See the License for the specific language governing permissions and limitations under
* the License.
*/
public class RatesHolder {
private static final int MAX_RATES_COUNT = 10;
private static RatesHolder instance;
private SparseArray<List<RatesEvent>> rateEventsSparse;
public static RatesHolder getInstance() {
if (instance == null)
instance = new RatesHolder();
return instance;
}
public RatesEvent getLatestEvent(int source_type) {
if (rateEventsSparse != null && rateEventsSparse.get(source_type, null) != null) {
List<RatesEvent> events = rateEventsSparse.get(source_type);
return events.get(events.size() - 1);
}
return null;
}
| public <T extends BaseRate> void addRate(List<T> rates, long fetchTime, int type) { |
erdemolkun/instant-rates | app/src/main/java/dynoapps/exchange_rates/network/DolarTlKurService.java | // Path: app/src/main/java/dynoapps/exchange_rates/model/rates/DolarTlKurRate.java
// public class DolarTlKurRate extends AvgRate {
//
// @Override
// public void toRateType() {
// if (TextUtils.isEmpty(type)) rateType = UNKNOWN;
// int rateType = UNKNOWN;
// switch (type) {
// case "USDTRY":
// rateType = USD;
// break;
// case "EURTRY":
// rateType = EUR;
// break;
// case "EURUSD":
// rateType = EUR_USD;
// break;
// case "XAUUSD":
// rateType = ONS;
// break;
// }
// this.rateType = rateType;
// }
//
// @Override
// public void setRealValues() {
// if (rateType == UNKNOWN) return;
// String val = avg_val.replace("'", "").replace("$", "").trim();
// val_real_avg = Float.parseFloat(val);
// }
//
// @Override
// @NonNull
// public String toString() {
// return type.split("_")[0] + " -> : " + val_real_avg;
// }
//
// }
| import java.util.List;
import dynoapps.exchange_rates.model.rates.DolarTlKurRate;
import io.reactivex.Observable;
import retrofit2.http.GET;
import retrofit2.http.Headers;
import retrofit2.http.Query; | package dynoapps.exchange_rates.network;
/**
* Created by erdemmac on 24/10/2016.
*/
public interface DolarTlKurService {
@Headers({
"Content-Type:text/html"
})
@GET("/refresh/header/viewHeader.php") | // Path: app/src/main/java/dynoapps/exchange_rates/model/rates/DolarTlKurRate.java
// public class DolarTlKurRate extends AvgRate {
//
// @Override
// public void toRateType() {
// if (TextUtils.isEmpty(type)) rateType = UNKNOWN;
// int rateType = UNKNOWN;
// switch (type) {
// case "USDTRY":
// rateType = USD;
// break;
// case "EURTRY":
// rateType = EUR;
// break;
// case "EURUSD":
// rateType = EUR_USD;
// break;
// case "XAUUSD":
// rateType = ONS;
// break;
// }
// this.rateType = rateType;
// }
//
// @Override
// public void setRealValues() {
// if (rateType == UNKNOWN) return;
// String val = avg_val.replace("'", "").replace("$", "").trim();
// val_real_avg = Float.parseFloat(val);
// }
//
// @Override
// @NonNull
// public String toString() {
// return type.split("_")[0] + " -> : " + val_real_avg;
// }
//
// }
// Path: app/src/main/java/dynoapps/exchange_rates/network/DolarTlKurService.java
import java.util.List;
import dynoapps.exchange_rates.model.rates.DolarTlKurRate;
import io.reactivex.Observable;
import retrofit2.http.GET;
import retrofit2.http.Headers;
import retrofit2.http.Query;
package dynoapps.exchange_rates.network;
/**
* Created by erdemmac on 24/10/2016.
*/
public interface DolarTlKurService {
@Headers({
"Content-Type:text/html"
})
@GET("/refresh/header/viewHeader.php") | Observable<List<DolarTlKurRate>> rates(@Query("_") String time); |
erdemolkun/instant-rates | app/src/main/java/dynoapps/exchange_rates/converters/ParagarantiConverter.java | // Path: app/src/main/java/dynoapps/exchange_rates/model/rates/BaseRate.java
// public abstract class BaseRate implements IConvertable, IRate {
//
// public String type;
//
// @RateDef
// protected int rateType;
//
// BaseRate() {
// }
//
// @Override
// public int getRateType() {
// return rateType;
// }
//
// public String getFormatted(float val) {
// return RateUtils.valueToUI(val, rateType);
// }
// }
//
// Path: app/src/main/java/dynoapps/exchange_rates/model/rates/ParaGarantiRate.java
// public class ParaGarantiRate extends AvgRate {
//
// public String symbol;
// public String last;
//
// @Override
// public void toRateType() {
// if (TextUtils.isEmpty(symbol)) rateType = UNKNOWN;
// int rateType = UNKNOWN;
// switch (symbol) {
// case "KUSD":
// rateType = USD;
// break;
// case "KEUR":
// rateType = EUR;
// break;
// case "EUR":
// rateType = EUR_USD;
// break;
// }
// this.rateType = rateType;
// }
//
// @Override
// public void setRealValues() {
// if (rateType == UNKNOWN) return;
// last = last.replace(',', '.');
// String val = last.replace("'", "").replace("$", "").trim();
// Float real_val = RateUtils.toFloat(val);
// val_real_avg = real_val != null ? real_val : 0.0f;
// }
//
// @Override
// @NonNull
// public String toString() {
// return "SYMBOL : " + symbol + " Value : " + last;
// }
//
// }
//
// Path: app/src/main/java/dynoapps/exchange_rates/util/L.java
// public class L {
//
// private static final String TAG = "ExchangeRates";
//
// private static final String LOG_PREFIX = "";
// private static final int LOG_PREFIX_LENGTH = LOG_PREFIX.length();
// private static final int MAX_LOG_TAG_LENGTH = 23;
// private static final int MAX_CHAR_LENGTH = 320;
//
// public static String makeLogTag(String str) {
// if (str.length() > MAX_LOG_TAG_LENGTH - LOG_PREFIX_LENGTH) {
// return LOG_PREFIX + str.substring(0, MAX_LOG_TAG_LENGTH - LOG_PREFIX_LENGTH - 1);
// }
//
// return LOG_PREFIX + str;
// }
//
// public static void e(String tag, String msg) {
// Log.e(makeLogTag(tag), msg);
// }
//
// public static void e(String tag, Throwable th) {
// Log.e(tag, "", th);
// }
//
// public static void i(String tag, String msg) {
// Log.i(makeLogTag(tag), msg);
// }
//
// public static void ex(Exception ex) {
// Log.e(TAG, "", ex);
// }
//
// public static void ex(Exception ex, String message) {
// Log.e(TAG, message, ex);
// }
// }
| import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;
import org.w3c.dom.Text;
import org.xml.sax.SAXException;
import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.lang.annotation.Annotation;
import java.lang.reflect.Type;
import java.nio.charset.StandardCharsets;
import java.util.ArrayList;
import java.util.List;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;
import androidx.annotation.NonNull;
import dynoapps.exchange_rates.model.rates.BaseRate;
import dynoapps.exchange_rates.model.rates.ParaGarantiRate;
import dynoapps.exchange_rates.util.L;
import okhttp3.ResponseBody;
import retrofit2.Converter;
import retrofit2.Retrofit; | package dynoapps.exchange_rates.converters;
/**
* Created by erdemmac on 24/11/2016.
*/
public class ParagarantiConverter implements Converter<ResponseBody, List<BaseRate>> {
private static final ParagarantiConverter INSTANCE = new ParagarantiConverter();
private ParagarantiConverter() {
}
/**
* Sample response body
* </p>
**/
@Override
public List<BaseRate> convert(@NonNull ResponseBody value) throws IOException {
ArrayList<BaseRate> rates = new ArrayList<>();
String responseBody = value.string();
InputStream inputStream = new ByteArrayInputStream(responseBody.getBytes(StandardCharsets.UTF_8));
try {
Document d = DocumentBuilderFactory.newInstance().newDocumentBuilder().parse(inputStream);
NodeList nodeList = d.getChildNodes().item(1).getChildNodes();
for (int i = 0; i < nodeList.getLength(); i++) {
Node node = nodeList.item(i);
if (node instanceof Element) {
Element element = (Element) node;
if (element.getTagName().equals("STOCK")) {
NodeList stockChildNodes = node.getChildNodes(); | // Path: app/src/main/java/dynoapps/exchange_rates/model/rates/BaseRate.java
// public abstract class BaseRate implements IConvertable, IRate {
//
// public String type;
//
// @RateDef
// protected int rateType;
//
// BaseRate() {
// }
//
// @Override
// public int getRateType() {
// return rateType;
// }
//
// public String getFormatted(float val) {
// return RateUtils.valueToUI(val, rateType);
// }
// }
//
// Path: app/src/main/java/dynoapps/exchange_rates/model/rates/ParaGarantiRate.java
// public class ParaGarantiRate extends AvgRate {
//
// public String symbol;
// public String last;
//
// @Override
// public void toRateType() {
// if (TextUtils.isEmpty(symbol)) rateType = UNKNOWN;
// int rateType = UNKNOWN;
// switch (symbol) {
// case "KUSD":
// rateType = USD;
// break;
// case "KEUR":
// rateType = EUR;
// break;
// case "EUR":
// rateType = EUR_USD;
// break;
// }
// this.rateType = rateType;
// }
//
// @Override
// public void setRealValues() {
// if (rateType == UNKNOWN) return;
// last = last.replace(',', '.');
// String val = last.replace("'", "").replace("$", "").trim();
// Float real_val = RateUtils.toFloat(val);
// val_real_avg = real_val != null ? real_val : 0.0f;
// }
//
// @Override
// @NonNull
// public String toString() {
// return "SYMBOL : " + symbol + " Value : " + last;
// }
//
// }
//
// Path: app/src/main/java/dynoapps/exchange_rates/util/L.java
// public class L {
//
// private static final String TAG = "ExchangeRates";
//
// private static final String LOG_PREFIX = "";
// private static final int LOG_PREFIX_LENGTH = LOG_PREFIX.length();
// private static final int MAX_LOG_TAG_LENGTH = 23;
// private static final int MAX_CHAR_LENGTH = 320;
//
// public static String makeLogTag(String str) {
// if (str.length() > MAX_LOG_TAG_LENGTH - LOG_PREFIX_LENGTH) {
// return LOG_PREFIX + str.substring(0, MAX_LOG_TAG_LENGTH - LOG_PREFIX_LENGTH - 1);
// }
//
// return LOG_PREFIX + str;
// }
//
// public static void e(String tag, String msg) {
// Log.e(makeLogTag(tag), msg);
// }
//
// public static void e(String tag, Throwable th) {
// Log.e(tag, "", th);
// }
//
// public static void i(String tag, String msg) {
// Log.i(makeLogTag(tag), msg);
// }
//
// public static void ex(Exception ex) {
// Log.e(TAG, "", ex);
// }
//
// public static void ex(Exception ex, String message) {
// Log.e(TAG, message, ex);
// }
// }
// Path: app/src/main/java/dynoapps/exchange_rates/converters/ParagarantiConverter.java
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;
import org.w3c.dom.Text;
import org.xml.sax.SAXException;
import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.lang.annotation.Annotation;
import java.lang.reflect.Type;
import java.nio.charset.StandardCharsets;
import java.util.ArrayList;
import java.util.List;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;
import androidx.annotation.NonNull;
import dynoapps.exchange_rates.model.rates.BaseRate;
import dynoapps.exchange_rates.model.rates.ParaGarantiRate;
import dynoapps.exchange_rates.util.L;
import okhttp3.ResponseBody;
import retrofit2.Converter;
import retrofit2.Retrofit;
package dynoapps.exchange_rates.converters;
/**
* Created by erdemmac on 24/11/2016.
*/
public class ParagarantiConverter implements Converter<ResponseBody, List<BaseRate>> {
private static final ParagarantiConverter INSTANCE = new ParagarantiConverter();
private ParagarantiConverter() {
}
/**
* Sample response body
* </p>
**/
@Override
public List<BaseRate> convert(@NonNull ResponseBody value) throws IOException {
ArrayList<BaseRate> rates = new ArrayList<>();
String responseBody = value.string();
InputStream inputStream = new ByteArrayInputStream(responseBody.getBytes(StandardCharsets.UTF_8));
try {
Document d = DocumentBuilderFactory.newInstance().newDocumentBuilder().parse(inputStream);
NodeList nodeList = d.getChildNodes().item(1).getChildNodes();
for (int i = 0; i < nodeList.getLength(); i++) {
Node node = nodeList.item(i);
if (node instanceof Element) {
Element element = (Element) node;
if (element.getTagName().equals("STOCK")) {
NodeList stockChildNodes = node.getChildNodes(); | ParaGarantiRate rate = new ParaGarantiRate(); |
erdemolkun/instant-rates | app/src/main/java/dynoapps/exchange_rates/util/AppUtils.java | // Path: app/src/main/java/dynoapps/exchange_rates/App.java
// public class App extends Application {
// private static App appInstance;
//
// public static App getInstance() {
// return appInstance;
// }
//
// @NonNull
// public static Context context() {
// return appInstance.getApplicationContext();
// }
//
// public AlarmsRepository provideAlarmsRepository() {
// return AlarmsRepository.getInstance(getApplicationContext());
// }
//
// @SuppressLint("CheckResult")
// @Override
// public void onCreate() {
// super.onCreate();
// appInstance = this;
//
// RxJavaPlugins.setErrorHandler(throwable -> L.e("App", throwable.getLocalizedMessage()));
// }
//
// /**
// * Enum used to identify the tracker that needs to be used for tracking.
// * <p/>
// * A single tracker is usually enough for most purposes. In case you do need multiple trackers,
// * storing them all in Application object helps ensure that they are created only once per
// * application instance.
// */
// public enum TrackerName {
// APP_TRACKER, // Tracker used only in this app.
// GLOBAL_TRACKER, // Tracker used by all the apps from a company. eg: roll-up tracking.
// }
//
//
// }
| import android.content.Context;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.text.TextUtils;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import dynoapps.exchange_rates.App; | package dynoapps.exchange_rates.util;
/**
* Created by erdemmac on 26/11/15.
*/
public class AppUtils {
public static PackageInfo getPackageInfo(Context context) {
try {
return context.getPackageManager().getPackageInfo(context.getPackageName(), 0);
} catch (PackageManager.NameNotFoundException e) {
// Should not happen.
throw new RuntimeException("Could not get package name: " + e);
}
}
public static String getAppVersion() { | // Path: app/src/main/java/dynoapps/exchange_rates/App.java
// public class App extends Application {
// private static App appInstance;
//
// public static App getInstance() {
// return appInstance;
// }
//
// @NonNull
// public static Context context() {
// return appInstance.getApplicationContext();
// }
//
// public AlarmsRepository provideAlarmsRepository() {
// return AlarmsRepository.getInstance(getApplicationContext());
// }
//
// @SuppressLint("CheckResult")
// @Override
// public void onCreate() {
// super.onCreate();
// appInstance = this;
//
// RxJavaPlugins.setErrorHandler(throwable -> L.e("App", throwable.getLocalizedMessage()));
// }
//
// /**
// * Enum used to identify the tracker that needs to be used for tracking.
// * <p/>
// * A single tracker is usually enough for most purposes. In case you do need multiple trackers,
// * storing them all in Application object helps ensure that they are created only once per
// * application instance.
// */
// public enum TrackerName {
// APP_TRACKER, // Tracker used only in this app.
// GLOBAL_TRACKER, // Tracker used by all the apps from a company. eg: roll-up tracking.
// }
//
//
// }
// Path: app/src/main/java/dynoapps/exchange_rates/util/AppUtils.java
import android.content.Context;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.text.TextUtils;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import dynoapps.exchange_rates.App;
package dynoapps.exchange_rates.util;
/**
* Created by erdemmac on 26/11/15.
*/
public class AppUtils {
public static PackageInfo getPackageInfo(Context context) {
try {
return context.getPackageManager().getPackageInfo(context.getPackageName(), 0);
} catch (PackageManager.NameNotFoundException e) {
// Should not happen.
throw new RuntimeException("Could not get package name: " + e);
}
}
public static String getAppVersion() { | Context context = App.context(); |
erdemolkun/instant-rates | app/src/main/java/dynoapps/exchange_rates/service/ServiceStopActionReceiver.java | // Path: app/src/main/java/dynoapps/exchange_rates/util/L.java
// public class L {
//
// private static final String TAG = "ExchangeRates";
//
// private static final String LOG_PREFIX = "";
// private static final int LOG_PREFIX_LENGTH = LOG_PREFIX.length();
// private static final int MAX_LOG_TAG_LENGTH = 23;
// private static final int MAX_CHAR_LENGTH = 320;
//
// public static String makeLogTag(String str) {
// if (str.length() > MAX_LOG_TAG_LENGTH - LOG_PREFIX_LENGTH) {
// return LOG_PREFIX + str.substring(0, MAX_LOG_TAG_LENGTH - LOG_PREFIX_LENGTH - 1);
// }
//
// return LOG_PREFIX + str;
// }
//
// public static void e(String tag, String msg) {
// Log.e(makeLogTag(tag), msg);
// }
//
// public static void e(String tag, Throwable th) {
// Log.e(tag, "", th);
// }
//
// public static void i(String tag, String msg) {
// Log.i(makeLogTag(tag), msg);
// }
//
// public static void ex(Exception ex) {
// Log.e(TAG, "", ex);
// }
//
// public static void ex(Exception ex, String message) {
// Log.e(TAG, message, ex);
// }
// }
| import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import dynoapps.exchange_rates.util.L;
import io.reactivex.subjects.PublishSubject; | package dynoapps.exchange_rates.service;
public class ServiceStopActionReceiver extends BroadcastReceiver {
private static final PublishSubject<Boolean> stopSubject = PublishSubject.create();
public static PublishSubject<Boolean> getStopSubject() {
return stopSubject;
}
@Override
public void onReceive(Context context, Intent intent) {
stopSubject.onNext(true);
try {
context.stopService(new Intent(context, RatePollingService.class));
} catch (Exception e) { | // Path: app/src/main/java/dynoapps/exchange_rates/util/L.java
// public class L {
//
// private static final String TAG = "ExchangeRates";
//
// private static final String LOG_PREFIX = "";
// private static final int LOG_PREFIX_LENGTH = LOG_PREFIX.length();
// private static final int MAX_LOG_TAG_LENGTH = 23;
// private static final int MAX_CHAR_LENGTH = 320;
//
// public static String makeLogTag(String str) {
// if (str.length() > MAX_LOG_TAG_LENGTH - LOG_PREFIX_LENGTH) {
// return LOG_PREFIX + str.substring(0, MAX_LOG_TAG_LENGTH - LOG_PREFIX_LENGTH - 1);
// }
//
// return LOG_PREFIX + str;
// }
//
// public static void e(String tag, String msg) {
// Log.e(makeLogTag(tag), msg);
// }
//
// public static void e(String tag, Throwable th) {
// Log.e(tag, "", th);
// }
//
// public static void i(String tag, String msg) {
// Log.i(makeLogTag(tag), msg);
// }
//
// public static void ex(Exception ex) {
// Log.e(TAG, "", ex);
// }
//
// public static void ex(Exception ex, String message) {
// Log.e(TAG, message, ex);
// }
// }
// Path: app/src/main/java/dynoapps/exchange_rates/service/ServiceStopActionReceiver.java
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import dynoapps.exchange_rates.util.L;
import io.reactivex.subjects.PublishSubject;
package dynoapps.exchange_rates.service;
public class ServiceStopActionReceiver extends BroadcastReceiver {
private static final PublishSubject<Boolean> stopSubject = PublishSubject.create();
public static PublishSubject<Boolean> getStopSubject() {
return stopSubject;
}
@Override
public void onReceive(Context context, Intent intent) {
stopSubject.onNext(true);
try {
context.stopService(new Intent(context, RatePollingService.class));
} catch (Exception e) { | L.ex(e, "ServiceStopActionReceiver"); |
erdemolkun/instant-rates | app/src/main/java/dynoapps/exchange_rates/model/rates/ParaGarantiRate.java | // Path: app/src/main/java/dynoapps/exchange_rates/util/RateUtils.java
// public class RateUtils {
// private static final Formatter formatter2 = new Formatter(2, 0);
// private static final Formatter formatter5 = new Formatter(5, 2);
//
// public static <T extends BaseRate> T getRate(List<T> rates, @IRate.RateDef int rateType) {
// if (rates == null) return null;
// for (T rate : rates) {
// if (rate.getRateType() == rateType) {
// return rate;
// }
// }
// return null;
// }
//
// public static String valueToUI(Float val, @IRate.RateDef int rateType) {
// if (val == null) return "";
// String formatted = formatValue(val, rateType);
// if (rateType == IRate.EUR_USD) {
// return formatted;
// } else if (rateType == IRate.ONS) {
// return App.context().getString(R.string.placeholder_dollar, formatted);
// } else {
// return App.context().getString(R.string.placeholder_tl, formatted);
// }
// }
//
// public static String formatValue(float val, int rateType) {
// if (rateType == IRate.ONS || rateType == IRate.ONS_TRY) {
// return formatter2.format(val);
// } else {
// return formatter5.format(val);
// }
// }
//
// public static String rateName(int rate_type) {
// if (rate_type == IRate.EUR) {
// return "EUR"; // todo refactor with side menu names.
// } else if (rate_type == IRate.USD) {
// return "USD";
// } else if (rate_type == IRate.EUR_USD) {
// return "EUR_USD";
// } else if (rate_type == IRate.ONS) {
// return "ONS";
// }
// return "";
// }
//
// public static
// @DrawableRes
// int getRateIcon(int rateType) {
// if (rateType == IRate.EUR) {
// return R.drawable.ic_euro;
// } else if (rateType == IRate.ONS) {
// return R.drawable.ic_gold;
// } else if (rateType == IRate.USD) {
// return R.drawable.ic_dollar;
// } else if (rateType == IRate.EUR_USD) {
// return R.drawable.ic_exchange_eur_usd;
// }
// return -1;
// }
//
// @Nullable
// public static Float toFloat(String str) {
// if (TextUtils.isEmpty(str)) return null;
// str = str.trim();
//
// try {
// return Float.parseFloat(str);
// } catch (Exception e) {
// try {
// DecimalFormatSymbols symbols = new DecimalFormatSymbols();
// symbols.setDecimalSeparator(DecimalFormatSymbols.getInstance().getDecimalSeparator());
// symbols.setGroupingSeparator(DecimalFormatSymbols.getInstance().getGroupingSeparator());
// DecimalFormat format = new DecimalFormat("###,###,###,##0.#####");
// format.setDecimalFormatSymbols(symbols);
// return format.parse(str).floatValue();
// } catch (Exception ignored) {
//
// }
// }
// return null;
// }
// }
| import android.text.TextUtils;
import androidx.annotation.NonNull;
import dynoapps.exchange_rates.util.RateUtils; | package dynoapps.exchange_rates.model.rates;
/**
* Created by erdemmac on 24/11/2016.
*/
public class ParaGarantiRate extends AvgRate {
public String symbol;
public String last;
@Override
public void toRateType() {
if (TextUtils.isEmpty(symbol)) rateType = UNKNOWN;
int rateType = UNKNOWN;
switch (symbol) {
case "KUSD":
rateType = USD;
break;
case "KEUR":
rateType = EUR;
break;
case "EUR":
rateType = EUR_USD;
break;
}
this.rateType = rateType;
}
@Override
public void setRealValues() {
if (rateType == UNKNOWN) return;
last = last.replace(',', '.');
String val = last.replace("'", "").replace("$", "").trim(); | // Path: app/src/main/java/dynoapps/exchange_rates/util/RateUtils.java
// public class RateUtils {
// private static final Formatter formatter2 = new Formatter(2, 0);
// private static final Formatter formatter5 = new Formatter(5, 2);
//
// public static <T extends BaseRate> T getRate(List<T> rates, @IRate.RateDef int rateType) {
// if (rates == null) return null;
// for (T rate : rates) {
// if (rate.getRateType() == rateType) {
// return rate;
// }
// }
// return null;
// }
//
// public static String valueToUI(Float val, @IRate.RateDef int rateType) {
// if (val == null) return "";
// String formatted = formatValue(val, rateType);
// if (rateType == IRate.EUR_USD) {
// return formatted;
// } else if (rateType == IRate.ONS) {
// return App.context().getString(R.string.placeholder_dollar, formatted);
// } else {
// return App.context().getString(R.string.placeholder_tl, formatted);
// }
// }
//
// public static String formatValue(float val, int rateType) {
// if (rateType == IRate.ONS || rateType == IRate.ONS_TRY) {
// return formatter2.format(val);
// } else {
// return formatter5.format(val);
// }
// }
//
// public static String rateName(int rate_type) {
// if (rate_type == IRate.EUR) {
// return "EUR"; // todo refactor with side menu names.
// } else if (rate_type == IRate.USD) {
// return "USD";
// } else if (rate_type == IRate.EUR_USD) {
// return "EUR_USD";
// } else if (rate_type == IRate.ONS) {
// return "ONS";
// }
// return "";
// }
//
// public static
// @DrawableRes
// int getRateIcon(int rateType) {
// if (rateType == IRate.EUR) {
// return R.drawable.ic_euro;
// } else if (rateType == IRate.ONS) {
// return R.drawable.ic_gold;
// } else if (rateType == IRate.USD) {
// return R.drawable.ic_dollar;
// } else if (rateType == IRate.EUR_USD) {
// return R.drawable.ic_exchange_eur_usd;
// }
// return -1;
// }
//
// @Nullable
// public static Float toFloat(String str) {
// if (TextUtils.isEmpty(str)) return null;
// str = str.trim();
//
// try {
// return Float.parseFloat(str);
// } catch (Exception e) {
// try {
// DecimalFormatSymbols symbols = new DecimalFormatSymbols();
// symbols.setDecimalSeparator(DecimalFormatSymbols.getInstance().getDecimalSeparator());
// symbols.setGroupingSeparator(DecimalFormatSymbols.getInstance().getGroupingSeparator());
// DecimalFormat format = new DecimalFormat("###,###,###,##0.#####");
// format.setDecimalFormatSymbols(symbols);
// return format.parse(str).floatValue();
// } catch (Exception ignored) {
//
// }
// }
// return null;
// }
// }
// Path: app/src/main/java/dynoapps/exchange_rates/model/rates/ParaGarantiRate.java
import android.text.TextUtils;
import androidx.annotation.NonNull;
import dynoapps.exchange_rates.util.RateUtils;
package dynoapps.exchange_rates.model.rates;
/**
* Created by erdemmac on 24/11/2016.
*/
public class ParaGarantiRate extends AvgRate {
public String symbol;
public String last;
@Override
public void toRateType() {
if (TextUtils.isEmpty(symbol)) rateType = UNKNOWN;
int rateType = UNKNOWN;
switch (symbol) {
case "KUSD":
rateType = USD;
break;
case "KEUR":
rateType = EUR;
break;
case "EUR":
rateType = EUR_USD;
break;
}
this.rateType = rateType;
}
@Override
public void setRealValues() {
if (rateType == UNKNOWN) return;
last = last.replace(',', '.');
String val = last.replace("'", "").replace("$", "").trim(); | Float real_val = RateUtils.toFloat(val); |
erdemolkun/instant-rates | app/src/main/java/dynoapps/exchange_rates/network/BigparaService.java | // Path: app/src/main/java/dynoapps/exchange_rates/model/rates/BigparaRate.java
// public class BigparaRate extends BuySellRate {
//
// @Override
// public void toRateType() {
// int rateType = UNKNOWN;
// String plain_type = type;
// plain_type = plain_type.toLowerCase();
// if (plain_type.contains("dolar")) {
// rateType = USD;
// } else if (plain_type.contains("euro")) {
// rateType = EUR;
// } else if (plain_type.contains("altın")) {
// rateType = ONS_TRY;
// } else if (plain_type.contains("parite")) {
// rateType = EUR_USD;
// }
// this.rateType = rateType;
// }
// }
| import java.util.List;
import dynoapps.exchange_rates.model.rates.BigparaRate;
import io.reactivex.Observable;
import retrofit2.http.GET;
import retrofit2.http.Headers; | package dynoapps.exchange_rates.network;
/**
* Created by erdemmac on 25/11/2016.
*/
public interface BigparaService {
@Headers({
"Content-Type:text/html; charset=utf-8"
})
@GET("doviz/dolar/") | // Path: app/src/main/java/dynoapps/exchange_rates/model/rates/BigparaRate.java
// public class BigparaRate extends BuySellRate {
//
// @Override
// public void toRateType() {
// int rateType = UNKNOWN;
// String plain_type = type;
// plain_type = plain_type.toLowerCase();
// if (plain_type.contains("dolar")) {
// rateType = USD;
// } else if (plain_type.contains("euro")) {
// rateType = EUR;
// } else if (plain_type.contains("altın")) {
// rateType = ONS_TRY;
// } else if (plain_type.contains("parite")) {
// rateType = EUR_USD;
// }
// this.rateType = rateType;
// }
// }
// Path: app/src/main/java/dynoapps/exchange_rates/network/BigparaService.java
import java.util.List;
import dynoapps.exchange_rates.model.rates.BigparaRate;
import io.reactivex.Observable;
import retrofit2.http.GET;
import retrofit2.http.Headers;
package dynoapps.exchange_rates.network;
/**
* Created by erdemmac on 25/11/2016.
*/
public interface BigparaService {
@Headers({
"Content-Type:text/html; charset=utf-8"
})
@GET("doviz/dolar/") | Observable<List<BigparaRate>> rates(); |
erdemolkun/instant-rates | app/src/main/java/dynoapps/exchange_rates/converters/EnparaConverter.java | // Path: app/src/main/java/dynoapps/exchange_rates/model/rates/BaseRate.java
// public abstract class BaseRate implements IConvertable, IRate {
//
// public String type;
//
// @RateDef
// protected int rateType;
//
// BaseRate() {
// }
//
// @Override
// public int getRateType() {
// return rateType;
// }
//
// public String getFormatted(float val) {
// return RateUtils.valueToUI(val, rateType);
// }
// }
//
// Path: app/src/main/java/dynoapps/exchange_rates/model/rates/EnparaRate.java
// public class EnparaRate extends BuySellRate {
//
// @Override
// public void toRateType() {
// int rateType = UNKNOWN;
// String plain_type = type.replace("\n", "");
// plain_type = plain_type.toLowerCase();
// if (plain_type.contains("parite")) {
// rateType = EUR_USD;
// } else if (plain_type.contains("usd")) {
// rateType = USD;
// } else if (plain_type.contains("eur")) {
// rateType = EUR;
// } else if (plain_type.contains("altın (gram)")) {
// rateType = ONS_TRY;
// }
// this.rateType = rateType;
// }
//
// @Override
// public void setRealValues() {
// String val = valueSell.replace(" TL", "").replace(",", ".").trim();
// valueSellReal = Float.valueOf(val);
//
// val = valueBuy.replace(" TL", "").replace(",", ".").trim();
// valueBuyReal = Float.valueOf(val);
// }
// }
| import org.jsoup.Jsoup;
import org.jsoup.nodes.Element;
import org.jsoup.select.Elements;
import java.io.IOException;
import java.lang.annotation.Annotation;
import java.lang.reflect.Type;
import java.util.ArrayList;
import java.util.List;
import androidx.annotation.NonNull;
import dynoapps.exchange_rates.model.rates.BaseRate;
import dynoapps.exchange_rates.model.rates.EnparaRate;
import okhttp3.ResponseBody;
import retrofit2.Converter;
import retrofit2.Retrofit; | package dynoapps.exchange_rates.converters;
/**
* Copyright 2016 Erdem OLKUN
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except
* in compliance with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software distributed under the License
* is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express
* or implied. See the License for the specific language governing permissions and limitations under
* the License.
*
* Created by erdemmac on 24/11/2016.
*/
public class EnparaConverter implements Converter<ResponseBody, List<BaseRate>> {
private static final EnparaConverter INSTANCE = new EnparaConverter();
private static final String HOST = "https://www.qnbfinansbank.enpara.com";
private EnparaConverter() {
}
@Override
public List<BaseRate> convert(@NonNull ResponseBody value) throws IOException {
ArrayList<BaseRate> rates = new ArrayList<>();
String responseBody = value.string();
final Elements shotElements = Jsoup.parse(responseBody, HOST).getElementsByClass("enpara-gold-exchange-rates__table-item");
for (Element element : shotElements) {
BaseRate rate = parseRate(element);
rates.add(rate);
}
return rates;
}
| // Path: app/src/main/java/dynoapps/exchange_rates/model/rates/BaseRate.java
// public abstract class BaseRate implements IConvertable, IRate {
//
// public String type;
//
// @RateDef
// protected int rateType;
//
// BaseRate() {
// }
//
// @Override
// public int getRateType() {
// return rateType;
// }
//
// public String getFormatted(float val) {
// return RateUtils.valueToUI(val, rateType);
// }
// }
//
// Path: app/src/main/java/dynoapps/exchange_rates/model/rates/EnparaRate.java
// public class EnparaRate extends BuySellRate {
//
// @Override
// public void toRateType() {
// int rateType = UNKNOWN;
// String plain_type = type.replace("\n", "");
// plain_type = plain_type.toLowerCase();
// if (plain_type.contains("parite")) {
// rateType = EUR_USD;
// } else if (plain_type.contains("usd")) {
// rateType = USD;
// } else if (plain_type.contains("eur")) {
// rateType = EUR;
// } else if (plain_type.contains("altın (gram)")) {
// rateType = ONS_TRY;
// }
// this.rateType = rateType;
// }
//
// @Override
// public void setRealValues() {
// String val = valueSell.replace(" TL", "").replace(",", ".").trim();
// valueSellReal = Float.valueOf(val);
//
// val = valueBuy.replace(" TL", "").replace(",", ".").trim();
// valueBuyReal = Float.valueOf(val);
// }
// }
// Path: app/src/main/java/dynoapps/exchange_rates/converters/EnparaConverter.java
import org.jsoup.Jsoup;
import org.jsoup.nodes.Element;
import org.jsoup.select.Elements;
import java.io.IOException;
import java.lang.annotation.Annotation;
import java.lang.reflect.Type;
import java.util.ArrayList;
import java.util.List;
import androidx.annotation.NonNull;
import dynoapps.exchange_rates.model.rates.BaseRate;
import dynoapps.exchange_rates.model.rates.EnparaRate;
import okhttp3.ResponseBody;
import retrofit2.Converter;
import retrofit2.Retrofit;
package dynoapps.exchange_rates.converters;
/**
* Copyright 2016 Erdem OLKUN
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except
* in compliance with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software distributed under the License
* is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express
* or implied. See the License for the specific language governing permissions and limitations under
* the License.
*
* Created by erdemmac on 24/11/2016.
*/
public class EnparaConverter implements Converter<ResponseBody, List<BaseRate>> {
private static final EnparaConverter INSTANCE = new EnparaConverter();
private static final String HOST = "https://www.qnbfinansbank.enpara.com";
private EnparaConverter() {
}
@Override
public List<BaseRate> convert(@NonNull ResponseBody value) throws IOException {
ArrayList<BaseRate> rates = new ArrayList<>();
String responseBody = value.string();
final Elements shotElements = Jsoup.parse(responseBody, HOST).getElementsByClass("enpara-gold-exchange-rates__table-item");
for (Element element : shotElements) {
BaseRate rate = parseRate(element);
rates.add(rate);
}
return rates;
}
| private EnparaRate parseRate(Element element) { |
erdemolkun/instant-rates | app/src/main/java/dynoapps/exchange_rates/network/BloombergService.java | // Path: app/src/main/java/dynoapps/exchange_rates/model/rates/BloombergRate.java
// public class BloombergRate extends AvgRate {
//
// @Override
// public void toRateType() {
// if (TextUtils.isEmpty(type)) rateType = UNKNOWN;
// int rateType = UNKNOWN;
// switch (type) {
// case "USDTRY Curncy":
// rateType = USD;
// break;
// case "EURTRY Curncy":
// rateType = EUR;
// break;
// case "EURUSD Curncy":
// rateType = EUR_USD;
// break;
// case "XAU Curncy":
// rateType = ONS;
// break;
// }
// this.rateType = rateType;
// }
//
// @Override
// public void setRealValues() {
// if (rateType == UNKNOWN) return;
// avg_val = avg_val.replace(".", "").replace(',', '.');
// val_real_avg = Float.parseFloat(avg_val);
// }
// }
| import java.util.List;
import dynoapps.exchange_rates.model.rates.BloombergRate;
import io.reactivex.Observable;
import retrofit2.http.GET;
import retrofit2.http.Headers; | package dynoapps.exchange_rates.network;
/**
* Created by erdemmac on 24/10/2016.
*/
public interface BloombergService {
@Headers({
"Content-Type:text/html; charset=utf-8"
})
@GET("/") | // Path: app/src/main/java/dynoapps/exchange_rates/model/rates/BloombergRate.java
// public class BloombergRate extends AvgRate {
//
// @Override
// public void toRateType() {
// if (TextUtils.isEmpty(type)) rateType = UNKNOWN;
// int rateType = UNKNOWN;
// switch (type) {
// case "USDTRY Curncy":
// rateType = USD;
// break;
// case "EURTRY Curncy":
// rateType = EUR;
// break;
// case "EURUSD Curncy":
// rateType = EUR_USD;
// break;
// case "XAU Curncy":
// rateType = ONS;
// break;
// }
// this.rateType = rateType;
// }
//
// @Override
// public void setRealValues() {
// if (rateType == UNKNOWN) return;
// avg_val = avg_val.replace(".", "").replace(',', '.');
// val_real_avg = Float.parseFloat(avg_val);
// }
// }
// Path: app/src/main/java/dynoapps/exchange_rates/network/BloombergService.java
import java.util.List;
import dynoapps.exchange_rates.model.rates.BloombergRate;
import io.reactivex.Observable;
import retrofit2.http.GET;
import retrofit2.http.Headers;
package dynoapps.exchange_rates.network;
/**
* Created by erdemmac on 24/10/2016.
*/
public interface BloombergService {
@Headers({
"Content-Type:text/html; charset=utf-8"
})
@GET("/") | Observable<List<BloombergRate>> rates(); |
Martin404/jeecg-activiti-framework | src/main/java/org/jeecgframework/web/cgreport/service/impl/excel/CgReportExcelServiceImpl.java | // Path: src/main/java/org/jeecgframework/web/cgreport/service/excel/CgReportExcelServiceI.java
// public interface CgReportExcelServiceI extends CommonService{
// /**
// *
// * @param title 标题
// * @param titleSet 报表头
// * @param dataSet 报表内容
// * @return
// */
// public HSSFWorkbook exportExcel(String title, Collection<?> titleSet,Collection<?> dataSet);
// }
| import java.util.Collection;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import org.jeecgframework.web.cgreport.service.excel.CgReportExcelServiceI;
import org.apache.poi.hssf.usermodel.HSSFCellStyle;
import org.apache.poi.hssf.usermodel.HSSFRichTextString;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.hssf.util.HSSFColor;
import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.ss.usermodel.CellStyle;
import org.apache.poi.ss.usermodel.RichTextString;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.ss.usermodel.Sheet;
import org.jeecgframework.core.common.service.impl.CommonServiceImpl;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional; | package org.jeecgframework.web.cgreport.service.impl.excel;
@Service(value="cgReportExcelService")
@Transactional
public class CgReportExcelServiceImpl extends CommonServiceImpl implements | // Path: src/main/java/org/jeecgframework/web/cgreport/service/excel/CgReportExcelServiceI.java
// public interface CgReportExcelServiceI extends CommonService{
// /**
// *
// * @param title 标题
// * @param titleSet 报表头
// * @param dataSet 报表内容
// * @return
// */
// public HSSFWorkbook exportExcel(String title, Collection<?> titleSet,Collection<?> dataSet);
// }
// Path: src/main/java/org/jeecgframework/web/cgreport/service/impl/excel/CgReportExcelServiceImpl.java
import java.util.Collection;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import org.jeecgframework.web.cgreport.service.excel.CgReportExcelServiceI;
import org.apache.poi.hssf.usermodel.HSSFCellStyle;
import org.apache.poi.hssf.usermodel.HSSFRichTextString;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.hssf.util.HSSFColor;
import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.ss.usermodel.CellStyle;
import org.apache.poi.ss.usermodel.RichTextString;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.ss.usermodel.Sheet;
import org.jeecgframework.core.common.service.impl.CommonServiceImpl;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
package org.jeecgframework.web.cgreport.service.impl.excel;
@Service(value="cgReportExcelService")
@Transactional
public class CgReportExcelServiceImpl extends CommonServiceImpl implements | CgReportExcelServiceI { |
mjdbc/mjdbc | src/test/java/com/github/mjdbc/test/asset/sql/DbValueSql.java | // Path: src/main/java/com/github/mjdbc/type/DbInt.java
// public interface DbInt {
// /**
// * @return database object representation.
// */
// int getDbValue();
// }
//
// Path: src/main/java/com/github/mjdbc/type/DbLong.java
// public interface DbLong {
// /**
// * @return database object representation.
// */
// long getDbValue();
// }
//
// Path: src/main/java/com/github/mjdbc/type/DbString.java
// public interface DbString {
// /**
// * @return database object representation.
// */
// String getDbValue();
// }
//
// Path: src/main/java/com/github/mjdbc/type/DbTimestamp.java
// public interface DbTimestamp {
// /**
// * @return database object representation.
// */
// Timestamp getDbValue();
// }
| import com.github.mjdbc.Bind;
import com.github.mjdbc.Sql;
import com.github.mjdbc.type.DbInt;
import com.github.mjdbc.type.DbLong;
import com.github.mjdbc.type.DbString;
import com.github.mjdbc.type.DbTimestamp;
import java.sql.Timestamp;
import org.jetbrains.annotations.Nullable; | package com.github.mjdbc.test.asset.sql;
/**
* Sql interface to test various Java types.
*/
public interface DbValueSql {
@Sql("SELECT integer_field FROM custom_types")
Integer getNullableInt();
@Sql("UPDATE custom_types SET integer_field = :value") | // Path: src/main/java/com/github/mjdbc/type/DbInt.java
// public interface DbInt {
// /**
// * @return database object representation.
// */
// int getDbValue();
// }
//
// Path: src/main/java/com/github/mjdbc/type/DbLong.java
// public interface DbLong {
// /**
// * @return database object representation.
// */
// long getDbValue();
// }
//
// Path: src/main/java/com/github/mjdbc/type/DbString.java
// public interface DbString {
// /**
// * @return database object representation.
// */
// String getDbValue();
// }
//
// Path: src/main/java/com/github/mjdbc/type/DbTimestamp.java
// public interface DbTimestamp {
// /**
// * @return database object representation.
// */
// Timestamp getDbValue();
// }
// Path: src/test/java/com/github/mjdbc/test/asset/sql/DbValueSql.java
import com.github.mjdbc.Bind;
import com.github.mjdbc.Sql;
import com.github.mjdbc.type.DbInt;
import com.github.mjdbc.type.DbLong;
import com.github.mjdbc.type.DbString;
import com.github.mjdbc.type.DbTimestamp;
import java.sql.Timestamp;
import org.jetbrains.annotations.Nullable;
package com.github.mjdbc.test.asset.sql;
/**
* Sql interface to test various Java types.
*/
public interface DbValueSql {
@Sql("SELECT integer_field FROM custom_types")
Integer getNullableInt();
@Sql("UPDATE custom_types SET integer_field = :value") | void setNullableDbInt(@Bind("value") @Nullable DbInt value); |
mjdbc/mjdbc | src/test/java/com/github/mjdbc/test/asset/sql/DbValueSql.java | // Path: src/main/java/com/github/mjdbc/type/DbInt.java
// public interface DbInt {
// /**
// * @return database object representation.
// */
// int getDbValue();
// }
//
// Path: src/main/java/com/github/mjdbc/type/DbLong.java
// public interface DbLong {
// /**
// * @return database object representation.
// */
// long getDbValue();
// }
//
// Path: src/main/java/com/github/mjdbc/type/DbString.java
// public interface DbString {
// /**
// * @return database object representation.
// */
// String getDbValue();
// }
//
// Path: src/main/java/com/github/mjdbc/type/DbTimestamp.java
// public interface DbTimestamp {
// /**
// * @return database object representation.
// */
// Timestamp getDbValue();
// }
| import com.github.mjdbc.Bind;
import com.github.mjdbc.Sql;
import com.github.mjdbc.type.DbInt;
import com.github.mjdbc.type.DbLong;
import com.github.mjdbc.type.DbString;
import com.github.mjdbc.type.DbTimestamp;
import java.sql.Timestamp;
import org.jetbrains.annotations.Nullable; | package com.github.mjdbc.test.asset.sql;
/**
* Sql interface to test various Java types.
*/
public interface DbValueSql {
@Sql("SELECT integer_field FROM custom_types")
Integer getNullableInt();
@Sql("UPDATE custom_types SET integer_field = :value")
void setNullableDbInt(@Bind("value") @Nullable DbInt value);
@Sql("SELECT long_field FROM custom_types")
Long getNullableLong();
@Sql("UPDATE custom_types SET long_field = :value") | // Path: src/main/java/com/github/mjdbc/type/DbInt.java
// public interface DbInt {
// /**
// * @return database object representation.
// */
// int getDbValue();
// }
//
// Path: src/main/java/com/github/mjdbc/type/DbLong.java
// public interface DbLong {
// /**
// * @return database object representation.
// */
// long getDbValue();
// }
//
// Path: src/main/java/com/github/mjdbc/type/DbString.java
// public interface DbString {
// /**
// * @return database object representation.
// */
// String getDbValue();
// }
//
// Path: src/main/java/com/github/mjdbc/type/DbTimestamp.java
// public interface DbTimestamp {
// /**
// * @return database object representation.
// */
// Timestamp getDbValue();
// }
// Path: src/test/java/com/github/mjdbc/test/asset/sql/DbValueSql.java
import com.github.mjdbc.Bind;
import com.github.mjdbc.Sql;
import com.github.mjdbc.type.DbInt;
import com.github.mjdbc.type.DbLong;
import com.github.mjdbc.type.DbString;
import com.github.mjdbc.type.DbTimestamp;
import java.sql.Timestamp;
import org.jetbrains.annotations.Nullable;
package com.github.mjdbc.test.asset.sql;
/**
* Sql interface to test various Java types.
*/
public interface DbValueSql {
@Sql("SELECT integer_field FROM custom_types")
Integer getNullableInt();
@Sql("UPDATE custom_types SET integer_field = :value")
void setNullableDbInt(@Bind("value") @Nullable DbInt value);
@Sql("SELECT long_field FROM custom_types")
Long getNullableLong();
@Sql("UPDATE custom_types SET long_field = :value") | void setNullableDbLong(@Bind("value") @Nullable DbLong value); |
mjdbc/mjdbc | src/test/java/com/github/mjdbc/test/asset/sql/DbValueSql.java | // Path: src/main/java/com/github/mjdbc/type/DbInt.java
// public interface DbInt {
// /**
// * @return database object representation.
// */
// int getDbValue();
// }
//
// Path: src/main/java/com/github/mjdbc/type/DbLong.java
// public interface DbLong {
// /**
// * @return database object representation.
// */
// long getDbValue();
// }
//
// Path: src/main/java/com/github/mjdbc/type/DbString.java
// public interface DbString {
// /**
// * @return database object representation.
// */
// String getDbValue();
// }
//
// Path: src/main/java/com/github/mjdbc/type/DbTimestamp.java
// public interface DbTimestamp {
// /**
// * @return database object representation.
// */
// Timestamp getDbValue();
// }
| import com.github.mjdbc.Bind;
import com.github.mjdbc.Sql;
import com.github.mjdbc.type.DbInt;
import com.github.mjdbc.type.DbLong;
import com.github.mjdbc.type.DbString;
import com.github.mjdbc.type.DbTimestamp;
import java.sql.Timestamp;
import org.jetbrains.annotations.Nullable; | package com.github.mjdbc.test.asset.sql;
/**
* Sql interface to test various Java types.
*/
public interface DbValueSql {
@Sql("SELECT integer_field FROM custom_types")
Integer getNullableInt();
@Sql("UPDATE custom_types SET integer_field = :value")
void setNullableDbInt(@Bind("value") @Nullable DbInt value);
@Sql("SELECT long_field FROM custom_types")
Long getNullableLong();
@Sql("UPDATE custom_types SET long_field = :value")
void setNullableDbLong(@Bind("value") @Nullable DbLong value);
@Sql("SELECT varchar_field FROM custom_types")
String getNullableString();
@Sql("UPDATE custom_types SET varchar_field = :value") | // Path: src/main/java/com/github/mjdbc/type/DbInt.java
// public interface DbInt {
// /**
// * @return database object representation.
// */
// int getDbValue();
// }
//
// Path: src/main/java/com/github/mjdbc/type/DbLong.java
// public interface DbLong {
// /**
// * @return database object representation.
// */
// long getDbValue();
// }
//
// Path: src/main/java/com/github/mjdbc/type/DbString.java
// public interface DbString {
// /**
// * @return database object representation.
// */
// String getDbValue();
// }
//
// Path: src/main/java/com/github/mjdbc/type/DbTimestamp.java
// public interface DbTimestamp {
// /**
// * @return database object representation.
// */
// Timestamp getDbValue();
// }
// Path: src/test/java/com/github/mjdbc/test/asset/sql/DbValueSql.java
import com.github.mjdbc.Bind;
import com.github.mjdbc.Sql;
import com.github.mjdbc.type.DbInt;
import com.github.mjdbc.type.DbLong;
import com.github.mjdbc.type.DbString;
import com.github.mjdbc.type.DbTimestamp;
import java.sql.Timestamp;
import org.jetbrains.annotations.Nullable;
package com.github.mjdbc.test.asset.sql;
/**
* Sql interface to test various Java types.
*/
public interface DbValueSql {
@Sql("SELECT integer_field FROM custom_types")
Integer getNullableInt();
@Sql("UPDATE custom_types SET integer_field = :value")
void setNullableDbInt(@Bind("value") @Nullable DbInt value);
@Sql("SELECT long_field FROM custom_types")
Long getNullableLong();
@Sql("UPDATE custom_types SET long_field = :value")
void setNullableDbLong(@Bind("value") @Nullable DbLong value);
@Sql("SELECT varchar_field FROM custom_types")
String getNullableString();
@Sql("UPDATE custom_types SET varchar_field = :value") | void setNullableDbString(@Bind("value") @Nullable DbString value); |
mjdbc/mjdbc | src/test/java/com/github/mjdbc/test/asset/sql/DbValueSql.java | // Path: src/main/java/com/github/mjdbc/type/DbInt.java
// public interface DbInt {
// /**
// * @return database object representation.
// */
// int getDbValue();
// }
//
// Path: src/main/java/com/github/mjdbc/type/DbLong.java
// public interface DbLong {
// /**
// * @return database object representation.
// */
// long getDbValue();
// }
//
// Path: src/main/java/com/github/mjdbc/type/DbString.java
// public interface DbString {
// /**
// * @return database object representation.
// */
// String getDbValue();
// }
//
// Path: src/main/java/com/github/mjdbc/type/DbTimestamp.java
// public interface DbTimestamp {
// /**
// * @return database object representation.
// */
// Timestamp getDbValue();
// }
| import com.github.mjdbc.Bind;
import com.github.mjdbc.Sql;
import com.github.mjdbc.type.DbInt;
import com.github.mjdbc.type.DbLong;
import com.github.mjdbc.type.DbString;
import com.github.mjdbc.type.DbTimestamp;
import java.sql.Timestamp;
import org.jetbrains.annotations.Nullable; | package com.github.mjdbc.test.asset.sql;
/**
* Sql interface to test various Java types.
*/
public interface DbValueSql {
@Sql("SELECT integer_field FROM custom_types")
Integer getNullableInt();
@Sql("UPDATE custom_types SET integer_field = :value")
void setNullableDbInt(@Bind("value") @Nullable DbInt value);
@Sql("SELECT long_field FROM custom_types")
Long getNullableLong();
@Sql("UPDATE custom_types SET long_field = :value")
void setNullableDbLong(@Bind("value") @Nullable DbLong value);
@Sql("SELECT varchar_field FROM custom_types")
String getNullableString();
@Sql("UPDATE custom_types SET varchar_field = :value")
void setNullableDbString(@Bind("value") @Nullable DbString value);
@Sql("SELECT timestamp_field FROM custom_types")
Timestamp getNullableTimestamp();
@Sql("UPDATE custom_types SET timestamp_field = :value") | // Path: src/main/java/com/github/mjdbc/type/DbInt.java
// public interface DbInt {
// /**
// * @return database object representation.
// */
// int getDbValue();
// }
//
// Path: src/main/java/com/github/mjdbc/type/DbLong.java
// public interface DbLong {
// /**
// * @return database object representation.
// */
// long getDbValue();
// }
//
// Path: src/main/java/com/github/mjdbc/type/DbString.java
// public interface DbString {
// /**
// * @return database object representation.
// */
// String getDbValue();
// }
//
// Path: src/main/java/com/github/mjdbc/type/DbTimestamp.java
// public interface DbTimestamp {
// /**
// * @return database object representation.
// */
// Timestamp getDbValue();
// }
// Path: src/test/java/com/github/mjdbc/test/asset/sql/DbValueSql.java
import com.github.mjdbc.Bind;
import com.github.mjdbc.Sql;
import com.github.mjdbc.type.DbInt;
import com.github.mjdbc.type.DbLong;
import com.github.mjdbc.type.DbString;
import com.github.mjdbc.type.DbTimestamp;
import java.sql.Timestamp;
import org.jetbrains.annotations.Nullable;
package com.github.mjdbc.test.asset.sql;
/**
* Sql interface to test various Java types.
*/
public interface DbValueSql {
@Sql("SELECT integer_field FROM custom_types")
Integer getNullableInt();
@Sql("UPDATE custom_types SET integer_field = :value")
void setNullableDbInt(@Bind("value") @Nullable DbInt value);
@Sql("SELECT long_field FROM custom_types")
Long getNullableLong();
@Sql("UPDATE custom_types SET long_field = :value")
void setNullableDbLong(@Bind("value") @Nullable DbLong value);
@Sql("SELECT varchar_field FROM custom_types")
String getNullableString();
@Sql("UPDATE custom_types SET varchar_field = :value")
void setNullableDbString(@Bind("value") @Nullable DbString value);
@Sql("SELECT timestamp_field FROM custom_types")
Timestamp getNullableTimestamp();
@Sql("UPDATE custom_types SET timestamp_field = :value") | void setNullableDbTimestamp(@Bind("value") @Nullable DbTimestamp value); |
mjdbc/mjdbc | src/test/java/com/github/mjdbc/test/asset/model/GetterBean.java | // Path: src/main/java/com/github/mjdbc/DbMapper.java
// public interface DbMapper<T> {
//
// /**
// * Maps a single row or all rows to the corresponding Java object.
// * May return null for nullable primitive type fields (like nullable varchar field).
// * Must never return null for complex java property objects (beans).
// *
// * @param r - open result set.
// * @return Java object.
// * @throws SQLException if SQLException occurs during the mapping process
// */
// T map(@NotNull ResultSet r) throws SQLException;
// }
//
// Path: src/test/java/com/github/mjdbc/test/asset/types/DbIntValue.java
// public class DbIntValue extends AbstractDbInt {
// protected int value;
//
// public DbIntValue(int value) {
// this.value = value;
// }
//
// public final int getDbValue() {
// return value;
// }
//
// public String toString() {
// return getClass().getSimpleName() + "[" + value + "]";
// }
// }
| import com.github.mjdbc.DbMapper;
import com.github.mjdbc.Mapper;
import com.github.mjdbc.test.asset.types.DbIntValue; | package com.github.mjdbc.test.asset.model;
/**
* Bean with getters and setters methods and private fields.
*/
public class GetterBean {
private long id;
private boolean booleanField;
private int intField;
private String stringField;
| // Path: src/main/java/com/github/mjdbc/DbMapper.java
// public interface DbMapper<T> {
//
// /**
// * Maps a single row or all rows to the corresponding Java object.
// * May return null for nullable primitive type fields (like nullable varchar field).
// * Must never return null for complex java property objects (beans).
// *
// * @param r - open result set.
// * @return Java object.
// * @throws SQLException if SQLException occurs during the mapping process
// */
// T map(@NotNull ResultSet r) throws SQLException;
// }
//
// Path: src/test/java/com/github/mjdbc/test/asset/types/DbIntValue.java
// public class DbIntValue extends AbstractDbInt {
// protected int value;
//
// public DbIntValue(int value) {
// this.value = value;
// }
//
// public final int getDbValue() {
// return value;
// }
//
// public String toString() {
// return getClass().getSimpleName() + "[" + value + "]";
// }
// }
// Path: src/test/java/com/github/mjdbc/test/asset/model/GetterBean.java
import com.github.mjdbc.DbMapper;
import com.github.mjdbc.Mapper;
import com.github.mjdbc.test.asset.types.DbIntValue;
package com.github.mjdbc.test.asset.model;
/**
* Bean with getters and setters methods and private fields.
*/
public class GetterBean {
private long id;
private boolean booleanField;
private int intField;
private String stringField;
| private DbIntValue intValueField; |
mjdbc/mjdbc | src/test/java/com/github/mjdbc/test/asset/model/GetterBean.java | // Path: src/main/java/com/github/mjdbc/DbMapper.java
// public interface DbMapper<T> {
//
// /**
// * Maps a single row or all rows to the corresponding Java object.
// * May return null for nullable primitive type fields (like nullable varchar field).
// * Must never return null for complex java property objects (beans).
// *
// * @param r - open result set.
// * @return Java object.
// * @throws SQLException if SQLException occurs during the mapping process
// */
// T map(@NotNull ResultSet r) throws SQLException;
// }
//
// Path: src/test/java/com/github/mjdbc/test/asset/types/DbIntValue.java
// public class DbIntValue extends AbstractDbInt {
// protected int value;
//
// public DbIntValue(int value) {
// this.value = value;
// }
//
// public final int getDbValue() {
// return value;
// }
//
// public String toString() {
// return getClass().getSimpleName() + "[" + value + "]";
// }
// }
| import com.github.mjdbc.DbMapper;
import com.github.mjdbc.Mapper;
import com.github.mjdbc.test.asset.types.DbIntValue; | }
public int getIntField() {
return intField;
}
public void setIntField(int intField) {
this.intField = intField;
}
public String getStringField() {
return stringField;
}
public void setStringField(String stringField) {
this.stringField = stringField;
}
public DbIntValue getIntValueField() {
return intValueField;
}
public void setIntValueField(DbIntValue intValueField) {
this.intValueField = intValueField;
}
/**
* Class to create User object from result set.
*/
@Mapper | // Path: src/main/java/com/github/mjdbc/DbMapper.java
// public interface DbMapper<T> {
//
// /**
// * Maps a single row or all rows to the corresponding Java object.
// * May return null for nullable primitive type fields (like nullable varchar field).
// * Must never return null for complex java property objects (beans).
// *
// * @param r - open result set.
// * @return Java object.
// * @throws SQLException if SQLException occurs during the mapping process
// */
// T map(@NotNull ResultSet r) throws SQLException;
// }
//
// Path: src/test/java/com/github/mjdbc/test/asset/types/DbIntValue.java
// public class DbIntValue extends AbstractDbInt {
// protected int value;
//
// public DbIntValue(int value) {
// this.value = value;
// }
//
// public final int getDbValue() {
// return value;
// }
//
// public String toString() {
// return getClass().getSimpleName() + "[" + value + "]";
// }
// }
// Path: src/test/java/com/github/mjdbc/test/asset/model/GetterBean.java
import com.github.mjdbc.DbMapper;
import com.github.mjdbc.Mapper;
import com.github.mjdbc.test.asset.types.DbIntValue;
}
public int getIntField() {
return intField;
}
public void setIntField(int intField) {
this.intField = intField;
}
public String getStringField() {
return stringField;
}
public void setStringField(String stringField) {
this.stringField = stringField;
}
public DbIntValue getIntValueField() {
return intValueField;
}
public void setIntValueField(DbIntValue intValueField) {
this.intValueField = intValueField;
}
/**
* Class to create User object from result set.
*/
@Mapper | public static final DbMapper<GetterBean> MAPPER = (r) -> { |
mjdbc/mjdbc | src/test/java/com/github/mjdbc/test/asset/sql/BeanWithStaticFieldMapperSql.java | // Path: src/test/java/com/github/mjdbc/test/asset/model/BeanWithStaticFieldMapper.java
// public class BeanWithStaticFieldMapper {
//
// @Mapper
// public static final DbMapper<BeanWithStaticFieldMapper> MAPPER_v1_1 = r -> null;
//
// }
| import com.github.mjdbc.Sql;
import com.github.mjdbc.test.asset.model.BeanWithStaticFieldMapper; | package com.github.mjdbc.test.asset.sql;
public interface BeanWithStaticFieldMapperSql {
@Sql("SELECT 1") | // Path: src/test/java/com/github/mjdbc/test/asset/model/BeanWithStaticFieldMapper.java
// public class BeanWithStaticFieldMapper {
//
// @Mapper
// public static final DbMapper<BeanWithStaticFieldMapper> MAPPER_v1_1 = r -> null;
//
// }
// Path: src/test/java/com/github/mjdbc/test/asset/sql/BeanWithStaticFieldMapperSql.java
import com.github.mjdbc.Sql;
import com.github.mjdbc.test.asset.model.BeanWithStaticFieldMapper;
package com.github.mjdbc.test.asset.sql;
public interface BeanWithStaticFieldMapperSql {
@Sql("SELECT 1") | BeanWithStaticFieldMapper select(); |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.